Python interface to the Occam2DMT inversion workflow.
The pycsamt.models.occam2d subpackage builds, runs, reads, and
plots two-dimensional magnetotelluric and CSAMT inversions using the
Occam smooth-model approach [1]_, [2]_. The inversion seeks a model
that fits the data to a target normalized RMS while minimizing
roughness.
Build the complete input set for an Occam2D inversion.
InputBuilder is the main construction entry point for
the v2 Occam2D workflow. It takes one survey source and writes
the four
files consumed by the Occam2DMT Fortran program:
OccamDataFile.dat: observed data and uncertainty rows.
Occam2DMesh: finite-element mesh geometry.
Occam2DModel: mapping from mesh cells to parameters.
Startup: inversion controls and initial model vector.
The build chain follows Occam smooth inversion [1]_, [2]_.
The inversion later seeks the smoothest model that reaches a
target
normalized RMS misfit:
InputBuilder does not run the inversion. It prepares a
self-contained working directory that can be passed to
OccamRunner.
Parameters:
source (Sites, EDICollection, or iterable) – EDI-derived survey source used to build the Occam data
file. Accepted inputs include pycsamt.site.Sites,
an EDI collection, or any iterable of site-like objects.
Each item must expose frequency, apparent resistivity, and
phase arrays. Coordinates are strongly preferred because
they allow station offsets to be ordered along profile.
When coordinates are absent, fallback spacing is used.
workdir (path-like, default ".") – Directory that contains, or will receive, the Occam2D run
files. Builders write OccamDataFile.dat,
Occam2DMesh, Occam2DModel, and Startup inside
this directory. Runners execute the compiled binary from
this location and capture standard output and error logs
there. The directory is created when output is written.
config (OccamConfig, optional) – Configuration object controlling data selection, mesh
geometry, startup controls, file names, and executable
discovery. It centralizes choices such as modes, error
floors, frequency limits, layer counts, cell sizes, target
misfit, starting resistivity, and Occam file names. If
omitted, a default OccamConfig is created.
verbose (int or bool, default 0) – Verbosity level for progress reporting. 0 or False
keeps the object quiet. Positive values enable progress
messages through the instance logger; larger values may be
used by callers to request more diagnostic detail.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created
automatically. Pass an explicit logger when integrating
Occam2D objects into an application-level logging setup.
Variables:
source (object) – Original survey source passed to the builder. It is kept
so repeated build() calls can rebuild outputs with
different one-shot overrides.
workdir (pathlib.Path) – Output directory where Occam files are written.
config (OccamConfig) – Mutable run configuration used by the build steps.
data (OccamData or None) – Populated after build(). It stores station names,
offsets, frequencies, data-type codes, datum values, and
errors.
mesh (OccamMesh or None) – Finite-element mesh generated from data.offsets and
mesh-related configuration values.
model (OccamModel or None) – Model-parameter definition generated from mesh.
startup (OccamStartup or None) – Iteration-zero startup object generated from model.
Notes
Keyword overrides supplied to build() update the stored
config object before files are written. This makes later
calls convenient, but overrides persist unless the
caller restores the configuration.
The method executes the input-file pipeline in fixed order:
data, mesh, model, then startup. Each step depends on the
previous object, so failures usually identify the first bad
input in the chain.
The generated files are written using names stored in
self.config:
config.data_file
config.mesh_file
config.model_file
config.startup_file
One-shot arguments update the builder configuration before
writing
files. For example, n_layers=40 updates
self.config.n_layers and affects mesh, model, and startup
objects created by this call.
Parameters:
modes (list of str, optional) – Electromagnetic modes written to the data file. Supported
values are "TE" for the \(Z_{xy}\) component and
"TM" for the \(Z_{yx}\) component. Both apparent
resistivity and phase rows are written for each selected
mode. If omitted, config.modes is used.
n_layers (int, optional) – Number of active subsurface parameter layers in the Occam
model. Larger values allow the inversion to represent more
vertical structure, but they also increase the number of
model parameters and can make the problem less stable
without adequate data support.
cell_size (float, optional) – Horizontal cell width in metres near station positions.
Smaller values provide finer lateral resolution around the
profile but increase mesh size and runtime. This value
overrides config.cell_size_horizontal for one build
only.
error_floor_rho (float, optional) – Relative apparent-resistivity error floor used when data
built from EDI sources. The value is a fraction, for
example 0.05 for five percent. Occam stores apparent
resistivity in log10 units, so the floor is converted as
\(\sigma_d=\sigma_{\rho}/\ln(10)\). This prevents
very small resistivity errors from dominating inversion
objective.
error_floor_phase (float, optional) – Minimum absolute phase uncertainty in degrees. This value
is applied to phase rows when source errors are missing or
smaller than the floor. It stabilizes phase weighting
data in the Occam objective function.
freq_min (float, optional) – Lower frequency limit in hertz. Frequencies below this
value are excluded when building data from EDI sources.
Use this to remove low-frequency samples that are noisy,
poorly sampled, or outside the intended depth range.
freq_max (float, optional) – Upper frequency limit in hertz. Frequencies above this
value are excluded when building data from EDI sources.
Use this to remove high-frequency samples affected by
near-surface noise, static effects, or processing limits.
title (str, default "pycsamt Occam2D data file") – Free-text title written into the Occam data-file header.
Use it to record survey name, processing version,
inversion purpose, or other provenance attached to
the generated OccamDataFile.dat.
Returns:
Same builder instance, populated with data, mesh,
model, and startup objects.
OccamRunner is the execution layer of the Occam2D
workflow. It assumes that an input directory already
contains the files written by InputBuilder:
OccamDataFile.dat, Occam2DMesh, Occam2DModel,
and Startup. The runner resolves a compiled
executable, can compile the bundled Fortran source,
launches the solver in workdir, and captures standard
output and error streams.
Binary discovery follows a deterministic order:
explicit binary_path passed to the constructor;
executable named Occam2D or Occam2D.exe in
workdir;
executable found on the system PATH;
bundled _source directory, if automatic compilation
is enabled.
The synchronous run() method blocks until Occam2D
exits. The asynchronous run_async() method returns a
process handle and lets the caller poll is_running
or call wait().
Parameters:
workdir (path-like, default ".") – Directory containing the Occam2D run files. The binary
is executed with this directory as its current working
directory, so relative names inside Startup are
resolved there. Output logs are also written there.
binary_path (path-like, optional) – Explicit path to a compiled Occam2D executable. Use
this when the binary is stored outside workdir or
is not available on PATH. When omitted, discovery
the order described above.
startup_file (str, default "Startup") – Name of the startup file passed to the executable.
It is resolved relative to workdir.
verbose (int or bool, default 0) – Verbosity level inherited from OccamBase.
Positive values enable progress messages through the
instance logger.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created.
Variables:
workdir (pathlib.Path) – Run directory where the executable is launched.
exit_code (int or None) – Return code from the most recent completed run.
stdout_log (pathlib.Path) – File where process standard output is captured.
stderr_log (pathlib.Path) – File where process standard error is captured.
Notes
run() and run_async() do not build input
files. Use InputBuilder first when starting from
EDI data. The optional max_iter and
target_misfit arguments to run() patch the
startup file in place before launch.
The method resolves the executable path and stores it
on binary. It first honors the explicit
binary_path constructor argument, then checks
workdir, then the system PATH. If those fail
and auto_compile is True, it calls
compile() for the bundled Fortran source.
Parameters:
auto_compile (bool, default True) – If True, attempt to compile the bundled source
when no executable is found. Compilation requires
make and a Fortran compiler such as
gfortran.
Compilation is performed in the package _source
directory by invoking make with FC90 and
FCFLAGS variables. The resulting executable is
expected to be named Occam2D there.
This method does not copy the binary into workdir;
discover_binary() uses that path directly.
Parameters:
fc (str, default "gfortran") – Fortran compiler command passed to make as
FC90. Use this to select another compiler that
understands the bundled source.
flags (str, default "-O2") – Compiler flags passed to make as FCFLAGS.
Optimization flags are usually sufficient; debug
builds can pass flags such as "-g".
This method blocks until the executable exits. It
resolves the binary, optionally patches the startup
file, launches Occam2D<startup_file> inside
workdir, and writes process streams to
occam_stdout.log and occam_stderr.log.
Parameters:
max_iter (int, optional) – Temporary override for the Iterationstorun
field in the startup file. The override is written
in place before launch, so the file must be
writable.
target_misfit (float, optional) – Temporary override for the TargetMisfit field
in the startup file. This changes the run-control
file before launch.
auto_compile (bool, default True) – Passed to discover_binary(). If True,
missing binaries may trigger compilation.
Returns:
Process exit code. A value of 0 indicates that
the executable returned successfully.
The method resolves the binary and launches the solver
with subprocess.Popen. It returns immediately
with a process handle. Standard output and standard
error are redirected to stdout_log and
stderr_log.
Parameters:
auto_compile (bool, default True) – Passed to discover_binary(). If True,
missing binaries may trigger compilation.
Load and summarize a completed Occam2D inversion run.
InversionResult is the post-processing access layer
for an Occam2D working directory. It scans the directory
for input and output files, loads the selected iteration,
matches the response file, reads the log, and builds a
two-dimensional log10-resistivity grid on the mesh.
The reconstruction maps the iteration parameter vector to
model layers and mesh cells. If \(m_j\) is the
log10-resistivity value assigned to model parameter
\(j\), then the physical resistivity represented by a
cell in that parameter group is
\[\rho_j = 10^{m_j}.\]
The stored rho_2d array keeps \(m_j\), not
\(\rho_j\), because Occam iteration files store
log10-resistivity values.
Parameters:
workdir (path-like, default ".") – Directory produced by an Occam2D run. It should
contain an Occam2DMesh file, an Occam2DModel
file, a data file, a log file, .iter files, and
matching .resp files.
iteration (int or None, default None) – Iteration number to load. If None, the highest
numbered .iter file is selected. If the requested
iteration is unavailable, the loader falls back to the
last available iteration file.
verbose (int or bool, default 0) – Verbosity level inherited from OccamBase.
Positive values enable progress messages through the
instance logger.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created.
Variables:
workdir (pathlib.Path) – Directory scanned by the loader.
log (OccamLog or None) – Parsed convergence log when a log file is found.
mesh (OccamMesh or None) – Parsed finite-element mesh.
model (OccamModel or None) – Parsed model-parameter definition.
best_iter (OccamIter or None) – Selected iteration file. The name is kept for backward
compatibility; it may be the requested iteration or
last available iteration.
response (OccamResponse or None) – Response file matching the selected iteration when
available. If no exact match exists, the loader falls
back to the last response file.
data (OccamData or None) – Parsed observed-data file when available.
iter_files (list of pathlib.Path) – All .iter files found in workdir, sorted by
embedded iteration number.
resp_files (list of pathlib.Path) – All .resp files found in workdir, sorted by
embedded iteration number.
rho_2d (numpy.ndarray of float or None) – Log10-resistivity grid with shape
(mesh.n_zcells,mesh.n_xcells). Cells outside the
model domain are stored as nan.
Notes
The loader is deliberately tolerant. Missing optional
files leave corresponding attributes as None instead
of failing immediately. A missing working directory still
raises NotADirectoryError because there is no
useful scan to perform.
Write the selected model as a three-column ASCII file.
The exported file contains one row for each finite
cell in rho_2d. Columns are x_center,
z_center, and log10_rho. Horizontal
coordinates are centered around the profile midpoint
and depths are positive downward.
This format is useful for external plotting tools and
for workflows that expect Bo Yang-style iter2dat
output. The values remain in log10-resistivity units:
\[m = \log_{10}(\rho).\]
Parameters:
output_file (path-like) – Destination path for the exported ASCII model.
Parent directories are created when needed.
OccamData stores the station list, profile offsets,
global frequency table, data-type codes, datum values, and
uncertainty values written to OccamDataFile.dat. The
object is both a container for parsed files and the product
of EDI conversion by from_edi().
The Occam2D data file uses one row for each datum. Apparent
resistivity is stored in logarithmic form, while phase is
stored in degrees:
For PyCSAMT EDI arrays, TE mode is taken from
\(Z_{xy}\) and TM mode is taken from \(Z_{yx}\).
TM phase is shifted by \(180^\circ\) so passive-MT
\(Z_{yx}\) phases are written in the first quadrant.
Parameters:
title (str, default "pycsamt Occam2D data file") – Free-text title written into the Occam data-file header.
Use it to record survey name, processing version,
inversion purpose, or other provenance attached to
the generated OccamDataFile.dat.
config (OccamConfig, optional) – Configuration object controlling data selection, mesh
geometry, startup controls, file names, and executable
discovery. It centralizes choices such as modes, error
floors, frequency limits, layer counts, cell sizes, target
misfit, starting resistivity, and Occam file names. If
omitted, a default OccamConfig is created.
verbose (int or bool, default 0) – Verbosity level for progress reporting. 0 or False
keeps the object quiet. Positive values enable progress
messages through the instance logger; larger values may be
used by callers to request more diagnostic detail.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created
automatically. Pass an explicit logger when integrating
Occam2D objects into an application-level logging setup.
Variables:
format_str (str) – Occam format tag. The current writer uses
"OCCAM2MTDATA_1.0".
title (str) – Free-text title written to the data-file header.
config (OccamConfig) – Configuration used for default modes, frequency limits,
and error floors during EDI conversion.
sites (list of str) – Station names ordered along the profile. The same order is
used by mesh construction and all one-based site indices.
data_blocks (numpy.ndarray of float, shape (n_data, 5)) – Data rows with columns site_index, freq_index,
type_code, datum, and error. Indices are
one-based because they are written directly to Occam
files.
Notes
Occam2D type codes distinguish both data kind and component.
The common MT rows are 1 for RhoTE, 2 for
PhsTE, 5 for RhoTM, and 6 for PhsTM.
Additional impedance and tipper codes are exposed through
DATA_TYPE_CODES for readers and future writers.
Build an Occam data object from EDI-derived stations.
This constructor normalizes the accepted input source to a
list of site-like objects, estimates station chainages,
merges all available frequencies into a common descending
frequency table, applies frequency limits, and writes TE/TM
apparent-resistivity and phase rows using Occam type codes.
The EDI arrays are interpreted with the convention
For each accepted apparent-resistivity value \(\rho_a\),
the stored datum is \(\log_{10}(\rho_a)\). The
relative resistivity floor is converted to log10 uncertainty
by \(\sigma_d=\sigma_\rho/\ln(10)\). Phase rows use
degree errors and the TM phase is shifted by
\(180^\circ\).
Parameters:
source (Sites, EDICollection, or iterable) – EDI-derived survey source used to build the Occam data
file. Accepted inputs include pycsamt.site.Sites,
an EDI collection, or any iterable of site-like objects.
Each item must expose frequency, apparent resistivity, and
phase arrays. Coordinates are strongly preferred because
they allow station offsets to be ordered along profile.
When coordinates are absent, fallback spacing is used.
modes (list of str, optional) – Electromagnetic modes written to the data file. Supported
values are "TE" for the \(Z_{xy}\) component and
"TM" for the \(Z_{yx}\) component. Both apparent
resistivity and phase rows are written for each selected
mode. If omitted, config.modes is used.
config (OccamConfig, optional) – Configuration object controlling data selection, mesh
geometry, startup controls, file names, and executable
discovery. It centralizes choices such as modes, error
floors, frequency limits, layer counts, cell sizes, target
misfit, starting resistivity, and Occam file names. If
omitted, a default OccamConfig is created.
title (str, default "pycsamt Occam2D data file") – Free-text title written into the Occam data-file header.
Use it to record survey name, processing version,
inversion purpose, or other provenance attached to
the generated OccamDataFile.dat.
**kwargs – Additional keyword arguments passed to the OccamData
constructor. This is commonly used for verbose or
logger when progress messages are desired.
Returns:
Populated data object ready to be written as an
OCCAM2MTDATA_1.0 file.
The parser reads the format tag, title, station names,
offsets, frequency table, and numeric data block. Site and
frequency indices are kept in the one-based form used by
Occam2D so a read-write round trip preserves the original
file structure.
Parameters:
path (path-like) – Path to an Occam2D input or output file. The value may be
a string, pathlib.Path, or any object accepted by
pathlib.Path. Relative paths are interpreted from
the current working directory of the Python process.
Readers require the file to exist, while writers create
parent directories when the owning method supports output.
**kwargs – Additional keyword arguments forwarded to the
OccamData constructor before parsed values are
attached. Use this for config, verbose, or
logger.
Returns:
Parsed data-file container with arrays populated from
path.
The writer serializes the current title, station list,
offsets, frequency table, and data rows using the Occam2D
text layout.
Parent directories are created before writing. The method does
not modify the object, so it can be used repeatedly for
round-trip checks or alternative run directories.
Parameters:
path (path-like) – Path to an Occam2D input or output file. The value may be
a string, pathlib.Path, or any object accepted by
pathlib.Path. Relative paths are interpreted from
the current working directory of the Python process.
Readers require the file to exist, while writers create
parent directories when the owning method supports output.
OccamMesh stores the two-dimensional grid consumed by
the Occam2D forward solver. Horizontal cell widths define
the profile direction. Vertical widths define air and
earth layers, and character rows mark whether cells are
fixed, air, or boundary cells in the PW2D mesh format.
Node coordinates are cumulative sums of cell widths:
Depth \(z\) is positive downward. Mesh construction
uses station offsets from OccamData, horizontal
padding on both profile ends, optional air layers, and a
geometrically expanding earth-layer thickness sequence.
Parameters:
config (OccamConfig, optional) – Configuration object controlling the number of active
layers, number of air layers, near-surface cell sizes,
depth scaling, and horizontal padding. If omitted, a
default OccamConfig is created.
verbose (int or bool, default 0) – Verbosity level inherited from OccamBase.
Positive values enable progress messages through the
instance logger.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created.
Variables:
comment (str) – First line of the mesh file, usually a provenance
comment beginning with "MESHFILE".
x_nodes (numpy.ndarray of float, shape (n_xcells + 1,)) – Cumulative horizontal node positions in metres.
z_nodes (numpy.ndarray of float, shape (n_zcells + 1,)) – Cumulative depth node positions in metres, positive
downward.
cell_rows (list[str]) – Raw PW2D cell-type rows. Each character encodes the
cell type at one horizontal position. The "?"
character marks cells that may contribute to free
inversion parameters.
n_airlayers (int) – Number of rows treated as air layers.
Notes
The mesh file stores widths rather than absolute node
coordinates. x_nodes and z_nodes are
reconstructed by cumulative summation when reading or
building a mesh. The generated mesh uses seven padding
cells on each side to match the boundary-column code used
by OccamModel.from_mesh().
The method creates a finite-element mesh spanning the
profile described by data.offsets. It uses seven
padding cells on each side, station-zone cells near
the configured horizontal cell size, optional air
layers, and geometrically expanding earth layers.
The horizontal padding is chosen to match the boundary
columns used by OccamModel.from_mesh(). Interior
station-zone cells are adjusted so the number of cells
remains compatible with the model parameter grouping.
Parameters:
data (OccamData) – Populated data object. Its offsets array must
contain station chainages in metres. Offsets are
sorted before mesh construction.
config (OccamConfig, optional) – Configuration object controlling mesh geometry.
The builder uses cell_size_horizontal,
n_airlayers, n_layers,
cell_size_vertical_top, and depth_scale.
If omitted, a default OccamConfig is
created.
**kwargs – Additional keyword arguments forwarded to the
OccamMesh constructor. Use this for
verbose or logger.
The reader parses the comment line, control line,
horizontal widths, vertical widths, air-layer count,
and cell-type character rows. Node arrays are rebuilt
from cumulative sums of widths.
Parameters:
path (path-like) – Path to the mesh file. The value may be a string,
pathlib.Path, or any object accepted by
pathlib.Path.
**kwargs – Additional keyword arguments forwarded to the
OccamMesh constructor before parsed values are
attached. Use this for config, verbose, or
logger.
Returns:
Parsed mesh container with widths, nodes, and cell
rows populated.
The writer serializes the current comment, control
values, horizontal widths, vertical widths, and
cell-type rows to the native Occam2D mesh format.
Parent directories are created before writing.
Parameters:
path (path-like) – Destination path for the mesh file. The value may
be a string, pathlib.Path, or any object
accepted by pathlib.Path.
OccamModel links a finite-element OccamMesh to the
inversion parameter vector used by Occam2D. The model file
does not store resistivity values. Instead, it defines how
mesh cells are grouped into free or fixed parameters.
The startup and iteration files then store one value for
each parameter counted by n_params.
Each model layer contains integer column codes. Boundary
code 7 marks fixed edge columns tied to the binding
value, while active even codes represent free inversion
columns [1]_. If \(p_j\) is the code for one model
column, then the number of mesh cells represented by that
column is encoded by the code value itself. The PyCSAMT
builder uses 2 for interior columns and 7 for the
two boundary columns:
\[\mathbf{p}
=
[7,\;2,\;2,\;\ldots,\;2,\;7].\]
Parameters:
name (str, default "MODEL MADE BY PYCSAMT") – Model name written to the ModelName header field.
Use this for a short label that identifies the model
family, processing run, or inversion setup.
description (str, default "SMOOTH INVERSION") – Description written to the Description header
field. It is intended for human-readable provenance
and is preserved when the model is written to disk.
config (OccamConfig, optional) – Configuration object used for default file names and
related Occam2D settings. If omitted, a default
OccamConfig is created.
verbose (int or bool, default 0) – Verbosity level inherited from OccamBase.
Positive values enable progress messages through the
instance logger.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created.
Variables:
format_str (str) – Occam model format tag. The writer uses
"OCCAM2MTMOD_1.0".
name (str) – Model name written to the file header.
description (str) – Human-readable model description.
config (OccamConfig) – Configuration used by this object.
mesh_file (str) – Filename of the associated mesh used by the model
file, usually "Occam2DMesh".
mesh_type (str) – Mesh type string written to the header. Occam2D PW2D
meshes use "PW2D".
statics_file (str) – Optional static-shift file. The default "none"
means no static correction file is referenced.
prejudice_file (str) – Optional prejudice model file. The default "none"
means no prejudice file is referenced.
binding_offset (float, default 0.0) – Horizontal offset of the binding column. This is the
reference value used by boundary columns.
n_layers (int) – Number of active model layers after the header.
It is normally the number of non-air mesh rows.
Per-layer parameter specification. Each entry has the
following keys:
n_mergeint
Number of mesh z-rows merged into this layer.
n_colsint
Number of model columns in this layer.
paramsnumpy.ndarray of int, shape (n_cols,)
Parameter codes for each model column. Code 7
marks a boundary column; active even values mark
free inversion parameters.
n_exceptions (int) – Number of exception records at the end of the model
file. PyCSAMT currently writes 0.
Notes
n_params is the sum of n_cols over all model
layers. This value must match the ParamCount in the
startup and iteration files. n_free_params excludes
boundary columns with code 7.
The method converts a finite-element mesh into the
column mapping required by OCCAM2MTMOD_1.0. Air
rows are ignored. Each remaining earth row becomes one
model layer with n_merge=1. Horizontally, the
model uses fixed boundary columns and active interior
columns:
\[\mathbf{p}
=
[7,\;2,\;2,\;\ldots,\;2,\;7].\]
The leading and trailing 7 codes represent seven
mesh cells each at the profile boundaries. Interior
2 codes represent two mesh cells per free model
column. Therefore the total horizontal cell count is
\[n_x = 7 + 2n_i + 7,\]
where \(n_i\) is the number of interior model
columns. Meshes built by OccamMesh.from_data()
are constructed to satisfy this layout.
Parameters:
mesh (OccamMesh) – Populated mesh object defining horizontal and
vertical finite-element cells. It must provide
n_xcells, n_zcells, and n_airlayers.
Air layers are excluded from the model; all other
z-cells become inversion layers.
config (OccamConfig, optional) – Configuration object used for file names and
related Occam2D defaults. If omitted, a default
OccamConfig is created.
**kwargs – Additional keyword arguments forwarded to the
OccamModel constructor. This is commonly used
for name, description, verbose, or
logger.
Returns:
Model-definition object ready to be written as an
Occam2DModel file. The returned object has
n_layers equal to the number of active earth
rows and layers populated with parameter-code
arrays.
ValueError – Raised when the mesh has no active earth layers or
fewer than fourteen horizontal cells. Fourteen
cells are required for the two seven-cell boundary
columns.
The reader parses the model header and the per-layer
parameter-code blocks. Numeric header values are cast
to int or float where appropriate. Layer
params arrays are stored as numpy.int32 for
comparison with generated model mappings.
Parameters:
path (path-like) – Path to an Occam2D model file. The value may be a
string, pathlib.Path, or any object
accepted by pathlib.Path.
**kwargs – Additional keyword arguments forwarded to the
OccamModel constructor before parsed values
are attached. Use this for config,
verbose, or logger.
Returns:
Parsed model-definition container with header
fields and layer mappings populated from path.
The writer serializes the current header fields and
layer mappings to the Occam2D model layout. Parent
directories are created before writing. The object is
not modified, so the same instance can be written to
multiple run directories.
Parameters:
path (path-like) – Destination path for the model file. The value may
be a string, pathlib.Path, or any object
accepted by pathlib.Path.
OccamStartup stores the iteration-zero
OCCAMITER_FLEX file passed to the Occam2D executable.
It defines run controls, file references, inversion
options, and the initial model vector. Unlike .iter
files produced by the solver, a valid startup file has
Iteration:0.
The startup parameter vector is initialized as a uniform
half-space:
\[m_i = \log_{10}(\rho_0),
\qquad i = 1, \ldots, N_p.\]
Here \(\rho_0\) is config.initial_rho and
\(N_p\) is the number of model parameters defined by
OccamModel.
Parameters:
config (OccamConfig, optional) – Configuration object providing file names, inversion
controls, starting resistivity, target misfit,
roughness settings, and debug level. If omitted, a
default OccamConfig is created.
description (str, default "startup created by pycsamt") – Description written to the Description header.
Use it to record the purpose or provenance of the run.
verbose (int or bool, default 0) – Verbosity level inherited from OccamBase.
Positive values enable progress messages through the
instance logger.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created.
Variables:
format_str (str) – File format tag, always "OCCAMITER_FLEX".
OccamStartup writes the same flexible iteration format
that Occam later uses for .iter files. The distinction
is semantic: startup files carry Iteration:0 and are
input to the solver, while OccamIter files carry
non-zero iteration numbers and are output from the solver.
The method uses model.n_params to size the startup
vector and fills every entry with the log10 value of
starting half-space resistivity:
\[m_i = \log_{10}(\rho_0),
\qquad i = 1,\ldots,N_p.\]
This produces the standard smooth-inversion initial
model: a homogeneous half-space whose value is later
updated by the Occam solver.
Parameters:
model (OccamModel) – Populated model-definition object. It must contain
at least one parameter so the vector can be
sized consistently with the Occam2DModel file.
config (OccamConfig, optional) – Configuration object providing initial_rho,
model and data file names, iteration controls, and
inversion settings. If omitted, a default
OccamConfig is created.
**kwargs – Additional keyword arguments forwarded to the
OccamStartup constructor. Use this for
description, verbose, or logger.
Returns:
Startup object with n_params and uniform
param_values populated.
The reader parses an OCCAMITER_FLEX file and then
validates that its Iteration header is zero. Use
OccamIter.read() for non-zero iteration files
produced by the solver.
Parameters:
path (path-like) – Path to the startup file. The value may be a
string, pathlib.Path, or any object
accepted by pathlib.Path.
**kwargs – Additional keyword arguments forwarded to the
OccamStartup constructor before parsed values
are attached.
Returns:
Parsed startup object with header fields and
parameter vector populated.
OccamIter reads OCCAMITER_FLEX files written by
the Occam2D executable after one or more inversion
iterations. These files have the same structural format as
Startup but carry Iteration values greater than
zero and store the accepted model vector.
The parameter vector is stored in log10-resistivity units.
Physical resistivity is recovered as
\[\rho_i = 10^{m_i},\]
where \(m_i\) is the stored value for parameter
\(i\).
Parameters:
verbose (int or bool, default 0) – Verbosity level inherited from OccamBase.
Positive values enable progress messages through the
instance logger.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created.
Variables:
format_str (str) – File format tag, usually "OCCAMITER_FLEX".
description (str) – Iteration description written by Occam.
model_file (str) – Model file referenced by this iteration.
data_file (str) – Data file referenced by this iteration.
datetime_str (str) – Date and time string written by Occam.
max_iterations (int) – Iteration limit stored in the file.
OccamResponse stores the forward response written by
the Occam2D executable for one inversion iteration. The
response table has one row per datum and seven columns:
site index, frequency index, type code, error-floor value,
observed datum, modeled datum, and weighted residual.
The response residual is already weighted by the data
uncertainty used by Occam. The global RMS misfit is
therefore computed directly from the residual column:
where \(r_i\) is the weighted residual for datum
\(i\) and \(N\) is the number of response rows.
Values near one are often consistent with data errors that
are neither under-estimated nor over-estimated [1]_.
Parameters:
verbose (int or bool, default 0) – Verbosity level inherited from OccamBase.
Positive values enable progress messages through the
instance logger.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created.
Variables:
data (numpy.ndarray of float, shape (n_data, 7)) – Full raw table from the .resp file. Columns are
site_index, freq_index, type_code,
error_floor, observed, modeled, and
residual.
observed (numpy.ndarray of float, shape (n_data,)) – Observed data values from column 4. Values follow the
datum convention of OccamData: log10 apparent
resistivity for rho rows and degrees for phase rows.
modeled (numpy.ndarray of float, shape (n_data,)) – Forward-model predictions from column 5, ordered in
the same row order as observed.
residuals (numpy.ndarray of float, shape (n_data,)) – Weighted residuals from column 6. These values are the
residuals used to compute rms.
rms (float) – Root-mean-square weighted residual for all response
rows. Empty objects use 0.0.
Notes
Response files do not include a header. The parser accepts
any line with seven numeric columns and skips non-numeric
lines. Site and frequency indices are one-based to match
the Occam data file.
The reader parses seven-column numeric rows from a
response file produced by the Occam2D executable. The
first three columns are stored in the raw table as
floats because the file itself is numeric text, but
convenience properties expose site, frequency, and
type codes as integers.
Parameters:
path (path-like) – Path to the response file. The value may be a
string, pathlib.Path, or any object
accepted by pathlib.Path.
data_fn (path-like, optional) – Optional data-file path reserved for consistency
checks between observed data rows and response
rows. It is currently accepted for API stability
but is not used by the parser.
**kwargs – Additional keyword arguments forwarded to the
OccamResponse constructor. Use this for
verbose or logger.
Returns:
Parsed response container with raw data, observed
values, modeled values, residuals, and global RMS
populated.
OccamLog parses the text log written by the Occam2D
Fortran executable. The file records one block per inversion
iteration, including accepted misfit, model roughness,
Lagrange multiplier, and line-search step size. Parsed arrays
align by index, so iterations[i], rms[i],
roughness[i], lagrange[i], and stepsize[i]
describe the same iteration.
The main convergence statistic is the normalized RMS data
misfit. If \(r_i\) are weighted residuals for \(N\)
data, the reported quantity is commonly interpreted as
An inversion is usually considered well weighted when
\(\phi_d \approx 1\). The practical target still depends
on error estimates and modeling assumptions [1]_.
Parameters:
verbose (int or bool, default 0) – Verbosity level for progress reporting. 0 or False
keeps the object quiet. Positive values enable progress
messages through the instance logger; larger values may be
used by callers to request more diagnostic detail.
logger (logging.Logger, optional) – Logger used for progress and diagnostic messages. If
omitted, a class-specific PyCSAMT logger is created
automatically. Pass an explicit logger when integrating
Occam2D objects into an application-level logging setup.
Variables:
iterations (ndarray of int, shape (n_iter,)) – One-based iteration numbers parsed from **ITERATION
blocks. The values are preserved as written by Occam.
rms (ndarray of float, shape (n_iter,)) – Accepted normalized RMS misfit for each iteration. When
an iteration contains repeated search steps, the parser
keeps the last ANDIS= value in that block.
roughness (ndarray of float, shape (n_iter,)) – Model roughness reported by Occam. The final entry may be
nan when a run stops before writing ROUGHNESSIS.
lagrange (ndarray of float, shape (n_iter,)) – Accepted Lagrange multiplier, \(\mu\), for each
iteration. Values are read from MINIMUMTOLFROM or
INTERCEPTISATMU lines.
stepsize (ndarray of float, shape (n_iter,)) – Accepted step size for each iteration. The final entry may
be nan if convergence problems stop the run early.
Notes
The parser is intentionally tolerant of Occam2D log variants.
It ignores intermediate TOFMU search lines and keeps the
last accepted values in each iteration block. This behavior
matches logs where divergence problems trigger repeated
Lagrange searches before a step is accepted.
The reader scans the file line by line with a small state
machine. A **ITERATION line starts a new block and saves
the previous block. Within each block, the last accepted RMS,
roughness, Lagrange multiplier, and step size are retained.
This is useful for logs where Occam cuts the step size or
repeats the Lagrange search. Intermediate trial values are not
stored because they do not describe the accepted model.
Parameters:
path (path-like) – Path to an Occam2D input or output file. The value may be
a string, pathlib.Path, or any object accepted by
pathlib.Path. Relative paths are interpreted from
the current working directory of the Python process.
Readers require the file to exist, while writers create
parent directories when the owning method supports output.
**kwargs – Additional keyword arguments forwarded to the OccamLog
constructor. Use this for verbose or logger when
integrating the parser into a larger workflow.
Returns:
Parsed convergence-log container with one array entry per
completed iteration block.
PlotModel displays the selected iteration model from
InversionResult as a
depth section. It replaces plotOccam2DMT.m, and the
companion profile extractor replaces
ExtractOccam2DMTProfile.m.
Occam iteration files store model parameters as
\(\log_{10}\) resistivity. The plot converts them back
to ohm metres before drawing:
\[\rho(x, z) = 10^{m(x, z)}.\]
The mesh is centered around the profile midpoint.
Depth is positive downward.
Parameters:
result (InversionResult) – Loaded result containing rho_2d and mesh.
Station markers are drawn when result.data.offsets
is available.
rho_min (float, default 1.0, 1000.0) – Color-scale limits in ohm metres. They are passed to
matplotlib.colors.LogNorm; both values must
be positive.
rho_max (float, default 1.0, 1000.0) – Color-scale limits in ohm metres. They are passed to
matplotlib.colors.LogNorm; both values must
be positive.
depth_max (float, optional) – Maximum display depth in metres. If omitted, the full
mesh depth is shown.
show_stations (bool, default True) – If True, overlay station triangles at the surface
using the offsets stored in the data file.
profile_distance_unit ({"m", "km"}, default "km") – Unit used on the horizontal axis and by
extract_profile().
figsize (tuple of float, optional) – Matplotlib figure size. The default suits a profile
section.
cmap (str, default "jet_r") – Colormap used for the resistivity image.
dpi (int, default 100) – Figure resolution in dots per inch.
PlotResponse compares observed data from the Occam
file with modeled values from an Occam .resp file. It
replaces plotOccam2DMTResponse.m.
Apparent-resistivity rows are stored as log10 values.
They are converted before plotting:
\[\rho_a = 10^{d_\rho}.\]
Phase rows are plotted in degrees. The frequency index in
the table is mapped back to physical frequency when
corresponding OccamData object is available.
Parameters:
result (InversionResult) – Loaded result containing response and ideally
data. The response must expose the seven-column
table.
stations (list of str, list of int, or None, default None) – Stations to plot. Strings are matched against
result.data.sites. Integers are one-based site
indices when names are unavailable. If None,
stations are sampled from the response table.
modes (list of str, optional) – Electromagnetic modes to draw. Supported values are
"TE" and "TM".
period_axis (bool, default True) – Reserved for interface clarity. The implementation
uses period when frequencies are available and indices
otherwise.
max_stations (int, default 9) – Maximum number of station columns when stations is
None.
figsize (tuple of float, optional) – Figure size. If omitted, width scales with station
count.
cmap (str, default "jet_r") – Stored for a consistent interface. It is not used
by this curve plot.
dpi (int, default 100) – Figure resolution in dots per inch.
Returns:
Figure with apparent-resistivity and phase panels.
PlotPseudo displays one data component from the Occam
data file as a station-period view. It is the Python
replacement for plotOccam2DMTPseudo.m.
The horizontal axis is station offset in kilometres when
offsets are available. The vertical axis is
\(\log_{10}(T)\), where \(T = 1/f\) is period in
seconds. Apparent resistivity is converted from log10
storage to ohm metres; phase data remain in degrees.
Parameters:
result (InversionResult) – Loaded result containing an OccamData object
with data blocks, offsets, and frequencies.
mode ({"TE", "TM"}, default "TM") – Electromagnetic mode to display. "TE" maps to
codes 1 and 2; "TM" maps to codes 5 and 6.
Here \(r_i\) is the weighted residual for datum i.
A run is commonly acceptable when the RMS approaches the
target value of 1.0 [1]_.
Parameters:
result (InversionResult) – Loaded inversion result. It must expose log with
iterations, rms, roughness, lagrange,
and n_iter attributes.
show_roughness (bool, default True) – If True, add a secondary y-axis for roughness.
Roughness is plotted on a log scale because it can
vary by several orders of magnitude.
show_lagrange (bool, default False) – If True, add a lower panel for the accepted
Lagrange multiplier at each iteration.
target_line (bool, default True) – If True, draw a dashed line at RMS equal
to 1.0.
figsize (tuple of float, optional) – Matplotlib figure size passed through the shared base.
If omitted, the number of panels controls the size.
cmap (str, default "jet_r") – Stored for consistency with other plot classes.
It is not used by this line plot.
dpi (int, default 100) – Figure resolution in dots per inch.
Plot station-centered 1-D profiles from a 2-D Occam model.
PlotSounding1D samples the reconstructed 2-D
resistivity grid at the mesh column nearest each station.
The result is a set of resistivity-depth curves to compare
vertical structure below stations.
The plotted resistivity is converted from the log10 grid:
\[\rho(z) = 10^{m(z)}.\]
Air layers are omitted using result.mesh.n_airlayers.
Parameters:
result (InversionResult) – Loaded result containing rho_2d, mesh, and
data.offsets.
stations (list of str or None, default None) – Station names to plot. If None, stations are
sampled from all available offsets.
max_stations (int, default 16) – Maximum station profiles when stations is
None.
depth_max (float, optional) – Maximum plotted depth. If omitted, mesh depth
controls the lower limit.
PlotSiteMisfit summarizes the fit between observed and
modeled values at each station. The top panel is a
bar chart of RMS residual by station and data type. The
optional lower panel is a residual pseudosection.
Residuals are normalized by the error column in the Occam
response table:
Plot a compact grid of observed and modeled responses.
PlotResponseGrid is designed to scan many stations.
Each station uses two axes: apparent resistivity above and
phase below. Observed values are drawn as points and
modeled values as lines. Titles include per-site RMS when
response errors are available.
Apparent-resistivity values are converted from log10 Occam
storage before plotting:
\[\rho_a = 10^{d_\rho}.\]
Parameters:
result (InversionResult) – Loaded result with response and ideally data.
stations (list of str or None, default None) – Station names to include. If omitted, station indices
sampled from the response table.
n_cols (int, default 5) – Maximum number of station columns in each grid row.
modes (list of str, optional) – Modes to draw. Use "TE", "TM", or both.
max_stations (int, default 25) – Maximum station count included when stations is
None.
figsize (tuple of float, optional) – Figure size. Defaults scale with columns and rows.
cmap (str, default "jet_r") – Stored for interface consistency. It is unused by this
curve plot.
dpi (int, default 100) – Figure resolution in dots per inch.
OccamConfig groups the options shared by the Occam2D
builder, file containers, runner, and result loaders.
It is a plain dataclass, so users may set fields at
construction time or mutate them before calling
InputBuilder.
The configuration controls four parts of the workflow:
Electromagnetic modes written to the Occam data file.
"TE" selects the \(Z_{xy}\) component and
"TM" selects \(Z_{yx}\). Each selected mode
writes apparent-resistivity and phase rows.
error_floor_rhofloat
Relative apparent-resistivity error floor. A value of
0.05 means five percent. Because Occam stores
apparent resistivity as \(\log_{10}(\rho_a)\),
the builder converts this floor before writing data.
error_floor_phasefloat
Absolute phase error floor in degrees. This keeps
phase rows with unrealistically small source errors
from dominating the normalized data misfit.
freq_minfloat or None
Lower frequency limit in hertz. Frequencies below this
value are excluded when built from EDI sources.
None leaves the lower bound open.
freq_maxfloat or None
Upper frequency limit in hertz. Frequencies above this
value are excluded when built from EDI sources.
None leaves the upper bound open.
Users can generate an editable configuration file before
building an Occam2D run. Python is the default template
format because it supports rich inline comments and can be
read safely by from_file() using literal parsing.
YAML templates also keep comments. JSON templates store
explanations in a "_schema" metadata block and editable
values under "config" because standard JSON has no
comment syntax.
path (path-like, default "occam2d_config.py") – Destination file. If the path has no suffix, the
suffix is inferred from fmt and defaults to
.py.
fmt ({"py", "json", "yml", "yaml"}, optional) – Template format. Python and YAML templates include
comments. JSON templates include a "_schema"
metadata block because standard JSON does not
support comments.
Write a default editable Occam2D configuration file.
Parameters:
path (path-like, default "occam2d_config.py") – Destination file. Suffixes .py, .json,
.yml, and .yaml select the output format.
fmt ({"py", "json", "yml", "yaml"}, optional) – Explicit output format. When omitted, the suffix of
path is used; paths without a suffix produce a
Python template.