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.
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:
objectCore 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
- 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)
label (str | None)
movable (bool)
- Return type:
<MockQtModule name=’mock.ROI.__or__()’ id=’130747735995264’>
- 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:
- Returns:
Dictionary with partition data
- Return type:
dict | None
- __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:
- 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:
- compute_qmap()[source]
Recompute Q-map from current metadata.
- mask_evaluate(target, **kwargs)[source]
Evaluate a mask type without applying.
- 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.
- 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.
- save_partition(save_fname, root='/qmap')[source]
Save partition to HDF5 file.
- 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.
- apply_drawing()[source]
Apply all pending drawing ROIs to create a mask.
- Returns:
Mask array from drawing operations
- Return type:
- 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.
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:
- Returns:
Dictionary with ‘q’, ‘phi’, ‘r’ arrays
- Return type:
- 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:
- 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:
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:
- 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:
- 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)
- xpcsviewer.simplemask.qmap.compute_transmission_qmap(energy, center, shape, pix_dim, det_dist)[source]
Compute Q-map for transmission geometry.
- Parameters:
- 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:
- 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
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:
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:
- undo()¶
Undo the last mask change.
- redo()¶
Redo a previously undone change.
- reset()¶
Reset mask to initial state.
- 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:
- Returns:
List of (qlow, qhigh, pmin, pmax) tuples defining each ring
- Return type:
- class xpcsviewer.simplemask.area_mask.MaskBase(shape=(512, 1024))[source]
Bases:
objectBase class for all mask types.
- __init__(shape=(512, 1024))[source]
Initialize mask with given detector shape.
- get_mask()[source]
Return the mask as a 2D boolean array.
- Returns:
Boolean array where True = valid pixel, False = masked pixel
- Return type:
- class xpcsviewer.simplemask.area_mask.MaskList(shape=(512, 1024))[source]
Bases:
MaskBaseMask defined by a list of pixel coordinates.
- __init__(shape=(512, 1024))[source]
Initialize mask with given detector shape.
- append_zero_pt(row, col)[source]
Append a single pixel to the mask.
- class xpcsviewer.simplemask.area_mask.MaskFile(shape=(512, 1024), fname=None, **kwargs)[source]
Bases:
MaskBaseMask loaded from an HDF5 file.
- __init__(shape=(512, 1024), fname=None, **kwargs)[source]
Initialize mask with given detector shape.
- class xpcsviewer.simplemask.area_mask.MaskThreshold(shape=(512, 1024))[source]
Bases:
MaskBaseMask based on intensity thresholds.
- __init__(shape=(512, 1024))[source]
Initialize mask with given detector shape.
- 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.
- class xpcsviewer.simplemask.area_mask.MaskParameter(shape=(512, 1024))[source]
Bases:
MaskBaseMask based on Q-map parameter constraints (e.g., Q-rings).
- __init__(shape=(512, 1024))[source]
Initialize mask with given detector shape.
- 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:
MaskBaseMask from a direct boolean/integer array.
- __init__(shape=(512, 1024))[source]
Initialize mask with given detector shape.
- class xpcsviewer.simplemask.area_mask.MaskAssemble(shape=(128, 128), saxs_lin=None, qmap=None, max_history=50)[source]
Bases:
objectManager 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.
- apply(target)[source]
Apply a mask type and add to history.
- evaluate(target, **kwargs)[source]
Evaluate a mask type with given parameters.
- 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.
- 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:
- 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 ROIDRAWING_TOOLS['circle']- Circle ROIDRAWING_TOOLS['polygon']- Polygon ROIDRAWING_TOOLS['line']- Line ROI with widthDRAWING_TOOLS['ellipse']- Ellipse ROIERASER_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.
- xpcsviewer.simplemask.utils.optimize_integer_array(arr)[source]
Optimize the data type of an integer array to minimize memory.
- 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:
- 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:
- Returns:
True if maps are consistent, False otherwise
- Raises:
ValueError – If array shapes don’t match
- Return type:
- 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:
- 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.