pyextal.hdf5io.refinement

JAX refinement runs: /refinement/run_NNN.

Provides load_for_refinement / save_refinement / list_refinement_runs, and load_refinement_run for reading a run’s results back (physical units). JAX is imported only inside the functions that need it.

The /refinement group inside the HDF5 file holds one subgroup per optimization run, so multiple configurations can be compared within a single dataset file.

Layout of each run group

refinement/run_NNN/

attrs: timestamp, notes, + scalar OptConfig fields optimized_sf (n_reflections, 4) [xfre, xfim, afre, afim] gvectors (n_reflections, 3) thickness_ratio (n_layers,) simulated_data (n_beams, n_rows, n_cols) loss_history (n_steps,) crystal_dat str – the .dat the run used (attrs name, sha1) maps/ potential/charge maps made from the run (see save_map) history/

steps (n_snapshots,) optimizer step each snapshot was taken at structure_factor (n_snapshots, n_reflections, 4) physical units thickness (n_snapshots, n_layers) Angstrom intensity_scale, background, probe_sigma, probe_gamma (n_snapshots,)

metadata/

sg_batch, bigkz_batch, bigkn_batch, ig_batch, output_indices_reordered, mask, static_ughr, static_ughi, reflection_list, phase_real, phase_imag, bounds_json (attr — JSON string for upperbound/lowerbound/norm_mask)

Attributes

Classes

RefinedRun

A refinement run's structure factors and thickness, in physical units.

Functions

load_for_refinement(h5path)

Load pre-refinement data from HDF5 ready for the JAX optimizer.

save_refinement(h5path, config, optimized_param, ...)

Append a new run_NNN group to /refinement/ with all JAX optimization results.

list_refinement_runs(h5path)

Return a summary list of all refinement runs stored in the HDF5 file.

snapshot_steps(num_steps[, offset, every])

The optimizer step index of each snapshot optimize() keeps.

_save_param_history(grp, param_hist, metadata, steps, ...)

Write the parameter trajectory under history/ as plain arrays.

_refl_key(text)

'(np.int16(1), np.int16(-1), 0)' or '(1, -1, 0)' -> (1, -1, 0).

_denorm(p, lower, upper, mask)

jaxEngine.setParams.denorm_fn on plain numbers (bool before int).

_beam_table(layer_dict)

Per-layer {str(refl): {comp: value}} from bounds_json, keyed by hkl.

_resolve_run(ref, run)

load_refinement_run(h5path[, run])

Reads a refinement run's results in physical units.

Module Contents

pyextal.hdf5io.refinement.load_for_refinement(h5path)

Load pre-refinement data from HDF5 ready for the JAX optimizer.

Returns:

tilts jnp.array (n_rows, n_cols, 3) experimental_data jnp.array (n_rows, n_cols, n_beams) variance jnp.array (n_rows, n_cols, n_beams) geometry dict — thickness, scale, background, gl, rotation, allshift

Return type:

dict with keys

pyextal.hdf5io.refinement.save_refinement(h5path, config, optimized_param, metadata, loss_history, param_hist, sim, *, notes='', snapshot_steps=None, dat=None)

Append a new run_NNN group to /refinement/ with all JAX optimization results.

Each call creates the next run group (run_001, run_002, …) so multiple configurations can be saved to the same dataset file and compared.

Parameters:
  • h5path (path-like)

  • config (OptConfig namedtuple)

  • optimized_param (dict — output of optimize())

  • metadata (dict — output of setup_optimization_params())

  • loss_history (list of floats)

  • param_hist (list of param dicts (snapshots every N steps))

  • sim (array (n_rows, n_cols, n_beams) — output of simulate())

  • notes (str — human-readable label for this run (e.g. "3layers_chi2_lr1e-3"))

  • snapshot_steps (sequence of int, optional — the optimizer step each entry of) – param_hist was taken at, for the x axis of a trajectory plot. Use snapshot_steps() to build it. Falls back to even spacing across loss_history when omitted, which is right only if the snapshots are evenly spaced.

  • dat (path-like, optional — the .dat the run used; its text is embedded) – as crystal_dat so the run can be re-simulated or mapped later without the file at hand.

Return type:

str — the run key used (e.g. “run_003”)

pyextal.hdf5io.refinement.list_refinement_runs(h5path)

Return a summary list of all refinement runs stored in the HDF5 file.

Returns:

list of dicts, each with keys

Return type:

run, timestamp, notes, num_steps, loss_final

pyextal.hdf5io.refinement.snapshot_steps(num_steps, offset=0, every=5)

The optimizer step index of each snapshot optimize() keeps.

optimize appends the starting parameters once, then appends again after every every-th step, so a run of num_steps steps produces snapshots at steps 0, 1, every+1, 2*every+1, … Pass offset when the run is one segment of a longer refinement (the geometry loop calls optimize several times), so the returned indices are absolute rather than per-segment.

Parameters:
  • num_steps (int) – Steps in this call to optimize.

  • offset (int) – Steps already completed before it.

  • every (int) – optimize’s snapshot interval.

Returns:

One entry per snapshot, same length as the returned param_history.

Return type:

list of int

pyextal.hdf5io.refinement._save_param_history(grp, param_hist, metadata, steps, n_steps)

Write the parameter trajectory under history/ as plain arrays.

The snapshots optimize() returns are nested dicts of JAX arrays holding normalised values, so np.array(param_hist) builds an object array that h5py refuses – which is why this used to land in its caller’s except every single time and no run ever carried a history. Denormalise each snapshot and split it into one array per quantity instead.

Thickness is stored in Angstrom: the forward model uses the parameter as a ratio of metadata[‘initial_thickness’] (see model.propagate’s caller), so the physical value is denormalised_ratio * initial_thickness.

Parameters:
  • grp (h5py.Group) – The run group.

  • param_hist (list) – Snapshots from optimize().

  • metadata (dict) – From setup_optimization_params; supplies the bounds, the norm mask and initial_thickness.

  • steps (sequence or None) – Step index per snapshot; even spacing across n_steps when None.

  • n_steps (int) – Length of the loss history, for the fallback spacing.

class pyextal.hdf5io.refinement.RefinedRun

A refinement run’s structure factors and thickness, in physical units.

Variables:
  • h5 (Path) – The dataset file.

  • key (str) – The run’s group name under /refinement (‘run_003’).

  • gvectors (np.ndarray) – (n, 3) refined reflections.

  • sf (np.ndarray) – (nlayers, n, 4) [xfre, xfim, afre, afim], denormalised when the run normalised them.

  • nlayers (int) – Layers in the run.

  • symmetry_constraint (str) – ‘SpaceGroup’ or ‘Friedel’.

  • thickness (np.ndarray) – (nlayers,) layer thickness in Angstrom.

  • notes (str) – The run’s notes.

h5: pathlib.Path
key: str
gvectors: numpy.ndarray
sf: numpy.ndarray
nlayers: int
symmetry_constraint: str
thickness: numpy.ndarray
notes: str = ''
pyextal.hdf5io.refinement._NP_SCALAR
pyextal.hdf5io.refinement._refl_key(text)

'(np.int16(1), np.int16(-1), 0)' or '(1, -1, 0)' -> (1, -1, 0).

pyextal.hdf5io.refinement._denorm(p, lower, upper, mask)

jaxEngine.setParams.denorm_fn on plain numbers (bool before int).

pyextal.hdf5io.refinement._beam_table(layer_dict)

Per-layer {str(refl): {comp: value}} from bounds_json, keyed by hkl.

pyextal.hdf5io.refinement._resolve_run(ref, run)
pyextal.hdf5io.refinement.load_refinement_run(h5path, run=None)

Reads a refinement run’s results in physical units.

optimized_sf is stored as the optimizer saw it, so when the run normalised its reflections (reflections_normalize) the values are mapped back through the bounds in metadata.attrs['bounds_json'], exactly as jaxEngine.setParams.denormalize_params does.

Parameters:
  • h5path (path-like) – The dataset file.

  • run (str or int, optional) – Run key (‘run_003’) or number; defaults to the latest run.

Returns:

RefinedRun