Metadata-Version: 2.4
Name: pyAthina
Version: 0.8.5
Summary: Photoemission electron microscopy image processing workflows.
Author: pyAthina contributors
Project-URL: Documentation, https://evangelosgolias.gitlab.io/pyathina/
Project-URL: Repository, https://gitlab.com/evangelosgolias/pyathina
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: X11 Applications :: Qt
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: PyQt6
Requires-Dist: pyqtgraph>=0.13
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: scikit-image
Requires-Dist: scikit-learn
Requires-Dist: h5py
Requires-Dist: igor2
Requires-Dist: tifffile
Requires-Dist: opencv-python-headless
Requires-Dist: xarray
Provides-Extra: jupyter
Requires-Dist: ipykernel; extra == "jupyter"
Requires-Dist: jupyter-client; extra == "jupyter"
Requires-Dist: jupyterlab; extra == "jupyter"
Requires-Dist: qtconsole; extra == "jupyter"
Provides-Extra: docs
Requires-Dist: myst-parser; extra == "docs"
Requires-Dist: sphinx; extra == "docs"
Requires-Dist: sphinx-rtd-theme; extra == "docs"

# pyAthina

pyAthina is a python version of the in-house developed athina package for Igor Pro (see https://gitlab.com/evangelosgolias/athina). pyAthina emulates the functionalities of athina, **and it is AI-developed (Codex)**.

A lightweight PyQt6 + pyqtgraph skeleton for **P**hoto**E**mission **E**lectron **M**icroscopy image processing workflows.

## Install

```bash
pip install pyAthina
```

For development from a source checkout, install the local requirements with:

```bash
pip install -r requirements.txt
```

## Run

Any of these should work from the extracted project folder:

```bash
python -m pyAthina.main
```

```bash
python -m pyAthina
```

```bash
python run_pyAthina.py
```

## Documentation

See https://evangelosgolias.gitlab.io/pyathina/

The manuals now include task-oriented guides for:

- display, histogram visibility, contrast, RGB/grayscale conversion, and image
  export;
- ROI drawing, z/line/plane profiles, saved profile geometry, and distance
  measurements;
- interactive XMCD, live sum images, experimental three-point affine warping,
  and domain polar plots.

## Python scripting, Jupyter, and CLI

The **Scripting > Python console** menu opens a live Python console with:

- `session`: the current `PyAthinaSession`
- `data`: defensive xarray copies of experiment datasets
- `np`: NumPy
- `xr`: xarray

Examples:

```python
session.list()
image = data["root/source"]
result = session.apply(
    "bin",
    "root/source",
    name="source binned",
    z=1,
    y=2,
    x=2,
)
session.add(image.mean("z"), name="mean image", sources=["root/source"])
```

Datasets are changed only through explicit `session.add()` and
`session.apply()` calls. Derived datasets record their source IDs and browser
paths, operation, parameters, timestamp, interface, and pyAthina version.

Optional Jupyter support is installed with:

```bash
pip install -r requirements-jupyter.txt
```

Then choose **Scripting > Start Jupyter kernel**. pyAthina copies a connection
command to the clipboard and exposes the same live namespace to the kernel.

The standalone CLI works without launching Qt:

```bash
python -m pyAthina cli new experiment.h5
python -m pyAthina cli import experiment.h5 image.npy
python -m pyAthina cli list experiment.h5
python -m pyAthina cli apply experiment.h5 bin image \
  --name image_binned --param z=1 --param y=2 --param x=2
python -m pyAthina cli info experiment.h5 image_binned
```

Use `python -m pyAthina cli operations` to list available operations.

If you `cd` into the `pyAthina/` subfolder itself, you can also run:

```bash
python main.py
```


## Alignment modes

- **Correlation**: normalized spatial cross-correlation with sub-pixel peak refinement.
- **Phase correlation**: translation-only drift correction with sub-pixel shift estimation.
- **Image registration**: ECC-based registration on the ROI, with the estimated transform applied to the full image.
  - default: sub-pixel translation
  - optional: rotation
  - optional: scale
  - optional: skew

When scale or skew is enabled, the registration model becomes affine.


## Z profile improvements

- live ROI-driven z-profile updates while moving or resizing the ROI
- standalone popup plot window
- plot styling controls (grid, markers, line width)
- export z-profile as TXT (x, y columns)
- export plot as PNG


## Line profile

- Click **Line profile using line ROI**.
- Then press and drag on the image to draw the line.
- The popup profile updates when you move the line endpoints or change stack layer with the slider.
- The profile width is controlled by **Profile width (px)** in the Profiles dock.
- Saved z, line, and plane profiles receive a persistent color-linked
  acquisition annotation. The exact rectangular ROI or line-width band can
  be redrawn on the source image from the saved profile window, the plane
  profile window, or **Show acquisition geometry** in the Data Browser.
- Saving does not recolor the live profiler. Use **Show all saved profiles**
  to compare the saved colored regions on the source image with their
  matching line, z, and plane profile results.


## Xarray-backed import and axis metadata

The stack import layer creates an `xarray.DataArray` with dims `(z, y, x)`.

No sample data or synthetic coordinate ranges are enabled by default.
When file metadata is missing, pyAthina falls back to:

- `x`: pixel index (`0 .. nx-1`)
- `y`: pixel index (`0 .. ny-1`)
- `z`: layer index (`0 .. nz-1`)

HDF5 metadata parsing helpers are included, but the final mapping of file metadata into domain-specific xarray attrs is intentionally left as a placeholder for user customization.

For 3D datasets, **Image operations > Rotate axes** supports every permutation
of X, Y, and Z. The selected original axes become the new displayed X, Y, and
layer Z axes, while coordinate values, labels, units, source information, and
the axis-operation history are retained. Original per-layer metadata is
archived in the operation record when the layer axis changes.

The **Explore images** operations tab, also available as an individual panel,
contains **Save view**, **Apply view**, **Apply view to all**, and
**Linked view**. Linked view pairs the active image window with another
displayed window using matching X/Y axis units. Zooming or panning either
window immediately applies the same calibrated view range to its partner.
Holding Shift while moving the mouse over either image displays a hollow red
circle at the same physical axis position in the linked window. Activate
either linked window and press **Unlink view** to end the comparison.

Interactive XMCD includes a **Show stats** panel with average, standard
deviation, and RMS values for W1, factor-scaled W2, and XMCD, plus their
average-intensity ratio. Statistics follow factor and keyboard-drift updates
and automatically use only the rectangular ROI while one is active. The
statistics snapshot and ROI bounds are stored when the XMCD result is saved.

The same panel has compact display controls for histogram visibility,
mean ± 3σ contrast locking, aspect ratio, and tight display. **Show Sum** opens
a live auxiliary `(W1 + W2)` view. The experimental **Warp Image** workflow uses
three cursor pairs to affine-warp the private W2 working copy against W1 and
updates the XMCD calculation interactively.

The XMC(L)D tab also provides two single-stack averaging operations:

- **Split stack XMCD** divides the layers sequentially into two parts, averages
  each part, and calculates `(W1-W2)/(W1+W2)`. For odd stack lengths, the first
  part receives the extra layer.
- **XMCD using random sample** averages two samples of `N` layers. The samples
  are disjoint when `N <= layers/2`; above that limit they are independently
  sampled and necessarily overlap.

Both operations store the exact layer indices, calibrated Z values, source
dataset, and formula. Random sampling additionally records its seed, sampling
mode, and overlap so the result can be reproduced.

Every image display window has **Save image** and **Copy image** controls.
Saving exports the currently displayed layer as rendered, including physical
axes, histogram/color scale, ROIs, profile markings, and saved annotations.
The dialog selects the filename, directory, format, and resolution in DPI
(300 DPI by default); TIFF is the default, with PNG, JPEG, and WebP also
available. Copying
places the same high-resolution rendered view on the system clipboard for
direct pasting into applications such as PowerPoint.

The main **Export > Image/stack...** command exports dataset values rather
than the annotated display. For an entire stack it offers multi-image TIFF,
multi-page PDF, animated GIF, and animated WebP. For a single image it also
offers PNG, JPEG, and BMP. The dialog includes a DPI setting. TIFF retains the
original numerical values, coordinates, and metadata; rendered formats use a
common grayscale normalization and receive a JSON metadata sidecar.

**XMC(L)D > Fit XMLD map** fits every pixel of an angular image stack in a
background job using multiple worker threads. The default model is
`K0 + K1*cos(2*(x + K2))`; both the expression and Igor-style
`ATH_Constraints` are editable. Fitting uses one standard data-derived
initial vector with `K2=0` by default. **Multiple initial values** enables a
comma-separated list of alternate K2 starts and keeps the lowest chi-square.
The operation creates linked offset,
amplitude, phase, chi-square, and success maps, records the source dataset and
complete fit configuration in each output, and opens an inspection window.
Click or drag the crosshair on the phase map to compare the measured angular
profile with its fitted curve and coefficients. **Inspect XMLD fit**, beside
the fitting button, reopens this view independently from either the selected
source stack or any selected linked fit map. With no unambiguous selection,
pyAthina prompts for one of the saved fits.

### Igor Pro experiments

**Browse experiment** also opens Igor Pro `.h5xp` experiments in a separate
read-only tree. Numeric 2D and 3D waves can be
dragged, individually or by data folder, into the main Data Browser.

Igor wave dimensions are converted from `(x, y[, z])` to pyAthina's
`(z, y, x)` representation. Dimension scaling, units, labels, wave notes, and
available HDF5 attributes are retained in the xarray coordinates and
`igor_wave` metadata.
Commented debug snippets remain in the codebase so synthetic data can be re-enabled temporarily when needed.

## Elmitec / UView DAT import

Elmitec `.dat` images and stacks can be opened directly. The reader translates
the supplied UView C++ layout and Elmitec's File Formats specification. It
supports file-header versions 5 and newer, including the version-9 fixed image
offset at byte 16384, and imports:

- 16-bit image data, normalized internally to `(z, y, x)`
- file and per-image headers
- timestamps, processing state, rotation, markup blocks, and recipe bytes
- known LEEM parameters, units, exposure, FOV, stage positions, gauges, and spin

Unknown variable-length LEEM tags are retained as raw bytes with a parser warning
instead of being guessed. If a stack contains a varying Start Voltage or Energy
field, it is used as the z coordinate. When readable FOV metadata is present,
both spatial axes run linearly from `0` to FOV in micrometres. If FOV cannot be
read, x runs from `0` to image width and y from `0` to image height in pixels.

The Loader tab supports selecting multiple files or a folder of `.dat` files.
Double-clicking a folder in the Loader immediately loads all `.dat` files in
that folder as one `(z, y, x)` stack. DAT folder stacks use the folder name;
duplicate dataset names in the current data folder receive `_0`, `_1`, ...
suffixes. DAT stacks also store a `LoadedData` xarray attribute containing the
ordered `(index, filepath)` list used to build the stack.

## Experiment browser

pyAthina now uses two compact control windows:

- The **Data Browser** window contains **Loader** and **Data Browser** tabs.
- The separate **Image Processing** window contains **Profilers** and
  **Drift Correction** tabs.

Right-click a dataset to display it in an independent image window or remove it
from the experiment. Display windows include stack navigation, histogram
contrast controls, and the pyqtgraph colormap menu. Profiler and drift
operations always apply to the image window most recently brought to the
foreground. Drift correction includes a **Use ROI** option that estimates the
transform from the active image's rectangular ROI before applying it to the
complete stack.

The Data Browser tab can create experiment data folders, mark a selected folder
as the current data folder, and load new datasets into that current folder. A
red marker identifies the current data folder; the browser status marker turns
yellow when that folder is hidden inside a collapsed branch. Folder removal asks
for confirmation when contents would be removed. Dataset actions include
metadata display and linear x/y/z scaling with editable labels and units.

Drag a dataset row onto a folder row to move it into that data folder. The File
menu provides **Open Experiment**, **Save Experiment**, and **Save Experiment
As** actions. A pyAthina HDF5 experiment stores the complete folder tree,
current data folder, current and original stack data, xarray coordinates, axis
labels and units, source paths, dataset types, and xarray metadata. Changes made
after opening remain in memory until the experiment is saved again.

## Multi-core alignment and headless cluster use

The alignment backend can now use multiple worker processes.

- The GUI defaults **Worker processes** to all CPUs available to pyAthina. Set it to `1` for serial alignment.
- For headless cluster jobs, use:

```bash
python -m pyAthina.batch_align input.h5 aligned_stack.tif \
  --dataset-path /root/entry/instrument/tvips/data \
  --workers 8 \
  --reference-index 0 \
  --method image_registration \
  --auto-roi \
  --auto-roi-count 5 \
  --reference-mode frame_to_frame_cumulative
```

The CLI supports `--method correlation`, `--method phase_correlation`,
`--method image_registration`, and `--method feature_registration`. Add
`--auto-roi` to let pyAthina choose and robustly combine several feature-rich
ROIs automatically, or pass `--roi X Y W H` to keep using a specific pixel ROI.
Its worker count also defaults to all available CPUs.
