I/O Module

The homodyne.io module provides functions for saving and loading optimization results, experimental data, and analysis outputs.

Overview

Key Features:

  • JSON serialization of optimization results

  • NPZ file output for numerical data

  • JAX/NumPy array handling

  • MCMC diagnostic output formatting

Module Contents

I/O operations for homodyne XPCS analysis.

This module provides functions for saving and loading optimization results, experimental data, and analysis outputs.

Primary Functions

homodyne.io.save_nlsq_json_files

Save 3 JSON files: parameters, analysis results, convergence metrics.

homodyne.io.save_nlsq_npz_file

Save NPZ file with experimental/theoretical data and metadata.

homodyne.io.create_mcmc_parameters_dict

Create parameters dictionary with posterior statistics.

homodyne.io.create_mcmc_analysis_dict

Create analysis results dictionary for MCMC/CMC.

homodyne.io.create_mcmc_diagnostics_dict

Create diagnostics dictionary for MCMC/CMC.

homodyne.io.json_safe

Recursively convert numpy arrays and special types to JSON-safe types.

homodyne.io.json_serializer

JSON serializer for numpy arrays and other objects.

NLSQ Writers

Functions for saving NLSQ optimization results.

NLSQ result saving functions for homodyne XPCS analysis.

This module provides functions for saving NLSQ optimization results to disk, including JSON parameter files and NPZ data files. Extracted from cli/commands.py for better modularity.

homodyne.io.nlsq_writers.save_nlsq_json_files(param_dict, analysis_dict, convergence_dict, output_dir)[source]

Save 3 JSON files: parameters, analysis results, convergence metrics.

Parameters:
  • param_dict (dict[str, Any]) – Parameter dictionary with {name: {value, uncertainty}}

  • analysis_dict (dict[str, Any]) – Analysis results with method, fit_quality, dataset_info, etc.

  • convergence_dict (dict[str, Any]) – Convergence diagnostics with status, iterations, recovery_actions

  • output_dir (Path) – Output directory for JSON files

Returns:

Files saved to disk

Return type:

None

Notes

Creates 3 JSON files: - parameters.json: Complete parameter values and uncertainties - analysis_results_nlsq.json: Analysis summary and fit quality - convergence_metrics.json: Convergence diagnostics and device info

homodyne.io.nlsq_writers.save_nlsq_npz_file(phi_angles, c2_exp, c2_raw, c2_scaled, c2_solver, per_angle_scaling, per_angle_scaling_solver, residuals, residuals_norm, t1, t2, q, output_dir)[source]

Save NPZ file with experimental/theoretical data and metadata.

Parameters:
  • phi_angles (ndarray) – Scattering angles (n_angles,)

  • c2_exp (ndarray) – Experimental correlation data (n_angles, n_t1, n_t2)

  • c2_raw (ndarray) – Raw theoretical fits before scaling (n_angles, n_t1, n_t2)

  • c2_scaled (ndarray) – Scaled theoretical fits (n_angles, n_t1, n_t2)

  • c2_solver (ndarray | None) – Solver-evaluated theoretical fits (optional, n_angles, n_t1, n_t2)

  • per_angle_scaling (ndarray) – Per-angle scaling parameters (n_angles, 2) [contrast, offset]

  • per_angle_scaling_solver (ndarray) – Original per-angle scaling parameters from the solver (n_angles, 2)

  • residuals (ndarray) – Residuals: exp - scaled (n_angles, n_t1, n_t2)

  • residuals_norm (ndarray) – Normalized residuals (n_angles, n_t1, n_t2)

  • t1 (ndarray) – Time array 1 (n_t1,)

  • t2 (ndarray) – Time array 2 (n_t2,)

  • q (float) – Wavevector magnitude [1/Å]

  • output_dir (Path) – Output directory

Returns:

NPZ file saved to disk

Return type:

None

Output Files

NLSQ optimization produces two output files:

JSON Files (human-readable):

  • fit_results.json: Best-fit parameters, uncertainties, and metadata

  • optimization_diagnostics.json: Convergence information and iteration history

NPZ Files (numerical data):

  • fitted_data.npz: Arrays including fitted C2 surface, residuals, and per-angle scaling

MCMC Writers

Functions for saving MCMC/CMC optimization results.

MCMC result saving functions for homodyne XPCS analysis.

This module provides functions for creating dictionaries to save MCMC/CMC optimization results to disk. Extracted from cli/commands.py for better modularity.

homodyne.io.mcmc_writers.create_mcmc_parameters_dict(result)[source]

Create parameters dictionary with posterior statistics.

Parameters:

result (Any) – MCMC result with posterior samples and statistics

Returns:

Structured parameter dictionary with posterior mean ± std

Return type:

dict

homodyne.io.mcmc_writers.create_mcmc_analysis_dict(result, data, method_name)[source]

Create analysis results dictionary for MCMC/CMC.

Parameters:
  • result (Any) – MCMC result with diagnostics

  • data (dict[str, Any]) – Experimental data dictionary

  • method_name (str) – “mcmc” or “cmc”

Returns:

Analysis summary dictionary

Return type:

dict

homodyne.io.mcmc_writers.create_mcmc_diagnostics_dict(result)[source]

Create diagnostics dictionary for MCMC/CMC.

Parameters:

result (Any) – MCMC result with convergence diagnostics

Returns:

Diagnostics dictionary with convergence metrics

Return type:

dict

Output Structure

MCMC results are formatted for:

  • ArviZ-compatible posterior analysis

  • Publication-quality uncertainty reporting

  • Convergence diagnostic summaries

JSON Utilities

Helper functions for JSON serialization of scientific data.

JSON utility functions for homodyne I/O operations.

This module provides helper functions for JSON serialization of numpy arrays and other complex objects.

homodyne.io.json_utils.json_safe(value)[source]

Recursively convert numpy arrays and special types to JSON-safe types.

Parameters:

value (Any) – Value to convert (can be nested dict, list, numpy array, etc.)

Returns:

JSON-serializable version of the input

Return type:

Any

Examples

>>> json_safe(np.array([1, 2, 3]))
[1, 2, 3]
>>> json_safe({"arr": np.array([1.0, 2.0]), "val": np.float64(3.14)})
{'arr': [1.0, 2.0], 'val': 3.14}
homodyne.io.json_utils.json_serializer(obj)[source]

JSON serializer for numpy arrays and other objects.

Use as the default argument to json.dump/dumps.

Parameters:

obj (Any) – Object to serialize

Returns:

JSON-serializable version of the object

Return type:

Any

Raises:

TypeError – If object cannot be serialized (will be converted to string)

Examples

>>> import json
>>> json.dumps({"arr": np.array([1, 2, 3])}, default=json_serializer)
'{"arr": [1, 2, 3]}'

Supported Types

The JSON utilities handle:

  • NumPy arrays and scalars

  • JAX arrays (converted to NumPy)

  • Complex numbers

  • NaN and Inf values

  • Nested dictionaries and lists

Usage Examples

Saving NLSQ Results:

from pathlib import Path
from homodyne.io import save_nlsq_json_files, save_nlsq_npz_file

# Save JSON files (3 separate dicts: parameters, analysis, convergence)
save_nlsq_json_files(
    param_dict=param_dict,
    analysis_dict=analysis_dict,
    convergence_dict=convergence_dict,
    output_dir=Path("./results"),
)

# Save NPZ file (arrays for fitted data, residuals, scaling)
save_nlsq_npz_file(
    phi_angles=phi_angles,
    c2_exp=c2_exp,
    c2_raw=c2_raw,
    c2_scaled=c2_scaled,
    c2_solver=c2_solver,
    per_angle_scaling=per_angle_scaling,
    per_angle_scaling_solver=per_angle_scaling_solver,
    residuals=residuals,
    output_dir=Path("./results"),
)

Creating MCMC Output:

from homodyne.io import create_mcmc_parameters_dict, create_mcmc_diagnostics_dict

# Format parameters for output (takes the full CMCResult)
params = create_mcmc_parameters_dict(result=cmc_result)

# Format diagnostics (takes the full CMCResult)
diagnostics = create_mcmc_diagnostics_dict(result=cmc_result)

JSON-Safe Conversion:

from homodyne.io import json_safe
import numpy as np

# Convert arrays to JSON-serializable format
data = {'array': np.array([1.0, 2.0, 3.0])}
safe_data = json_safe(data)

See Also

  • homodyne.optimization - Optimization result classes

  • homodyne.viz - Visualization of results

  • homodyne.config - Configuration management