Skip to content

Reconstruction algorithms

Every solver exposes the same run method and releases the Python GIL while executing Rust reconstruction code. The choice of solver controls its update rule, recoverable quantities, and algorithm-specific parameters.

AlternatingProjection

AlternatingProjection(
    *,
    iterations: int = 50,
    object_step: float = 1.0,
    batch_size: int = 1,
    epsilon: float = 1e-10,
    loss_type: str = "amplitude_mse",
)

Bases: _Algorithm

Alternating-projection FPM reconstruction.

Each frame selects an overlapping object-spectrum patch, propagates it through the pupil, replaces the predicted detector amplitude with the measured amplitude while retaining phase, and back-projects the correction.

Parameters:

Name Type Description Default
iterations int

Complete passes through the acquisition schedule.

50
object_step float

Relaxation factor for object-spectrum corrections.

1.0
batch_size int

Measured frames supplied to each reconstruction step.

1
epsilon float

Positive numerical floor for divisions and dark fields.

1e-10
loss_type str

Diagnostic loss; the projection itself always enforces amplitude.

'amplitude_mse'
References

Zheng, Horstmeyer, and Yang, Wide-field, high-resolution Fourier ptychographic microscopy (2013).

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

AdaptiveAlternatingProjection

AdaptiveAlternatingProjection(
    *,
    iterations: int = 50,
    initial_object_step: float = 1.0,
    progress_threshold: float = 0.01,
    reduction_factor: float = 0.5,
    minimum_object_step: float = 0.001,
    batch_size: int = 1,
    epsilon: float = 1e-10,
)

Bases: _Algorithm

Noise-robust alternating projection with a pass-adaptive object step.

One object step is shared by every frame in a complete acquisition pass. The method retains that step while the accumulated amplitude-MSE objective makes sufficient relative progress and otherwise reduces it to a positive floor. Feedback reuses the objective evaluated by the projections, so it requires no extra forward pass. Batching does not change adaptation cadence or the numerical path; changing the frame schedule intentionally can.

Parameters:

Name Type Description Default
iterations int

Complete passes through the acquisition schedule.

50
initial_object_step float

Positive object relaxation used before the first reduction.

1.0
progress_threshold float

Relative pass-objective decrease required to retain the current step.

0.01
reduction_factor float

Factor in (0, 1) applied when progress is insufficient.

0.5
minimum_object_step float

Positive step floor no greater than initial_object_step.

0.001
batch_size int

Measured frames supplied to each reconstruction step.

1
epsilon float

Positive numerical floor used in projection and relative progress.

1e-10
Notes

Feedback is the frame-weighted mean of per-frame, mask-aware amplitude MSE after configured gains and background. The implementation uses the paper's inexpensive accumulated-objective approximation, recovers only the object, and keeps the compiled pupil fixed. The cited convergence proof assumes convex component objectives; FPM phase retrieval is non-convex.

Checkpoints preserve the current step, preceding objective, active pass sums, and controller parameters. Resume requires matching parameters. A checkpoint without adaptive auxiliary state is treated as a warm start and establishes a new feedback baseline. Physical JointReconstruction is unsupported because model recompilation invalidates the objective history.

References

Zuo, Sun, and Chen, Adaptive step-size strategy for noise-robust Fourier ptychographic microscopy, Optics Express 24(18), 20724-20744 (2016).

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

Fpie

Fpie(
    *,
    iterations: int = 50,
    object_step: float = 0.8,
    stability: float = 0.1,
    batch_size: int = 1,
    epsilon: float = 1e-10,
    loss_type: str = "amplitude_mse",
)

Bases: _Algorithm

Regularized ptychographic iterative engine adapted to FPM.

The amplitude-projection correction is preconditioned by a blend of local and maximum pupil power, suppressing unstable updates in weak-transfer regions.

Parameters:

Name Type Description Default
iterations int

Complete passes through the acquisition schedule.

50
object_step float

Relaxation factor for object-spectrum corrections.

0.8
stability float

Blend from local (0) to maximum (1) pupil power in the denominator.

0.1
batch_size int

Measured frames supplied to each reconstruction step.

1
epsilon float

Positive floor added to the rPIE denominator.

1e-10
loss_type str

Diagnostic loss; the projection itself always enforces amplitude.

'amplitude_mse'
References

Maiden, Johnson, and Li, Further improvements to the ptychographical iterative engine (2017).

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

Mpie

Mpie(
    *,
    iterations: int = 50,
    object_step: float = 0.2,
    stability: float = 0.05,
    momentum_interval: int = 30,
    momentum_friction: float = 0.9,
    momentum_feedback: float = 0.9,
    batch_size: int = 1,
    epsilon: float = 1e-10,
    loss_type: str = "amplitude_mse",
)

Bases: _Algorithm

Momentum-accelerated regularized PIE adapted to image-plane FPM.

The algorithm applies the object-only rPIE projection used by Fpie and periodically accelerates the centered complex object spectrum. A multiplexed measurement counts once after all source modes are inserted, zero-weight frames do not advance the interval, and batching does not change momentum cadence. Velocity, anchor, and a partial interval are preserved in checkpoints.

The cited method was tested for scanned ptychography and accelerates both object and probe. This implementation keeps the FPM pupil fixed and exposes separate friction and feedback controls. Equal values reproduce the paper's single object momentum coefficient.

Parameters:

Name Type Description Default
iterations int

Complete passes through the acquisition schedule.

50
object_step float

Positive scale applied to each rPIE object-spectrum correction.

0.2
stability float

Blend from local (0) to maximum (1) pupil power in the denominator.

0.05
momentum_interval int

Positive-weight measured-frame updates between momentum events.

30
momentum_friction float

Previous-velocity fraction in the half-open interval [0, 1).

0.9
momentum_feedback float

Updated-velocity fraction added to the object, in [0, 1].

0.9
batch_size int

Measured frames supplied to each reconstruction step. This does not change momentum cadence.

1
epsilon float

Positive floor added to the rPIE denominator.

1e-10
loss_type str

Diagnostic loss; the projection itself always enforces amplitude.

'amplitude_mse'
References

A. Maiden, D. Johnson, and P. Li, Further improvements to the ptychographical iterative engine (2017), Optica 4(7), 736–745.

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

Epry

Epry(
    *,
    iterations: int = 100,
    object_step: float = 0.8,
    pupil_step: float = 0.1,
    batch_size: int = 1,
    recover_pupil: bool = True,
    constrain_pupil_support: bool = True,
    recover_frame_gains: bool = False,
    gain_step: float = 0.2,
    gain_bounds: tuple[float, float] = (1e-06, 1000000.0),
    recover_background: bool = False,
    background_step: float = 0.2,
    background_bounds: tuple[float, float] = (
        0.0,
        1000000000000.0,
    ),
    epsilon: float = 1e-10,
    loss_type: str = "amplitude_mse",
)

Bases: _Algorithm

Embedded pupil-recovery reconstruction for FPM.

EPRY uses projected exit-wave errors to update the object spectrum and complex pupil together, separating specimen structure from aberrations. Per-frame gain and background recovery are fpm-rs extensions.

With pupil recovery enabled, iteration-boundary results match the compiled pupil's supported energy and phase reference and fix the remaining object piston. Affine pupil phase is removed on axes with zero effective subpixel offsets. It remains on fractional axes because bilinear crop interpolation does not preserve that ambiguity exactly. Canonicalization precedes iteration callbacks, checkpoints, final results, and resumed work.

Parameters:

Name Type Description Default
iterations int

Complete passes through the acquisition schedule.

100
object_step float

Relaxation factors for object and pupil corrections.

0.8
pupil_step float

Relaxation factors for object and pupil corrections.

0.8
batch_size int

Measured frames supplied to each step.

1
recover_pupil bool

Whether to update the complex pupil.

True
constrain_pupil_support bool

Whether to zero pupil values outside the compiled aperture.

True
recover_frame_gains bool

Whether to estimate multiplicative gains or uniform additive backgrounds.

False
recover_background bool

Whether to estimate multiplicative gains or uniform additive backgrounds.

False
gain_step float

Fractions of each calibration estimate applied per update.

0.2
background_step float

Fractions of each calibration estimate applied per update.

0.2
gain_bounds tuple[float, float]

Inclusive lower and upper limits for recovered calibration values.

(1e-06, 1000000.0)
background_bounds tuple[float, float]

Inclusive lower and upper limits for recovered calibration values.

(1e-06, 1000000.0)
epsilon float

Positive numerical floor for normalized updates.

1e-10
loss_type str

Diagnostic loss; the projection itself always enforces amplitude.

'amplitude_mse'
References

X. Ou, G. Zheng, and C. Yang, Embedded pupil function recovery for Fourier ptychographic microscopy (2014), Optics Express 22(5), 4960-4972.

A. Fannjiang and P. Chen, Blind ptychography: uniqueness and ambiguities (2020), Inverse Problems 36, 045005. fpm-rs uses a Fourier-domain object and retains affine phase on fractionally interpolated axes.

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

Admm

Admm(
    *,
    iterations: int = 100,
    object_step: float = 0.8,
    penalty: float = 1.0,
    dual_relaxation: float = 1.0,
    batch_size: int | None = None,
    epsilon: float = 1e-10,
)

Bases: _Algorithm

Linearized ADMM reconstruction for FPM.

Per-mode auxiliary and dual fields separate detector-amplitude fitting from object consensus. Steps alternate an amplitude proximal operation, a pupil-preconditioned object update, and a scaled-dual update.

Parameters:

Name Type Description Default
iterations int

Complete passes through the acquisition schedule.

100
object_step float

Step size of the linearized object update.

0.8
penalty float

Positive augmented-Lagrangian consensus penalty.

1.0
dual_relaxation float

Scaled-dual relaxation in the inclusive range [0, 2].

1.0
batch_size int | None

Frames per step; None processes all frames together.

None
epsilon float

Positive numerical floor for normalized updates.

1e-10
References

Wang et al., Fourier Ptychographic Microscopy via Alternating Direction Method of Multipliers (2022).

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

GlobalGaussNewton

GlobalGaussNewton(
    *,
    iterations: int = 20,
    damping: float = 0.001,
    maximum_cg_iterations: int = 12,
    cg_relative_tolerance: float = 0.001,
    maximum_line_search_steps: int = 8,
    line_search_reduction: float = 0.5,
    line_search_sufficient_decrease: float = 0.0001,
    epsilon: float = 1e-10,
)

Bases: _Algorithm

Matrix-free damped Gauss–Newton fixed-pupil object reconstruction.

The solver minimizes the full-stack, frame-weighted amplitude-MSE objective in intrinsic intensity units. Analytic Jacobian and adjoint products are applied through the compiled crop, fixed pupil, and FFT model without forming a Jacobian or Hessian. A coverage-damped normal equation is solved by preconditioned conjugate gradients and accepted by full-data Armijo backtracking.

Masks, frame weights, known gains and backgrounds, fractional crops, and incoherent multiplexing are supported. Each outer update processes every frame for the gradient, normal-operator products, and line search, so this method trades substantially more work per iteration for global curvature coupling. The pupil and calibration values remain fixed during each object update. Because no curvature persists across iterations, this solver can also be used inside JointReconstruction.

Parameters:

Name Type Description Default
iterations int

Complete global object updates.

20
damping float

Positive coefficient multiplying coverage-scaled diagonal damping.

0.001
maximum_cg_iterations int

Maximum matrix-free conjugate-gradient iterations per object update.

12
cg_relative_tolerance float

Relative linear-residual stopping tolerance in (0, 1).

0.001
maximum_line_search_steps int

Maximum full-data trial-objective evaluations per object update.

8
line_search_reduction float

Multiplicative backtracking factor in (0, 1).

0.5
line_search_sufficient_decrease float

Armijo sufficient-decrease coefficient in (0, 1).

0.0001
epsilon float

Positive floor for dark-field derivatives and Fourier coverage.

1e-10

Raises:

Type Description
InvalidParameterError

If a limit or positive scale is zero, non-finite, or outside its documented interval.

NumericalError

If a matrix-free product is non-finite, conjugate-gradient curvature is non-positive, the direction is not descending, or backtracking cannot accept a finite trial. A rejected trial does not modify the object.

Notes

The result arrays use the same shapes, dtypes, axis order, ownership, and checkpoint behavior as other reconstruction algorithms. Checkpoints occur only after an atomic global update; same-parameter resume is exact.

References

L.-H. Yeh, J. Dong, J. Zhong, L. Tian, M. Chen, G. Tang, M. Soltanolkotabi, and L. Waller, Experimental robustness of Fourier ptychography phase retrieval algorithms, Optics Express 23(26), 33214-33240 (2015). fpm-rs uses a matrix-free damped Gauss–Newton approximation to the amplitude residual, rather than the paper's explicitly formed exact CR-calculus Hessian.

S. Kandel, S. Maddali, Y. S. G. Nashed, S. O. Hruszkewycz, C. Jacobsen, and M. Allain, Efficient ptychographic phase retrieval via a matrix-free Levenberg–Marquardt algorithm, Optics Express 29(15), 23019-23055 (2021). That work treats diffraction-plane ptychography with automatic differentiation; fpm-rs uses analytic products for image-plane Fourier ptychography.

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

GradientDescent

GradientDescent(
    *,
    iterations: int = 100,
    object_step: float = 0.5,
    batch_size: int = 1,
    epsilon: float = 1e-10,
    loss_type: str = "amplitude_mse",
    poisson_truncation_threshold: float | None = None,
    recover_illumination: bool = False,
    illumination_step: float = 0.1,
    illumination_finite_difference: float = 0.05,
    illumination_bounds: float = 1.0,
    recover_pupil: bool = False,
    pupil_step: float = 0.05,
    constrain_pupil_support: bool = True,
    object_tv: float = 0.0,
    object_tv_epsilon: float = 1e-06,
    pupil_smoothing: float = 0.0,
    parallel_workers: int = 0,
)

Bases: _Algorithm

Wirtinger-style loss-gradient reconstruction for Fourier ptychography.

The solver differentiates a selected data loss through the FPM forward model, averages mini-batch gradients, and applies a pupil-power- preconditioned object update. Pupil and illumination recovery and object or pupil regularization are optional.

With pupil recovery enabled, iteration-boundary results match the compiled pupil's supported energy and phase reference and fix the remaining object piston. Affine pupil phase is removed on axes with zero effective subpixel offsets. It remains on fractional axes because bilinear crop interpolation does not preserve that ambiguity exactly. Canonicalization precedes iteration callbacks, checkpoints, final results, and resumed work.

Parameters:

Name Type Description Default
iterations int

Complete passes through the acquisition schedule.

100
object_step float

Step size of the preconditioned object update.

0.5
batch_size int

Frame gradients averaged into one update.

1
epsilon float

Positive floor used by losses and preconditioners.

1e-10
loss_type str

Data loss to optimize and report.

'amplitude_mse'
poisson_truncation_threshold float | None

Positive signal-dependent Poisson outlier coefficient. None keeps the ordinary untruncated gradient; the cited TPWFP work used 25. The gate uses intrinsic intensities and mini-batch residual statistics, and one decision is shared by all modes of a multiplexed pixel.

None
recover_illumination bool

Whether to estimate source offsets on the Fourier grid.

False
illumination_step float

Offset-update step, finite-difference spacing, and maximum absolute correction, all expressed in Fourier-grid pixels where applicable.

0.1
illumination_finite_difference float

Offset-update step, finite-difference spacing, and maximum absolute correction, all expressed in Fourier-grid pixels where applicable.

0.1
illumination_bounds float

Offset-update step, finite-difference spacing, and maximum absolute correction, all expressed in Fourier-grid pixels where applicable.

0.1
recover_pupil bool

Whether and how to update the complex pupil within its aperture.

False
pupil_step bool

Whether and how to update the complex pupil within its aperture.

False
constrain_pupil_support bool

Whether and how to update the complex pupil within its aperture.

False
object_tv float

Complex-object total-variation weight and smoothing constant; a zero weight disables the regularizer.

0.0
object_tv_epsilon float

Complex-object total-variation weight and smoothing constant; a zero weight disables the regularizer.

0.0
pupil_smoothing float

Nonnegative quadratic pupil-smoothing weight.

0.0
parallel_workers int

Worker limit; zero selects available CPU parallelism.

0
References

L. Bian, J. Suo, G. Zheng, K. Guo, F. Chen, and Q. Dai, Fourier ptychographic reconstruction using Wirtinger flow optimization (2015), Optics Express 23(4), 4856-4866.

L. Bian, J. Suo, J. Chung, X. Ou, C. Yang, F. Chen, and Q. Dai, Fourier ptychographic reconstruction using Poisson maximum likelihood and truncated Wirtinger gradient (2016), Scientific Reports 6, 27384. fpm-rs uses a mini-batch statistic and fixed object step; optional pupil and illumination recovery extend the paper's object-only presentation.

A. Fannjiang and P. Chen, Blind ptychography: uniqueness and ambiguities (2020), Inverse Problems 36, 045005. fpm-rs uses a Fourier-domain object and retains affine phase on fractionally interpolated axes.

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> ReconstructionResult

Run reconstruction without holding the Python GIL.

Parameters:

Name Type Description Default
problem ReconstructionProblem

Validated measurements and compiled model.

required
callbacks Iterable[Callback] | None

Optional callbacks invoked in their listed order.

None
resume_from ReconstructionCheckpoint | None

Compatible checkpoint whose algorithm state and completed progress should be restored.

None
schedule str

Frame order: "sequential", "reverse", or "shuffled".

'sequential'
schedule_seed int

Deterministic seed used only by the shuffled schedule.

0

Physical planar-array calibration

Bright-field initialization

BrightfieldCircleOptions

BrightfieldCircleOptions(
    *,
    frame_indices: Sequence[int] | None = None,
    center_search_radius_na: float = 0.02,
    brightfield_margin_na: float = 0.002,
    pupil_radius_search_na: float = 0.01,
    gaussian_sigma_pixels: float = 2.0,
    angular_samples: int = 180,
    radial_derivative_step_pixels: float = 1.0,
    minimum_arc_fraction: float = 0.2,
    minimum_edge_contrast: float = 0.01,
    mean_spectrum_floor: float = 1e-08,
    robust_residual_scale_na: float = 0.002,
    maximum_fit_steps: int = 100,
    fit_relative_tolerance: float = 1e-08,
    fit_initial_step_size: float = 0.5,
    fit_minimum_step_size: float = 1e-06,
    fit_step_reduction: float = 0.5,
    rank_tolerance: float = 1e-08,
    pupil_radius_tolerance_na: float = 0.02,
)

Controls for bright-field circle detection and bounded physical fitting.

All center and pupil-radius quantities use dimensionless numerical-aperture units. Pixel quantities refer to the low-resolution Fourier grid. An explicit frame_indices sequence contains acquisition-frame indices, not physical source indices.

frame_indices instance-attribute

frame_indices: list[int] | None

Explicit acquisition-frame subset, or None for safe automatic selection.

center_search_radius_na instance-attribute

center_search_radius_na: float

Maximum center displacement from each nominal source in NA.

brightfield_margin_na instance-attribute

brightfield_margin_na: float

Positive margin retained inside the objective-NA boundary.

pupil_radius_search_na instance-attribute

pupil_radius_search_na: float

Half-width of the pupil-radius search in NA.

gaussian_sigma_pixels instance-attribute

gaussian_sigma_pixels: float

Fourier-magnitude smoothing standard deviation in pixels.

angular_samples instance-attribute

angular_samples: int

Uniform angular samples used for every circular score.

radial_derivative_step_pixels instance-attribute

radial_derivative_step_pixels: float

Radial finite-difference displacement in Fourier-grid pixels.

minimum_arc_fraction instance-attribute

minimum_arc_fraction: float

Minimum usable fraction of the requested circumference.

minimum_edge_contrast instance-attribute

minimum_edge_contrast: float

Minimum normalized first-derivative score for acceptance.

mean_spectrum_floor instance-attribute

mean_spectrum_floor: float

Relative positive floor applied during mean-spectrum division.

robust_residual_scale_na instance-attribute

robust_residual_scale_na: float

Huber transition scale for physical-fit residual components in NA.

maximum_fit_steps instance-attribute

maximum_fit_steps: int

Maximum bounded physical-fit steps.

fit_relative_tolerance instance-attribute

fit_relative_tolerance: float

Relative objective improvement required to continue fitting.

fit_initial_step_size instance-attribute

fit_initial_step_size: float

Initial line-search step in normalized parameter coordinates.

fit_minimum_step_size instance-attribute

fit_minimum_step_size: float

Smallest normalized line-search step attempted.

fit_step_reduction instance-attribute

fit_step_reduction: float

Multiplicative backtracking factor in (0, 1).

rank_tolerance instance-attribute

rank_tolerance: float

Relative pivot threshold for the data-Jacobian rank test.

pupil_radius_tolerance_na instance-attribute

pupil_radius_tolerance_na: float

Maximum accepted pupil-radius mismatch from configured objective NA.

PlanarArrayInitializationCallback

PlanarArrayInitializationCallback(
    callable: Callable[[dict[str, object]], bool | None],
)

Wrap a callable receiving initializer-specific progress dictionaries.

The callable receives stage, completed, total, and optional frame_index entries. Return False to cancel or None/True to continue. The initializer releases the GIL while working and reacquires it only for these callbacks.

BrightfieldCircleInitializer

BrightfieldCircleInitializer(
    parameters: PlanarArrayCalibrationParameters,
    *,
    options: BrightfieldCircleOptions | None = None,
)

Detect bright-field pupil circles and fit a physical planar-array warm start.

The method assumes monochromatic coherent image-plane measurements, a thin specimen with enough texture/reference interference, and a shift-invariant circular pupil. It accepts only single-source, all-valid, strictly bright-field frames. It does not reconstruct an object, alter Optics, or estimate independent source shifts, powers, gains, or backgrounds.

Use the returned illumination/model directly or pass them to JointReconstruction for canonical measurement-loss refinement. The call blocks, releases the GIL during both streaming measurement passes and physical fitting, and reacquires it only for an optional progress callback.

References

J. Sun, Q. Chen, Y. Zhang, and C. Zuo, “Efficient positional misalignment correction method for Fourier ptychographic microscopy,” Biomedical Optics Express 7(4), 1336–1350 (2016). Unlike that reconstruction-time independent aperture search, this initializer directly fits detected centers to the bounded physical geometry.

R. Eckert, Z. F. Phillips, and L. Waller, “Efficient illumination angle self-calibration in Fourier ptychography,” Applied Optics 57(19), 5434–5442 (2018). This implementation adopts the bright-field circular-edge initialization concept, not the iterative spectral-correlation stage or three-dimensional variants.

parameters instance-attribute

Selected global translation, rotation, pitch, or reference-index variables.

options instance-attribute

Circle-detection and bounded-fit controls.

initialize

initialize(
    measurements: FloatArray | MeasurementStack,
    optics: Optics,
    nominal_illumination: Illumination,
    model: ImagePlaneModel,
    *,
    frame_weights: Sequence[float] | None = None,
    masks: MaskArray | None = None,
    callback: PlanarArrayInitializationCallback
    | None = None,
) -> PlanarArrayInitializationResult

Run two streaming spectral passes and a bounded physical fit.

Parameters:

Name Type Description Default
measurements FloatArray | MeasurementStack

Float64 (frames, height, width) intensities or an existing MeasurementStack. Inputs are copied when constructing a stack.

required
optics Optics

Physical optics used to compile model.

required
nominal_illumination Illumination

Physical planar-array illumination used to compile model.

required
model ImagePlaneModel

Matching image-plane model. Updated complex pupil values and known background are retained unchanged.

required
frame_weights Sequence[float] | None

Optional metadata for raw NumPy input. Masks must be uint8 with the same shape; selected frames must be all-valid.

None
masks Sequence[float] | None

Optional metadata for raw NumPy input. Masks must be uint8 with the same shape; selected frames must be all-valid.

None
callback PlanarArrayInitializationCallback | None

Optional initializer progress callback.

None

Raises:

Type Description
InvalidMeasurementsError

If candidate frames, spectra, or detected circles are unusable.

InvalidParameterError

If the selected physical variables are unidentifiable or violate the calibration gauge constraints.

UnsupportedError

If geometry or selected variables are outside the supported scope.

Measurement-loss calibration

CalibrationParameterSpec

CalibrationParameterSpec(
    lower_bound: float,
    upper_bound: float,
    *,
    scale: float = 1.0,
    finite_difference_step: float | None = None,
    prior_center: float | None = None,
    regularization_strength: float = 0.0,
)

Numerical controls for one bounded physical parameter.

Bounds, finite-difference steps, prior centers, and scales use the physical unit of the selected parameter: metres for translations, pitches, and offsets; radians for rotations; and dimensionless values otherwise.

lower_bound instance-attribute

lower_bound: float

Inclusive lower bound in the parameter's physical unit.

upper_bound instance-attribute

upper_bound: float

Inclusive upper bound in the parameter's physical unit.

scale instance-attribute

scale: float

Positive physical increment represented by one normalized unit.

finite_difference_step instance-attribute

finite_difference_step: float

Positive perturbation used for central or one-sided differences.

prior_center instance-attribute

prior_center: float | None

Optional center of the quadratic prior in physical units.

regularization_strength instance-attribute

regularization_strength: float

Nonnegative coefficient of the quadratic prior.

PlanarArrayCalibrationParameters

PlanarArrayCalibrationParameters(
    *,
    translation: tuple[bool, bool, bool] = (
        False,
        False,
        False,
    ),
    rotation: tuple[bool, bool, bool] = (
        False,
        False,
        False,
    ),
    pitch: tuple[bool, bool] = (False, False),
    reference_index: tuple[bool, bool] = (False, False),
    position_offsets: Sequence[int] = (),
    relative_source_power: bool = False,
    frame_gains: bool = False,
    translation_spec: CalibrationParameterSpec
    | None = None,
    rotation_spec: CalibrationParameterSpec | None = None,
    pitch_spec: CalibrationParameterSpec | None = None,
    reference_index_spec: CalibrationParameterSpec
    | None = None,
    position_offset_spec: CalibrationParameterSpec
    | None = None,
    relative_source_power_spec: CalibrationParameterSpec
    | None = None,
    frame_gain_spec: CalibrationParameterSpec | None = None,
)

Explicit physical parameters selected for planar LED-array calibration.

Unselected groups remain fixed. position_offsets contains stable row-major source indices; each selected source exposes local XYZ offsets. Lateral translation cannot be combined with the corresponding reference index, and source powers cannot be combined with frame gains because those choices contain unresolved gauges.

translation instance-attribute

translation: tuple[bool, bool, bool]

Active (tx, ty, tz) pose components in metres.

rotation instance-attribute

rotation: tuple[bool, bool, bool]

Active extrinsic (rx, ry, rz) components in radians.

pitch instance-attribute

pitch: tuple[bool, bool]

Active (pitch_x, pitch_y) lattice spacings in metres.

reference_index instance-attribute

reference_index: tuple[bool, bool]

Active fractional (column, row) reference-index coordinates.

position_offsets instance-attribute

position_offsets: list[int]

Sorted row-major source indices whose XYZ offsets are active.

relative_source_power instance-attribute

relative_source_power: bool

Whether mean-one per-source relative intensities are active.

frame_gains instance-attribute

frame_gains: bool

Whether mean-one per-frame intensity gains are active.

translation_specs instance-attribute

translation_specs: tuple[
    CalibrationParameterSpec | None,
    CalibrationParameterSpec | None,
    CalibrationParameterSpec | None,
]

Inspectable per-component (tx, ty, tz) numerical specifications.

rotation_specs instance-attribute

rotation_specs: tuple[
    CalibrationParameterSpec | None,
    CalibrationParameterSpec | None,
    CalibrationParameterSpec | None,
]

Inspectable per-component (rx, ry, rz) numerical specifications.

pitch_specs instance-attribute

pitch_specs: tuple[
    CalibrationParameterSpec | None,
    CalibrationParameterSpec | None,
]

Inspectable per-component (pitch_x, pitch_y) specifications.

reference_index_specs instance-attribute

reference_index_specs: tuple[
    CalibrationParameterSpec | None,
    CalibrationParameterSpec | None,
]

Inspectable reference-column and reference-row specifications.

position_offset_specs instance-attribute

position_offset_specs: dict[
    int,
    tuple[
        CalibrationParameterSpec,
        CalibrationParameterSpec,
        CalibrationParameterSpec,
    ],
]

Inspectable source-indexed XYZ offset specifications.

relative_source_power_spec instance-attribute

relative_source_power_spec: CalibrationParameterSpec | None

Common numerical specification for active source powers.

frame_gain_spec instance-attribute

frame_gain_spec: CalibrationParameterSpec | None

Common numerical specification for active frame gains.

BoundedFiniteDifferenceOptimizer

BoundedFiniteDifferenceOptimizer(
    *,
    max_steps: int = 2,
    relative_tolerance: float = 1e-06,
    initial_step_size: float = 0.25,
    minimum_step_size: float = 1e-06,
    step_reduction: float = 0.5,
)

Deterministic scaled finite differences with bounded backtracking.

max_steps instance-attribute

max_steps: int

Maximum bounded gradient steps per illumination-update phase.

relative_tolerance instance-attribute

relative_tolerance: float

Relative objective-improvement threshold for convergence.

initial_step_size instance-attribute

initial_step_size: float

Initial step length in normalized parameter coordinates.

minimum_step_size instance-attribute

minimum_step_size: float

Smallest normalized step attempted by backtracking.

step_reduction instance-attribute

step_reduction: float

Factor in (0, 1) applied after a rejected trial.

IlluminationCalibration

IlluminationCalibration(
    parameters: PlanarArrayCalibrationParameters,
    *,
    optimizer: BoundedFiniteDifferenceOptimizer
    | None = None,
    loss_type: str = "amplitude_mse",
)

Physical parameter selection, bounded optimizer, and canonical data loss.

The default amplitude_mse is the same measurement-domain objective used by reconstruction diagnostics. Masks and frame weights are honored.

parameters instance-attribute

Explicit planar-array parameter selection and numerical specifications.

optimizer instance-attribute

Bounded deterministic optimizer settings.

loss_type instance-attribute

loss_type: str

Canonical measurement-domain loss name.

JointReconstruction

JointReconstruction(
    object_algorithm: Fpie | Epry | GlobalGaussNewton,
    optics: Optics,
    initial_illumination: Illumination,
    illumination_calibration: IlluminationCalibration,
    *,
    outer_iterations: int = 10,
    object_iterations_per_outer: int = 1,
    illumination_steps_per_outer: int = 1,
)

Alternate analytic object/pupil updates with bounded physical LED calibration.

The initial model in problem must have been compiled from optics and initial_illumination. Rotations are active right-handed extrinsic XYZ radians, positions and pitches are metres, and multiplicative groups are normalized to mean one. This implementation uses the canonical forward model; unlike generic k-vector correction it always returns a realizable PlanarLEDArray illumination.

object_algorithm accepts Fpie, Epry, or GlobalGaussNewton. The global solver keeps the pupil fixed and starts a fresh matrix-free linearization after each calibrated-model refresh; EPRY may update the pupil between physical phases.

References

Sun et al., Efficient positional misalignment correction method for Fourier ptychographic microscopy (2016). The implementation differs by using deterministic bounded finite differences rather than simulated annealing.

run

run(
    problem: ReconstructionProblem,
    *,
    callbacks: Iterable[Callback] | None = None,
    resume_from: ReconstructionCheckpoint | None = None,
    schedule: str = "sequential",
    schedule_seed: int = 0,
) -> JointReconstructionResult

Run or resume alternating reconstruction without holding the Python GIL.

Callbacks receive the standard iteration context plus namespaced object metrics and physical_illumination data, regularization, update-count, and rejection metrics.