Analysis (pylorenzmie.analysis)#

Mask#

class pylorenzmie.analysis.Mask.Mask(shape=None, fraction=0.1, exclude=None)[source]#

Bases: LMObject

Pixel selection mask for subsampling a hologram during fitting.

Randomly selects a fraction of pixels for analysis, with optional exclusion of saturated, NaN, or infinite pixels. Regenerates automatically whenever shape, fraction, or exclude is changed.

Inherits from pylorenzmie.lib.LMObject.

Parameters:
  • shape (tuple[int, int], optional) – (height, width) of the image. Default: None.

  • fraction (float, optional) – Fraction of pixels to include. Default: 0.1.

  • exclude (numpy.ndarray of bool, optional) – Boolean array of pixels to force-exclude. Default: None.

Notes

Call update() to resample the mask without changing any parameter. Subclasses may override _select() to implement non-uniform sampling strategies.

References

  1. T. G. Dimiduk, R. W. Perry, J. Fung and V. N. Manoharan, “Random-subset fitting of digital holograms for fast three-dimensional particle tracking,” Applied Optics 53, G177–G183 (2014).

shape: tuple[int, int] | None = None#
fraction: float = 0.1#
exclude: ndarray[tuple[Any, ...], dtype[bool]] | None = None#
property properties: dict[str, bool | int | float | str]#

fraction of pixels to sample.

Type:

Mask configuration

update()[source]#

Regenerate the mask with the current parameters.

Return type:

None

classmethod example()[source]#
Return type:

None

RadialMask#

class pylorenzmie.analysis.RadialMask.RadialMask(shape=None, fraction=0.1, exclude=None)[source]#

Bases: Mask

Pixel selection mask with radially-weighted sampling probability.

Overrides Mask._select() to sample pixels with a probability that varies with radial distance from the image center.

When fraction < 0.5 the image center has probability zero of being selected; probability increases toward the edges, emphasizing the outer ring fringes of a holographic pattern. When fraction >= 0.5 all pixels have a nonzero selection probability; the distribution becomes more uniform as fraction → 1.

Inherits all parameters from Mask.

Localizer#

class pylorenzmie.analysis.Localizer.Localizer(diameter=31, nfringes=20)[source]#

Bases: LMObject

Detect and localize holographic features in a normalized image.

Uses CircleTransform to enhance ring-like patterns, then calls trackpy.locate() to find feature centers. Bounding boxes are sized to enclose a specified number of fringes.

Inherits from pylorenzmie.lib.LMObject.

Parameters:
  • diameter (int, optional) – Nominal feature diameter passed to trackpy.locate [pixels]. Default: 31.

  • nfringes (int, optional) – Number of interference fringes to enclose in each bounding box. Default: 20.

property properties: dict[str, bool | int | float | str]#

nfringes and diameter.

Type:

Localization parameters

localize(image, diameter=None, nfringes=None, **kwargs)[source]#

Localize features in a normalized holographic microscopy image.

Parameters:
  • image (numpy.ndarray or list of numpy.ndarray) – Normalized hologram intensity.

  • diameter (int, optional) – Override diameter for this call.

  • nfringes (int, optional) – Override nfringes for this call.

  • **kwargs – Additional keyword arguments passed to trackpy.locate.

Return type:

DataFrame

Returns:

predictions (pandas.DataFrame) – Columns: x_p, y_p, bbox. bbox is ((x0, y0), width, height).

detect(image, diameter=None, nfringes=None, **kwargs)#

Localize features in a normalized holographic microscopy image.

Parameters:
  • image (numpy.ndarray or list of numpy.ndarray) – Normalized hologram intensity.

  • diameter (int, optional) – Override diameter for this call.

  • nfringes (int, optional) – Override nfringes for this call.

  • **kwargs – Additional keyword arguments passed to trackpy.locate.

Return type:

DataFrame

Returns:

predictions (pandas.DataFrame) – Columns: x_p, y_p, bbox. bbox is ((x0, y0), width, height).

crop(image, bbox)[source]#

Crop an image to a bounding box.

Parameters:
  • image (numpy.ndarray) – Full-frame image.

  • bbox (tuple) – ((x0, y0), width, height).

Return type:

ndarray[tuple[Any, ...], dtype[float]] | ndarray[tuple[Any, ...], dtype[int]]

Returns:

cropped (numpy.ndarray) – Sub-image of shape (height, width).

classmethod example()[source]#
Return type:

None

Estimator#

class pylorenzmie.analysis.Estimator.Estimator(instrument, n_p=1.5, k_p=0.0)[source]#

Bases: LMObject

Estimate initial parameters of a holographic feature.

Uses the azimuthal average of a cropped hologram to estimate the axial position and radius of the scattering particle, providing initial values for Optimizer.

Inherits from pylorenzmie.lib.LMObject.

Parameters:
  • instrument (Instrument) – Optical parameters of the microscope.

  • n_p (float, optional) – Particle refractive index. Default: 1.5. Cannot be estimated from the azimuthal profile; serves as an initial value for the optimizer.

  • k_p (float, optional) – Imaginary part of the refractive index. Default: 0.

Notes

Call estimate() to populate all particle parameters. Results are available via properties afterwards.

predict() is a backward-compatibility alias for estimate().

This class provides a lightweight conventional-algorithm baseline. For higher-quality initial estimates — including n_p — use the CATCH deep neural network model [1] [2].

References

instrument: Instrument#
n_p: float = 1.5#
k_p: float = 0.0#
property properties: dict[str, bool | int | float | str]#

Estimated particle properties.

estimate(feature)[source]#

Estimate particle properties from a holographic crop.

Parameters:

feature (numpy.ndarray or list of numpy.ndarray) – Normalized hologram crop(s).

Return type:

Series | DataFrame | list[Series | DataFrame]

Returns:

result (pandas.Series or list of pandas.Series) – Estimated particle properties.

classmethod example()[source]#
Return type:

None

Optimizer#

class pylorenzmie.analysis.Optimizer.Optimizer(model=None, data=None, robust=False, fixed=None, settings=None, **kwargs)[source]#

Bases: LMObject

Fit a generative light-scattering model to holographic data.

Wraps scipy.optimize.least_squares(). The method class attribute must appear as a substring of the model’s method string for the pairing to be valid (e.g. 'numpy' matches both 'numpy' and 'cupy numpy').

Parameters:
  • model (LorenzMie, optional) – Generative scattering model. Default: LorenzMie().

  • data (numpy.ndarray, optional) – Target intensities for optimization.

  • robust (bool, optional) – Use robust Cauchy loss instead of standard least squares. Default: False.

  • fixed (list[str], optional) – Names of model properties held constant during fitting. Default: ['noise', 'numerical_aperture'].

  • settings (dict, optional) – Keyword arguments forwarded to scipy.optimize.least_squares. Defaults to sensible values for holographic particle fitting.

  • **kwargs – Forwarded to LorenzMie() when model is not supplied.

result#

Fitted values and uncertainties after optimize() has run; None before the first call.

Type:

pandas.Series or None

metadata#

Fixed model properties and optimizer settings.

Type:

pandas.Series

method: str = 'numpy'#
property properties: dict[str, bool | int | float | str]#

Optimizer settings merged with model properties.

property settings: dict[str, bool | int | float | str]#

Settings forwarded to scipy.optimize.least_squares.

Notes

method: 'lm' (Levenberg-Marquardt, default), 'trf', or 'dogbox'. Only 'lm' supports loss='linear'.

loss: 'linear' (standard LS), 'cauchy', 'huber', 'soft_l1', or 'arctan'.

x_scale: 'jac' for dynamic rescaling, or an explicit array of scales matched to the free parameters.

property robust: bool#

True if using robust (non-linear loss) optimization.

property fixed: list[str]#

Model properties held constant during fitting.

property variables: list[str]#

Model properties that will be optimized.

property result: Series | None#

Fitted values, uncertainties, and statistics.

Returns None before optimize() has been called. Each fitted parameter p appears alongside d``+``p (its uncertainty). Also includes success, npix, and redchi.

property metadata: Series#

Fixed model properties and optimizer settings.

optimize()[source]#

Fit model to data.

Return type:

Series

Returns:

result (pandas.Series) – Fitted values, uncertainties, and goodness-of-fit statistics.

report()[source]#

Format fitting results as a human-readable string.

Return type:

str

Returns:

str – One line per fitted parameter showing value ± uncertainty, followed by pixel count and reduced chi-squared.

classmethod example(verbose=False, **kwargs)[source]#
Return type:

None

cupyOptimizer#

class pylorenzmie.analysis.cupyOptimizer.cupyOptimizer(*args, double_precision=True, **kwargs)[source]#

Bases: Optimizer

GPU-accelerated optimizer using CuPy.

Subclass of Optimizer that keeps hologram computation and residual evaluation on the GPU. Only the final residual vector is transferred to the CPU for scipy’s Levenberg-Marquardt solver.

Inherits from Optimizer.

Parameters:
  • double_precision (bool, optional) – If True (default), use double-precision arithmetic on the GPU.

  • *args, **kwargs – Passed to Optimizer.

Notes

The method attribute is 'cupy', which is a substring of cupyLorenzMie.method = 'cupy numpy', satisfying the optimizer compatibility check.

method: str = 'cupy'#
property data#

Feature#

class pylorenzmie.analysis.Feature.Feature(data=None, coordinates=None, mask=None, model=None, fixed=None)[source]#

Bases: LMObject

A holographic feature associated with a single particle.

Bundles image data, pixel coordinates, a pixel mask, a generative scattering model, an initial-parameter estimator, and an optimizer for a single particle crop.

Parameters:
  • data (numpy.ndarray, optional) – Normalized hologram crop.

  • coordinates (numpy.ndarray, optional) – Pixel coordinates of shape (2, npts).

  • mask (Mask, optional) – Pixel selection mask. Default: Mask().

  • model (LorenzMie, optional) – Generative scattering model. Default: LorenzMie().

  • fixed (list[str], optional) – Model properties held constant during fitting. Default: the Optimizer default (['noise', 'numerical_aperture']).

property mask: Mask#

Pixel selection mask.

property data: ndarray[tuple[Any, ...], dtype[float]] | ndarray[tuple[Any, ...], dtype[int]]#

Normalized hologram crop.

property coordinates: ndarray[tuple[Any, ...], dtype[float]]#

Pixel coordinates, shape (2, npts).

property particle: Particle#

Particle associated with the scattering model.

property model: LorenzMie#

Generative scattering model.

property fraction: float#

Fraction of pixels passed to the optimizer.

property properties: dict[str, bool | int | float | str]#

Feature pipeline configuration.

estimate()[source]#

Estimate initial particle parameters from the hologram crop.

Sets z_p, a_p, n_p on the particle from the azimuthal profile. Sets x_p, y_p to the center of the feature in the coordinate system of coordinates (local or frame).

Return type:

Series

Returns:

properties (pandas.Series) – Estimated particle properties.

optimize()[source]#

Optimize particle parameters to fit the hologram crop.

Return type:

Series

Returns:

result (pandas.Series) – Fitted values, uncertainties, and goodness-of-fit statistics.

hologram()[source]#

Hologram predicted by the current model over all pixels.

Return type:

ndarray[tuple[Any, ...], dtype[float]] | ndarray[tuple[Any, ...], dtype[int]]

Returns:

hologram (numpy.ndarray) – Predicted intensity, same shape as data.

residuals()[source]#

Difference between the predicted hologram and the data.

Return type:

ndarray[tuple[Any, ...], dtype[float]] | ndarray[tuple[Any, ...], dtype[int]]

Returns:

residuals (numpy.ndarray) – hologram() - data, same shape as data.

classmethod example()[source]#
Return type:

None

Frame#

class pylorenzmie.analysis.Frame.Frame(instrument=None, localizer=None, data=None)[source]#

Bases: LMObject

Full-frame holographic microscopy analysis pipeline.

Manages detection, estimation, and optimization of all particle features in a single normalized hologram. Instrument settings are shared across all features detected in the frame.

Inherits from pylorenzmie.lib.LMObject.

Parameters:
  • instrument (Instrument, optional) – Microscope parameters shared by all features. Default: Instrument().

  • localizer (Localizer, optional) – Feature detection backend. Default: Localizer().

  • data (numpy.ndarray, optional) – Normalized hologram. Setting data clears any previous detection results.

shape#

Height × width of the most recently assigned image.

Type:

tuple[int, int]

coordinates#

Pixel coordinate grid of shape (2, height, width).

Type:

numpy.ndarray

features#

Feature objects created by the most recent detect() call.

Type:

list[Feature]

bboxes#

Bounding boxes ((x0, y0), w, h) for current features.

Type:

list

results#

Tracking and characterization results from the most recent optimize() or analyze() call.

Type:

pandas.DataFrame

property properties: dict[str, bool | int | float | str]#

Adjustable parameters of this object.

Returns a flat dict mapping parameter names to their current values. Only parameters included here are visible to the serialization methods and to Optimizer during fitting.

Subclasses must override the getter using:

@ParentClass.properties.getter
def properties(self) -> Properties:
    props = super().properties
    props.update(...)
    return props

The base-class getter returns an empty dict; the base-class setter iterates over the supplied dict and calls setattr for every key that already exists as an attribute. Unknown keys are silently ignored and logged at DEBUG level.

property shape: tuple[int, int]#

Height × width of the current image.

property coordinates: ndarray#

Pixel coordinate grid, shape (2, height, width).

property data: ndarray[tuple[Any, ...], dtype[float]] | ndarray[tuple[Any, ...], dtype[int]] | None#

Normalized hologram intensity.

property results: Series | DataFrame | list[Series | DataFrame]#

Tracking and characterization results from the most recent fit.

property features: list[Feature]#

Features detected in the current frame.

property bboxes: list#

Bounding boxes of current features, each ((x0, y0), w, h).

detect()[source]#

Detect and localize features in data.

Return type:

int

Returns:

nfeatures (int) – Number of features found.

estimate()[source]#

Estimate parameters for all current features.

Return type:

None

optimize()[source]#

Optimize parameters for all current features.

Return type:

Series | DataFrame | list[Series | DataFrame]

Returns:

results (pandas.DataFrame) – Fitted values, uncertainties, and goodness-of-fit for each feature.

analyze(data=None)[source]#

Detect features, estimate parameters, and optimize fits.

Parameters:

data (numpy.ndarray, optional) – Normalized hologram. Updates data if provided.

Return type:

Series | DataFrame | list[Series | DataFrame]

Returns:

results (pandas.DataFrame) – Optimized parameters of the generative model for each detected feature.

classmethod example()[source]#
Return type:

None

Trajectory#

class pylorenzmie.analysis.Trajectory.Trajectory[source]#

Bases: LMObject

Accumulate per-frame characterization results over time.

Each call to append() stores one frame’s worth of Frame output. data returns the combined time series as a single pandas.DataFrame.

Inherits from pylorenzmie.lib.LMObject.

property properties: dict[str, bool | int | float | str]#

Adjustable parameters of this object.

Returns a flat dict mapping parameter names to their current values. Only parameters included here are visible to the serialization methods and to Optimizer during fitting.

Subclasses must override the getter using:

@ParentClass.properties.getter
def properties(self) -> Properties:
    props = super().properties
    props.update(...)
    return props

The base-class getter returns an empty dict; the base-class setter iterates over the supplied dict and calls setattr for every key that already exists as an attribute. Unknown keys are silently ignored and logged at DEBUG level.

property data: DataFrame#

All results concatenated into a single DataFrame.

append(results)[source]#

Append one frame of results.

Parameters:

results (pandas.DataFrame or pandas.Series) – Output from Frame.optimize() or Frame.analyze().

Return type:

None

clear()[source]#

Remove all stored results.

Return type:

None

to_csv(path, **kwargs)[source]#

Write accumulated results to a CSV file.

Parameters:
  • path (str) – Destination file path.

  • **kwargs – Additional keyword arguments passed to pandas.DataFrame.to_csv().

Return type:

None

classmethod example()[source]#
Return type:

None