pyextal.hdf5io

HDF5 I/O: one file per dataset, from extraction to refinement and maps.

Layout

{sample}.h5 ├── attrs: crystal_dat (name), acquisition_prefix, date ├── crystal_dat str the extraction .dat’s text, when known (store_dat) ├── raw/ dp, variance, g_vectors save_raw ├── pre_refinement/ save_pre_refinement │ ├── attrs: thickness, scale, background, gl, rotation, grid_shape │ ├── simgrid (n_rows, n_cols, 3), templates / variance (n_beams, n_rows, n_cols) │ ├── roi_regions (n_regions, 4, 2), g_include (n_beams, 3), allshift (n_shifts, 2) │ └── crystal_dat str the pre-refinement .dat, when known └── refinement/

└── run_NNN/ save_refinement

├── attrs: timestamp, notes, scalar OptConfig fields ├── optimized_sf (nlayers*n_refl, 4), gvectors (n_refl, 3), │ thickness_ratio, simulated_data, loss_history, history/, metadata/ ├── crystal_dat str the .dat the run used └── maps/<name>/ potential / charge maps save_map

Modules: raw (raw and pre_refinement), refinement (runs), crystal (embedded .dat), maps (maps). Nothing here imports JAX at module level; the refinement writers import it when called.

Submodules

Classes

PreRefinementResult

RefinedRun

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

Functions

save_raw(h5path, dp, variance, g_vectors, *[, prefix, ...])

Write raw LARBED measurement into /raw of an HDF5 file.

save_pre_refinement(h5path, roi, fine, g_include)

Write pre-refinement outputs from a LARBEDROI + FineOptimize run to HDF5.

load_pre_refinement(h5path)

Load pre-refinement outputs.

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.

load_refinement_run(h5path[, run])

Reads a refinement run's results in physical units.

snapshot_steps(num_steps[, offset, every])

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

store_dat(group, dat_path)

Embeds a .dat file's text in an open HDF5 group, replacing any copy.

read_dat(group)

(name, text) of the .dat embedded in an open group, or None.

embedded_dat(h5[, run, n_beams, stage])

The embedded .dat locate_dat would pick, or None.

locate_dat(h5[, run, n_beams, stage])

Finds the .dat for a dataset file, and says how it was chosen.

dat_for(h5[, run, n_beams, stage])

The path of locate_dat's choice.

save_map(run, name, result[, overwrite])

Writes a pyextal.potentialMap.MapResult under its run.

load_map(run, name)

Reads a map written by save_map.

list_maps(run)

Summaries of the maps stored under a run.

Package Contents

class pyextal.hdf5io.PreRefinementResult

Bases: tuple

simgrid
templates
variance
roi_regions
geometry
g_include
grid_shape
pyextal.hdf5io.save_raw(h5path, dp, variance, g_vectors, *, prefix='', crystal_dat='', date='')

Write raw LARBED measurement into /raw of an HDF5 file.

Parameters:
  • h5path (path-like)

  • dp ((n_beams, ny, nx) array)

  • variance ((n_beams, ny, nx) array)

  • g_vectors ((n_beams, 3) int array — Miller indices)

  • prefix (optional provenance strings. When) – crystal_dat names an existing file its text is embedded as /crystal_dat (see store_dat) and the attr holds its name.

  • crystal_dat (optional provenance strings. When) – crystal_dat names an existing file its text is embedded as /crystal_dat (see store_dat) and the attr holds its name.

  • date (optional provenance strings. When) – crystal_dat names an existing file its text is embedded as /crystal_dat (see store_dat) and the attr holds its name.

pyextal.hdf5io.save_pre_refinement(h5path, roi, fine, g_include)

Write pre-refinement outputs from a LARBEDROI + FineOptimize run to HDF5.

Replaces the 6 np.save calls in the notebook export cell. The arrays are stored in 2D spatial form (n_rows, n_cols) so the file is self-describing.

Parameters:
  • h5path (path-like)

  • roi (LARBEDROI (must have had selectROI called — simGrid, templates, variance present))

  • fine (FineOptimize (must have been run — fine.thickness, fine.errorFunc.scale/.background))

  • g_include (list of (h,k,l) tuples — the reflections included in the ROI)

pyextal.hdf5io.load_pre_refinement(h5path)

Load pre-refinement outputs.

Returns:

simgrid (n_rows, n_cols, 3) templates (n_beams, n_rows, n_cols) variance (n_beams, n_rows, n_cols) roi_regions (n_regions, 4, 2) geometry dict — thickness, scale, background, gl, rotation, allshift g_include (n_beams, 3) int array grid_shape (n_rows, n_cols)

Return type:

PreRefinementResult namedtuple with fields

class pyextal.hdf5io.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.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.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.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.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

pyextal.hdf5io.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.store_dat(group, dat_path)

Embeds a .dat file’s text in an open HDF5 group, replacing any copy.

Parameters:
  • group (h5py.Group) – Open, writable group (or the file itself).

  • dat_path (path-like) – The .dat.

pyextal.hdf5io.read_dat(group)

(name, text) of the .dat embedded in an open group, or None.

pyextal.hdf5io.embedded_dat(h5, run=None, n_beams=None, stage=None)

The embedded .dat locate_dat would pick, or None.

Args and order as in locate_dat, without its on-disk fallbacks.

Returns:

(Path, str).

Return type:

tuple or None

pyextal.hdf5io.locate_dat(h5, run=None, n_beams=None, stage=None)

Finds the .dat for a dataset file, and says how it was chosen.

In order: the copy embedded in refinement run; the one embedded for stage (‘pre_refinement’); the root copy; the dat named in a legacy /paths group; the one .dat beside the file whose out block lists n_beams reflections. File-level candidates (all but the run’s own copy) must list n_beams reflections when that is known, since pre-refinement and refinement can use different beam sets. n_beams defaults to the file’s experimental beam count.

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

  • run (str or int, optional) – Refinement run key (‘run_003’) or number.

  • n_beams (int, optional) – Reflections the .dat must output.

  • stage (str, optional) – Also look in this group’s embedded copy.

Returns:

(Path, str).

Return type:

tuple

Raises:

FileNotFoundError – If nothing qualifies.

pyextal.hdf5io.dat_for(h5, run=None, n_beams=None, stage=None)

The path of locate_dat’s choice.

pyextal.hdf5io.save_map(run, name, result, overwrite=False)

Writes a pyextal.potentialMap.MapResult under its run.

Parameters:
  • run (RefinedRun) – The run the map was made from.

  • name (str) – Map name, e.g. ‘proj110_potential’.

  • result (MapResult) – The maps.

  • overwrite (bool) – Replace an existing map of that name.

Returns:

The group path written.

Return type:

str

pyextal.hdf5io.load_map(run, name)

Reads a map written by save_map.

Returns:

MapResult

pyextal.hdf5io.list_maps(run)

Summaries of the maps stored under a run.

Returns:

name, kind, dim, layer, shape, timestamp.

Return type:

list of dict