SimpleMask

The xpcsviewer.simplemask module provides mask editing and Q-map functionality for XPCS analysis.

Module Overview

SimpleMaskWindow

The main window class for mask editing.

class xpcsviewer.simplemask.SimpleMaskWindow(*args, **kwargs)

Bases:

Signals

mask_exported: Signal(np.ndarray)

Emitted when mask is exported to XPCS Viewer.

qmap_exported: Signal(dict)

Emitted when partition is exported to XPCS Viewer.

Key Methods

load_from_viewer(detector_image, metadata)

Load detector image and metadata from XPCS Viewer.

Parameters:
  • detector_image – 2D numpy array of detector data

  • metadata – Dictionary with geometry parameters (bcx, bcy, det_dist, pix_dim, energy)

export_mask_to_viewer()

Export current mask via mask_exported signal.

export_partition_to_viewer()

Export current partition via qmap_exported signal.

SimpleMaskKernel

Core computation logic for mask operations.

class xpcsviewer.simplemask.simplemask_kernel.SimpleMaskKernel(pg_hdl=None, infobar=None)[source]

Bases: object

Core kernel for SimpleMask operations.

This class manages mask creation, editing, Q-map computation, and partition generation for XPCS analysis.

Parameters:
  • pg_hdl (<MockQtModule name='mock.ImageView.__or__()' id='130747735990560'>)

  • infobar (Any | None)

shape

Detector shape as (height, width)

detector_image

2D array of detector data

mask

Current combined mask array

qmap

Dictionary of Q-map arrays

qmap_unit

Dictionary of Q-map units

metadata

Geometry metadata dictionary

Key Methods

read_data(det_image, parameters)[source]

Initialize kernel with detector data and geometry.

Parameters:
Return type:

bool

add_drawing(drawing_type, params)[source]

Add a drawing ROI to the kernel.

Parameters:
  • drawing_type – One of ‘rectangle’, ‘circle’, ‘polygon’, ‘line’, ‘ellipse’

  • params – Dictionary with ROI parameters

  • sl_type (Literal['Rectangle', 'Circle', 'Ellipse', 'Polygon', 'Line'])

  • sl_mode (Literal['exclusive', 'inclusive'])

  • num_edges (int | None)

  • radius (float)

  • color (str)

  • width (int)

  • second_point (tuple[float, float] | None)

  • label (str | None)

  • movable (bool)

Return type:

<MockQtModule name=’mock.ROI.__or__()’ id=’130747735995264’>

apply_drawing(inclusive=False)[source]

Apply all drawings to create/update the mask.

Return type:

ndarray

mask_action(action='apply')[source]

Perform mask action (apply, undo, redo, reset).

Parameters:

action (Literal['undo', 'redo', 'reset'])

Return type:

None

compute_partition(dq_num=10, sq_num=100, dp_num=36, sp_num=360)[source]

Compute Q-space partition for correlation analysis.

Parameters:
  • dq_num (int) – Number of dynamic Q-bins

  • sq_num (int) – Number of static Q-bins

  • dp_num (int) – Number of dynamic phi-bins

  • sp_num (int) – Number of static phi-bins

  • mode (str)

  • style (str)

  • phi_offset (float)

  • symmetry_fold (int)

Returns:

Dictionary with partition data

Return type:

dict | None

save_mask(file_path)[source]

Save mask to HDF5 file.

Parameters:

save_name (str)

Return type:

None

load_mask(file_path)[source]

Load mask from HDF5 file.

Parameters:
Return type:

bool

__init__(pg_hdl=None, infobar=None)[source]

Initialize SimpleMask kernel.

Parameters:
  • pg_hdl (<MockQtModule name='mock.ImageView.__or__()' id='130747735990560'>) – PyQtGraph ImageView handle for display

  • infobar (Any | None) – Status bar widget for messages

is_ready()[source]

Check if kernel has data loaded.

Returns:

True if detector image is loaded

Return type:

bool

read_data(detector_image, metadata)[source]

Load detector data and initialize mask.

Parameters:
  • detector_image (ndarray) – 2D array of detector counts

  • metadata (dict[str, Any]) – Dictionary with geometry parameters: - bcx: Beam center X (column) - bcy: Beam center Y (row) - det_dist: Detector distance (mm) - pix_dim: Pixel size (mm) - energy: X-ray energy (keV) - shape: Detector shape (height, width)

Returns:

True if successful

Return type:

bool

compute_qmap()[source]

Recompute Q-map from current metadata.

Returns:

Tuple of (qmap_dict, units_dict)

Return type:

tuple[dict[str, ndarray], dict[str, str]]

mask_evaluate(target, **kwargs)[source]

Evaluate a mask type without applying.

Parameters:
  • target (str) – Mask type key

  • **kwargs – Parameters for mask evaluation

Returns:

Description string from the mask worker

Return type:

str

mask_action(action='undo')[source]

Execute undo/redo/reset on mask history.

Parameters:

action (Literal['undo', 'redo', 'reset']) – One of “undo”, “redo”, or “reset”

Return type:

None

mask_apply(target=None)[source]

Apply a mask type and update current mask.

Parameters:

target (str | None) – Mask type to apply, or None to get current mask

Returns:

Current combined mask array

Return type:

ndarray

save_mask(save_name)[source]

Save mask to HDF5 file.

Parameters:

save_name (str) – Output file path (.h5/.hdf5)

Return type:

None

load_mask(fname, key='mask')[source]

Load mask from HDF5 file.

Parameters:
  • fname (str) – Path to HDF5 file

  • key (str) – Dataset key for mask data

Returns:

True if successful

Return type:

bool

save_partition(save_fname, root='/qmap')[source]

Save partition to HDF5 file.

Parameters:
  • save_fname (str) – Output file path (.h5/.hdf5)

  • root (str) – HDF5 group path for partition data

Return type:

None

show_location(pos)[source]

Display pixel coordinates and Q values at mouse position.

Parameters:

pos – Mouse scene position

Return type:

None

show_saxs(cmap='jet', log=True, plot_center=True)[source]

Display detector image with optional beam center marker.

Parameters:
  • cmap (str) – Matplotlib colormap name

  • log (bool) – Whether to use log scale (unused, kept for API compatibility)

  • plot_center (bool) – Whether to display beam center marker

Return type:

None

apply_drawing()[source]

Apply all pending drawing ROIs to create a mask.

Returns:

Mask array from drawing operations

Return type:

ndarray

add_drawing(sl_type='Polygon', sl_mode='exclusive', num_edges=None, radius=60, color='r', width=3, second_point=None, label=None, movable=True)[source]

Add a drawing ROI to the view.

Parameters:
  • sl_type (Literal['Rectangle', 'Circle', 'Ellipse', 'Polygon', 'Line']) – Shape type - Rectangle, Circle, Ellipse, Polygon, or Line

  • sl_mode (Literal['exclusive', 'inclusive']) – “exclusive” masks pixels, “inclusive” preserves pixels

  • num_edges (int | None) – Number of edges for Polygon (random 6-10 if None)

  • radius (float) – Default radius for Circle

  • color (str) – Pen color

  • width (int) – Pen width

  • second_point (tuple[float, float] | None) – End point for Line ROI

  • label (str | None) – ROI label (auto-generated if None)

  • movable (bool) – Whether ROI can be moved

Returns:

Created ROI object, or None if creation failed

Return type:

<MockQtModule name=’mock.ROI.__or__()’ id=’130747735995264’>

remove_roi(roi_key)[source]

Remove an ROI by key.

Parameters:

roi_key (str) – Label of the ROI to remove

Return type:

None

compute_partition(mode='q-phi', dq_num=10, sq_num=100, dp_num=36, sp_num=360, style='linear', phi_offset=0.0, symmetry_fold=1)[source]

Compute Q-space partition for XPCS analysis.

Parameters:
  • mode (str) – Partition mode (e.g., “q-phi”, “x-y”)

  • dq_num (int) – Number of dynamic Q bins

  • sq_num (int) – Number of static Q bins

  • dp_num (int) – Number of dynamic phi bins

  • sp_num (int) – Number of static phi bins

  • style (str) – Binning style - “linear” or “logarithmic”

  • phi_offset (float) – Phi angle offset

  • symmetry_fold (int) – Symmetry fold for phi

Returns:

Partition dictionary or None if no data

Return type:

dict | None

update_parameters(new_metadata)[source]

Update geometry parameters and recompute Q-map.

Parameters:

new_metadata (dict[str, Any]) – Dictionary with updated geometry values

Return type:

None

get_center(mode='xy')[source]

Get beam center coordinates.

Parameters:

mode (Literal['xy', 'vh']) – “xy” for (x, y) = (column, row), “vh” for (vertical, horizontal)

Returns:

Beam center coordinates

Return type:

tuple[float | None, float | None]

Q-Map Module

Q-map computation from detector geometry.

Q-map computation for SimpleMask.

This module provides functions to compute momentum transfer (Q) maps for transmission and reflection geometries based on detector geometry parameters.

Uses backend abstraction for GPU acceleration when available. Ported from pySimpleMask with backend abstraction for JAX support.

Key Functions

xpcsviewer.simplemask.qmap.compute_qmap(shape, bcx, bcy, det_dist, pix_dim, energy, orientation='N')[source]

Compute Q-map for detector geometry.

Parameters:
  • shape – Detector shape (rows, cols)

  • bcx – Beam center X (column)

  • bcy – Beam center Y (row)

  • det_dist – Sample-to-detector distance (mm)

  • pix_dim – Pixel dimension (mm)

  • energy – X-ray energy (keV)

  • orientation – Detector orientation (‘N’, ‘E’, ‘S’, ‘W’)

  • stype (str)

  • metadata (dict)

Returns:

Dictionary with ‘q’, ‘phi’, ‘r’ arrays

Return type:

tuple[dict[str, ndarray], dict[str, str]]

xpcsviewer.simplemask.qmap.compute_qmap(stype, metadata)[source]

Compute Q-map based on scattering geometry type.

Parameters:
  • stype (str) – Scattering type - “Transmission” or “Reflection”

  • metadata (dict) – Dictionary containing geometry parameters: - energy: X-ray energy in keV - bcx: Beam center X (column) in pixels - bcy: Beam center Y (row) in pixels - shape: Detector shape (height, width) - pix_dim: Pixel size in mm - det_dist: Sample-to-detector distance in mm - alpha_i_deg: Incident angle in degrees (reflection only) - orientation: Detector orientation (reflection only)

Returns:

Tuple of (qmap_dict, units_dict) where qmap_dict contains arrays for various Q-space coordinates and units_dict contains their units.

Raises:

ValueError – If required geometry parameters are missing (None)

Return type:

tuple[dict[str, ndarray], dict[str, str]]

xpcsviewer.simplemask.qmap.compute_q_at_pixel(center_x, center_y, pixel_x, pixel_y, energy, pix_dim, det_dist)[source]

Compute Q value at a single pixel (differentiable).

This function is differentiable with respect to center_x, center_y, and det_dist when using the JAX backend, enabling gradient-based calibration optimization.

Parameters:
  • center_x (float) – Beam center X position (column) in pixels

  • center_y (float) – Beam center Y position (row) in pixels

  • pixel_x (float) – Pixel X position (column)

  • pixel_y (float) – Pixel Y position (row)

  • energy (float) – X-ray energy in keV

  • pix_dim (float) – Pixel dimension in mm

  • det_dist (float) – Sample-to-detector distance in mm

Returns:

Q value at the pixel position in Å⁻¹

Return type:

float | Any

Example

>>> import jax
>>> from xpcsviewer.simplemask.qmap import compute_q_at_pixel
>>> # Compute Q
>>> q = compute_q_at_pixel(128.0, 128.0, 200.0, 200.0, 10.0, 0.075, 5000.0)
>>> # Compute gradient with respect to beam center
>>> grad_fn = jax.grad(compute_q_at_pixel, argnums=(0, 1))
>>> dq_dcx, dq_dcy = grad_fn(128.0, 128.0, 200.0, 200.0, 10.0, 0.075, 5000.0)
xpcsviewer.simplemask.qmap.compute_q_sum_squared(center_x, center_y, pixel_positions, energy, pix_dim, det_dist)[source]

Compute sum of squared Q values at given pixels (differentiable).

This function is useful for gradient-based calibration objectives. It is differentiable with respect to center_x, center_y, and det_dist when using the JAX backend.

Parameters:
  • center_x (float) – Beam center X position (column) in pixels

  • center_y (float) – Beam center Y position (row) in pixels

  • pixel_positions (list[tuple[float, float]]) – List of (x, y) pixel positions

  • energy (float) – X-ray energy in keV

  • pix_dim (float) – Pixel dimension in mm

  • det_dist (float) – Sample-to-detector distance in mm

Returns:

Sum of Q² values at all pixel positions

Return type:

float | Any

xpcsviewer.simplemask.qmap.create_q_objective(target_q_values, pixel_positions, energy, pix_dim)[source]

Create a differentiable objective function for Q-map calibration.

Creates an objective function that measures the squared difference between predicted and target Q values. The objective is differentiable with respect to beam center and detector distance.

Parameters:
  • target_q_values (ndarray) – Array of target Q values at each position

  • pixel_positions (list[tuple[float, float]]) – List of (x, y) pixel coordinates

  • energy (float) – X-ray energy in keV

  • pix_dim (float) – Pixel dimension in mm

Returns:

f(center_x, center_y, det_dist) -> loss

Return type:

Callable objective function

Example

>>> import jax
>>> from xpcsviewer.simplemask.qmap import create_q_objective
>>> objective = create_q_objective(target_q, positions, 10.0, 0.075)
>>> # Compute loss
>>> loss = objective(128.0, 128.0, 5000.0)
>>> # Compute gradient
>>> grad_fn = jax.grad(objective, argnums=(0, 1, 2))
>>> dcx, dcy, ddist = grad_fn(128.0, 128.0, 5000.0)
Raises:

RuntimeError – If JAX backend is not available.

Parameters:
Return type:

Callable

xpcsviewer.simplemask.qmap.compute_transmission_qmap(energy, center, shape, pix_dim, det_dist)[source]

Compute Q-map for transmission geometry.

Parameters:
  • energy (float) – X-ray energy in keV

  • center (tuple[float, float]) – Beam center as (row, column) in pixels

  • shape (tuple[int, int]) – Detector shape as (height, width)

  • pix_dim (float) – Pixel dimension in mm

  • det_dist (float) – Sample-to-detector distance in mm

Returns:

Tuple of (qmap, qmap_unit) dictionaries.

qmap contains:

  • phi: Azimuthal angle (degrees)

  • TTH: Two-theta angle (degrees)

  • q: Momentum transfer magnitude (Angstrom^-1)

  • qx, qy: Q components (Angstrom^-1)

  • x, y: Pixel coordinates

qmap_unit contains unit strings for each map.

Return type:

tuple[dict[str, ndarray], dict[str, str]]

xpcsviewer.simplemask.qmap.compute_reflection_qmap(energy, center, shape, pix_dim, det_dist, alpha_i_deg=0.14, orientation='north')[source]

Compute Q-map for reflection (grazing incidence) geometry.

Parameters:
  • energy (float) – X-ray energy in keV

  • center (tuple[float, float]) – Beam center as (row, column) in pixels

  • shape (tuple[int, int]) – Detector shape as (height, width)

  • pix_dim (float) – Pixel dimension in mm

  • det_dist (float) – Sample-to-detector distance in mm

  • alpha_i_deg (float) – Incident angle in degrees (default 0.14)

  • orientation (str) – Detector orientation - “north”, “south”, “east”, “west”

Returns:

Tuple of (qmap, qmap_unit) dictionaries.

qmap contains additional reflection-specific arrays:

  • qz, qr: Vertical and radial Q components

  • alpha_f: Exit angle

  • tth: In-plane two-theta

Return type:

tuple[dict[str, ndarray], dict[str, str]]

Area Mask Module

Mask assembly with undo/redo history.

Mask assembly classes for SimpleMask.

This module provides classes for creating, combining, and managing detector masks. Supports various mask types including file-based, threshold-based, parameter-based, and drawing-based masks.

Ported from pySimpleMask with modifications: - Removed TIFF support for initial release (HDF5 only) - Removed skimage.io dependency - Uses backend abstraction for GPU acceleration when available.

Key Classes

class xpcsviewer.simplemask.area_mask.MaskAssemble[source]

Manages mask with undo/redo history.

Parameters:
apply(mask_component)[source]

Apply a mask component and add to history.

Parameters:

target (str | None)

Return type:

ndarray

undo()

Undo the last mask change.

redo()

Redo a previously undone change.

reset()

Reset mask to initial state.

get_mask()[source]

Get the current combined mask.

Return type:

ndarray

xpcsviewer.simplemask.area_mask.create_qring(qmin, qmax, pmin, pmax, qnum=1, flag_const_width=True)[source]

Create Q-ring definitions for mask parameter constraints.

Parameters:
  • qmin (float) – Minimum Q value

  • qmax (float) – Maximum Q value

  • pmin (float) – Minimum phi value

  • pmax (float) – Maximum phi value

  • qnum (int) – Number of Q rings to generate

  • flag_const_width (bool) – If True, rings have constant width; if False, width scales

Returns:

List of (qlow, qhigh, pmin, pmax) tuples defining each ring

Return type:

list[tuple[float, float, float, float]]

class xpcsviewer.simplemask.area_mask.MaskBase(shape=(512, 1024))[source]

Bases: object

Base class for all mask types.

Parameters:

shape (tuple[int, int])

__init__(shape=(512, 1024))[source]

Initialize mask with given detector shape.

Parameters:

shape (tuple[int, int]) – Detector dimensions as (height, width)

Return type:

None

evaluate(**kwargs)[source]

Evaluate mask (base method).

Parameters:

kwargs (Any)

Return type:

None

describe()[source]

Return description of mask statistics.

Return type:

str

get_mask()[source]

Return the mask as a 2D boolean array.

Returns:

Boolean array where True = valid pixel, False = masked pixel

Return type:

ndarray

combine_mask(mask)[source]

Combine this mask with another mask.

Parameters:

mask (ndarray | None) – Existing mask to combine with, or None

Returns:

Combined mask array

Return type:

ndarray

class xpcsviewer.simplemask.area_mask.MaskList(shape=(512, 1024))[source]

Bases: MaskBase

Mask defined by a list of pixel coordinates.

Parameters:

shape (tuple[int, int])

__init__(shape=(512, 1024))[source]

Initialize mask with given detector shape.

Parameters:

shape (tuple[int, int]) – Detector dimensions as (height, width)

Return type:

None

append_zero_pt(row, col)[source]

Append a single pixel to the mask.

Parameters:
  • row (int) – Row index

  • col (int) – Column index

Return type:

None

evaluate(zero_loc=None, **kwargs)[source]

Set the mask from a coordinate array.

Parameters:
  • zero_loc (ndarray | None) – Array of shape (2, N) with [rows, cols] of masked pixels

  • kwargs (Any)

Return type:

None

class xpcsviewer.simplemask.area_mask.MaskFile(shape=(512, 1024), fname=None, **kwargs)[source]

Bases: MaskBase

Mask loaded from an HDF5 file.

Parameters:
__init__(shape=(512, 1024), fname=None, **kwargs)[source]

Initialize mask with given detector shape.

Parameters:
  • shape (tuple[int, int]) – Detector dimensions as (height, width)

  • fname (str | None)

Return type:

None

evaluate(fname=None, key=None, **kwargs)[source]

Load mask from an HDF5 file.

Parameters:
  • fname (str | None) – Path to HDF5 file

  • key (str | None) – Dataset key within the HDF5 file containing the mask

  • kwargs (Any)

Return type:

None

class xpcsviewer.simplemask.area_mask.MaskThreshold(shape=(512, 1024))[source]

Bases: MaskBase

Mask based on intensity thresholds.

Parameters:

shape (tuple[int, int])

__init__(shape=(512, 1024))[source]

Initialize mask with given detector shape.

Parameters:

shape (tuple[int, int]) – Detector dimensions as (height, width)

Return type:

None

evaluate(saxs_lin=None, low=0, high=100000000.0, low_enable=True, high_enable=True, **kwargs)[source]

Create mask based on intensity thresholds.

Uses backend abstraction for GPU acceleration when available.

Parameters:
  • saxs_lin (ndarray | None) – 2D intensity array

  • low (float) – Lower threshold value

  • high (float) – Upper threshold value

  • low_enable (bool) – Whether to apply lower threshold

  • high_enable (bool) – Whether to apply upper threshold

  • kwargs (Any)

Return type:

None

class xpcsviewer.simplemask.area_mask.MaskParameter(shape=(512, 1024))[source]

Bases: MaskBase

Mask based on Q-map parameter constraints (e.g., Q-rings).

Parameters:

shape (tuple[int, int])

__init__(shape=(512, 1024))[source]

Initialize mask with given detector shape.

Parameters:

shape (tuple[int, int]) – Detector dimensions as (height, width)

Return type:

None

evaluate(qmap=None, constraints=None, **kwargs)[source]

Create mask based on Q-map constraints.

Uses backend abstraction for GPU acceleration when available.

Parameters:
  • qmap (dict[str, ndarray] | None) – Dictionary of Q-map arrays

  • constraints (list[tuple[str, str, str, float, float]] | None) – List of (map_name, logic, unit, vbeg, vend) tuples - map_name: Key in qmap dict (e.g., “q”, “phi”) - logic: “AND” or “OR” - unit: Unit string (e.g., “deg”) - vbeg, vend: Value range bounds

  • kwargs (Any)

Return type:

None

class xpcsviewer.simplemask.area_mask.MaskArray(shape=(512, 1024))[source]

Bases: MaskBase

Mask from a direct boolean/integer array.

Parameters:

shape (tuple[int, int])

__init__(shape=(512, 1024))[source]

Initialize mask with given detector shape.

Parameters:

shape (tuple[int, int]) – Detector dimensions as (height, width)

Return type:

None

evaluate(arr=None, **kwargs)[source]

Set mask from an array.

Parameters:
  • arr (ndarray | None) – Boolean or integer array where nonzero = masked

  • kwargs (Any)

Return type:

None

class xpcsviewer.simplemask.area_mask.MaskAssemble(shape=(128, 128), saxs_lin=None, qmap=None, max_history=50)[source]

Bases: object

Manager for combining multiple mask types with undo/redo support.

Maintains a history of mask states enabling undo, redo, and reset operations. Individual mask workers (threshold, file, draw, parameter, etc.) are evaluated independently and combined via logical AND.

Parameters:
shape

Detector dimensions as (height, width).

workers

Dictionary of named mask worker instances.

mask_record

List of historical mask states.

mask_ptr

Index into mask_record for the current state.

__init__(shape=(128, 128), saxs_lin=None, qmap=None, max_history=50)[source]

Initialize mask assembly with detector shape and optional data.

Parameters:
  • shape (tuple[int, int]) – Detector dimensions as (height, width)

  • saxs_lin (ndarray | None) – 2D intensity array for threshold masking

  • qmap (dict[str, ndarray] | None) – Q-map dictionary for parameter masking

  • max_history (int) – Maximum number of undo steps to retain. Older entries are dropped when the limit is reached to prevent unbounded memory growth (a 2048×2048 boolean mask costs ~4 MB per step).

Return type:

None

update_qmap(qmap_all)[source]

Update the Q-map used for parameter masking.

Parameters:

qmap_all (dict[str, ndarray]) – Dictionary of Q-map arrays

Return type:

None

apply(target)[source]

Apply a mask type and add to history.

Parameters:

target (str | None) – Mask type key (e.g., “mask_draw”, “mask_threshold”) or None to return current mask

Returns:

Current combined mask array

Return type:

ndarray

evaluate(target, **kwargs)[source]

Evaluate a mask type with given parameters.

Parameters:
  • target (str) – Mask type key

  • **kwargs (Any) – Parameters for the mask evaluation

Returns:

Description string from the mask worker

Return type:

str

redo_undo(action='redo')[source]

Navigate mask history.

Parameters:

action (str) – One of “undo”, “redo”, or “reset”

Return type:

None

get_one_mask(target)[source]

Get mask from a single worker.

Parameters:

target (str) – Mask type key

Returns:

Mask array from the specified worker

Return type:

ndarray

get_mask()[source]

Get the current combined mask.

Returns:

A copy of the current mask from history. Safe for external callers that may mutate the result. Use _get_mask_ref() internally where the result is only read.

Return type:

ndarray

property blemish: ndarray

Get the blemish mask (pixels marked as bad in blemish file).

Returns:

Boolean array where True = valid pixel, False = blemish pixel

Drawing Tools Module

Tool definitions for mask drawing.

Available Tools

  • DRAWING_TOOLS['rectangle'] - Rectangle ROI

  • DRAWING_TOOLS['circle'] - Circle ROI

  • DRAWING_TOOLS['polygon'] - Polygon ROI

  • DRAWING_TOOLS['line'] - Line ROI with width

  • DRAWING_TOOLS['ellipse'] - Ellipse ROI

  • ERASER_TOOL - Eraser (inclusive mode)

Utils Module

Partition utilities for Q-binning.

Utility functions for SimpleMask partitioning.

This module provides functions for generating Q-space partitions and combining partition maps for XPCS analysis.

Uses backend abstraction for GPU acceleration when available. Ported from pySimpleMask with backend abstraction for JAX support.

xpcsviewer.simplemask.utils.hash_numpy_dict(input_dictionary)[source]

Compute a stable SHA256 hash for a dictionary containing NumPy arrays.

Parameters:

input_dictionary (dict[str, Any]) – Dictionary with NumPy arrays and other values

Returns:

SHA256 hash string of the dictionary contents

Return type:

str

xpcsviewer.simplemask.utils.optimize_integer_array(arr)[source]

Optimize the data type of an integer array to minimize memory.

Parameters:

arr (ndarray) – NumPy array of integers

Returns:

Array with optimized integer dtype, or original if not applicable

Return type:

ndarray

xpcsviewer.simplemask.utils.generate_partition(map_name, mask, xmap, num_pts, style='linear', phi_offset=None, symmetry_fold=1)[source]

Generate a partition map for X-ray scattering analysis.

Parameters:
  • map_name (str) – Name of the map (“q”, “phi”, “x”, “y”)

  • mask (ndarray) – 2D boolean mask array (True = valid)

  • xmap (ndarray) – 2D array of values to partition

  • num_pts (int) – Number of partition bins

  • style (str) – Binning style - “linear” or “logarithmic”

  • phi_offset (float | None) – Offset for phi angle (only for phi map)

  • symmetry_fold (int) – Symmetry fold for phi partitioning

Returns:

  • map_name: Name of the partition

  • num_pts: Number of bins

  • partition: 2D array of bin labels (1-indexed, 0=masked)

  • v_list: Array of bin center values

Return type:

Dictionary with keys

xpcsviewer.simplemask.utils.combine_partitions(pack1, pack2, prefix='dynamic')[source]

Combine two partition maps into a single partition space.

Parameters:
  • pack1 (dict[str, str | int | ndarray]) – First partition dictionary (e.g., Q partition)

  • pack2 (dict[str, str | int | ndarray]) – Second partition dictionary (e.g., phi partition)

  • prefix (str) – Prefix for output keys (“dynamic” or “static”)

Returns:

  • {prefix}_num_pts: [num_pts1, num_pts2]

  • {prefix}_roi_map: Combined 2D partition array

  • {prefix}_v_list_dim0: Bin centers for first dimension

  • {prefix}_v_list_dim1: Bin centers for second dimension

  • {prefix}_index_mapping: Unique partition indices

Return type:

Dictionary with combined partition

xpcsviewer.simplemask.utils.check_consistency(dqmap, sqmap, mask)[source]

Check consistency between dynamic and static Q-maps.

Ensures each unique value in sqmap corresponds to only one unique value in dqmap.

Parameters:
  • dqmap (ndarray) – Dynamic Q-map (coarse bins)

  • sqmap (ndarray) – Static Q-map (fine bins)

  • mask (ndarray) – Boolean mask array

Returns:

True if maps are consistent, False otherwise

Raises:

ValueError – If array shapes don’t match

Return type:

bool

xpcsviewer.simplemask.utils.create_partition(qmap, mask, n_bins=36, spacing='linear')[source]

Create a Q-space partition from a Q-map.

Convenience wrapper around generate_partition for simple Q-binning.

Parameters:
  • qmap (ndarray) – 2D array of Q-values (momentum transfer)

  • mask (ndarray) – 2D boolean mask array (True = valid)

  • n_bins (int) – Number of partition bins (default 36)

  • spacing (str) – Binning style - “linear” or “log” (default “linear”)

Returns:

  • map_name: “q”

  • num_pts: Number of bins

  • partition: 2D array of bin labels (1-indexed, 0=masked)

  • v_list: Array of bin center Q-values

Return type:

Dictionary with keys

PyQtGraph Modifications

Custom ROI classes for drawing tools.

Custom PyQtGraph components for SimpleMask.

This module provides customized PyQtGraph widgets and ROI classes for the SimpleMask editor.

Ported from pySimpleMask with minimal modifications.

Key Classes

class xpcsviewer.simplemask.pyqtgraph_mod.LineROI

Custom line ROI with adjustable width for mask drawing.

Calibration Module

Beam center refinement and detector geometry calibration utilities.