pycsamt.ai.inversion.config#

Configuration for pyCSAMT 1-D AI-based EM inversion.

The module exposes InversionConfig, a dataclass that collects every tuneable parameter for EMInverter1D — architecture, training loop, regularisation, checkpointing, and output.

The recommended workflow mirrors the pattern used by ModEmConfig and OccamConfig:

  1. Call InversionConfig.write_template() to generate a fully annotated source-of-truth file (Python, JSON, or YAML).

  2. Edit the file to reflect the desired architecture and training budget.

  3. Load the edited file with InversionConfig.from_file().

  4. Optionally call InversionConfig.validate() to catch range errors.

  5. Call InversionConfig.to_inverter() to get a ready-to-fit EMInverter1D.

  6. Call inv.fit(dataset, **cfg.to_fit_kwargs()) to train.

Quick start#

Generate a default template, edit it, train:

from pycsamt.ai.inversion.config import InversionConfig
from pycsamt.forward.batch import ForwardDataset

# 1 — write annotated source-of-truth file
InversionConfig.write_template("my_inversion.yml")

# 2 — edit my_inversion.yml …

# 3 — load and train
cfg = InversionConfig.from_file("my_inversion.yml")
cfg.validate()

ds = ForwardDataset.load("mt1d_train.npz")
inv = cfg.to_inverter()
inv.fit(ds, **cfg.to_fit_kwargs())
inv.save(cfg.checkpoint_path())

Snapshot a fitted inverter for reproducibility:

cfg = InversionConfig.from_inverter(inv)
cfg.write_template("snapshot.yml")

Classes

InversionConfig([arch, n_layers, solver, ...])

Collect settings that define a 1-D AI-based EM inversion run.

class pycsamt.ai.inversion.config.InversionConfig(arch='resnet', n_layers=5, solver='mt1d', device=None, include_phase=True, log_thickness=True, augment_noise=0.02, epochs=100, batch_size=256, lr=0.001, weight_decay=1e-05, patience=20, min_delta=1e-05, val_frac=0.1, grad_clip=1.0, seed=None, checkpoint_dir='checkpoints', checkpoint_name='em_inverter', save_best=True, verbose=True)[source]

Bases: object

Collect settings that define a 1-D AI-based EM inversion run.

InversionConfig is the configuration object for EMInverter1D. It covers four concern areas: network architecture, training hyperparameters, regularisation, and checkpoint management.

The recommended workflow:

  1. Generate a template with write_template().

  2. Edit the values in the generated file.

  3. Load the edited file with from_file().

  4. Optionally call validate() to catch range errors.

  5. Call to_inverter() to instantiate a ready-to-fit EMInverter1D.

  6. Pass to_fit_kwargs() to inv.fit(dataset, **cfg.to_fit_kwargs()).

Parameters:
  • arch ({'resnet', 'cnn1d', 'fcn'}) – Network architecture.

  • n_layers (int) – Number of earth layers (including halfspace).

  • solver ({'mt1d', 'csamt1d', 'tem1d'}) – Forward solver this inverter targets.

  • device (str or None) – Compute device; None auto-detects (CUDA > MPS > CPU).

  • include_phase (bool) – Include impedance phase in the input feature vector.

  • log_thickness (bool) – Apply log10 to thickness targets during training.

  • augment_noise (float) – On-the-fly per-epoch noise augmentation level.

  • epochs (int) – Maximum training epochs.

  • batch_size (int) – Mini-batch size.

  • lr (float) – Initial Adam learning rate.

  • weight_decay (float) – Adam L2 regularisation coefficient.

  • patience (int) – Early-stopping patience (epochs without improvement).

  • min_delta (float) – Minimum validation-loss decrease to count as an improvement.

  • val_frac (float) – Fraction of data used for validation.

  • grad_clip (float or None) – Gradient-norm clipping threshold; None disables clipping.

  • seed (int or None) – Random seed for train/val split.

  • checkpoint_dir (str or None) – Directory for checkpoint files; None disables auto-saving.

  • checkpoint_name (str) – Base file name for checkpoints (without extension).

  • save_best (bool) – Auto-save the best checkpoint after training.

  • verbose (bool) – Print training progress.

Examples

Default configuration (ResNet, 5 layers, MT1D):

>>> cfg = InversionConfig()
>>> cfg.arch
'resnet'

Deep ResNet for a crystalline-crust survey:

>>> cfg = InversionConfig(
...     arch="resnet",
...     n_layers=6,
...     solver="mt1d",
...     epochs=300,
...     lr=5e-4,
...     seed=0,
... )

Round-trip template:

>>> path = InversionConfig.write_template("inv_config.yml")
>>> cfg = InversionConfig.from_file(path)
>>> cfg.solver
'mt1d'

Snapshot a fitted inverter:

>>> cfg = InversionConfig.from_inverter(inv)
>>> cfg.write_template("run_snapshot.py")
arch: str = 'resnet'
n_layers: int = 5
solver: str = 'mt1d'
device: str | None = None
include_phase: bool = True
log_thickness: bool = True
augment_noise: float = 0.02
epochs: int = 100
batch_size: int = 256
lr: float = 0.001
weight_decay: float = 1e-05
patience: int = 20
min_delta: float = 1e-05
val_frac: float = 0.1
grad_clip: float | None = 1.0
seed: int | None = None
checkpoint_dir: str | None = 'checkpoints'
checkpoint_name: str = 'em_inverter'
save_best: bool = True
verbose: bool = True
validate()[source]

Check parameter ranges and raise ValueError on errors.

Raises:

ValueError – Descriptive message pointing to the offending parameter.

Return type:

None

to_inverter()[source]

Instantiate a EMInverter1D.

Returns an untrained inverter configured according to the architecture and feature settings stored in this config. Call inv.fit(dataset, **cfg.to_fit_kwargs()) to train it.

Return type:

EMInverter1D

Examples

>>> cfg = InversionConfig(arch="cnn1d", n_layers=4, epochs=50)
>>> inv = cfg.to_inverter()
>>> type(inv).__name__
'EMInverter1D'
to_fit_kwargs()[source]

Assemble keyword arguments for EMInverter1D.fit().

The returned dict is ready to be unpacked directly:

inv = cfg.to_inverter()
inv.fit(dataset, **cfg.to_fit_kwargs())
Returns:

Keys: epochs, batch_size, lr, patience, val_frac, grad_clip, seed, verbose.

Return type:

dict

Notes

weight_decay and min_delta are EMTrainer parameters not currently exposed through EMInverter1D.fit. They are stored in InversionConfig for documentation and round-trip reproducibility but are not included in the returned dict.

checkpoint_path()[source]

Return the full checkpoint file path, or None if disabled.

Return type:

pathlib.Path or None

classmethod from_inverter(inv)[source]

Snapshot a fitted (or unfitted) inverter’s architecture settings.

Creates an InversionConfig whose architecture and feature fields match those of inv. Training hyperparameters are reset to their defaults because the inverter does not record them after training.

Use this to generate a reproducible record of a training run:

cfg = InversionConfig.from_inverter(inv)
cfg.write_template("run_snapshot.py")
Parameters:

inv (EMInverter1D) – Source inverter (fitted or unfitted).

Return type:

InversionConfig

to_template(path='inversion_config.py', *, fmt=None)[source]

Write this configuration to an annotated source-of-truth file.

Parameters:
  • path (path-like, default "inversion_config.py") – Destination file. The suffix selects the output format (.py, .json, .yml).

  • fmt ({"py", "json", "yml", "yaml"}, optional) – Explicit format override.

Return type:

pathlib.Path

classmethod write_template(path='inversion_config.py', *, fmt=None)[source]

Generate a documented source-of-truth configuration file.

Creates a file with default parameter values and an inline comment for every parameter. Edit the file, then load with from_file().

Parameters:
  • path (path-like, default "inversion_config.py") – Destination file.

  • fmt ({"py", "json", "yml", "yaml"}, optional) – Explicit format override.

Return type:

pathlib.Path

Examples

>>> from pycsamt.ai.inversion.config import InversionConfig
>>> path = InversionConfig.write_template("my_inv.yml")
>>> path.suffix
'.yml'
classmethod from_file(path, *, strict=True)[source]

Load a configuration from a source-of-truth file.

Parameters:
  • path (path-like) – Python, JSON, YML, or YAML file generated by write_template() or following the same structure.

  • strict (bool, default True) – If True, unknown keys raise ValueError. If False, unknown keys are silently ignored.

Return type:

InversionConfig

Examples

>>> InversionConfig.write_template("inv_config.json")
PosixPath('inv_config.json')
>>> cfg = InversionConfig.from_file("inv_config.json")
>>> cfg.arch
'resnet'
classmethod read(path, *, strict=True)

Alias — matches the convention used by ModEmConfig and OccamConfig.

Parameters:
Return type:

InversionConfig

summary()[source]

Return a human-readable multi-line summary of the configuration.

Return type:

str