heterodyne.core.config
Configuration Management for Heterodyne Scattering Analysis
Centralized configuration system for XPCS analysis under nonequilibrium conditions. Provides JSON-based configuration management with validation, hierarchical parameter organization, and performance optimization features.
Key Features: - Hierarchical JSON configuration with validation - Runtime parameter override capabilities - Performance-optimized configuration access with caching - Comprehensive logging system with rotation and formatting - Physical parameter validation and bounds checking - Angle filtering configuration for computational efficiency - Test configuration management for different analysis scenarios
Configuration Structure: - analyzer_parameters: Core physics parameters (q-vector, time steps, geometry) - experimental_data: Data paths, file formats, and loading options - analysis_settings: Mode selection (static vs laminar flow) - optimization_config: Method settings, hyperparameters, angle filtering - parameter_space: Physical bounds, priors, and parameter constraints - performance_settings: Computational optimization flags
Authors: Wei Chen, Hongrui He Institution: Argonne National Laboratory
- class heterodyne.core.config.LoggingConfig[source]
Bases:
TypedDictTyped configuration for logging system.
- class heterodyne.core.config.AngleRange[source]
Bases:
TypedDictTyped configuration for angle filtering ranges.
- class heterodyne.core.config.AngleFilteringConfig[source]
Bases:
TypedDictTyped configuration for angle filtering.
- target_ranges: list[AngleRange]
- class heterodyne.core.config.OptimizationMethodConfig[source]
Bases:
TypedDictTyped configuration for optimization method parameters.
- class heterodyne.core.config.ClassicalOptimizationConfig[source]
Bases:
TypedDictTyped configuration for classical optimization methods.
- method_options: dict[str, OptimizationMethodConfig]
- class heterodyne.core.config.OptimizationConfig[source]
Bases:
TypedDictTyped configuration for optimization settings.
- angle_filtering: AngleFilteringConfig
- classical_optimization: ClassicalOptimizationConfig
- class heterodyne.core.config.ParameterBound[source]
Bases:
TypedDictTyped configuration for parameter bounds.
- class heterodyne.core.config.ParameterSpaceConfig[source]
Bases:
TypedDictTyped configuration for parameter space definition.
- bounds: list[ParameterBound]
- class heterodyne.core.config.InitialParametersConfig[source]
Bases:
TypedDictTyped configuration for initial parameter values.
- active_parameters: NotRequired[list[str]]
- class heterodyne.core.config.AnalysisSettings[source]
Bases:
TypedDictTyped configuration for analysis mode settings.
- static_submode: NotRequired[str]
- class heterodyne.core.config.ExperimentalDataConfig[source]
Bases:
TypedDictTyped configuration for experimental data paths.
- heterodyne.core.config.configure_logging(cfg=None, *, level=None, log_file=None)[source]
Configure centralized logging system with hierarchy and handlers.
This function sets up a complete logging infrastructure: - Creates a logger hierarchy (root + module logger) - Sets up RotatingFileHandler with size-based rotation - Optionally creates StreamHandler for console output - Applies consistent formatting and log levels
- Parameters:
cfg (dict, optional) – Logging configuration dictionary with keys: - log_to_file: bool, enable file logging - log_to_console: bool, enable console logging - log_filename: str, log file path - level: str, logging level (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’) - format: str, log message format string - rotation: dict with ‘max_bytes’ and ‘backup_count’
level (Any, optional) – Logging level for backward compatibility (can be string or logging constant)
log_file (str, optional) – Log file path for backward compatibility
- Returns:
Configured logger instance for reuse
- Return type:
- class heterodyne.core.config.ConfigManager(config_file='heterodyne_config.json', config=None)[source]
Bases:
objectCentralized configuration manager for heterodyne scattering analysis.
This class orchestrates the entire configuration system for XPCS analysis, providing structured access to all analysis parameters with validation, caching, and runtime override capabilities.
Core Responsibilities: - JSON configuration file loading with comprehensive error handling - Hierarchical parameter validation (physics, computation, file paths) - Performance-optimized configuration access through intelligent caching - Runtime configuration overrides for analysis mode switching - Logging system setup with rotation and appropriate formatting - Test configuration management for different experimental scenarios
Configuration Hierarchy: - analyzer_parameters: Physics parameters (q-vector, time steps, gap size) - experimental_data: Data file paths, loading options, caching settings - analysis_settings: Mode selection (static/laminar flow), model descriptions - optimization_config: Method settings, angle filtering, hyperparameters - parameter_space: Physical parameter bounds, prior distributions - performance_settings: Parallelization, computational optimizations - validation_rules: Data quality checks and minimum requirements - advanced_settings: Fine-tuning options for specialized use cases
- Usage:
config_manager = ConfigManager(‘my_config.json’) is_static = config_manager.is_static_mode_enabled() angle_ranges = config_manager.get_target_angle_ranges()
- __init__(config_file='heterodyne_config.json', config=None)[source]
Initialize configuration manager.
- load_config(config_file=None)[source]
Load and parse JSON configuration file with comprehensive error handling and security validation.
Implements performance-optimized loading with buffering, structure optimization for runtime access, security validation, and graceful fallback to default configuration if primary config fails.
Security Features: - Input validation and sanitization - Path traversal prevention - Configuration structure validation - Parameter bounds checking
Error Handling: - FileNotFoundError: Missing configuration file - JSONDecodeError: Malformed JSON syntax - ValidationError: Security validation failures - General exceptions: Unexpected loading issues
Performance Optimizations: - 8KB buffering for efficient file I/O - Configuration structure caching for fast access - Timing instrumentation for performance monitoring
- validate_config()[source]
Comprehensive validation of configuration parameters.
Performs multi-level validation to ensure configuration integrity:
Structural Validation: - Required sections presence (analyzer_parameters, experimental_data, etc.) - Configuration hierarchy completeness - Parameter type consistency
Physical Parameter Validation: - Frame range consistency (start < end, sufficient frames) - Wavevector positivity and reasonable magnitude - Time step positivity - Gap size physical reasonableness
Data Validation: - Minimum frame count requirements - Parameter bounds consistency - File path accessibility (optional)
- Raises:
ValueError – Invalid configuration parameters or structure
FileNotFoundError – Missing required data files (if validation enabled)
- Return type:
- validate_parameter_bounds(parameters)[source]
Validate that parameters are within the configured bounds.
- get_parameter(section, parameter, default=None)[source]
Get a parameter value from a specific configuration section.
- set_parameter(section, parameter, value)[source]
Set a parameter value in a specific configuration section.
- save_config(file_path)[source]
Save the current configuration to a JSON file.
- Parameters:
file_path (str) – Path where the configuration file should be saved
- Raises:
ValueError – If no configuration is loaded
FileNotFoundError – If the parent directory doesn’t exist
- Return type:
None
- setup_logging()[source]
Configure logging based on configuration using centralized configure_logging().
- Return type:
Logger | None
- get(*keys, default=None)[source]
Get nested configuration value.
- Parameters:
*keys (str) – Sequence of nested keys
default (any) – Default value if key not found
- Return type:
Configuration value or default
- get_angle_filtering_config()[source]
Get angle filtering configuration with defaults.
- Returns:
Angle filtering configuration including: - enabled: bool, whether angle filtering is enabled - target_ranges: list of dicts with min_angle and max_angle - fallback_to_all_angles: bool, whether to use all angles if no targets found
- Return type:
- is_angle_filtering_enabled()[source]
Check if angle filtering is enabled in configuration.
- Returns:
True if angle filtering should be used, False otherwise
- Return type:
- should_fallback_to_all_angles()[source]
Check if system should fallback to all angles when no targets found.
- Returns:
True if should fallback to all angles, False to raise error
- Return type:
- is_static_mode_enabled()[source]
Check if static mode is enabled in configuration.
DEPRECATED: Static mode has been removed in favor of the heterodyne model. This method now raises an error if static mode is detected.
- Returns:
Always returns False (static mode no longer supported)
- Return type:
- Raises:
ValueError – If static mode configuration is detected
- get_static_submode()[source]
Get the static sub-mode for analysis.
DEPRECATED: Static submodes have been removed.
- Returns:
Always returns None (static modes no longer supported)
- Return type:
str | None
- Raises:
ValueError – If static submode configuration is detected
- get_analysis_mode()[source]
Get the current analysis mode.
- Returns:
“heterodyne” - 14-parameter model
- Return type:
- get_effective_parameter_count()[source]
Get the effective number of model parameters.
- Returns:
Always returns 14 for the heterodyne model. The heterodyne model uses 14 parameters: - Reference transport coefficients (3): D0_ref, alpha_ref, D_offset_ref - Sample transport coefficients (3): D0_sample, alpha_sample, D_offset_sample - Velocity coefficients (3): v0, beta, v_offset - Fraction coefficients (4): f0, f1, f2, f3 - Flow angle (1): phi0
- Return type:
- get_default_14_parameters()[source]
Get default values for 14-parameter heterodyne model.
For backward compatibility, initializes sample parameters to match reference parameters (g1_sample = g1_ref initially).
- load_template(template_name)[source]
Load a configuration template by name.
- Parameters:
template_name (str) – Name of the template to load
- Returns:
Template configuration dictionary
- Return type:
- Raises:
ValueError – If template name is not found
FileNotFoundError – If template file doesn’t exist
- create_backup()[source]
Create a backup of the current configuration.
- Returns:
Deep copy of the current configuration
- Return type:
- Raises:
ValueError – If no configuration is loaded
- class heterodyne.core.config.PerformanceMonitor[source]
Bases:
objectPerformance monitoring and profiling utilities.
Provides lightweight profiling and memory monitoring for optimization of computational kernels.
- __call__(operation_name)[source]
Make PerformanceMonitor callable as a context manager.
- Parameters:
operation_name (str) – Name of the operation being monitored
- Returns:
Context manager for timing the operation
- Return type:
_TimingContext
- start(operation_name='default_operation')[source]
Start monitoring an operation.
- Parameters:
operation_name (str, optional) – Name of the operation being monitored
- Returns:
Context manager for timing the operation
- Return type:
_TimingContext
- time_function(func_name)[source]
Context manager for timing function execution.
- Parameters:
func_name (str) – Name of function being timed
Usage
-----
monitor.time_function("my_function") (with) – # function code here pass
- Return type:
_TimingContext