Configuration¶
Configuration management, the immutable parameter registry, parameter space definitions with dual prior system, and shared type aliases.
Config Manager¶
Configuration manager for heterodyne analysis.
- exception heterodyne.config.manager.ConfigurationError[source]
Bases:
ExceptionRaised when configuration is invalid.
- class heterodyne.config.manager.ConfigManager[source]
Bases:
objectManager for heterodyne analysis configuration.
Handles loading, validation, and access to configuration settings.
- __init__(config)[source]
Initialize with configuration dictionary.
- classmethod from_yaml(path)[source]
Load configuration from YAML file.
- classmethod from_dict(config)[source]
Create from dictionary.
- classmethod from_json(path)[source]
Load configuration from JSON file.
- property raw_config: dict[str, Any]
Get raw configuration dictionary (deep copy to prevent mutation).
- property data_file_path: Path
Path to experimental data file.
- property file_format: str
Data file format.
- property cache_file_path: Path | None
Directory for cache files (falls back to data_folder_path, then None).
- property cache_filename_template: str | None
Template for cache filenames with ${variable} substitution.
- property cache_compression: bool
Whether to compress cache files.
- property dt: float
Time step [seconds].
- property start_frame: int
Starting frame (1-indexed).
- property end_frame: int
Ending frame (1-indexed, inclusive).
- property time_length: int
Number of time points (derived from frame range).
- property t_start: int
Starting time index, 0-indexed (derived from start_frame).
- property wavevector_q: float
Scattering wavevector magnitude [Å⁻¹].
- get_parameter_value(group, name)[source]
Get a specific parameter value.
- get_parameter_vary(group, name)[source]
Check if parameter varies in optimization.
- property optimization_method: str
Optimization method (‘nlsq’ or ‘cmc’).
- property nlsq_config: dict[str, Any]
NLSQ optimization settings (returns a copy to prevent mutation).
- update_optimization_config(section, key, value)[source]
Update a single optimization config key in-place.
- get_config()[source]
Return a deep copy of the raw configuration dictionary.
- get_cmc_config()[source]
Return merged CMC config with defaults applied.
- property output_dir: Path
Output directory path.
Parameter Registry¶
Immutable MappingProxyType-based registry defining all 16 parameters
(14 physics + 2 scaling) with bounds, defaults, and prior specifications.
Parameter registry with metadata and bounds for heterodyne model.
All length units use Å (angstroms) for consistency with practical XPCS convention.
- class heterodyne.config.parameter_registry.ParameterInfo[source]
Bases:
objectMetadata for a single model parameter.
- name
Parameter name matching canonical order in parameter_names.py.
- default
Default value (must be within [min_bound, max_bound]).
- min_bound
Lower bound for optimization.
- max_bound
Upper bound for optimization.
- description
Human-readable description.
- unit
Physical unit string (e.g. “Ų/s^α”).
- group
Parameter group name.
- vary_default
Whether this parameter varies by default in optimization.
- log_space
If True, MCMC samplers should reparameterize in log-space.
- prior_mean
Center of the default Bayesian prior (None = midpoint of bounds).
- prior_std
Width of the default Bayesian prior (None = half-range of bounds).
- is_scaling
If True, this parameter participates in per-angle expansion.
- is_physical
If True, this is a physical model parameter (not scaling).
- is_flow
If True, this parameter is related to flow/velocity.
- name: str
- default: float
- min_bound: float
- max_bound: float
- description: str
- unit: str = ''
- group: str = ''
- vary_default: bool = True
- log_space: bool = False
- is_scaling: bool = False
- is_physical: bool = True
- is_flow: bool = False
- __init__(name, default, min_bound, max_bound, description, unit='', group='', vary_default=True, log_space=False, prior_mean=None, prior_std=None, is_scaling=False, is_physical=True, is_flow=False)
- class heterodyne.config.parameter_registry.ParameterRegistry[source]
Bases:
objectRegistry of all heterodyne model parameters with metadata.
- __getitem__(name)[source]
Get parameter info by name.
- Return type:
ParameterInfo
- __iter__()[source]
Iterate over parameter names in canonical order (14 physics + 2 scaling).
- get_bounds()[source]
Get (lower_bounds, upper_bounds) as lists.
- get_varying_indices(vary_flags)[source]
Get indices of parameters that vary in optimization.
- get_log_space_names()[source]
Get names of parameters that should be sampled in log-space.
- __init__(_parameters=<factory>)
Parameter Manager¶
Parameter manager for heterodyne model optimization.
- class heterodyne.config.parameter_manager.BoundDict[source]
Bases:
TypedDictBound specification for a single parameter.
- name: str
- min: float
- max: float
- type: str
- class heterodyne.config.parameter_manager.ParameterManager[source]
Bases:
objectManages parameter values, constraints, and transformations.
Provides the bridge between configuration and optimization by: - Managing which parameters vary vs are fixed - Handling parameter transformations (e.g., bounded -> unbounded) - Constructing full parameter arrays from varying subsets - Validating parameter values against physics constraints
Performance caching is enabled by default for repeated bound and active-parameter queries.
- space: ParameterSpace
- __post_init__()[source]
Build default bounds lookup from the registry, then merge config overrides.
- Return type:
- property n_params: int
Total number of physics model parameters (14).
- property n_varying: int
Number of physics parameters that vary in optimization.
- get_initial_values()[source]
Get initial parameter values for optimization.
Returns the config-specified starting point, not the current fitted state. Reads from the frozen snapshot set at construction time so that repeated calls (e.g. across multi-angle loops) always return the same config values even after model.set_params() has mutated space.values.
- Return type:
- Returns:
Array of shape (n_varying,) with initial values for varying params.
- get_full_values()[source]
Get all 14 parameter values.
Returns a read-only cached array (
writeable=False). Use.copy()if mutation is required.- Return type:
- Returns:
Array of shape (14,).
- get_bounds()[source]
Get bounds for varying physics parameters.
- expand_varying_to_full(varying_params)[source]
Expand varying parameters to full 14-parameter array.
Fixed parameters are filled from stored values.
- extract_varying(full_params)[source]
Extract varying parameters from full array.
- update_values(params)[source]
Update stored parameter values.
- get_parameter_dict()[source]
Get current parameter values as dictionary.
- set_vary(name, vary)[source]
Set whether a parameter varies in optimization.
Invalidates relevant caches.
- set_bounds(name, lower, upper)[source]
Set bounds for a parameter.
Invalidates the bounds cache for any query that includes this parameter.
- validate_physics(params=None)[source]
Validate parameters against physics constraints.
- classmethod from_config(config)[source]
Create ParameterManager from configuration dictionary.
- get_group_values(group)[source]
Get parameter values for a specific group.
- get_parameter_bounds(parameter_names=None)[source]
Get parameter bounds configuration with caching.
- Parameters:
parameter_names (
list[str] |None) – Names of parameters to retrieve bounds for. If None, returns bounds for all 16 parameters (14 physics + 2 scaling) in canonical order.- Return type:
list[BoundDict]- Returns:
List of BoundDict entries with keys ‘name’, ‘min’, ‘max’, ‘type’.
Notes
Results are cached per unique (sorted) parameter set. Cache is invalidated automatically by set_bounds().
- get_bounds_as_tuples(parameter_names=None)[source]
Get parameter bounds as a list of (min, max) tuples.
Convenience method for compatibility with optimization code that expects the scipy-style bounds format.
- get_bounds_as_arrays(parameter_names=None)[source]
Get parameter bounds as separate lower and upper numpy arrays.
Convenience method for NLSQ and JAX optimizers that consume separate lower/upper bound arrays.
- get_active_parameters()[source]
Get physics parameter names that are marked as varying.
Returns the 14-element physics parameters (excludes scaling) whose
varyflag is True in the current ParameterSpace. Falls back to all 14 physics parameters if the space has no explicit vary flags set.Results are cached; call set_vary() to invalidate automatically.
- get_all_parameter_names()[source]
Get all parameter names: scaling parameters first, then physics.
- get_effective_parameter_count()[source]
Number of active (varying) physics parameters, excluding scaling.
- Return type:
- Returns:
Count of physics parameters whose vary flag is True.
- get_total_parameter_count()[source]
Total parameter count including both scaling and physics parameters.
- Return type:
- Returns:
Always 16 for the heterodyne model (14 physics + 2 scaling).
- get_fixed_parameters()[source]
Return physics parameters that are held fixed during optimization.
A parameter is considered fixed when its
varyflag is False in the ParameterSpace. Scaling parameters (contrast, offset) are excluded from this result — use get_parameter_dict() to access their values.
- is_parameter_active(param_name)[source]
Check whether a physics parameter is active (vary=True).
- get_optimizable_parameters()[source]
Return physics parameters that should be optimized.
Equivalent to active parameters (vary=True). Scaling parameters are handled separately and are not included.
- validate_physical_constraints(params=None, severity_level='warning')[source]
Validate physics-based constraints beyond simple bound checking.
Checks for physically impossible or unusual parameter combinations based on the heterodyne two-component scattering model.
- Parameters:
params (
dict[str,float] |ndarray|None) – Parameter dict, array of shape (14,), or None to use stored values. Dict keys must be physics parameter names.severity_level (
str) – Minimum severity to include in the result. One of: -"error"— physically impossible values only. -"warning"— unusual but possible values (default). -"info"— all noteworthy observations. Currently the heterodyne validator does not distinguish severity internally; this argument is accepted for API parity with homodyne and is reserved for future use.
- Return type:
ValidationResult- Returns:
ValidationResult with
is_valid,errors, andwarnings.
- __init__(space=<factory>)
Parameter Space¶
Parameter space definition with prior distributions for Bayesian inference.
- class heterodyne.config.parameter_space.PriorType[source]
Bases:
EnumAvailable prior distribution types.
- UNIFORM = 'uniform'
- NORMAL = 'normal'
- TRUNCATED_NORMAL = 'truncated_normal'
- LOGNORMAL = 'lognormal'
- HALFNORMAL = 'halfnormal'
- EXPONENTIAL = 'exponential'
- BETA_SCALED = 'beta_scaled'
- class heterodyne.config.parameter_space.PriorDistribution[source]
Bases:
objectPrior distribution specification for a parameter.
- prior_type: PriorType
- classmethod uniform(low, high)[source]
Create uniform prior.
- Return type:
PriorDistribution
- classmethod normal(loc, scale)[source]
Create normal (Gaussian) prior.
- Return type:
PriorDistribution
- classmethod lognormal(loc, scale)[source]
Create log-normal prior (for positive parameters).
- Return type:
PriorDistribution
- classmethod halfnormal(scale)[source]
Create half-normal prior (for positive parameters).
- Return type:
PriorDistribution
- classmethod truncated_normal(loc, scale, low, high)[source]
Create truncated normal prior (bounded Gaussian).
- Return type:
PriorDistribution
- classmethod beta_scaled(low, high, concentration1, concentration2)[source]
Create a Beta prior scaled to [low, high].
The distribution is Beta(concentration1, concentration2) affine-transformed to the interval [low, high]. This is useful for bounded parameters where you want to express a prior belief about the shape within the bounds.
- Parameters:
- Return type:
PriorDistribution- Returns:
PriorDistribution with BETA_SCALED type.
- to_numpyro(name)[source]
Convert to NumPyro distribution.
- __init__(prior_type, params=<factory>)
- class heterodyne.config.parameter_space.ParameterSpace[source]
Bases:
objectComplete parameter space for heterodyne model optimization.
Manages parameter values, bounds, vary flags, and priors.
- property n_total: int
Total number of parameters.
- property n_varying: int
Number of parameters that vary in optimization.
- get_initial_array()[source]
Get initial values as numpy array in canonical order.
- Return type:
- Returns:
Array of shape (14,) with parameter values
- to_config()[source]
Serialize this space to a dict compatible with
from_config().Produces the
initial_parametersflat-format understood by_apply_initial_parameters(). Bounds and priors are not serialized — workers rebuild them from the registry defaults. Only values andactive_parameters(vary flags) are round-tripped.
- get_bounds_arrays()[source]
Get bounds as numpy arrays.
- get_vary_mask()[source]
Get boolean mask for varying parameters.
- Return type:
- Returns:
Boolean array of shape (14,)
- array_to_dict(arr)[source]
Convert parameter array to dictionary.
- update_from_dict(params)[source]
Update parameter values from dictionary.
- Parameters:
params (
dict[str,float]) – Dict with parameter names as keys- Raises:
ValueError – If a key doesn’t match any known parameter
- Return type:
- validate()[source]
Validate parameter space configuration.
Covers all 16 parameters (14 physics + 2 scaling) so a malformed
contrast/offsetbound is caught at config-load time instead of propagating into the optimizer.Bounds are checked for every parameter — varying and fixed — because fixed parameters still drive model outputs and CMC warm-starts. The one explicit exception: parameters in
_FIXED_ZERO_SENTINELS(currentlyv0) are allowed to be 0.0 when fixed, because their min_bound is an optimizer stability floor that does not apply when the optimizer never touches the value.
- convert_to_beta_priors()[source]
Convert all TruncatedNormal priors to BetaScaled priors.
For each parameter whose prior is TRUNCATED_NORMAL, this method computes equivalent Beta concentration parameters via the method of moments and replaces the prior in-place with a BETA_SCALED distribution over the same bounds.
Parameters with other prior types are left unchanged.
- Return type:
- with_single_angle_stabilization()[source]
Return a new ParameterSpace with tightened bounds for single-angle analysis.
Narrows contrast bounds to [value-0.2, value+0.2] and offset bounds to [value-0.1, value+0.1], clamped to the original bounds.
- Return type:
ParameterSpace- Returns:
A new ParameterSpace with tightened scaling bounds.
- classmethod from_config(config)[source]
Create ParameterSpace from configuration dictionary.
Supports two input formats (homodyne parity):
Grouped format (preferred) —
parameters.{group}.{param}:parameters: reference: D0_ref: value: 5000.0 min: 200.0 max: 50000.0 vary: true
Flat format —
initial_parameters.parameter_names+values:initial_parameters: parameter_names: [D0_ref, alpha_ref] values: [5000.0, 0.5] active_parameters: [D0_ref] # optional vary subset
When both are present, grouped format takes precedence (it is applied second so its values overwrite flat-format values).
- __init__(values=<factory>, vary=<factory>, bounds=<factory>, priors=<factory>)
- heterodyne.config.parameter_space.clamp_to_open_interval(value, low, high, epsilon=1e-6)[source]
Clamp value to the open interval (low+epsilon, high-epsilon).
Useful for Beta distribution parameters that must be strictly within their support bounds.
Parameter Names¶
Parameter name constants for 14-parameter heterodyne model.
The heterodyne model describes two-component correlation with: - Reference component: diffusive transport (D0_ref, alpha_ref, D_offset_ref) - Sample component: diffusive transport (D0_sample, alpha_sample, D_offset_sample) - Velocity field: time-dependent flow (v0, beta, v_offset) - Fraction: sample fraction evolution (f0, f1, f2, f3) - Angle: flow angle relative to q-vector (phi0)
- heterodyne.config.parameter_names.get_param_index(name)[source]
Get index of parameter in flattened array.
Type Aliases¶
TypedDict definitions for configuration structures.
- class heterodyne.config.types.ParameterConfig[source]
Bases:
TypedDictConfiguration for a single parameter.
- value: float
- min: float
- max: float
- vary: bool
- prior: NotRequired[str]
- prior_params: NotRequired[dict[str, float]]
- class heterodyne.config.types.ParameterGroupConfig[source]
Bases:
TypedDictConfiguration for a parameter group.
Keys use full parameter names matching parameter_space.from_config(). Group ‘reference’: D0_ref, alpha_ref, D_offset_ref Group ‘sample’: D0_sample, alpha_sample, D_offset_sample Group ‘velocity’: v0, beta, v_offset Group ‘fraction’: f0, f1, f2, f3 Group ‘angle’: phi0
- D0_ref: NotRequired[ParameterConfig]
- alpha_ref: NotRequired[ParameterConfig]
- D_offset_ref: NotRequired[ParameterConfig]
- D0_sample: NotRequired[ParameterConfig]
- alpha_sample: NotRequired[ParameterConfig]
- D_offset_sample: NotRequired[ParameterConfig]
- v0: NotRequired[ParameterConfig]
- beta: NotRequired[ParameterConfig]
- v_offset: NotRequired[ParameterConfig]
- f0: NotRequired[ParameterConfig]
- f1: NotRequired[ParameterConfig]
- f2: NotRequired[ParameterConfig]
- f3: NotRequired[ParameterConfig]
- phi0: NotRequired[ParameterConfig]
- class heterodyne.config.types.NLSQOptimizationConfig[source]
Bases:
TypedDictNLSQ optimization configuration.
- max_iterations: NotRequired[int]
- tolerance: NotRequired[float]
- method: NotRequired[str]
- multistart: NotRequired[bool]
- multistart_n: NotRequired[int]
- nlsq_prior_width_factor: NotRequired[float]
- class heterodyne.config.types.CMCOptimizationConfig[source]
Bases:
TypedDictCMC (Consensus Monte Carlo) configuration.
- enable: NotRequired[Literal['auto', 'always', 'never']]
- num_warmup: NotRequired[int]
- num_samples: NotRequired[int]
- num_chains: NotRequired[int]
- target_accept_prob: NotRequired[float]
- max_tree_depth: NotRequired[int]
- max_r_hat: NotRequired[float]
- class heterodyne.config.types.OptimizationConfig[source]
Bases:
TypedDictFull optimization configuration.
- method: str
- nlsq: NotRequired[NLSQOptimizationConfig]
- cmc: NotRequired[CMCOptimizationConfig]
- class heterodyne.config.types.ExperimentalDataConfig[source]
Bases:
TypedDictExperimental data file configuration.
- file_path: str
- data_folder_path: NotRequired[str]
- file_format: NotRequired[str]
- class heterodyne.config.types.TemporalConfig[source]
Bases:
TypedDictTemporal/timing configuration.
- dt: float
- time_length: int
- t_start: NotRequired[int]
- class heterodyne.config.types.ScatteringConfig[source]
Bases:
TypedDictScattering geometry configuration.
- wavevector_q: float
- phi_angles: NotRequired[list[float]]
- class heterodyne.config.types.OutputConfig[source]
Bases:
TypedDictOutput configuration.
- output_dir: NotRequired[str]
- save_correlation: NotRequired[bool]
- save_residuals: NotRequired[bool]
- format: NotRequired[str]
- class heterodyne.config.types.HeterodyneConfig[source]
Bases:
TypedDictComplete heterodyne analysis configuration.
- experimental_data: ExperimentalDataConfig
- temporal: TemporalConfig
- scattering: ScatteringConfig
- optimization: OptimizationConfig
- output: NotRequired[OutputConfig]
- class heterodyne.config.types.CMCShardingConfig[source]
Bases:
TypedDictSharding configuration for Consensus Monte Carlo.
- n_shards: NotRequired[int]
- shard_strategy: NotRequired[str]
- min_pairs_per_shard: NotRequired[int]
- class heterodyne.config.types.CMCInitializationConfig[source]
Bases:
TypedDictInitialization strategy for CMC chains.
- method: NotRequired[str]
- nlsq_chi2_threshold: NotRequired[float]
- jitter_scale: NotRequired[float]
- class heterodyne.config.types.CMCBackendConfig[source]
Bases:
TypedDictBackend configuration for CMC sampling.
- sampler: NotRequired[str]
- jit_compile: NotRequired[bool]
- progress_bar: NotRequired[bool]
- class heterodyne.config.types.CMCValidationConfig[source]
Bases:
TypedDictConvergence validation criteria for CMC.
- max_r_hat: NotRequired[float]
- min_ess: NotRequired[int]
- min_bfmi: NotRequired[float]
- max_divergences: NotRequired[int]
- class heterodyne.config.types.CMCCombinationConfig[source]
Bases:
TypedDictShard combination strategy for CMC.
- method: NotRequired[str]
- weights: NotRequired[list[float]]
- class heterodyne.config.types.CMCPerShardMCMCConfig[source]
Bases:
TypedDictPer-shard MCMC sampler settings.
- num_warmup: NotRequired[int]
- num_samples: NotRequired[int]
- num_chains: NotRequired[int]
- target_accept_prob: NotRequired[float]
- max_tree_depth: NotRequired[int]
- class heterodyne.config.types.StreamingConfig[source]
Bases:
TypedDictStreaming data ingestion configuration.
- enable: NotRequired[bool]
- chunk_size: NotRequired[int]
- buffer_size: NotRequired[int]
- class heterodyne.config.types.StratificationConfig[source]
Bases:
TypedDictData stratification configuration.
- enable: NotRequired[bool]
- n_strata: NotRequired[int]
- strategy: NotRequired[str]
- class heterodyne.config.types.SequentialConfig[source]
Bases:
TypedDictSequential optimization configuration.
- enable: NotRequired[bool]
- max_iterations: NotRequired[int]
- convergence_threshold: NotRequired[float]
- class heterodyne.config.types.HardwareConfig[source]
Bases:
TypedDictHardware and resource configuration.
- device: NotRequired[str]
- n_threads: NotRequired[int]
- memory_limit_gb: NotRequired[float]
- numa_aware: NotRequired[bool]
- class heterodyne.config.types.LoggingConfig[source]
Bases:
TypedDictLogging configuration.
- level: NotRequired[str]
- file: NotRequired[str]
- structured: NotRequired[bool]
- log_convergence: NotRequired[bool]
- class heterodyne.config.types.MetadataConfig[source]
Bases:
TypedDictExperiment metadata configuration.
- experiment_id: NotRequired[str]
- operator: NotRequired[str]
- beamline: NotRequired[str]
- sample_name: NotRequired[str]
- notes: NotRequired[str]
- class heterodyne.config.types.AnalysisConfig[source]
Bases:
TypedDictTop-level analysis configuration.
- method: str
- phi_angles: NotRequired[list[float]]
- q: NotRequired[float]
- dt: NotRequired[float]
- scaling_mode: NotRequired[str]
- class heterodyne.config.types.AnalyzerParametersConfig[source]
Bases:
TypedDictGrouped parameter configuration for the analyzer.
- reference: NotRequired[ParameterGroupConfig]
- sample: NotRequired[ParameterGroupConfig]
- velocity: NotRequired[ParameterGroupConfig]
- fraction: NotRequired[ParameterGroupConfig]
- angle: NotRequired[ParameterGroupConfig]
- scaling: NotRequired[ParameterGroupConfig]
- class heterodyne.config.types.HmcConfig[source]
Bases:
TypedDictHMC-specific sampler configuration.
- step_size: NotRequired[float]
- num_leapfrog_steps: NotRequired[int]
- adapt_step_size: NotRequired[bool]
- adapt_mass_matrix: NotRequired[bool]
- class heterodyne.config.types.PhiFilteringConfig[source]
Bases:
TypedDictPhi-angle filtering configuration.
- include_angles: NotRequired[list[float]]
- exclude_angles: NotRequired[list[float]]
- tolerance: NotRequired[float]