Metadata-Version: 2.4
Name: pysimplemask
Version: 0.4.0
Summary: A GUI for creating mask and q-partition maps for scattering patterns in preparation for SAXS/WAXS/XPCS data reduction
Author-email: Miaoqi Chu <mqichu@anl.gov>
Maintainer-email: Miaoqi Chu <mqichu@anl.gov>
License: Apache License
                                   Version 2.0, January 2004
                        
        Copyright © 2026 UChicago Argonne, LLC. All right reserved
        
        ARGONNE NATIONAL LABORATORY, WITH A FACILITY IN THE STATE OF ILLINOIS, IS
        OWNED BY THE UNITED STATES GOVERNMENT, AND OPERATED BY UCHICAGO ARGONNE, LLC
        UNDER PROVISION OF A CONTRACT WITH THE DEPARTMENT OF ENERGY.
        
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
Project-URL: bugs, https://github.com/AdvancedPhotonSource/pySimpleMask/issues
Project-URL: changelog, https://github.com/AdvancedPhotonSource/pySimpleMask/blob/master/changelog.md
Project-URL: homepage, https://github.com/AdvancedPhotonSource/pySimpleMask
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Visualization
Classifier: Operating System :: OS Independent
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: h5py
Requires-Dist: hdf5plugin
Requires-Dist: scikit-image
Requires-Dist: matplotlib
Requires-Dist: pyqtgraph
Requires-Dist: PySide6>=6.8
Requires-Dist: astropy
Requires-Dist: imagecodecs
Requires-Dist: tifffile
Provides-Extra: dev
Requires-Dist: coverage; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Requires-Dist: pytest; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Provides-Extra: web
Requires-Dist: dash>=2.14; extra == "web"
Requires-Dist: plotly>=5.18; extra == "web"
Dynamic: license-file

# pySimpleMask

[![PyPI version](https://img.shields.io/pypi/v/pysimplemask.svg)](https://pypi.python.org/pypi/pysimplemask)

**pySimpleMask** is a tool for creating masks and Q-partition maps for X-ray scattering
patterns, supporting SAXS, WAXS, and XPCS data reduction. It ships both a desktop GUI
and a **headless Python API** that can drive the full pipeline from scripts.

## Features

- **Versatile data support** — HDF5 (NeXus/XPCS), IMM, Rigaku 500k/3M binary, TIFF,
  native TIFF images (NativeFiles beamline with editable placeholder metadata).
  Supported beamlines: APS 8-ID-I (transmission) and APS 9-ID-D (reflection/GISAXS).
  XPCS result HDF5 files (containing an `/xpcs` group) are auto-detected and their
  saved partition is restored on load.
  On free-threaded Python (CPython 3.13+ `--disable-gil`), LZ4-chunked HDF5 files are
  read with a thread-parallel HDF5-bypass path (no GIL, no HDF5 mutex) for faster
  frame averaging; standard Python falls back automatically.
- **Interactive masking**
  - Drawing tools: polygons, circles, ellipses, rectangles, line-width ROIs.
  - Binary threshold (low / high intensity limits with dtype presets).
  - Blemish/bad-pixel maps (TIFF or HDF5).
  - Additional mask file import (TIFF or HDF5).
  - Manual pixel selection by click or coordinate list.
  - **Outlier removal** — two strategies:
    - *CircularRings*: SAXS 1-D azimuthal average comparison per q-ring.
    - *AdjacentPixels*: fixed-size spatial boxes, sorted brightest-first.
    - Both support percentile-clip and MAD metrics.
  - Parametric masking by q-map range (q, phi, x, y, …).
  - Undo / redo / reset mask history.
- **Beam-center finding** — iterative centro-symmetry cross-correlation, converges
  in 1–2 passes; bounded crop for speed on large detectors.
- **Partition generation**
  - Q-Phi (dynamic + static resolution pair).
  - X-Y spatial partitions.
  - Ellipse-corrected Q-Phi (eq-ephi).
  - Custom axis pair from any q-map channel.
- **Visualization** — real-time display of scattering, mask, preview, and partition
  maps; adjustable colormap, log scale, beam-center marker; raw-frame browser with
  per-frame or averaged display for multi-frame HDF5 files.
- **Web viewer** — browser-based interface (Dash/Plotly) exposing the full mask and
  partition workflow; launch with `pysimplemask web`.
- **Output** — TIFF mask, Nexus-compatible HDF5 partition (hash + version stamped),
  one-page PDF pipeline summary, `pysimplemask-combine-qmaps` CLI to merge two partition files.

## Installation

### From PyPI
```bash
pip install pysimplemask
```

### From Source
```bash
git clone https://github.com/AdvancedPhotonSource/pySimpleMask.git
cd pySimpleMask
pip install .
```

## GUI Usage

Launch the desktop application:

```bash
pysimplemask                          # or: pysimplemask gui
pysimplemask --path /path/to/data    # open at a specific directory
```

### Workflow

1. **Load data** — select a raw file and click **Load**. Beam center, energy, detector
   distance and pixel size are read from the NeXus metadata; defaults are used if metadata
   is absent.
2. **Define mask** — use the Mask tabs (Blemish/Files, Draw, Binary, Manual, Outlier,
   Parametrization). Click **Evaluate** to preview, **Apply** to commit each layer.
   Undo/Redo/Reset are always available.
3. **Compute partition** — go to the Partition panel, choose a mode and bin counts,
   click **Compute Partition**.
4. **Save** — export as *Mask-Only* (TIFF) or *Nexus-XPCS* (HDF5, includes mask,
   partition maps, and instrument metadata).

GUI state (splitter positions, beamline selection) is persisted in
`~/.pysimplemask/config.json`.

## Headless / Scripted Usage

`import pysimplemask` is **Qt-free**. The full masking and partition pipeline is
available without a display:

```python
from pysimplemask.core import SimpleMaskModel

m = SimpleMaskModel()
m.read_data("scan.h5", beamline="APS_8IDI", begin_idx=0, num_frames=-1)

# threshold mask
m.mask_evaluate("mask_threshold", low=0, high=65535, low_enable=False, high_enable=True)
m.mask_apply("mask_threshold")

# geometric mask (polygon)
m.add_polygon([(r0, c0), (r1, c1), (r2, c2)], mode="exclusive")
m.evaluate_draw()
m.mask_apply("mask_draw")

# q-phi partition
m.compute_partition(mode="q-phi", dq_num=10, sq_num=100, dp_num=36, sp_num=360)
m.save_partition("qmap.hdf")
m.save_mask("mask.tif")
```

Geometry helpers available on the model: `add_polygon`, `add_circle`, `add_ellipse`,
`add_rectangle`, `add_line` (all accept `mode="exclusive"` or `"inclusive"`).

## Web Viewer

```bash
pysimplemask web                     # start the Dash web server (default port 8050)
pysimplemask web --port 8080
```

Open `http://localhost:8050` in a browser. The web viewer exposes the same mask
and partition workflow as the desktop GUI, including all six mask tabs, four
partition modes, and partition/mask save.

## CLI Tools

```bash
# Build a qmap from a raw scattering file (full headless pipeline).
# A PDF summary report is written alongside the qmap by default.
pysimplemask-build-qmap scan.hdf --output-qmap qmap.hdf --output-mask mask.tif

# Key options (see --help for all):
pysimplemask-build-qmap scan.hdf \
    --beamline APS_8IDI \
    --num-frames 0 \
    --blemish blemish.tif \
    --threshold-high 65535 \
    --param-constraint q:AND:0.01:0.15 \   # geometry-based mask: keep q in [0.01, 0.15]
    --param-constraint phi:AND:-30:30 \     # and phi in [-30°, 30°]
    --mode q-phi \
    --dq-num 10 --sq-num 100 \
    --dp-num 36 --sp-num 360 \
    --output-qmap qmap.hdf \
    --output-mask mask.tif \
    --report summary.pdf              # omit to auto-name, pass "" to skip

# Merge two existing qmap files
pysimplemask-combine-qmaps file1.hdf file2.hdf output.hdf
```

## Development

```bash
pip install -e ".[dev]"   # install with ruff, pytest, mypy

make test                 # run tests
make lint                 # ruff check
make ui                   # regenerate gui/view/ui_mask.py from gui/view/mask.ui
# or: python src/pysimplemask/gui/view/compile_ui.py
```

The project follows an MVC layout: `src/pysimplemask/core/` (Qt-free, scriptable engine)
and `src/pysimplemask/gui/` (PySide6 + pyqtgraph view/model/control). See `CLAUDE.md`
for the full architecture reference.

## Docker

Build (Docker or Podman):
```bash
docker build -t pysimplemask .
podman build -t pysimplemask .
```

Run on Linux (requires X11 forwarding for the GUI):
```bash
xhost +local:   # allow local X11 connections

# Docker
docker run -it --rm -e DISPLAY=$DISPLAY \
    -v /tmp/.X11-unix:/tmp/.X11-unix \
    -v $(pwd):/data pysimplemask

# Podman (SELinux systems)
podman run -it --rm -e DISPLAY=$DISPLAY \
    -v /tmp/.X11-unix:/tmp/.X11-unix \
    --security-opt label=type:container_runtime_t \
    -v $(pwd):/data pysimplemask
```

A convenience script that auto-detects Docker/Podman, builds if needed, and
launches with X11 forwarding is provided at `scripts/run_container.sh`.

## Credits

- **Author**: Miaoqi Chu (mqichu@anl.gov)
- **License**: Apache 2.0 — Copyright © UChicago Argonne LLC
