Metadata-Version: 2.4
Name: mapstorch
Version: 0.0.2
Summary: A differentiable modeling package for automating X-ray fluorescence (XRF) analysis
Author-email: Xiangyu Yin <xyin@anl.gov>
License: Copyright (c) 2024, UChicago Argonne, LLC. All rights reserved.
        
        Copyright 2024. UChicago Argonne, LLC. This software was produced
        under U.S. Government contract DE-AC02-06CH11357 for Argonne National
        Laboratory (ANL), which is operated by UChicago Argonne, LLC for the
        U.S. Department of Energy. The U.S. Government has rights to use,
        reproduce, and distribute this software.  NEITHER THE GOVERNMENT NOR
        UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
        ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.  If software is
        modified to produce derivative works, such modified software should
        be clearly marked, so as not to confuse it with the version available
        from ANL.
        
        Additionally, redistribution and use in source and binary forms, with
        or without modification, are permitted provided that the following
        conditions are met:
        
            * Redistributions of source code must retain the above copyright
              notice, this list of conditions and the following disclaimer.
        
            * Redistributions in binary form must reproduce the above copyright
              notice, this list of conditions and the following disclaimer in
              the documentation and/or other materials provided with the
              distribution.
        
            * Neither the name of UChicago Argonne, LLC, Argonne National
              Laboratory, ANL, the U.S. Government, nor the names of its
              contributors may be used to endorse or promote products derived
              from this software without specific prior written permission.
        
        THIS SOFTWARE IS PROVIDED BY UChicago Argonne, LLC AND CONTRIBUTORS
        "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
        LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
        FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UChicago
        Argonne, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
        INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
        BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
        LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
        LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
        ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
        POSSIBILITY OF SUCH DAMAGE.
Project-URL: Homepage, https://github.com/xyin-anl/MapsTorch
Project-URL: Repository, https://github.com/xyin-anl/MapsTorch
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: h5py
Requires-Dist: tqdm
Requires-Dist: numpy
Requires-Dist: torch
Provides-Extra: plot
Requires-Dist: matplotlib; extra == "plot"
Requires-Dist: scienceplots<3,>=2.2.0; extra == "plot"
Provides-Extra: widget
Requires-Dist: anywidget; extra == "widget"
Requires-Dist: traitlets; extra == "widget"
Provides-Extra: apps
Requires-Dist: mapstorch[plot,widget]; extra == "apps"
Requires-Dist: marimo; extra == "apps"
Requires-Dist: plotly; extra == "apps"
Requires-Dist: pandas; extra == "apps"
Requires-Dist: scipy; extra == "apps"
Provides-Extra: all
Requires-Dist: mapstorch[apps]; extra == "all"
Dynamic: license-file

> [!TIP]
> Play with a demo dataset on [Hugging Space](https://huggingface.co/spaces/shawnyin/MapsTorch)

<p align="center">
  <img src="assets/logo.png" alt="MapsTorch Logo" width="400"/>
</p>

## MapsTorch

MapsTorch is a differentiable modeling package for automating X-ray fluorescence (XRF) analysis. It combines the physics-based [MAPS](https://www.aps.anl.gov/Microscopy/Software-and-Tools-MAPS) model with PyTorch's automatic differentiation framework.

Key features:

- Parameter optimization for XRF spectrum fitting
- Element selection decision support
- Integration with existing [XRF-Maps](https://github.com/xyin-anl/XRF-Maps) workflows

See [paper](https://doi.org/10.1107/S160057752501032X) for technical details.

## Get Started

Python 3.10 or newer is required. The core engine supports NumPy 2 and needs
only NumPy, PyTorch, h5py, and tqdm:

```sh
pip install mapstorch
```

Optional tools are available as extras:

```sh
pip install 'mapstorch[plot]'    # Matplotlib plots and SciencePlots styles
pip install 'mapstorch[widget]'  # Notebook widgets
pip install 'mapstorch[apps]'    # Apps and scripts, including plots and widgets
pip install 'mapstorch[all]'     # All optional tools
```

**Develop with Pixi**

We keep the development environment reproducible with [Pixi](https://pixi.sh/). Once Pixi is installed:

1. Resolve the environment: `pixi install`
2. Enter the shell: `pixi shell`
3. Install MapsTorch in editable mode: `pixi run install`

After that you can run examples or scripts in the Pixi shell, e.g. `python scripts/fit_spec.py -h` or `marimo run apps/guess_elements.py`.

## Prepare Data

MapsTorch works with HDF5 files produced by [XRFMaps](https://github.com/xyin-anl/XRF-Maps). The HDF5 file must contain:

- Spectra volume data in `MAPS/mca_arr` group
- Integrated spectra array in `MAPS/int_spec` group

For numpy array data, use the `create_dataset` function in `mapstorch.io`:

```python
def create_dataset(
    spec_vol,
    energy_dim,
    output_path,
    fit_elems=None,
    dtype=np.float32,
    compression="gzip",
    compression_opts=4,
):
    """Create an HDF5 file compatible with read_dataset function.

    Args:
        spec_vol: 3D numpy array or path to .npy file containing spectral volume
        energy_dim: Which dimension (0,1,2) contains the energy channels
        output_path: Path where to save the HDF5 file
        fit_elems: Optional list of element names
        dtype: numpy dtype for data storage (e.g. np.float32, np.float16). Default: np.float32
        compression: Compression filter to use. Options: 'gzip', 'lzf', None. Default: 'gzip'
        compression_opts: Compression settings. For 'gzip', this is the compression level (0-9). Default: 4
    """
```

## Interactive Apps

We provide marimo notebooks in the `apps` folder that can be run as web apps (download the notebooks and run them in a Python environment with `mapstorch` installed):

### Guess elements:

```
marimo run guess_elements.py
```

[![Guessing elements](https://img.youtube.com/vi/dJQiLpy4r-Q/0.jpg)](https://www.youtube.com/watch?v=dJQiLpy4r-Q)

### Optimize parameters:

```
marimo run optimize_parameters.py
```

[![Optimizing parameters](https://img.youtube.com/vi/d8Z2n-97f9Q/0.jpg)](https://www.youtube.com/watch?v=d8Z2n-97f9Q)

## Example Scripts

The `scripts` folder contains example scripts like `fit_spec.py` for fitting integrated spectra. Usage:

```
python fit_spec.py DATASET.h5 -e 12.0
```

If you have an override parameters file:
```
python fit_spec.py DATASET.h5 -e 12.0 --override_params_file parameters_override.txt
```

For all options:

```
python scripts/fit_spec.py -h
```

## Contact

- Bug reports and feature requests: Open GitHub Issues
- Contributions: Fork repository, create branch, submit pull request
- XRF analysis help: Contact xyin@anl.gov or aglowacki@anl.gov

## Acknowledgement

This research used resources of the Advanced Photon Source, an U.S. Department of Energy (DOE) Office of Science User Facility operated for the DOE Office of Science by Argonne National Laboratory under Contract No. DE-AC02-06CH11357. The authors acknowledge funding support from Argonne LDRD 2023-0049.
