Options
The following classes define the configuration options for Pty-chi reconstructions.
Base Options
- class ptychi.api.options.base.Options[source]
Bases:
object- load_from_dict(d: dict, strict: bool = False) Options[source]
Load option values from a dictionary.
- Parameters:
- Returns:
This options object with the loaded values applied.
- Return type:
- Raises:
ValueError – If
strictis True and anoptions_class_namevalue does not match the corresponding options class.
- class ptychi.api.options.base.ObjectOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, slice_spacings_m: list | tuple | None = None, slice_spacing_options: SliceSpacingOptions = <factory>, pixel_size_m: float = 1.0, pixel_size_aspect_ratio: float = 1.0, l1_norm_constraint: ObjectL1NormConstraintOptions = <factory>, l2_norm_constraint: ObjectL2NormConstraintOptions = <factory>, smoothness_constraint: ObjectSmoothnessConstraintOptions = <factory>, total_variation: ObjectTotalVariationOptions = <factory>, hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase = <factory>, remove_grid_artifacts: RemoveGridArtifactsOptions = <factory>, multislice_regularization: ObjectMultisliceRegularizationOptions = <factory>, patch_interpolation_method: PatchInterpolationMethods = PatchInterpolationMethods.FOURIER, remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions = <factory>, build_preconditioner_with_all_modes: bool = False, determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = ObjectPosOriginCoordsMethods.SUPPORT, position_origin_coords: list | tuple | None = None)[source]
Bases:
ParameterOptions- build_preconditioner_with_all_modes: bool = False
If True, the probe illumination map used for the preconditioner is built using the sum of intensities of all probe modes. This may help address some issues if some probe modes contain highly localized high-intensity anomalies, if the selected reconstructor uses preconditioner to regularize object updates. However, it might lead to slower convergence speed.
- determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = 'support'
The method to determine the pixel coordinates of the object that corresponds to the origin of the probe positions.
Probe positions are given as a list of coordinates that can be either positive or negative and have arbitrary offsets, while the object buffer is a discrete tensor where the pixel indices are 0-based and the origin is at the top left corner. The position origin coordinates are used to determine how the given probe positions are mapped to the object buffer: the origin of the probe positions (0, 0) is mapped to the pixel indices given by the position origin coordinates, and as such, the pixel indices of all probe positions are calculated as
` positions_pxind = positions + position_origin_coords `POSITIONS: the origin coordinates are determined as buffer_center - (positions.max() + positions.min()) / 2. This puts the mid-point of the position range at the center of the buffer. It is more adaptive; however, in the case that one initializes a reconstruction with a previously reconstructed object and corrected probe positions, the center coordinates are not necessarily the same, which can cause the positions to mismatch between both reconstructions.
SUPPORT: the origin coordinates are determined as the center of the support of the object. This is helpful to keep the center coordinates consistent between consecutive reconstructions, but the probe positions given should (at least approximately) zero-centered, i.e., -postitions.min() ~ positions.max() to prevent out-of-bound errors.
SPECIFIED: the origin coordinates are specified by the user. To make this setting effective, position_origin_coords should be specified.
- hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase
- initial_guess: Tensor | ndarray | list | tuple | None = None
A (h, w) complex tensor of the object initial guess.
- l1_norm_constraint: ObjectL1NormConstraintOptions
- l2_norm_constraint: ObjectL2NormConstraintOptions
- multislice_regularization: ObjectMultisliceRegularizationOptions
- patch_interpolation_method: PatchInterpolationMethods = 'fourier'
Selects interpolation for object patch sampling and probe subpixel shifts. Both sampling operators support Fourier, bilinear, nearest, and cubic interpolation. CUBIC uses an interpolating cubic B-spline with a periodic coefficient prefilter over the complete object.
- pixel_size_aspect_ratio: float = 1.0
The aspect ratio of the pixel size, defined as width (x) / height (y).
- pixel_size_m: float = 1.0
The pixel size in meters. When pixel size is non-square, this should be the width (x) of the pixel size.
- position_origin_coords: list | tuple | None = None
The user-specified origin coordinates of the object. To make this setting effective, determine_position_origin_coords_by should be set to SPECIFIED.
Probe positions are given as a list of coordinates that can be either positive or negative and have arbitrary offsets, while the object buffer is a discrete tensor where the pixel indices are 0-based and the origin is at the top left corner. The position origin coordinates are used to determine how the given probe positions are mapped to the object buffer: the origin of the probe positions (0, 0) is mapped to the pixel indices given by the position origin coordinates, and as such, the pixel indices of all probe positions are calculated as
` positions_pxind = positions + position_origin_coords `
- remove_grid_artifacts: RemoveGridArtifactsOptions
- remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions
- slice_spacing_options: SliceSpacingOptions
- slice_spacings_m: list | tuple | None = None
Slice spacings in meters. This should be provided if the object is multislice.
If the slice spacings need to be optimized, set slice_spacing_options.optimizable to True. In that case, the slice spacings provided here are supposed to be the initial guess.
- smoothness_constraint: ObjectSmoothnessConstraintOptions
- total_variation: ObjectTotalVariationOptions
- class ptychi.api.options.base.ProbeOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, pixel_size_m: float | None = None, pixel_size_aspect_ratio: float | None = None, power_constraint: ProbePowerConstraintOptions = <factory>, orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions = <factory>, orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions = <factory>, support_constraint: ProbeSupportConstraintOptions = <factory>, center_constraint: ProbeCenterConstraintOptions = <factory>, eigenmode_update_relaxation: float = 1.0)[source]
Bases:
ParameterOptionsThe probe configuration.
The first OPR mode of all incoherent modes are always optimized aslong as optimizable is True. In addition to thtat, eigenmodes (of the first incoherent mode) are optimized when:
The probe has multiple OPR modes;
OPRModeWeightsConfig is given.
- center_constraint: ProbeCenterConstraintOptions
- initial_guess: Tensor | ndarray | list | tuple | None = None
A (n_opr_modes, n_modes, h, w) complex tensor of the probe initial guess.
- orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions
- orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions
- pixel_size_aspect_ratio: float | None = None
Probe pixel width/height ratio. If
None, inherit the object ratio.The width and aspect ratio are inherited independently, so either value may be overridden without specifying the other one.
- pixel_size_m: float | None = None
Probe pixel width in meters. If
None, inherit the object pixel width.
- power_constraint: ProbePowerConstraintOptions
- support_constraint: ProbeSupportConstraintOptions
- class ptychi.api.options.base.ProbePositionOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 0.3, optimizer_params: dict = <factory>, position_x_px: Tensor | ndarray | list | tuple | None = None, position_y_px: Tensor | ndarray | list | tuple | None = None, constrain_position_mean: bool = False, correction_options: PositionCorrectionOptions = <factory>, affine_transform_constraint: PositionAffineTransformConstraintOptions = <factory>)[source]
Bases:
ParameterOptions- affine_transform_constraint: PositionAffineTransformConstraintOptions
When enabled, an affine transformation from initial positions to current positions is fit, and positions deviating from the expected positions given by the affine transformation are penalized.
- constrain_position_mean: bool = False
Whether to subtract the mean from positions after updating positions.
- correction_options: PositionCorrectionOptions
Detailed options for position correction.
- class ptychi.api.options.base.OPRModeWeightsOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_weights: Tensor | ndarray | list | tuple | None = None, optimize_eigenmode_weights: bool = True, optimize_intensity_variation: bool = False, primary_mode_weight_floor: float | None = None, smoothing: OPRModeWeightsSmoothingOptions = <factory>, update_relaxation: float = 1.0)[source]
Bases:
ParameterOptions- initial_weights: Tensor | ndarray | list | tuple | None = None
The initial weight(s) of the eigenmode(s). Acceptable values include the following:
a (n_scan_points, n_opr_modes) array of initial weights for every point.
a (n_opr_modes,) array that gives the weights of each OPR mode. These weights will be duplicated for every point.
- optimizable: bool = False
The master switch of optimizability of OPR mode weights. This option must be set to True for either optimize_eigenmode_weights or optimize_intensity_variation to take effect.
- optimize_eigenmode_weights: bool = True
Whether to optimize eigenmode weights, i.e., the weights of the second and following OPR modes.
At least one of optimize_eigenmode_weights and optimize_intensity_variation should be set to True if optimizable is True.
- optimize_intensity_variation: bool = False
Whether to optimize intensity variation, i.e., the weight of the first OPR mode.
At least one of optimize_eigenmode_weights and optimize_intensity_variation should be set to True if optimizable is True.
- primary_mode_weight_floor: float | None = None
Lower bound for the weight of the primary (0th) OPR mode. If None, no lower bound is applied.
- smoothing: OPRModeWeightsSmoothingOptions
- class ptychi.api.options.base.FeatureOptions(enabled: bool, optimization_plan: OptimizationPlan)[source]
Bases:
OptionsAbstract base class that is inherited by sub-feature dataclasses. This class is used to determining if/when a feature is used.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.SynthesisDictLearnProbeOptions(d_mat: list | tuple | None = None, d_mat_conj_transpose: list | tuple | None = None, d_mat_pinv: list | tuple | None = None, probe_sparse_code: list | tuple | None = None, probe_sparse_code_nnz: float | None = None, enabled: bool = False)[source]
Bases:
Options- d_mat: list | tuple | None = None
The synthesis sparse dictionary matrix; contains the basis functions that will be used to represent the probe via the sparse code weights.
- d_mat_conj_transpose: list | tuple | None = None
Conjugate transpose of the synthesis sparse dictionary matrix.
- class ptychi.api.options.base.PositionCorrectionOptions(correction_type: PositionCorrectionTypes = PositionCorrectionTypes.GRADIENT, differentiation_method: ImageGradientMethods = ImageGradientMethods.FOURIER_DIFFERENTIATION, cross_correlation_scale: int = 20000, cross_correlation_real_space_width: float = 0.01, cross_correlation_probe_threshold: float = 0.1, slice_for_correction: int | None = None, clip_update_magnitude_by_mad: bool = True, update_magnitude_limit: float | None = 0.1)[source]
Bases:
OptionsOptions used for specifying the position correction function.
- clip_update_magnitude_by_mad: bool = True
If True, the update magnitude is eventually clipped by 10 times the mean absolute deviation (MAD) of the updates. When update_magnitude_limit is set, the limit will be set to the smaller of them, i.e., min(update_magnitude_limit, 10 * MAD).
- correction_type: PositionCorrectionTypes = 'gradient'
Type of algorithm used to calculate the position correction update.
- cross_correlation_probe_threshold: float = 0.1
The probe intensity threshold used to calculate the probe mask.
- differentiation_method: ImageGradientMethods = 'fourier_differentiation'
The method for calculating the gradient of the object. Only used when correction_type is GRADIENT. “FOURIER_DIFFERENTIATION” is usually the fastest, but it might be less stable when the object is noisy or non-smooth, under which circumstance “GAUSSIAN” or “FOURIER_SHIFT” may offer better stability. “NEAREST” is not recommended.
- slice_for_correction: int | None = None
The object slice for which the position correction is calculated. If None, the middle slice is chosen.
- update_magnitude_limit: float | None = 0.1
The maximum allowed magnitude of position update in each axis. Updates larger than this value are clipped. Set to None or inf to disable the constraint. When clip_update_magnitude_by_mad is True, the actual limit will be set to the smaller of update_magnitude_limit and 10 * MAD.
- class ptychi.api.options.base.PositionAffineTransformConstraintOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, degrees_of_freedom: Sequence[AffineDegreesOfFreedom] = (AffineDegreesOfFreedom.ROTATION, AffineDegreesOfFreedom.SCALE, AffineDegreesOfFreedom.SHEAR, AffineDegreesOfFreedom.ASYMMETRY), position_weight_update_interval: int = 10, apply_constraint: bool = True, max_expected_error: float = 1.0, override_update_flexibility: float | None = None)[source]
Bases:
FeatureOptionsSettings for imposing an affine transformation constraint on the probe positions.
- apply_constraint: bool = True
Constraint is applied to probe positions only when this is True. When False, probe position weights and affine transformation matrix are still computed and stored in the ProbePositions object so that they can be logged and analyzed externally, but the positions are not altered.
- degrees_of_freedom: Sequence[AffineDegreesOfFreedom] = (AffineDegreesOfFreedom.ROTATION, AffineDegreesOfFreedom.SCALE, AffineDegreesOfFreedom.SHEAR, AffineDegreesOfFreedom.ASYMMETRY)
The degrees of freedom to include in the affine transformation.
- max_expected_error: float = 1.0
The maximum expected position error, given in pixels. Note that this is different from update_magnitude_limit, and is only used in the estimation of friction in affine transformation constraint.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- override_update_flexibility: float | None = None
If set, the update flexibility will be set to this value instead of being determined by the actual errors and max expected error. The value should be betweem 0 and 1. If affine constraint is causing instability, setting this to a smaller value may help.
- class ptychi.api.options.base.DetectorResponseOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1.0, optimizer_params: dict = <factory>, optimize_gain: bool = False, optimize_offset: bool = True, gain_floor: float = 1e-06, offset_nonnegative: bool = False)[source]
Bases:
ParameterOptionsRefinement of the shared detector gain and offset maps.
- optimize_gain: bool = False
Refine gain, normalizing its mean over valid pixels to one after each update. This fixes the global scale ambiguity with the probe.
- step_size: float = 1.0
Optimizer learning rate. For analytical solvers, unit SGD applies the epoch-wise intensity least-squares fit; smaller steps relax toward it. Closure-based optimizers minimize squared distance to this fixed fit. Autodiff uses the gradient of its configured loss and may need a smaller rate.
- class ptychi.api.options.base.ForwardModelOptions(detector_response_options: DetectorResponseOptions = <factory>, shift_operator: ShiftOperators = ShiftOperators.AUTO, low_memory_mode: bool = False, pad_for_shift: int | None = 0, subpixel_shift_all_probe_modes: bool = False, diffraction_pattern_blur_sigma: float | None = None)[source]
Bases:
Options- detector_response_options: DetectorResponseOptions
Options for detector response refinement. Omitted maps initialize to identity.
- diffraction_pattern_blur_sigma: float | None = None
If not None, simulated diffraction patterns are blurred with a Gaussian kernel of this sigma. This is useful to mitigate the effect of the detector’s point spread function.
- low_memory_mode: bool = False
If True, forward propagation of ptychography will be done using less vectorized code. This reduces the speed, but also lowers memory usage.
- pad_for_shift: int | None = 0
If not None, the image is padded with border values by this amount before shifting.
- shift_operator: ShiftOperators = 'auto'
Object sampling operator. AUTO uses periodic full-object shifting for finite propagation distance when both probe dimensions exceed 80% of the object dimensions on the probe pixel grid. PATCH preserves patch-based sampling. FULL_OBJECT honors the object’s interpolation method and ignores pad_for_shift.
- subpixel_shift_all_probe_modes: bool = False
If True, the subpixel part of each probe position is applied to all incoherent probe modes. If False, only the first mode is shifted (as in PtychoShelves), so the other modes sit at the nearest whole pixel, up to half a pixel away from the probe position. Enable this for mixed-state reconstructions where modes beyond the first carry significant power. Analytical reconstructors apply the matching adjoint shift to the probe update directions.
- class ptychi.api.options.base.ObjectMultisliceRegularizationOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, weight: float = 0, unwrap_phase: bool = True, unwrap_image_grad_method: ImageGradientMethods = ImageGradientMethods.FOURIER_DIFFERENTIATION, unwrap_image_integration_method: ImageIntegrationMethods = ImageIntegrationMethods.FOURIER)[source]
Bases:
FeatureOptionsSettings for multislice regularization of the object.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- unwrap_image_grad_method: ImageGradientMethods = 'fourier_differentiation'
The method for calculating the phase gradient during phase unwrapping.
FOURIER_SHIFT: Use Fourier shift to perform shift.
NEAREST: Use nearest neighbor to perform shift.
FOURIER_DIFFERENTIATION: Use Fourier differentiation.
- unwrap_image_integration_method: ImageIntegrationMethods = 'fourier'
The method for integrating the phase gradient during phase unwrapping.
FOURIER: Use Fourier integration as implemented in PtychoShelves.
DECONVOLUTION: Deconvolve a ramp filter.
DISCRETE: Use cumulative sum.
- class ptychi.api.options.base.ObjectL1NormConstraintOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, weight: float = 0)[source]
Bases:
FeatureOptionsSettings for the L1 norm constraint.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.ObjectL2NormConstraintOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, weight: float = 0)[source]
Bases:
FeatureOptionsSettings for the L2 norm constraint.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.ObjectSmoothnessConstraintOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, alpha: float = 0)[source]
Bases:
FeatureOptionsSettings for smoothing the real and imaginary components of the object.
- alpha: float = 0
The relaxation smoothing constant. This value should be in the range 0 < alpha <= 1/8.
Smoothing is done by constructing a 3x3 kernel of
alpha, alpha, alpha alpha, 1 - 8 * alpha, alpha alpha, alpha, alpha
and convolving it with each complex object slice. When alpha == 1 / 8, the smoothing power is maximal. The value of alpha should not be larger than 1 / 8.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.ObjectTotalVariationOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, weight: float = 0)[source]
Bases:
FeatureOptionsSettings for total variation constraint on the object.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.RemoveGridArtifactsOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, period_x_m: float = 1e-07, period_y_m: float = 1e-07, window_size: int = 5, direction: Directions = Directions.XY, component: MagPhaseComponents = MagPhaseComponents.PHASE)[source]
Bases:
FeatureOptionsSettings for grid artifact removal in the object’s phase, applied at the end of an epoch
- component: MagPhaseComponents = 'phase'
The component of the object to remove grid artifacts from.
- direction: Directions = 'xy'
The direction of grid artifact removal.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.RemoveObjectProbeAmbiguityOptions(enabled: bool = True, optimization_plan: OptimizationPlan = <factory>)[source]
Bases:
FeatureOptionsSettings for removing the object-probe ambiguity, where the object is scaled by its norm so that the mean transmission is kept around 1, and the probe is scaled accordingly.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.SliceSpacingOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1e-10, optimizer_params: dict = <factory>)[source]
Bases:
ParameterOptions- optimizable: bool = False
Whether the slice spacings are optimizable.
Known issue: slice spacing optimization only works with AutodiffPtychography, and we have to use loss.backward(retain_graph=True) to make it work with AD. This might result in growing per-epoch walltime and memory usage. We are working on a better solution.
- optimization_plan: OptimizationPlan
Optimization plan for the parameter.
- optimizer: Optimizers = 'sgd'
The optimizer to use for optimizing the slice spacings.
- class ptychi.api.options.base.ProbePowerConstraintOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, probe_power: float = 0.0, scale_object: bool = True)[source]
Bases:
FeatureOptionsSettings for scaling the probe and object intensity.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- probe_power: float = 0.0
Target real-space sum of squared probe magnitudes over pixels and incoherent modes, without a pixel-area factor. With OPR, the probe is composed using the mean OPR weights when available. The probe and optionally the object are scaled to enforce this target. To convert detector counts under lossless propagation, divide their sum by
ptychi.propagate.get_intensity_scaling_factor(propagator, probe_shape). For the default Fourier propagator this divisor isheight * width.
- class ptychi.api.options.base.ProbeOrthogonalizeIncoherentModesOptions(enabled: bool = True, optimization_plan: OptimizationPlan = <factory>, method: OrthogonalizationMethods = OrthogonalizationMethods.SVD, sort_by_occupancy: bool = False)[source]
Bases:
FeatureOptionsSettings for orthogonalizing incoherent probe modes.
- method: OrthogonalizationMethods = 'svd'
The method to use for incoherent_mode orthogonalization.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.ProbeOrthogonalizeOPRModesOptions(enabled: bool = True, optimization_plan: OptimizationPlan = <factory>)[source]
Bases:
FeatureOptionsSettings for orthogonalizing OPR modes.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.ProbeSupportConstraintOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, fixed_probe_support: ProbeSupportMethods = ProbeSupportMethods.NONE, fixed_probe_support_params: list | tuple | None = None, threshold: float = 0.005)[source]
Bases:
FeatureOptionsSettings for probe support constraint. The constraint applies shrinkwrapping, where small values below a threshold are set to 0. It can also optionally apply a probe support mask before shrinkwrapping.
- fixed_probe_support: ProbeSupportMethods = 'none'
If not NONE, a fixed probe support mask is generated and applied before shrinkwrapping. The mask is applied to each incoherent probe mode. Choices are: ELLIPSE, RECTANGLE.
- fixed_probe_support_params: list | tuple | None = None
If using the use_fixed_probe_support option, define the center, widths, and heights for the ellipse/rectangle, format is: [center (rows), center (columns), side length (rows), side length (columns)]
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.ProbeCenterConstraintOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, use_total_intensity_for_com: bool = False, use_intensity_for_com: bool = False, center_modes_individually: bool = False)[source]
Bases:
FeatureOptionsSettings for constraining the probe’s center of mass to the center of the probe array.
- center_modes_individually: bool = False
If True, each mode is shifted individually based on their own center of mass.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
- class ptychi.api.options.base.OPRModeWeightsSmoothingOptions(enabled: bool = False, optimization_plan: OptimizationPlan = <factory>, method: OPRWeightSmoothingMethods = OPRWeightSmoothingMethods.MEDIAN, polynomial_degree: int = 4)[source]
Bases:
FeatureOptionsSettings for smoothing OPR mode weights.
- method: OPRWeightSmoothingMethods = 'median'
The method for smoothing OPR mode weights.
MEDIAN: applying a median filter to the weights of each mode.
POLYNOMIAL: fit the weights of each mode with a polynomial of selected degree.
- optimization_plan: OptimizationPlan
Schedules when the feature is executed.
Data Options
- class ptychi.api.options.data.PtychographyDataOptions(data: Tensor | ndarray | list | tuple | None = None, free_space_propagation_distance_m: float = inf, wavelength_m: float = 1e-09, fft_shift: bool = True, valid_pixel_mask: Tensor | ndarray | list | tuple | None = None, save_data_on_device: bool = False)[source]
Bases:
Options- data: Tensor | ndarray | list | tuple | None = None
The intensity data. Use collected data as they are; data should NOT be FFT-shifted or square-rooted.
- fft_shift: bool = True
Whether to FFT-shift the diffraction data when building the dataset. For far-field ptychography, the forward model does not shift the image after FFT, meaning the predicted intensity has its DC component at the top left corner. To match the prediction, measured intensity should be pre-shifted if the DC component of the given diffraction patterns is at the center.
However, if the given diffraction patterns are already shifted so that the DC compoenent is at the top left, or if you are reconstructing near-field ptychography data where the forward model does not involve Fraunhofer diffraction implemented with FFT, ensure this option is set to False to avoid the erroneous shifting.
- free_space_propagation_distance_m: float = inf
The free-space propagation distance in meters, or inf for far-field.
- save_data_on_device: bool = False
Whether to save the diffraction data on acceleration devices like GPU.
Difference Map (DM) Options
- class ptychi.api.options.dm.DMOptions(data_options: PtychographyDataOptions = <factory>, reconstructor_options: DMReconstructorOptions = <factory>, object_options: DMObjectOptions = <factory>, probe_options: DMProbeOptions = <factory>, probe_position_options: DMProbePositionOptions = <factory>, opr_mode_weight_options: DMOPRModeWeightsOptions = <factory>)[source]
Bases:
PtychographyTaskOptions- object_options: DMObjectOptions
- opr_mode_weight_options: DMOPRModeWeightsOptions
- probe_options: DMProbeOptions
- probe_position_options: DMProbePositionOptions
- reconstructor_options: DMReconstructorOptions
- class ptychi.api.options.dm.DMReconstructorOptions(num_epochs: int = 100, batch_size: int = 100, batching_mode: BatchingModes = BatchingModes.RANDOM, compact_mode_update_clustering: bool = False, compact_mode_update_clustering_stride: int = 1, default_device: Devices = Devices.GPU, default_dtype: Dtypes = Dtypes.FLOAT32, use_double_precision_for_fft: bool = False, allow_nondeterministic_algorithms: bool = True, random_seed: int | None = None, displayed_loss_function: LossFunctions | None = LossFunctions.MSE_SQRT, exclude_measured_pixels_below: float | None = None, forward_model_options: ForwardModelOptions = <factory>, exit_wave_update_relaxation: float = 1, chunk_length: int = 1)[source]
Bases:
ReconstructorOptions- chunk_length: int = 1
Number of scan points used in each chunk of the difference map exit wave update loop. Smaller values are more memory efficient, but can be slower.
- get_reconstructor_type() Reconstructors[source]
- class ptychi.api.options.dm.DMObjectOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, slice_spacings_m: list | tuple | None = None, slice_spacing_options: SliceSpacingOptions = <factory>, pixel_size_m: float = 1.0, pixel_size_aspect_ratio: float = 1.0, l1_norm_constraint: ObjectL1NormConstraintOptions = <factory>, l2_norm_constraint: ObjectL2NormConstraintOptions = <factory>, smoothness_constraint: ObjectSmoothnessConstraintOptions = <factory>, total_variation: ObjectTotalVariationOptions = <factory>, hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase = <factory>, remove_grid_artifacts: RemoveGridArtifactsOptions = <factory>, multislice_regularization: ObjectMultisliceRegularizationOptions = <factory>, patch_interpolation_method: PatchInterpolationMethods = PatchInterpolationMethods.FOURIER, remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions = <factory>, build_preconditioner_with_all_modes: bool = False, determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = ObjectPosOriginCoordsMethods.SUPPORT, position_origin_coords: list | tuple | None = None, amplitude_clamp_limit: float = 1000, inertia: float = 0)[source]
Bases:
ObjectOptions
- class ptychi.api.options.dm.DMProbeOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, pixel_size_m: float | None = None, pixel_size_aspect_ratio: float | None = None, power_constraint: ProbePowerConstraintOptions = <factory>, orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions = <factory>, orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions = <factory>, support_constraint: ProbeSupportConstraintOptions = <factory>, center_constraint: ProbeCenterConstraintOptions = <factory>, eigenmode_update_relaxation: float = 1.0, inertia: float = 0)[source]
Bases:
ProbeOptions
- class ptychi.api.options.dm.DMProbePositionOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 0.3, optimizer_params: dict = <factory>, position_x_px: Tensor | ndarray | list | tuple | None = None, position_y_px: Tensor | ndarray | list | tuple | None = None, constrain_position_mean: bool = False, correction_options: PositionCorrectionOptions = <factory>, affine_transform_constraint: PositionAffineTransformConstraintOptions = <factory>)[source]
Bases:
ProbePositionOptions
- class ptychi.api.options.dm.DMOPRModeWeightsOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_weights: Tensor | ndarray | list | tuple | None = None, optimize_eigenmode_weights: bool = True, optimize_intensity_variation: bool = False, primary_mode_weight_floor: float | None = None, smoothing: OPRModeWeightsSmoothingOptions = <factory>, update_relaxation: float = 1.0)[source]
Bases:
OPRModeWeightsOptions
Relaxed Averaged Alternating Reflections (RAAR) Options
- class ptychi.api.options.raar.RAAROptions(data_options: PtychographyDataOptions = <factory>, reconstructor_options: RAARReconstructorOptions = <factory>, object_options: RAARObjectOptions = <factory>, probe_options: RAARProbeOptions = <factory>, probe_position_options: RAARProbePositionOptions = <factory>, opr_mode_weight_options: RAAROPRModeWeightsOptions = <factory>)[source]
Bases:
PtychographyTaskOptions- object_options: RAARObjectOptions
- opr_mode_weight_options: RAAROPRModeWeightsOptions
- probe_options: RAARProbeOptions
- probe_position_options: RAARProbePositionOptions
- reconstructor_options: RAARReconstructorOptions
Reconstructor Options
- class ptychi.api.options.raar.RAARReconstructorOptions(num_epochs: int = 100, batch_size: int = 100, batching_mode: BatchingModes = BatchingModes.RANDOM, compact_mode_update_clustering: bool = False, compact_mode_update_clustering_stride: int = 1, default_device: Devices = Devices.GPU, default_dtype: Dtypes = Dtypes.FLOAT32, use_double_precision_for_fft: bool = False, allow_nondeterministic_algorithms: bool = True, random_seed: int | None = None, displayed_loss_function: LossFunctions | None = LossFunctions.MSE_SQRT, exclude_measured_pixels_below: float | None = None, forward_model_options: ForwardModelOptions = <factory>, beta: float = 0.75, chunk_length: int = 1)[source]
Bases:
ReconstructorOptions- chunk_length: int = 1
Number of scan points processed together during exit-wave projections. Smaller values use less temporary memory, but can be slower.
- get_reconstructor_type() Reconstructors[source]
Object Options
- class ptychi.api.options.raar.RAARObjectOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, slice_spacings_m: list | tuple | None = None, slice_spacing_options: SliceSpacingOptions = <factory>, pixel_size_m: float = 1.0, pixel_size_aspect_ratio: float = 1.0, l1_norm_constraint: ObjectL1NormConstraintOptions = <factory>, l2_norm_constraint: ObjectL2NormConstraintOptions = <factory>, smoothness_constraint: ObjectSmoothnessConstraintOptions = <factory>, total_variation: ObjectTotalVariationOptions = <factory>, hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase = <factory>, remove_grid_artifacts: RemoveGridArtifactsOptions = <factory>, multislice_regularization: ObjectMultisliceRegularizationOptions = <factory>, patch_interpolation_method: PatchInterpolationMethods = PatchInterpolationMethods.FOURIER, remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions = <factory>, build_preconditioner_with_all_modes: bool = False, determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = ObjectPosOriginCoordsMethods.SUPPORT, position_origin_coords: list | tuple | None = None, amplitude_clamp_limit: float = 1000, inertia: float = 0)[source]
Bases:
ObjectOptions
Probe Options
- class ptychi.api.options.raar.RAARProbeOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, pixel_size_m: float | None = None, pixel_size_aspect_ratio: float | None = None, power_constraint: ProbePowerConstraintOptions = <factory>, orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions = <factory>, orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions = <factory>, support_constraint: ProbeSupportConstraintOptions = <factory>, center_constraint: ProbeCenterConstraintOptions = <factory>, eigenmode_update_relaxation: float = 1.0, inertia: float = 0)[source]
Bases:
ProbeOptions
Probe Position Options
- class ptychi.api.options.raar.RAARProbePositionOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 0.3, optimizer_params: dict = <factory>, position_x_px: Tensor | ndarray | list | tuple | None = None, position_y_px: Tensor | ndarray | list | tuple | None = None, constrain_position_mean: bool = False, correction_options: PositionCorrectionOptions = <factory>, affine_transform_constraint: PositionAffineTransformConstraintOptions = <factory>)[source]
Bases:
ProbePositionOptions
OPR Mode Weight Options
- class ptychi.api.options.raar.RAAROPRModeWeightsOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_weights: Tensor | ndarray | list | tuple | None = None, optimize_eigenmode_weights: bool = True, optimize_intensity_variation: bool = False, primary_mode_weight_floor: float | None = None, smoothing: OPRModeWeightsSmoothingOptions = <factory>, update_relaxation: float = 1.0)[source]
Bases:
OPRModeWeightsOptions
PIE Options
- class ptychi.api.options.pie.PIEOptions(data_options: PtychographyDataOptions = <factory>, reconstructor_options: PIEReconstructorOptions = <factory>, object_options: PIEObjectOptions = <factory>, probe_options: PIEProbeOptions = <factory>, probe_position_options: PIEProbePositionOptions = <factory>, opr_mode_weight_options: PIEOPRModeWeightsOptions = <factory>)[source]
Bases:
PtychographyTaskOptions- object_options: PIEObjectOptions
- opr_mode_weight_options: PIEOPRModeWeightsOptions
- probe_options: PIEProbeOptions
- probe_position_options: PIEProbePositionOptions
- reconstructor_options: PIEReconstructorOptions
- class ptychi.api.options.pie.PIEReconstructorOptions(num_epochs: int = 100, batch_size: int = 100, batching_mode: BatchingModes = BatchingModes.RANDOM, compact_mode_update_clustering: bool = False, compact_mode_update_clustering_stride: int = 1, default_device: Devices = Devices.GPU, default_dtype: Dtypes = Dtypes.FLOAT32, use_double_precision_for_fft: bool = False, allow_nondeterministic_algorithms: bool = True, random_seed: int | None = None, displayed_loss_function: LossFunctions | None = LossFunctions.MSE_SQRT, exclude_measured_pixels_below: float | None = None, forward_model_options: ForwardModelOptions = <factory>)[source]
Bases:
ReconstructorOptions- get_reconstructor_type() Reconstructors[source]
- class ptychi.api.options.pie.PIEObjectOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, slice_spacings_m: list | tuple | None = None, slice_spacing_options: SliceSpacingOptions = <factory>, pixel_size_m: float = 1.0, pixel_size_aspect_ratio: float = 1.0, l1_norm_constraint: ObjectL1NormConstraintOptions = <factory>, l2_norm_constraint: ObjectL2NormConstraintOptions = <factory>, smoothness_constraint: ObjectSmoothnessConstraintOptions = <factory>, total_variation: ObjectTotalVariationOptions = <factory>, hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase = <factory>, remove_grid_artifacts: RemoveGridArtifactsOptions = <factory>, multislice_regularization: ObjectMultisliceRegularizationOptions = <factory>, patch_interpolation_method: PatchInterpolationMethods = PatchInterpolationMethods.FOURIER, remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions = <factory>, build_preconditioner_with_all_modes: bool = False, determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = ObjectPosOriginCoordsMethods.SUPPORT, position_origin_coords: list | tuple | None = None, alpha: float = 0.1)[source]
Bases:
ObjectOptions
- class ptychi.api.options.pie.PIEProbeOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, pixel_size_m: float | None = None, pixel_size_aspect_ratio: float | None = None, power_constraint: ProbePowerConstraintOptions = <factory>, orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions = <factory>, orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions = <factory>, support_constraint: ProbeSupportConstraintOptions = <factory>, center_constraint: ProbeCenterConstraintOptions = <factory>, eigenmode_update_relaxation: float = 1.0, alpha: float = 0.1, experimental: PIEProbeExperimentalOptions = <factory>)[source]
Bases:
ProbeOptions- experimental: PIEProbeExperimentalOptions
- class ptychi.api.options.pie.PIEProbePositionOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 0.3, optimizer_params: dict = <factory>, position_x_px: Tensor | ndarray | list | tuple | None = None, position_y_px: Tensor | ndarray | list | tuple | None = None, constrain_position_mean: bool = False, correction_options: PositionCorrectionOptions = <factory>, affine_transform_constraint: PositionAffineTransformConstraintOptions = <factory>)[source]
Bases:
ProbePositionOptions
- class ptychi.api.options.pie.PIEOPRModeWeightsOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_weights: Tensor | ndarray | list | tuple | None = None, optimize_eigenmode_weights: bool = True, optimize_intensity_variation: bool = False, primary_mode_weight_floor: float | None = None, smoothing: OPRModeWeightsSmoothingOptions = <factory>, update_relaxation: float = 1.0)[source]
Bases:
OPRModeWeightsOptions
GM-rPIE and GM-MAGPIE Options
- class ptychi.api.options.magpie.MAGPIEOptions(data_options: PtychographyDataOptions = <factory>, reconstructor_options: MAGPIEReconstructorOptions = <factory>, object_options: MAGPIEObjectOptions = <factory>, probe_options: MAGPIEProbeOptions = <factory>, probe_position_options: MAGPIEProbePositionOptions = <factory>, opr_mode_weight_options: MAGPIEOPRModeWeightsOptions = <factory>)[source]
Bases:
PIEOptionsNative task options for GM-rPIE and GM-MAGPIE.
Both algorithms use
MAGPIEOptions. Setreconstructor_options.multigrid_levels = 1for GM-rPIE or a larger valid depth for GM-MAGPIE. The initial implementation supports one object slice and one coherent shared probe, random minibatches, and matching object/probe/detector sampling. Object and probe must both be optimized on every minibatch, with unit SGD settings and no step-size schedulers. Native gradient position correction and post-epoch constraints remain available.Object sampling must resolve to
ShiftOperators.PATCH. The defaultAUTOselection is accepted when it resolves toPATCH; near-field geometries with a probe approaching the object size can instead selectFULL_OBJECTand are rejected during setup. To use patch sampling for such a geometry, explicitly setreconstructor_options.forward_model_options.shift_operatortoenums.ShiftOperators.PATCH. Full-object sampling is unsupported because the synthesis assumes integer object-patch placement and fractional probe shifts.from ptychi.api import enums from ptychi.api.options import MAGPIEOptions from ptychi.api.task import PtychographyTask options = MAGPIEOptions() options.reconstructor_options.default_device = enums.Devices.CPU options.reconstructor_options.multigrid_levels = 1 # GM-rPIE # Supply your measured intensities, initial guesses, and positions. task = PtychographyTask( options, diffraction_data=intensities, object_data=object_guess, probe_data=probe_guess, probe_position_x_px=positions_x, probe_position_y_px=positions_y, ) task.run()
Probe synthesis approximates the reference algorithm’s weighted residual in common probe coordinates. Let \(S_k\) be the native padded probe shift, \(d_k=\widetilde P_k-S_kP\) the local geometric-mean probe correction, and \(\widetilde O_k\) the local geometric-mean object patch. Define \(T_k\) as the native coordinate shift with the opposite fractional displacement, using the same interpolation, replicate padding, and cropping. It differs from the actual padded adjoint \(S_k^*\).
The shared probe correction minimizes a nonnegative weighted consensus:
\[\begin{split}a_k &= S_k^*d_k, \\ c_k &= |T_k\widetilde O_k|^2, \\ \Delta P &= \underset{\delta}{\operatorname{argmin}}\; \frac12\sum_{k\in B}\left\| (T_k\widetilde O_k)\odot(\delta-a_k)\right\|_2^2 = \frac{\sum_{k\in B}c_k\odot a_k}{\sum_{k\in B}c_k}, \\ P_{\mathrm{new}} &= P+\Delta P.\end{split}\]Multiplication and division are elementwise; the displayed ratio applies where the total confidence is positive. The confidence has no floor or clipping. Zero total confidence uses the ordinary mean of the adjoint corrections. With finite intermediates, a singleton minibatch gives exactly its direct-adjoint correction, including a singleton at the end of a larger batch.
For ideal coordinate translations on a full or periodic domain, \(T_k=S_k^{-1}=S_k^*\), and translation preserves both the norm and pointwise products. Consequently,
\[\left\|\widetilde O_k\odot(S_k\delta-d_k)\right\|_2^2 =\left\|(T_k\widetilde O_k)\odot(\delta-S_k^*d_k)\right\|_2^2.\]Discrete interpolation does not generally preserve products, and padding makes the reverse coordinate shift different from the adjoint. The implemented consensus is therefore an approximation; it does not guarantee exact minimization or monotone decrease of the original weighted residual objective.
Initial object and probe arrays must contain only finite values. Every object pixel must have nonzero amplitude because exact-zero object pixels cannot be updated by the geometric mean. The probe must contain at least one nonzero value; individual zero probe pixels are allowed. The constructed arrays are checked after dtype conversion, before reconstruction starts. Invalid values raise
MAGPIEInitializationErrorduring setup.ptychi.api.task.PtychographyTaskvalidates the complete options configuration before constructing parameters. When constructing parameters andMAGPIEReconstructordirectly, calloptions.check()on a completeMAGPIEOptionsconfiguration first, use its corresponding parameter and reconstructor options, and callreconstructor.build()before reconstruction. The reconstructor’scheck_inputs()validates constructed data and forward-model compatibility; it does not repeat the options-validation hierarchy.- object_options: MAGPIEObjectOptions
- opr_mode_weight_options: MAGPIEOPRModeWeightsOptions
- probe_options: MAGPIEProbeOptions
- probe_position_options: MAGPIEProbePositionOptions
- reconstructor_options: MAGPIEReconstructorOptions
- class ptychi.api.options.magpie.MAGPIEReconstructorOptions(num_epochs: int = 100, batch_size: int = 100, batching_mode: BatchingModes = BatchingModes.RANDOM, compact_mode_update_clustering: bool = False, compact_mode_update_clustering_stride: int = 1, default_device: Devices = Devices.GPU, default_dtype: Dtypes = Dtypes.FLOAT32, use_double_precision_for_fft: bool = False, allow_nondeterministic_algorithms: bool = True, random_seed: int | None = None, displayed_loss_function: LossFunctions | None = LossFunctions.MSE_SQRT, exclude_measured_pixels_below: float | None = None, forward_model_options: ForwardModelOptions = <factory>, multigrid_levels: int = 1)[source]
Bases:
PIEReconstructorOptionsSettings for GM-rPIE (one level) or GM-MAGPIE (multiple levels).
Both algorithms use random minibatches, one object slice, one coherent shared probe, and matching object/probe/detector sampling. Resampling, OPR, and detector blur are not supported. Object and probe updates are synthesized together from their pre-update state and applied directly. Native gradient position correction and post-epoch constraints remain available.
- forward_model_options: ForwardModelOptions
Native forward-model options, with one-pixel subpixel-shift padding.
Only
ShiftOperators.PATCHsampling is supported.AUTOis accepted when it resolves toPATCHfor the constructed geometry. Detector blur is disabled; a zero blur sigma is normalized toNone.
- get_reconstructor_type() Reconstructors[source]
- multigrid_levels: int = 1
Number of object grid levels, including the original resolution.
Use 1 for GM-rPIE or a larger value for GM-MAGPIE. Each additional level halves each spatial dimension using 2-by-2 block averaging. The requested depth must fit the probe shape; excessive depths raise an error rather than being reduced silently.
- class ptychi.api.options.magpie.MAGPIEObjectOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, slice_spacings_m: list | tuple | None = None, slice_spacing_options: SliceSpacingOptions = <factory>, pixel_size_m: float = 1.0, pixel_size_aspect_ratio: float = 1.0, l1_norm_constraint: ObjectL1NormConstraintOptions = <factory>, l2_norm_constraint: ObjectL2NormConstraintOptions = <factory>, smoothness_constraint: ObjectSmoothnessConstraintOptions = <factory>, total_variation: ObjectTotalVariationOptions = <factory>, hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase = <factory>, remove_grid_artifacts: RemoveGridArtifactsOptions = <factory>, multislice_regularization: ObjectMultisliceRegularizationOptions = <factory>, patch_interpolation_method: PatchInterpolationMethods = PatchInterpolationMethods.FOURIER, remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions = <factory>, build_preconditioner_with_all_modes: bool = False, determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = ObjectPosOriginCoordsMethods.SUPPORT, position_origin_coords: list | tuple | None = None, alpha: float = 0.1)[source]
Bases:
PIEObjectOptionsA single directly represented object slice, updated every minibatch.
The inherited
alphais the nonnegative rPIE regularization factor used by the local object proposals.step_sizemust be 1, with plain SGD and no scheduler, since the synthesized update already incorporates its weights. Multislice propagation and slice-spacing refinement are unsupported.
- class ptychi.api.options.magpie.MAGPIEProbeOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, pixel_size_m: float | None = None, pixel_size_aspect_ratio: float | None = None, power_constraint: ProbePowerConstraintOptions = <factory>, orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions = <factory>, orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions = <factory>, support_constraint: ProbeSupportConstraintOptions = <factory>, center_constraint: ProbeCenterConstraintOptions = <factory>, eigenmode_update_relaxation: float = 1.0, alpha: float = 0.1, experimental: PIEProbeExperimentalOptions = <factory>)[source]
Bases:
PIEProbeOptionsOne directly represented coherent probe shared by all scan positions.
The inherited
alphais the nonnegative rPIE regularization factor used by local probe proposals. The probe is updated on every minibatch with unit SGD settings and no scheduler. Incoherent multimode probes, OPR, and synthesis-dictionary probe representations are unsupported.Local probe corrections use the native shift adjoint before being averaged with the intensity of each reverse-shifted local object patch. These weights are nonnegative without a floor or clipping. Zero total weight selects the ordinary mean; a singleton gives exactly the direct adjoint when the intermediates are finite. This coordinate-transport approximation differs from the reference synthesis and does not guarantee descent of its weighted residual objective for discrete padded shifts.
- class ptychi.api.options.magpie.MAGPIEProbePositionOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 0.3, optimizer_params: dict = <factory>, position_x_px: Tensor | ndarray | list | tuple | None = None, position_y_px: Tensor | ndarray | list | tuple | None = None, constrain_position_mean: bool = False, correction_options: PositionCorrectionOptions = <factory>, affine_transform_constraint: PositionAffineTransformConstraintOptions = <factory>)[source]
Bases:
PIEProbePositionOptionsNative gradient position correction, including its optimization schedule.
Cross-correlation position correction is not supported by this initial implementation.
- class ptychi.api.options.magpie.MAGPIEOPRModeWeightsOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_weights: Tensor | ndarray | list | tuple | None = None, optimize_eigenmode_weights: bool = True, optimize_intensity_variation: bool = False, primary_mode_weight_floor: float | None = None, smoothing: OPRModeWeightsSmoothingOptions = <factory>, update_relaxation: float = 1.0)[source]
Bases:
PIEOPRModeWeightsOptionsOPR and scan-dependent intensity weights are unsupported.
Keep weights fixed at unity and disable their optimization and smoothing. A single shared probe is used for every diffraction pattern.
LSQML Options
- class ptychi.api.options.lsqml.LSQMLOptions(data_options: PtychographyDataOptions = <factory>, reconstructor_options: LSQMLReconstructorOptions = <factory>, object_options: LSQMLObjectOptions = <factory>, probe_options: LSQMLProbeOptions = <factory>, probe_position_options: LSQMLProbePositionOptions = <factory>, opr_mode_weight_options: LSQMLOPRModeWeightsOptions = <factory>)[source]
Bases:
PtychographyTaskOptions- object_options: LSQMLObjectOptions
- opr_mode_weight_options: LSQMLOPRModeWeightsOptions
- probe_options: LSQMLProbeOptions
- probe_position_options: LSQMLProbePositionOptions
- reconstructor_options: LSQMLReconstructorOptions
- class ptychi.api.options.lsqml.LSQMLReconstructorOptions(num_epochs: int = 100, batch_size: int = 100, batching_mode: BatchingModes = BatchingModes.RANDOM, compact_mode_update_clustering: bool = False, compact_mode_update_clustering_stride: int = 1, default_device: Devices = Devices.GPU, default_dtype: Dtypes = Dtypes.FLOAT32, use_double_precision_for_fft: bool = False, allow_nondeterministic_algorithms: bool = True, random_seed: int | None = None, displayed_loss_function: LossFunctions | None = LossFunctions.MSE_SQRT, exclude_measured_pixels_below: float | None = None, forward_model_options: ForwardModelOptions = <factory>, noise_model: NoiseModels = NoiseModels.GAUSSIAN, gaussian_noise_std: float = 0.5, single_slice_solve_obj_prb_step_size_jointly: bool = True, multislice_solve_obj_prb_step_size_jointly: bool = False, solve_step_sizes_only_using_first_probe_mode: bool = True, momentum_acceleration_gain: float = 0.0, momentum_acceleration_gradient_mixing_factor: float | None = 1, rescale_probe_intensity_in_first_epoch: bool = True, preconditioning_damping_factor: float = 0.1)[source]
Bases:
ReconstructorOptions- check(options: LSQMLOptions)[source]
Check if options values are valid.
- gaussian_noise_std: float = 0.5
The standard deviation of the gaussian noise. Only used when noise_model == enums.NoiseModels.GAUSSIAN.
- get_reconstructor_type() Reconstructors[source]
- momentum_acceleration_gain: float = 0.0
The gain of momentum acceleration for object and probe. If 0, momentum acceleration is not used.
- momentum_acceleration_gradient_mixing_factor: float | None = 1
Controls how the current gradient is mixed with the accumulated velocity in LSQML momentum acceleration:
velocity = (1 - friction) * velocity + momentum_acceleration_gradient_mixing_factor * delta_o
If None, this mixing factor is automatically chosen to be friction:
velocity = (1 - friction) * velocity + friction * delta_o
Using None usually provides better stability. However, it may cause the speed of convergence to be too slow in some cases. Set this parameter to 1 to reproduce the behavior in PtychoShelves.
- multislice_solve_obj_prb_step_size_jointly: bool = False
Whether to solve the object/probe step size jointly for multislice objects at the first slice. Slices other than the first are always solved independently. For single-slice objects, use single_slice_solve_obj_prb_step_size_jointly instead.
- noise_model: NoiseModels = 'gaussian'
The noise model to use.
- preconditioning_damping_factor: float = 0.1
The damping factor for applying preconditioning to the object update, which is calculated as:
delta_o_hat = delta_o_hat / torch.sqrt(preconditioner ** 2 + (preconditioner.max() * mixing_factor) ** 2)
- rescale_probe_intensity_in_first_epoch: bool = True
If True, probe intensity is rescaled in the first epoch using the average intensity of all diffraction patterns. Set this to False if you want the probe intensity to stay constant. You may also want to check ObjectOptions.remove_object_probe_ambiguity.
- class ptychi.api.options.lsqml.LSQMLObjectOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, slice_spacings_m: list | tuple | None = None, slice_spacing_options: SliceSpacingOptions = <factory>, pixel_size_m: float = 1.0, pixel_size_aspect_ratio: float = 1.0, l1_norm_constraint: ObjectL1NormConstraintOptions = <factory>, l2_norm_constraint: ObjectL2NormConstraintOptions = <factory>, smoothness_constraint: ObjectSmoothnessConstraintOptions = <factory>, total_variation: ObjectTotalVariationOptions = <factory>, hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase = <factory>, remove_grid_artifacts: RemoveGridArtifactsOptions = <factory>, multislice_regularization: ObjectMultisliceRegularizationOptions = <factory>, patch_interpolation_method: PatchInterpolationMethods = PatchInterpolationMethods.FOURIER, remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions = <factory>, build_preconditioner_with_all_modes: bool = False, determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = ObjectPosOriginCoordsMethods.SUPPORT, position_origin_coords: list | tuple | None = None, optimal_step_size_scaler: float = 0.9, multimodal_update: bool = True)[source]
Bases:
ObjectOptions
- class ptychi.api.options.lsqml.LSQMLProbeOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, pixel_size_m: float | None = None, pixel_size_aspect_ratio: float | None = None, power_constraint: ProbePowerConstraintOptions = <factory>, orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions = <factory>, orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions = <factory>, support_constraint: ProbeSupportConstraintOptions = <factory>, center_constraint: ProbeCenterConstraintOptions = <factory>, eigenmode_update_relaxation: float = 1.0, optimal_step_size_scaler: float = 0.9)[source]
Bases:
ProbeOptions
- class ptychi.api.options.lsqml.LSQMLProbePositionOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 0.3, optimizer_params: dict = <factory>, position_x_px: Tensor | ndarray | list | tuple | None = None, position_y_px: Tensor | ndarray | list | tuple | None = None, constrain_position_mean: bool = False, correction_options: PositionCorrectionOptions = <factory>, affine_transform_constraint: PositionAffineTransformConstraintOptions = <factory>, momentum_acceleration_gain: float = 0.0, momentum_acceleration_gradient_mixing_factor: float | None = 1, momentum_acceleration_memory: int = 3)[source]
Bases:
ProbePositionOptions- check(options: LSQMLOptions)[source]
Check if options values are valid.
- momentum_acceleration_gain: float = 0.0
The gain of momentum acceleration for probe positions. If 0, momentum acceleration is not used.
- momentum_acceleration_gradient_mixing_factor: float | None = 1
Controls how the current position update is mixed with the accumulated velocity in probe-position momentum acceleration:
velocity = (1 - friction) * velocity + momentum_acceleration_gradient_mixing_factor * delta_pos
If None, this mixing factor is automatically chosen to be friction. Set this parameter to 1 to reproduce the behavior in foldslice.
- class ptychi.api.options.lsqml.LSQMLOPRModeWeightsOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_weights: Tensor | ndarray | list | tuple | None = None, optimize_eigenmode_weights: bool = True, optimize_intensity_variation: bool = False, primary_mode_weight_floor: float | None = None, smoothing: OPRModeWeightsSmoothingOptions = <factory>, update_relaxation: float = 1.0)[source]
Bases:
OPRModeWeightsOptions
Autodiff Ptychography Options
- class ptychi.api.options.ad_ptychography.AutodiffPtychographyOptions(data_options: PtychographyDataOptions = <factory>, reconstructor_options: AutodiffPtychographyReconstructorOptions = <factory>, object_options: AutodiffPtychographyObjectOptions = <factory>, probe_options: AutodiffPtychographyProbeOptions = <factory>, probe_position_options: AutodiffPtychographyProbePositionOptions = <factory>, opr_mode_weight_options: AutodiffPtychographyOPRModeWeightsOptions = <factory>)[source]
Bases:
PtychographyTaskOptions- object_options: AutodiffPtychographyObjectOptions
- opr_mode_weight_options: AutodiffPtychographyOPRModeWeightsOptions
- probe_options: AutodiffPtychographyProbeOptions
- probe_position_options: AutodiffPtychographyProbePositionOptions
- reconstructor_options: AutodiffPtychographyReconstructorOptions
- class ptychi.api.options.ad_ptychography.AutodiffPtychographyReconstructorOptions(num_epochs: int = 100, batch_size: int = 100, batching_mode: BatchingModes = BatchingModes.RANDOM, compact_mode_update_clustering: bool = False, compact_mode_update_clustering_stride: int = 1, default_device: Devices = Devices.GPU, default_dtype: Dtypes = Dtypes.FLOAT32, use_double_precision_for_fft: bool = False, allow_nondeterministic_algorithms: bool = True, random_seed: int | None = None, displayed_loss_function: LossFunctions | None = LossFunctions.MSE_SQRT, exclude_measured_pixels_below: float | None = None, forward_model_options: ForwardModelOptions = <factory>, loss_function: LossFunctions = LossFunctions.MSE_SQRT, forward_model_class: enums.ForwardModels | Type[fm.ForwardModel] = ForwardModels.PLANAR_PTYCHOGRAPHY, forward_model_params: dict | None = None)[source]
Bases:
AutodiffReconstructorOptions- forward_model_class: ForwardModels | Type[ForwardModel] = 'planar_ptychography'
The forward model class.
- get_reconstructor_type() Reconstructors[source]
- class ptychi.api.options.ad_ptychography.AutodiffPtychographyObjectOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, slice_spacings_m: list | tuple | None = None, slice_spacing_options: SliceSpacingOptions = <factory>, pixel_size_m: float = 1.0, pixel_size_aspect_ratio: float = 1.0, l1_norm_constraint: ObjectL1NormConstraintOptions = <factory>, l2_norm_constraint: ObjectL2NormConstraintOptions = <factory>, smoothness_constraint: ObjectSmoothnessConstraintOptions = <factory>, total_variation: ObjectTotalVariationOptions = <factory>, hard_limits_magnitude_phase: ObjectHardLimitsMagnitudePhase = <factory>, remove_grid_artifacts: RemoveGridArtifactsOptions = <factory>, multislice_regularization: ObjectMultisliceRegularizationOptions = <factory>, patch_interpolation_method: PatchInterpolationMethods = PatchInterpolationMethods.FOURIER, remove_object_probe_ambiguity: RemoveObjectProbeAmbiguityOptions = <factory>, build_preconditioner_with_all_modes: bool = False, determine_position_origin_coords_by: ObjectPosOriginCoordsMethods = ObjectPosOriginCoordsMethods.SUPPORT, position_origin_coords: list | tuple | None = None, experimental: AutodiffPtychographyObjectExperimentalOptions = <factory>)[source]
Bases:
ObjectOptions- experimental: AutodiffPtychographyObjectExperimentalOptions
- class ptychi.api.options.ad_ptychography.AutodiffPtychographyProbeOptions(optimizable: bool = True, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_guess: Tensor | ndarray | list | tuple | None = None, pixel_size_m: float | None = None, pixel_size_aspect_ratio: float | None = None, power_constraint: ProbePowerConstraintOptions = <factory>, orthogonalize_incoherent_modes: ProbeOrthogonalizeIncoherentModesOptions = <factory>, orthogonalize_opr_modes: ProbeOrthogonalizeOPRModesOptions = <factory>, support_constraint: ProbeSupportConstraintOptions = <factory>, center_constraint: ProbeCenterConstraintOptions = <factory>, eigenmode_update_relaxation: float = 1.0, experimental: AutodiffPtychographyProbeExperimentalOptions = <factory>)[source]
Bases:
ProbeOptions- experimental: AutodiffPtychographyProbeExperimentalOptions
- class ptychi.api.options.ad_ptychography.AutodiffPtychographyProbePositionOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 0.3, optimizer_params: dict = <factory>, position_x_px: Tensor | ndarray | list | tuple | None = None, position_y_px: Tensor | ndarray | list | tuple | None = None, constrain_position_mean: bool = False, correction_options: PositionCorrectionOptions = <factory>, affine_transform_constraint: PositionAffineTransformConstraintOptions = <factory>)[source]
Bases:
ProbePositionOptions
- class ptychi.api.options.ad_ptychography.AutodiffPtychographyOPRModeWeightsOptions(optimizable: bool = False, optimization_plan: OptimizationPlan = <factory>, optimizer: Optimizers = Optimizers.SGD, step_size: float = 1, optimizer_params: dict = <factory>, initial_weights: Tensor | ndarray | list | tuple | None = None, optimize_eigenmode_weights: bool = True, optimize_intensity_variation: bool = False, primary_mode_weight_floor: float | None = None, smoothing: OPRModeWeightsSmoothingOptions = <factory>, update_relaxation: float = 1.0)[source]
Bases:
OPRModeWeightsOptions