Workflows, Interoperability & Provenance API#

Auto-Detection (pymorgan.detect)#

Universal format auto-detection and dispatching for PyMORGAN.

class pymorgan.detect.FormatMatch(dimension, data_type, confidence, reason, resolved_path)[source]#

Bases: object

Result of probing a file or directory for its PyMORGAN dataset format.

Parameters:
  • dimension (Literal['1D', '2D', 'steady_state', 'project', 'recipe'])

  • data_type (str)

  • confidence (float)

  • reason (str)

  • resolved_path (Path)

dimension: Literal['1D', '2D', 'steady_state', 'project', 'recipe']#
data_type: str#
confidence: float#
reason: str#
resolved_path: Path#
pymorgan.detect.detect_format(path, *, return_all=False)[source]#

Detect the PyMORGAN dataset/project/recipe format for path.

Parameters:
  • path (str | PathLike) – File or directory path to inspect.

  • return_all (bool) – When True, return a list of all matching FormatMatch entries ordered by descending confidence. When False (default), return the single highest-confidence match or None.

Return type:

FormatMatch | list[FormatMatch] | None

pymorgan.detect.load_auto(path, **kwargs)[source]#

Auto-detect the format at path and dispatch to the matching loader.

Parameters:

path (str | PathLike)

Glotaran / pyglotaran Interoperability (pymorgan.oneD.interop)#

Interoperability readers and writers for Glotaran / pyglotaran formats.

pymorgan.oneD.interop.read_glotaran_ascii(path)[source]#

Read a Glotaran / TIMP .ascii file (Time explicit or Wavelength explicit).

Parameters:

path (str | PathLike)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.interop.write_glotaran_ascii(dataset, path, *, orientation='time', signal_unit='mOD', use_corrected=True, detector=0)[source]#

Export a Dataset1D to Glotaran / TIMP .ascii format.

Parameters:
Return type:

Path

pymorgan.oneD.interop.read_glotaran_nc(path)[source]#

Read a Glotaran / pyglotaran NetCDF4 (CF-1.8 / HDF5) dataset (.nc).

Parameters:

path (str | PathLike)

Return type:

tuple[Any, Any, Any, dict, Any, Any, Any]

pymorgan.oneD.interop.write_glotaran_nc(dataset, path, *, signal_unit='mOD', use_corrected=True, detector=0, write_noise=True)[source]#

Export a Dataset1D as a CF-1.8 / NetCDF4-compatible .nc file.

Parameters:
Return type:

Path

FAIR HDF5 Metadata Helpers (pymorgan.hdf5_meta)#

FAIR / NeXus HDF5 metadata and compressed dataset helpers for PyMORGAN.

pymorgan.hdf5_meta.json_safe_value(val)[source]#

Recursively convert val to a JSON-serializable structure.

Returns (ok, converted) where ok is False for raw multi-element arrays or unsupported objects so caller mappings can drop them safely.

Parameters:

val (Any)

Return type:

tuple[bool, Any]

pymorgan.hdf5_meta.json_safe_units(mapping, *, drop_keys=frozenset({}))[source]#

Return a JSON-safe copy of mapping, dropping ndarray/excluded entries.

Parameters:
Return type:

dict[str, Any]

pymorgan.hdf5_meta.compute_source_sha256(source, *, max_bytes=52428800)[source]#

Return the hex SHA-256 of source if it is a regular file under max_bytes.

Parameters:
Return type:

str | None

pymorgan.hdf5_meta.extract_sample_info_metadata(units)[source]#

Collect sample-info strings and instrument metadata dictionaries from units.

Parameters:

units (dict[str, Any] | None)

Return type:

dict[str, Any]

pymorgan.hdf5_meta.write_fair_root_attrs(f, *, pymorgan_format, source=None, original_data_type=None, units=None, dataset=None, format_version='2.0')[source]#

Populate FAIR / NeXus root HDF5 attributes on f.

Parameters:
Return type:

None

pymorgan.hdf5_meta.restore_dataset_history(f, ds)[source]#

Restore processing history from history_json attr if supported by ds.

Parameters:

ds (Any)

Return type:

None

pymorgan.hdf5_meta.create_compressed_dataset(group, name, data, *, units=None, long_name=None, dtype=None)[source]#

Create a gzip+shuffle compressed HDF5 dataset with optional CF metadata attrs.

Parameters:
  • name (str)

  • data (Any)

  • units (str | None)

  • long_name (str | None)

pymorgan.hdf5_meta.serialize_chirp_fit(fit)[source]#

Serialize a ChirpFit dataclass to JSON.

Parameters:

fit (Any)

Return type:

str | None

pymorgan.hdf5_meta.deserialize_chirp_fit(raw_json)[source]#

Deserialize JSON created by serialize_chirp_fit() back into ChirpFit.

Parameters:

raw_json (str | bytes)

Processing Provenance & Script Export (pymorgan.provenance)#

Processing provenance, undo/redo history, and Python script export for PyMORGAN.

pymorgan.provenance.sanitize_params(params)[source]#

Return a JSON/TOML-safe parameter dictionary with None entries omitted.

Parameters:

params (Mapping[str, Any] | None)

Return type:

dict[str, Any]

pymorgan.provenance.format_step_label(op, params=None)[source]#

Build a concise human-readable label for a processing step.

Parameters:
Return type:

str

class pymorgan.provenance.ProcessingStep(op, params=<factory>, timestamp_utc=<factory>, label='')[source]#

Bases: object

Record of a single semantic processing operation applied to a dataset.

Parameters:
op: str#
params: dict[str, Any]#
timestamp_utc: str#
label: str = ''#
to_dict()[source]#

Serialize this step to a plain dictionary safe for JSON and TOML.

Return type:

dict[str, Any]

classmethod from_dict(data)[source]#

Reconstruct a ProcessingStep from a serialized dictionary.

Parameters:

data (Mapping[str, Any])

Return type:

ProcessingStep

class pymorgan.provenance.HistoryManager(*, max_snapshots=12)[source]#

Bases: object

Bounded undo/redo stack and semantic processing history for a dataset.

Parameters:

max_snapshots (int)

property steps: list[ProcessingStep]#

Ordered list of recorded processing steps.

property can_undo: bool#
property can_redo: bool#
property undo_label: str | None#
property redo_label: str | None#
property is_guarded: bool#
guard()[source]#

Re-entrancy guard preventing inner helper calls from recording extra steps.

Return type:

Iterator[None]

suppress()[source]#

Temporarily disable history recording (e.g. during internal GUI init).

Return type:

Iterator[None]

ensure_baseline(ds)[source]#

Capture the initial raw state once before the first recorded mutation.

Parameters:

ds (Any)

Return type:

None

record_call(ds, op, fn, *, params_fn=None, params=None, label='', coalesce=False, should_record=None)[source]#

Execute fn() inside the re-entrancy guard and record a step on success.

If fn() raises, no snapshot is pushed and history remains untouched.

Parameters:
commit_coalesced_external(ds, op, params, pre_snap=None, *, coalesce=True, label='')[source]#

Record or coalesce a step computed on a worker copy onto ds.

Parameters:
Return type:

None

update_last_step_param(op, key, value)[source]#

Update a parameter on the latest step if it matches op (e.g. post-save chirp path).

Parameters:
Return type:

bool

undo(ds)[source]#

Undo the most recent step (or coalesced step group) on ds.

Parameters:

ds (Any)

Return type:

bool

redo(ds)[source]#

Redo the most recently undone step on ds.

Parameters:

ds (Any)

Return type:

bool

reset_to_raw(ds)[source]#

Restore the raw initial baseline state and clear recorded history.

Parameters:

ds (Any)

Return type:

bool

revert_to(ds, step_index)[source]#

Revert ds to the state immediately after step_index (-1 = raw).

Parameters:
Return type:

bool

to_dicts()[source]#

Serialize all recorded steps as a list of plain dictionaries.

Return type:

list[dict[str, Any]]

load_dicts(items)[source]#

Replace recorded metadata steps from serialized dictionaries.

Parameters:

items (Sequence[Mapping[str, Any]])

Return type:

None

copy(*, deep=True)[source]#

Clone this manager without sharing mutable stack state.

Parameters:

deep (bool)

Return type:

HistoryManager

pymorgan.provenance.generate_python_script(ds, *, include_plot=True, include_settings=True, plot_kwargs=None)[source]#

Generate a clean, standalone, Ruff-valid Python script reproducing ds.

Parameters:
  • ds (Dataset1D or Dataset2D) – Processed dataset whose recorded history will be emitted.

  • include_plot (bool, default True) – Whether to append pm.apply_style(), a contour/map plot, and pm.show_plots().

  • include_settings (bool, default True) – Whether to emit pm.update_settings(...) for non-default settings.

  • plot_kwargs (mapping, optional) – Extra keyword arguments passed to ds.plot_contour(...) (1D) or ds.plot_map(...) (2D).

Return type:

str

Processing Recipes (pymorgan.recipe)#

Portable TOML processing recipes (.pmrecipe.toml) for PyMORGAN.

pymorgan.recipe.resolve_aux_path(raw_path, *, base_dir=None, dataset_source=None, fallback_abs=None)[source]#

Resolve an auxiliary file path against base_dir, dataset_source, or fallback_abs.

Parameters:
Return type:

Path

class pymorgan.recipe.Recipe(schema_version='1.0', name='Untitled Recipe', dimension='1D', data_type='auto', calibration_file=None, steps=<factory>, export_formats=<factory>, export_suffix='_PROCESSED', write_noise=True, description='')[source]#

Bases: object

Serializable, dataset-agnostic processing recipe (.pmrecipe.toml).

Parameters:
schema_version: str = '1.0'#
name: str = 'Untitled Recipe'#
dimension: Literal['1D', '2D'] = '1D'#
data_type: str = 'auto'#
calibration_file: str | None = None#
steps: list[dict[str, Any]]#
export_formats: list[str]#
export_suffix: str = '_PROCESSED'#
write_noise: bool = True#
description: str = ''#
classmethod from_dataset(ds, *, name=None, data_type=None, calibration_file=None, export_formats=None, export_suffix='_PROCESSED', write_noise=True, description='', base_dir=None)[source]#

Build a Recipe from a processed dataset’s recorded history.

Parameters:
Return type:

Recipe

to_dict(*, base_dir=None)[source]#

Serialize this recipe to a plain TOML/JSON-friendly dictionary.

Parameters:

base_dir (str | PathLike | None)

Return type:

dict[str, Any]

to_toml(*, base_dir=None)[source]#

Render this recipe as a commented TOML string.

Parameters:

base_dir (str | PathLike | None)

Return type:

str

save(path)[source]#

Save this recipe to path (.pmrecipe.toml).

Parameters:

path (str | PathLike)

Return type:

Path

classmethod from_dict(data)[source]#

Build a Recipe from a parsed TOML/JSON mapping.

Parameters:

data (Mapping[str, Any])

Return type:

Recipe

classmethod load(path)[source]#

Load and validate a Recipe from a .pmrecipe.toml file.

Parameters:

path (str | PathLike)

Return type:

Recipe

apply(dataset, *, base_dir=None)[source]#

Replay this recipe’s enabled steps onto dataset in-place and return it.

Parameters:

Batch Processing Engine (pymorgan.batch)#

Headless and GUI-callable batch processing engine for PyMORGAN.

class pymorgan.batch.BatchItemResult(input_path, data_type, status, elapsed_s=0.0, output_files=<factory>, error=None)[source]#

Bases: object

Result record for a single dataset in a batch run.

Parameters:
  • input_path (str)

  • data_type (str)

  • status (Literal['ok', 'error', 'skipped', 'cancelled', 'dry_run'])

  • elapsed_s (float)

  • output_files (list[str])

  • error (str | None)

input_path: str#
data_type: str#
status: Literal['ok', 'error', 'skipped', 'cancelled', 'dry_run']#
elapsed_s: float = 0.0#
output_files: list[str]#
error: str | None = None#
class pymorgan.batch.BatchReport(recipe_name, output_dir, total, succeeded, failed, skipped, cancelled=False, dry_run=False, elapsed_s=0.0, items=<factory>, report_csv=None, report_json=None)[source]#

Bases: object

Aggregated summary of a batch processing execution.

Parameters:
recipe_name: str#
output_dir: str#
total: int#
succeeded: int#
failed: int#
skipped: int#
cancelled: bool = False#
dry_run: bool = False#
elapsed_s: float = 0.0#
items: list[BatchItemResult]#
report_csv: str | None = None#
report_json: str | None = None#
pymorgan.batch.discover_batch_inputs(paths_or_dir, *, data_type='auto', dimension=None, glob_pattern=None, recursive=False)[source]#

Discover dataset files/folders suitable for batch processing.

Parameters:
  • paths_or_dir (path-like or iterable of path-like) – File path(s) or directory path(s) to scan.

  • data_type (str, default "auto") – Explicit PyMORGAN loader key (e.g. "PDAT", "P2DAT", "PyMESS_PP") or "auto" to sniff formats automatically.

  • dimension ({"1D", "2D"}, optional) – Filter auto-discovered inputs to a specific dimensionality.

  • glob_pattern (str, optional) – Optional filename wildcard pattern (e.g. "sample_*.pdat").

  • recursive (bool, default False) – Recurse into subdirectories when scanning folders.

Returns:

Sorted deduplicated list of (resolved_path, data_type) pairs.

Return type:

list of (Path, str)

pymorgan.batch.run_batch(inputs, recipe, output_dir, *, workers=1, on_error='skip', dry_run=False, base_dir=None, progress_callback=None, cancel_event=None)[source]#

Apply recipe across a sequence of dataset inputs and write reports.

Parameters:
  • inputs (sequence of path-like or (path, data_type) tuples) – Input datasets to process.

  • recipe (Recipe or path to .pmrecipe.toml) – Loaded Recipe instance or path to load one from.

  • output_dir (str or PathLike) – Directory where processed exports and batch_report.{csv,json} are saved.

  • workers (int, default 1) – Number of worker processes (workers > 1 uses ProcessPoolExecutor).

  • on_error ({"skip", "stop"}, default "skip") – Whether to continue past item errors ("skip") or abort remaining work.

  • dry_run (bool, default False) – If True, discover and report planned outputs without processing or writing files.

  • base_dir (str or PathLike, optional) – Base directory for resolving relative auxiliary files inside the recipe.

  • progress_callback (callable, optional) – Called as progress_callback(completed_count, total_count, item_result).

  • cancel_event (threading.Event-like, optional) – Object with is_set() -> bool checked between items for cooperative cancellation.

Return type:

BatchReport

pymorgan.batch.cli_main(argv=None)[source]#

CLI entrypoint for pymorgan batch and pymorgan-batch.

Parameters:

argv (Sequence[str] | None)

Return type:

int

Project Sessions (pymorgan.project)#

Portable TOML session/project files (.pmproj) for PyMORGAN.

pymorgan.project.resolve_session_path(entry, abs_fallback=None, *, base_dir=None, role='file', relocate_callback=None, warnings_out=None)[source]#

Resolve a project file/dir reference using relative first, then abs fallback, then callback.

Parameters:
Return type:

Path | None

class pymorgan.project.ProjectSession(schema_version='1.0', root_dir=None, root_dir_abs=None, active_tab=0, oneD=<factory>, twoD=<factory>, settings_overrides=<factory>, saved_utc='', project_path=None)[source]#

Bases: object

Serializable full workspace session (.pmproj) for PyMORGAN.

Parameters:
schema_version: str = '1.0'#
root_dir: str | None = None#
root_dir_abs: str | None = None#
active_tab: int = 0#
oneD: dict[str, Any]#
twoD: dict[str, Any]#
settings_overrides: dict[str, Any]#
saved_utc: str = ''#
project_path: Path | None = None#
to_dict(*, base_dir=None)[source]#

Serialize session to a TOML/JSON-ready dictionary.

Parameters:

base_dir (str | PathLike | None)

Return type:

dict[str, Any]

to_toml(*, base_dir=None)[source]#

Render this project session as commented TOML.

Parameters:

base_dir (str | PathLike | None)

Return type:

str

save(path)[source]#

Save project session to path (typically ending in .pmproj).

Parameters:

path (str | PathLike)

Return type:

Path

classmethod from_dict(data)[source]#

Construct a ProjectSession from a parsed TOML dictionary.

Parameters:

data (Mapping[str, Any])

Return type:

ProjectSession

classmethod load(path)[source]#

Load a ProjectSession from a .pmproj file.

Parameters:

path (str | PathLike)

Return type:

ProjectSession

classmethod from_main_window(win, *, base_dir=None)[source]#

Snapshot full interactive workspace state from a MainWindow instance.

Parameters:
Return type:

ProjectSession

apply_to_main_window(win, *, relocate_callback=None)[source]#

Restore this session onto win, returning any non-fatal warning strings.

Parameters:
Return type:

list[str]