2.23. pycsamt.format#

Backend-neutral PCSF and PCSM representations for electromagnetic inversion results, plus the human-readable PCBH borehole exchange contract. The package provides shared schemas, serialization, conversion adapters, model/borehole association, rendering contracts, and provenance helpers.

For format concepts, complete workflows, and browsable file examples, see PCSF — Common Subsurface Format. For spatial multi-hole projects, see PCBH — Common Borehole Format.

2.23.1. Public facade#

The most commonly used classes and functions are re-exported directly from pycsamt.format.

pyCSAMT Common Subsurface Format (PCSF) — backend-neutral inversion results.

See PYCSAMT-PCSF-INVERSION-FORMAT-PLAN.md at the repository root for the full design and phase-by-phase status.

The format core – schema, .pcsf and .pcsm I/O, provenance, inversion records, sampling, comparison and regridding – is the standalone pcsf package, the reference implementation of the format. schema, io, text, provenance, inversion_record, compare and regrid re-export it, so pycsamt.format.PCSFModel is pcsf.PCSFModel. pyCSAMT keeps what is specific to it: the adapters from its own result objects, the companion formats (PCBH, PCGL, PCGS, PCPT), multi-line assembly, topography sources and conversion dispatch.

Public second-level namespaces (importable as pycsamt.format.<name> right after import pycsamt.format, not only via an explicit from pycsamt.format.<name> import ...):

  • pycsamt.format.adapters — per-backend converters (adapters.occam2d_to_pcsf, adapters.modem3d_to_pcsf, adapters.mare2dem_to_pcsf), plus a solver-agnostic adapters.grid2d_to_pcsf/adapters.grid3d_to_pcsf/ adapters.mesh_to_pcsf for any AI/DL inversion result (see pycsamt.format.adapters.generic and pycsamt.format.provenance).

  • pycsamt.format.schema — the dataclasses re-exported at this top level (Grid2DGeometry, PCSFModel, …).

  • pycsamt.format.io — read_pcsf/write_pcsf, also re-exported here.

  • pycsamt.format.text — read_pcsm/write_pcsm/ pcsf_to_pcsm/pcsm_to_pcsf: PCSM, the hand-editable ASCII sibling of a .pcsf file, also re-exported here.

  • pycsamt.format.multiline, pycsamt.format.topography, pycsamt.format.pointcloud, pycsamt.format.regrid, pycsamt.format.compare — likewise re-exported here.

  • pycsamt.format.pointset — PCPT, a tiny .pcpt.json format for targets / points of interest (read_points, points_from_csv, points_from_xlsx), re-exported here.

  • pycsamt.format.geology — PCGL, a tiny .pcgl.json format for a resistivity-to-geology interpretation legend (GeologyLegend, read_legend, write_legend, legend_from_csv), re-exported here.

  • pycsamt.format.structure — PCGS, a tiny .pcgs.json format for field structural evidence – planar/linear measurements and fault traces (StructModel, read_structure, write_structure, structure_from_csv), re-exported here.

  • pycsamt.format.convert_engine — the UI-neutral “any source → PCSFModel” dispatch engine behind pycsamt format convert (detect, resolve_target, build_model, write_model, model_report). Any second consumer of this dispatch logic (a GUI, a notebook, another CLI) should import from here rather than reaching into pycsamt.cli.commands.format._base’s private Click wrappers.

class pycsamt.format.ComparisonResult(delta, rms, bias, correlation, n)#

Bases: object

Difference field and its summary statistics.

Variables:
  • delta (ndarray of float) – Point-wise difference \(\Delta_k\) (decades); NaN where either field is undefined.

  • rms (float) – Root-mean-square difference \(\varepsilon\) (decades).

  • bias (float) – Mean difference \(\beta\) (decades); positive when the first field is the more resistive.

  • correlation (float) – Pearson correlation \(R\) of the two fields; NaN when either field is constant or fewer than two points remain.

  • n (int) – Number of points where both fields are defined.

Parameters:

See also

compare_log10

Build a result from two sampled fields.

Examples

>>> from pcsf.algorithms import compare_log10
>>> res = compare_log10([1.0, 2.0], [1.0, 2.5])
>>> stats = res.as_dict()
>>> round(stats["rms"], 4), stats["bias"], stats["n"]
(0.3536, -0.25, 2)
delta: ndarray#
rms: float#
bias: float#
correlation: float#
n: int#
as_dict()#

Summary statistics as a plain dictionary.

Returns:

Keys rms, bias, correlation and n.

Return type:

dict

pycsamt.format.compare_log10(log_a, log_b)#

Compare two log10 resistivity fields sampled at the same points.

Parameters:
  • log_a (array_like) – \(\log_{10}\rho\) of two models at the same points, any but equal shapes; NaN marks undefined values.

  • log_b (array_like) – \(\log_{10}\rho\) of two models at the same points, any but equal shapes; NaN marks undefined values.

Returns:

Difference field and statistics over the points where both fields are finite.

Return type:

ComparisonResult

Raises:

GeometryError – If the two inputs have different shapes.

See also

pcsf.algorithms.sample_log10

Sample models at common points.

Notes

Over the \(N\) points where both fields are defined,

\[\Delta_k = a_k - b_k,\qquad \varepsilon = \Big[\frac{1}{N}\sum_k \Delta_k^2\Big]^{1/2}, \qquad \beta = \frac{1}{N}\sum_k \Delta_k,\]

and \(R\) is the Pearson correlation of \(a\) and \(b\). \(\varepsilon\) and \(\beta\) are in decades; \(R\) tells whether the two models place structures at the same positions regardless of their absolute level. With no common point, all statistics are NaN and n is zero.

Examples

>>> import numpy as np
>>> from pcsf.algorithms import compare_log10
>>> res = compare_log10([1.0, 2.0, np.nan, 4.0],
...                     [1.5, 2.0, 3.0, 4.5])
>>> res.n, round(res.bias, 4)
(3, -0.3333)
pycsamt.format.log_uncertainty(sigma, from_encoding, to_encoding='log10', rho=None)#

Convert a standard deviation of resistivity between encodings.

Parameters:
  • sigma (array_like) – Standard deviation in the source encoding: decades for "log10", nepers for "ln", ohm m for "linear".

  • from_encoding ({"log10", "ln", "linear"}) – Encoding of sigma.

  • to_encoding ({"log10", "ln", "linear"}, default "log10") – Encoding of the result.

  • rho (array_like, optional) – Resistivity (ohm m) at which a linear standard deviation is evaluated; required when either encoding is "linear" and broadcast against sigma.

Returns:

Standard deviation in the target encoding.

Return type:

ndarray of float

Raises:

EncodingError – If an encoding is unknown, or rho is missing for a conversion to or from "linear".

See also

lognormal_relative_std

Exact value of the linear spread.

transform_covariance

Same conversion for covariance matrices.

Notes

With \(\sigma_m\) the standard deviation of \(m = \log_{10}\rho\),

\[\sigma_{\ln\rho} = \ln(10)\,\sigma_m,\qquad \sigma_\rho \approx \rho\,\ln(10)\,\sigma_m .\]

The first relation is exact; the second is the delta method and underestimates the spread for large \(\sigma_m\).

Examples

>>> import numpy as np
>>> from pcsf.algorithms import log_uncertainty
>>> print(np.round(log_uncertainty([0.1], "log10", "ln"), 4))
[0.2303]
>>> s = log_uncertainty([0.1], "log10", "linear", rho=[100.0])
>>> print(np.round(s, 2))
[23.03]
class pycsamt.format.InversionRecord(solver, solver_version=None, data=<factory>, forward=<factory>, regularization=<factory>, misfit=<factory>, reliability=<factory>, citation=<factory>)#

Bases: object

How a resistivity model was obtained.

Parameters:
  • solver (str) – Inversion code, e.g. "Occam2D", "ModEM", "MARE2DEM".

  • solver_version (str, optional)

  • data (dict) – components (e.g. ["TE rho", "TE phase"] or ["Zxy", "Zyx"]), frequency_range_hz [f_min, f_max], n_frequencies, n_stations, errors (free text: error floors or the range of relative errors), sign_convention (e.g. "exp(+i omega t)"), source (data file, DOI or EMTF XML identifiers).

  • forward (dict) – dimensionality ("2D", "2.5D", "3D") and mesh (free text or cell counts).

  • regularization (dict) – type (e.g. "smoothness (Occam)"), trade_off (final Lagrange multiplier or damping), start_model.

  • misfit (dict) – final_rms, target_rms, n_iterations, termination (one of TERMINATIONS).

  • reliability (dict) – method and depth_of_investigation_m ({station: depth}).

  • citation (dict) – authors, title, year, doi, licence.

Raises:

ValueError – If misfit["termination"] is not one of TERMINATIONS.

See also

check_inversion_record

List missing fields.

attach_inversion_record

Store a record in a model.

Examples

>>> from pcsf.core.record import InversionRecord
>>> rec = InversionRecord(
...     "Occam2D",
...     misfit={"final_rms": 1.0, "termination": "stalled"},
... )
>>> InversionRecord.from_dict(rec.as_dict()) == rec
True
solver: str#
solver_version: str | None = None#
data: dict[str, Any]#
forward: dict[str, Any]#
regularization: dict[str, Any]#
misfit: dict[str, Any]#
reliability: dict[str, Any]#
citation: dict[str, Any]#
as_dict()#

Plain nested dictionary of the record.

Returns:

Deep copy of every field, suitable for JSON.

Return type:

dict

classmethod from_dict(payload)#

Build a record from a dictionary.

Parameters:

payload (dict) – As produced by as_dict(). Unknown keys are ignored, so that records written by a newer version can be read.

Return type:

InversionRecord

Raises:
pycsamt.format.attach_inversion_record(model, record)#

Store a record in model.metadata["inversion"].

Parameters:
  • model (PCSFModel) – Model to annotate; its metadata is replaced by a new dictionary (the old one is not mutated).

  • record (InversionRecord) – Record to store, as its dictionary form.

Returns:

model, for chaining.

Return type:

PCSFModel

See also

get_inversion_record

Read the record back.

Examples

>>> import pcsf
>>> from pcsf.core.record import (InversionRecord,
...     attach_inversion_record, get_inversion_record)
>>> model = pcsf.PCSFModel(
...     geometry=pcsf.Grid2DGeometry(x=[0.0], z=[5.0]),
...     resistivity=[[100.0]],
... )
>>> _ = attach_inversion_record(model, InversionRecord("Occam2D"))
>>> get_inversion_record(model).solver
'Occam2D'
pycsamt.format.check_inversion_record(record)#

List the missing required and recommended fields of a record.

Parameters:

record (InversionRecord or dict) – Record, or its dictionary form.

Returns:

{"required": [...], "recommended": [...]} with the dotted names of the missing fields, in the order of REQUIRED_FIELDS and RECOMMENDED_FIELDS. A field set to None, "", [] or {} is missing.

Return type:

dict

Examples

>>> from pcsf.core.record import (InversionRecord,
...                               check_inversion_record)
>>> rec = InversionRecord("ModEM", misfit={"final_rms": 1.1})
>>> check_inversion_record(rec)["required"][:2]
['data.components', 'data.frequency_range_hz']
pycsamt.format.get_inversion_record(model)#

Read the inversion record of a model.

Parameters:

model (PCSFModel) – Model whose metadata["inversion"] is read.

Returns:

The record, or None when the model has none.

Return type:

InversionRecord or None

See also

attach_inversion_record

Store a record.

Examples

>>> import pcsf
>>> from pcsf.core.record import get_inversion_record
>>> model = pcsf.PCSFModel(
...     geometry=pcsf.Grid2DGeometry(x=[0.0], z=[5.0]),
...     resistivity=[[100.0]],
... )
>>> get_inversion_record(model) is None
True
pycsamt.format.sample_log10(model, points)#

Evaluate log10 resistivity of a model at arbitrary points.

Parameters:
  • model (PCSFModel) – Model of kind grid2d, grid3d or mesh_unstructured with canonical per-cell resistivity in ohm m.

  • points (array_like) – Target points in the model frame, depth positive downward: (n, 2) as (x, z) for grid2d and meshes (planes "xz" and "xy"), (n, 3) as (x, y, z) for grid3d.

Returns:

\(\log_{10}\rho\) at each point (decades of ohm m); NaN outside the model and where resistivity is undefined.

Return type:

ndarray of float, shape (n,)

Raises:

GeometryError – If the geometry kind is unsupported, the points have the wrong shape, or a mesh does not have per-triangle resistivity.

See also

interpolation_weights

Weights used on grids.

pcsf.algorithms.compare_log10

Statistics of two sampled fields.

Notes

The operator is

\[\begin{split}\mathcal{S}_M(\mathbf{p}) = \begin{cases} \sum_c w_c(\mathbf{p})\, m_c & \text{grids},\\ m_{t(\mathbf{p})} & \text{triangular meshes}, \end{cases}\end{split}\]

with \(m_c = \log_{10}\rho_c\) at cell centres, \(w_c\) the multilinear weights, and \(t(\mathbf{p})\) the triangle containing \(\mathbf{p}\). Interpolating \(m\), not \(\rho\), weights relative changes equally in resistive and conductive parts of a model; on meshes the piecewise-constant rule keeps contrasts across region boundaries. The method is second order on smooth grid fields and first order on meshes.

Examples

>>> import pcsf
>>> from pcsf.algorithms import sample_log10
>>> model = pcsf.PCSFModel(
...     geometry=pcsf.Grid2DGeometry(x=[0.0, 10.0], z=[5.0]),
...     resistivity=[[10.0, 1000.0]],
... )
>>> print(sample_log10(model, [[5.0, 5.0], [50.0, 5.0]]))
[ 2. nan]
pycsamt.format.read_pcbh(path, *, validate=True, max_bytes=16777216, max_boreholes=10000, max_intervals=1000000, max_nesting=32)#

Read a canonical PCBH JSON file.

Parameters:
  • path (path-like) – Input .pcbh.json file.

  • validate (bool, default True) – Run semantic validation before returning.

  • max_bytes (int) – Positive limits for untrusted input.

  • max_boreholes (int) – Positive limits for untrusted input.

  • max_intervals (int) – Positive limits for untrusted input.

  • max_nesting (int) – Positive limits for untrusted input.

Returns:

Parsed and optionally validated document.

Return type:

PCBHDocument

Raises:
  • OSError – If the file cannot be read.

  • UnicodeError – If the file is not UTF-8.

  • ValueError – If JSON, structure, version, or limits are invalid.

  • PCBHValidationError – If semantic validation fails.

pycsamt.format.write_pcbh(document, path, *, validate=True, indent=2)#

Atomically write a canonical PCBH JSON file.

Parameters:
  • document (PCBHDocument) – Document to serialize.

  • path (path-like) – Destination path. Parent directories are created when needed.

  • validate (bool, default True) – Run semantic validation before writing.

  • indent (int, default 2) – Positive JSON indentation width.

Returns:

Destination path.

Return type:

pathlib.Path

Raises:
  • TypeError – If document is not a PCBH document.

  • ValueError – If validation, JSON values, or indent are invalid.

  • OSError – If the atomic write fails.

Notes

The temporary file is created beside the destination so os.replace() remains an atomic same-filesystem operation.

pycsamt.format.desurvey(borehole, *, boundaries=())#

Generate a 3-D centerline for borehole.

Survey stations after total depth are rejected by schema validation. If the first survey station is below the collar, its attitude is extended back to MD 0. Likewise, the final attitude is extended to total depth.

Parameters:
Return type:

DesurveyedTrajectory

pycsamt.format.boreholes_from_csv(path, *, columns=None, constants=None, strict=True, delimiter=None, document_id=None, created_by='pycsamt CSV importer', max_bytes=10485760, max_rows=250000)#

Import a combined collar-and-interval CSV as a PCBH document.

Parameters:
  • path (path-like) – UTF-8 CSV containing repeated collar fields and interval rows.

  • columns (dict, optional) – Explicit {canonical_field: source_header} mapping. Canonical names use dotted paths such as borehole.id and interval.from_md.

  • constants (dict, optional) – Constant canonical values, commonly crs.horizontal. Constants take precedence over mapped row values.

  • strict (bool, default=True) – Raise PCBHCSVImportError if any error is recorded. In permissive mode, invalid rows are rejected and valid rows returned.

  • delimiter ({',', ';', 't', '|'}, optional) – Explicit delimiter. If omitted, detection is restricted to this set.

  • document_id (str, optional) – PCBH document identifier. Defaults to csv:<file stem>.

  • created_by (str, default='pycsamt CSV importer') – Provenance name stored on the document.

  • max_bytes (int, default=10485760) – Maximum source size in bytes.

  • max_rows (int, default=250000) – Maximum number of data rows.

Returns:

  • document (PCBHDocument) – Valid document containing every accepted row.

  • report (ImportReport) – Source checksum, mappings, inferences, counts, and diagnostics.

Raises:
  • PCBHCSVImportError – If the file structure is unusable, no valid boreholes remain, or strict mode records an error. The exception exposes report.

  • ValueError – If a resource limit or delimiter parameter is invalid.

Return type:

tuple[PCBHDocument, ImportReport]

Notes

Missing tokens are normalized before conversion and never stringified. Repeated collar and total-depth values must agree within a borehole.

pycsamt.format.boreholes_from_csv_directory(directory, *, manifest='import.yaml', strict=True, document_id=None, created_by='pycsamt relational CSV importer')#

Import joined collar, survey, log, structure, sample, assay tables.

Parameters:
Return type:

tuple[PCBHDocument, ImportReport]

pycsamt.format.write_csv_directory(document, directory)#

Export supported PCBH content as a relational CSV directory.

Parameters:
  • document (PCBHDocument)

  • directory (str | Path)

Return type:

Path

pycsamt.format.borehole_from_las(path, *, collar, crs_horizontal, kind='unknown', status='unknown', depth_curve='DEPT', resistivity_curve='RESD', lithology_curve='LITH', max_samples=250000)#

Import a LAS 2.0 curve subset while retaining curve metadata.

Parameters:
  • path (str | Path)

  • collar (Collar)

  • crs_horizontal (str)

  • kind (str)

  • status (str)

  • depth_curve (str)

  • resistivity_curve (str)

  • lithology_curve (str | None)

  • max_samples (int)

Return type:

tuple[PCBHDocument, ImportReport]

pycsamt.format.write_las_subset(borehole, path, *, null_value=-9999.25, company='pycsamt')#

Write inline PCBH curves, or an interval-derived LAS subset.

Parameters:
  • borehole (PCBHBorehole)

  • path (str | Path)

  • null_value (float)

  • company (str)

Return type:

tuple[Path, LASExportReport]

pycsamt.format.build_render_model(document, *, family='lithology', selected_ids=None, radius_policy=None, lod_tolerance=0.0, sampling_step_md=10.0, max_points_per_hole=10000)#

Build a render model with a short-lived builder.

Parameters mirror BoreholeRenderBuilder.build(). Distances are in the document coordinate/depth unit and no CRS transformation is applied.

Parameters:
  • document (PCBHDocument)

  • family (str)

  • selected_ids (set[str] | None)

  • radius_policy (DisplayRadiusPolicy | None)

  • lod_tolerance (float)

  • sampling_step_md (float)

  • max_points_per_hole (int)

Return type:

PCBHRenderModel

pycsamt.format.embed_pcbh(model, document, *, uri=None)#

Return a model copy with a validated portable PCBH attachment.

Parameters:
  • model (PCSFModel)

  • document (PCBHDocument)

  • uri (str | None)

Return type:

PCSFModel

pycsamt.format.reference_pcbh(model, uri, sha256)#

Return a model copy with an external PCBH reference.

Parameters:
Return type:

PCSFModel

pycsamt.format.extract_pcbh(model)#

Return embedded PCBH data without resolving external resources.

Parameters:

model (PCSFModel)

Return type:

PCBHDocument | None

pycsamt.format.align_pcbh_to_pcsf(document, model, *, vertical_offset=None, sampling_step_md=10.0)#

Transform PCBH paths into PCSF x/y/depth coordinates.

vertical_offset is required when PCBH and PCSF vertical references cannot be established as identical. It is added to PCBH elevations before conversion to PCSF depth-positive-down coordinates.

Parameters:
  • document (PCBHDocument)

  • model (PCSFModel)

  • vertical_offset (float | None)

  • sampling_step_md (float)

Return type:

PCBHAlignmentReport

pycsamt.format.write_geojson(document, path, *, target_crs='EPSG:4326', include_z=True)#

Write WGS84 collar Points and trajectory LineStrings as GeoJSON.

Parameters:
  • document (PCBHDocument)

  • path (str | Path)

  • target_crs (str)

  • include_z (bool)

Return type:

tuple[Path, PCBHExportReport]

pycsamt.format.write_vtp(document, path, *, family='lithology', sides=8)#

Write interval tubes as ASCII VTK XML PolyData (.vtp).

Parameters:
  • document (PCBHDocument)

  • path (str | Path)

  • family (str)

  • sides (int)

Return type:

tuple[Path, PCBHExportReport]

pycsamt.format.write_gltf(document, path, *, family='lithology', sides=8)#

Write browser-ready glTF 2.0 (.gltf) or binary GLB tubes.

Parameters:
  • document (PCBHDocument)

  • path (str | Path)

  • family (str)

  • sides (int)

Return type:

tuple[Path, PCBHExportReport]

class pycsamt.format.SourceKind(category, path, is_dir, backend=None, geometry=None, target_geometry=None, confidence='high', detail='', hints=<factory>)#

Bases: object

Outcome of detect_source().

Variables:
  • category (str) – "pcsf" | "pcsm" | "solver" | "ai_arrays" | "unknown".

  • path (pathlib.Path) – The path that was probed (a file, or a solver working directory).

  • is_dir (bool) – Whether path is a directory.

  • backend (str or None) – "occam2d" | "modem" | "mare2dem" for solver sources, else None.

  • geometry (str or None) – For pcsf / pcsm: the peeked geometry kind.

  • target_geometry (str or None) – For solver / ai_arrays: the PCSF geometry the conversion will produce.

  • confidence (str) – "high" | "medium" | "low".

  • detail (str) – Human-readable one-line explanation.

  • hints (dict) – Extra paths / keys the converter needs (see module docstring).

Parameters:
category: str#
path: Path#
is_dir: bool#
backend: str | None = None#
geometry: str | None = None#
target_geometry: str | None = None#
confidence: str = 'high'#
detail: str = ''#
hints: dict[str, Any]#
property convertible: bool#

True when this source can be fed to pycsamt format convert.

to_dict()#

JSON-friendly plain-dict view.

Return type:

dict[str, Any]

pycsamt.format.detect_source(path, *, solver_hint=None)#

Detect what path is and how it should convert to PCSF/PCSM.

Parameters:
  • path (path-like) – A .pcsf / .pcsm / .npz / .npy file, a solver-specific file (.iter, .rho, .poly, .resistivity, …), or a solver working directory.

  • solver_hint ({"occam2d", "modem", "mare2dem"}, optional) – Force the solver backend instead of fingerprinting it. Ignored for PCSF/PCSM/array sources.

Return type:

SourceKind

Raises:

FileNotFoundError – If path does not exist.

pycsamt.format.describe_source(sk)#

Return a short multi-line human summary of sk.

Parameters:

sk (SourceKind)

Return type:

str

class pycsamt.format.Grid2DGeometry(x, z, x_nodes=None, z_nodes=None, origin=None, azimuth_deg=None)#

Bases: PCSFObject

Rectilinear geometry of one 2-D section (Occam2D).

Parameters:
  • x (ndarray (n_x,)) – Real station chainage, metres — never a solver’s mesh-local frame (see the Occam2D coordinate-frame note in the Occam2D adapter).

  • z (ndarray (n_z,)) – Depth cell centres, metres, positive downward.

  • x_nodes (ndarray, optional) – Cell-edge coordinates, one longer than x/z.

  • z_nodes (ndarray, optional) – Cell-edge coordinates, one longer than x/z.

  • origin (ndarray (2,), optional) – Real-world offset when x is locally referenced.

  • azimuth_deg (float, optional) – Profile bearing, for georeferencing back to the survey line.

Examples

>>> from pcsf import Grid2DGeometry
>>> g = Grid2DGeometry(x=[0.0, 50.0, 100.0], z=[5.0, 15.0])
>>> g.resistivity_shape
(2, 3)
kind: ClassVar[str] = 'grid2d'#
x: ndarray#
z: ndarray#
x_nodes: ndarray | None = None#
z_nodes: ndarray | None = None#
origin: ndarray | None = None#
azimuth_deg: float | None = None#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If x or z is not 1-D, a node array does not have one more element than its centres, or origin does not have shape (2,).

Return type:

None

property resistivity_shape: tuple[int, int]#

Shape (n_z, n_x) of the resistivity array.

class pycsamt.format.Grid3DGeometry(x, y, z, x_nodes=None, y_nodes=None, z_nodes=None, origin=None, rotation_deg=0.0, n_air=0)#

Bases: PCSFObject

Native 3-D tensor volume geometry (ModEM).

Parameters:
  • x (ndarray) – Cell-centre coordinates, metres.

  • y (ndarray) – Cell-centre coordinates, metres.

  • z (ndarray) – Cell-centre coordinates, metres.

  • x_nodes (ndarray, optional) – Cell-edge coordinates.

  • y_nodes (ndarray, optional) – Cell-edge coordinates.

  • z_nodes (ndarray, optional) – Cell-edge coordinates.

  • origin (ndarray (3,), optional) – Real-world grid origin.

  • rotation_deg (float, default 0.0) – Grid rotation about the vertical axis.

  • n_air (int, default 0) – Explicit air-layer count (unlike Occam2D’s inferred count).

Examples

>>> from pcsf.core.schema import Grid3DGeometry
>>> g = Grid3DGeometry(x=[0.0, 1.0], y=[0.0], z=[1.0, 2.0, 3.0])
>>> g.resistivity_shape
(3, 1, 2)
kind: ClassVar[str] = 'grid3d'#
x: ndarray#
y: ndarray#
z: ndarray#
x_nodes: ndarray | None = None#
y_nodes: ndarray | None = None#
z_nodes: ndarray | None = None#
origin: ndarray | None = None#
rotation_deg: float = 0.0#
n_air: int = 0#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If a centre array is not 1-D or a node array does not have one more element than its centres.

Return type:

None

property resistivity_shape: tuple[int, int, int]#
class pycsamt.format.UnstructuredMeshGeometry(nodes, connectivity, region_ids, plane='xz')#

Bases: PCSFObject

Native unstructured triangular mesh geometry (MARE2DEM).

Preserves the mesh as-is (no forced regrid onto a tensor grid), so a MARE2DEM result keeps its real element resolution.

Parameters:
  • nodes (ndarray (n, 2) or (n, 3)) – Node coordinates, metres.

  • connectivity (ndarray (m, 3), int) – Triangle node indices.

  • region_ids (ndarray (m,), int) – Region id per triangle.

  • plane ({"xz", "xy", "3d"}, default "xz") – Physical plane the mesh lives in. MARE2DEM profiles are conventionally in (y, z) but stored generically as plane="xz" with x holding the profile’s own along-line coordinate.

Examples

>>> from pcsf.core.schema import UnstructuredMeshGeometry
>>> mesh = UnstructuredMeshGeometry(
...     nodes=[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]],
...     connectivity=[[0, 1, 2]],
...     region_ids=[0],
... )
>>> mesh.n_regions
1
kind: ClassVar[str] = 'mesh_unstructured'#
nodes: ndarray#
connectivity: ndarray#
region_ids: ndarray#
plane: str = 'xz'#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If an array has the wrong shape, plane is unknown, or the connectivity references a node that does not exist.

Return type:

None

property n_regions: int#

Number of distinct region ids.

class pycsamt.format.LineEntry(line_id, geometry, resistivity, offset_y=0.0, offset_kind='synthetic', azimuth_deg=None)#

Bases: PCSFObject

One profile within a MultilineGeometry.

Parameters:
  • line_id (str) – Unique identifier for this line.

  • geometry (Grid2DGeometry) – The line’s own 2-D section geometry.

  • resistivity (ndarray (n_z, n_x)) – Canonical linear ohm.m resistivity for this line.

  • offset_y (float) – Cross-line position, metres.

  • offset_kind ({"real", "synthetic"}, default "synthetic") – Whether offset_y comes from real survey geometry or is a placeholder spacing for display only.

  • azimuth_deg (float, optional) – Line bearing.

Examples

>>> from pcsf.core.schema import Grid2DGeometry, LineEntry
>>> line = LineEntry(
...     "L1", Grid2DGeometry(x=[0.0, 10.0], z=[5.0]),
...     resistivity=[[100.0, 200.0]], offset_y=250.0,
...     offset_kind="real",
... )
>>> line.validate()
line_id: str#
geometry: Grid2DGeometry#
resistivity: ndarray#
offset_y: float = 0.0#
offset_kind: str = 'synthetic'#
azimuth_deg: float | None = None#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If the resistivity shape does not match the geometry or offset_kind is unknown.

Return type:

None

class pycsamt.format.DerivedVolume(grid, resistivity, derivation_method='linear_interp', derived_from=<factory>, synthesized=True)#

Bases: PCSFObject

Optional 3-D volume synthesized from stacked lines.

The volume is always labelled as synthesized, so that a reader never mistakes an interpolated stack of 2-D sections for a 3-D inversion (rule C7).

Parameters:
  • grid (Grid3DGeometry) – Grid of the volume.

  • resistivity (ndarray of shape (n_z, n_y, n_x)) – Resistivity in ohm m.

  • derivation_method (str, default "linear_interp") – One of DERIVATION_METHODS.

  • derived_from (list of str) – Identifiers of the lines used.

  • synthesized (bool, default True) – Must stay True for a conforming file.

Examples

>>> import numpy as np
>>> from pcsf.core.schema import DerivedVolume, Grid3DGeometry
>>> grid = Grid3DGeometry(x=[0.0, 10.0], y=[0.0, 100.0], z=[5.0])
>>> vol = DerivedVolume(grid, np.full((1, 2, 2), 100.0),
...                     derived_from=["L0", "L1"])
>>> vol.synthesized
True
grid: Grid3DGeometry#
resistivity: ndarray#
derivation_method: str = 'linear_interp'#
derived_from: list[str]#
synthesized: bool = True#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If the resistivity shape does not match the grid or derivation_method is unknown.

Return type:

None

class pycsamt.format.MultilineGeometry(lines=<factory>, derived_volume=None)#

Bases: PCSFObject

A set of 2-D profiles with their real positions.

Each line carries its own geometry and resistivity, so that fence and block views are built from stored data rather than reconstructed at render time. The optional derived volume is a documented, reproducible synthesis.

Parameters:
  • lines (list of LineEntry) – Profiles, with unique identifiers.

  • derived_volume (DerivedVolume, optional) – Volume interpolated from the lines.

Examples

>>> from pcsf.core.schema import (Grid2DGeometry, LineEntry,
...                               MultilineGeometry)
>>> geo = Grid2DGeometry(x=[0.0, 10.0], z=[5.0])
>>> lines = [LineEntry(f"L{i}", geo, [[100.0, 200.0]], 100.0 * i)
...          for i in range(2)]
>>> MultilineGeometry(lines).validate()
kind: ClassVar[str] = 'multiline'#
lines: list[LineEntry]#
derived_volume: DerivedVolume | None = None#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If there is no line, line identifiers repeat, or a line or the derived volume is invalid.

Return type:

None

class pycsamt.format.StationTable(name=<factory>, x=<factory>, y=<factory>, z=<factory>, line_id=None, lon=None, lat=None)#

Bases: PCSFObject

Survey station positions, shared by all geometry kinds.

Parameters:
  • name (list of str) – Station names.

  • x (ndarray of shape (n,)) – Positions in the model frame, in metres: chainage along the profile for grid2d, the grid frame for grid3d, the mesh frame for mesh_unstructured. They are never geographic coordinates.

  • y (ndarray of shape (n,)) – Positions in the model frame, in metres: chainage along the profile for grid2d, the grid frame for grid3d, the mesh frame for mesh_unstructured. They are never geographic coordinates.

  • z (ndarray of shape (n,)) – Positions in the model frame, in metres: chainage along the profile for grid2d, the grid frame for grid3d, the mesh frame for mesh_unstructured. They are never geographic coordinates.

  • line_id (list of str, optional) – Line of each station, for multiline models.

  • lon (ndarray of shape (n,), optional) – WGS84 longitude and latitude in decimal degrees; the only carrier of real-world position. Both or neither must be given.

  • lat (ndarray of shape (n,), optional) – WGS84 longitude and latitude in decimal degrees; the only carrier of real-world position. Both or neither must be given.

Examples

>>> from pcsf.core.schema import StationTable
>>> st = StationTable(name=["S1", "S2"], x=[0.0, 50.0],
...                   y=[0.0, 0.0], z=[0.0, 0.0],
...                   lon=[-5.0, -5.0])
>>> st.validate()
Traceback (most recent call last):
...
pcsf.exceptions.GeometryError: StationTable.lon and .lat must ...
name: list[str]#
x: ndarray#
y: ndarray#
z: ndarray#
line_id: list[str] | None = None#
lon: ndarray | None = None#
lat: ndarray | None = None#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If an array length differs from the number of names, or only one of lon and lat is set.

Return type:

None

class pycsamt.format.TopographyPerStation(station_id=<factory>, elevation=<factory>)#

Bases: PCSFObject

Elevation of each station.

Parameters:
  • station_id (list of str) – Station names, matching StationTable.

  • elevation (ndarray of shape (n,)) – Elevation in metres above the vertical datum.

Examples

>>> from pcsf.core.schema import TopographyPerStation
>>> topo = TopographyPerStation(["S1", "S2"], [312.5, 298.0])
>>> topo.validate()
kind: ClassVar[str] = 'per_station'#
station_id: list[str]#
elevation: ndarray#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If elevation and station_id differ in length.

Return type:

None

class pycsamt.format.TopographyRaster(x, y, elevation)#

Bases: PCSFObject

Gridded elevation surface, independent of stations.

Unlike TopographyPerStation, this carries no station identifiers at all: it is a standalone terrain surface a consumer can sample at any coordinate, not a per-station lookup table. It adds no raster-library dependency: it is built from x, y and elevation arrays obtained by the caller, and pcsf never parses georeferenced raster files.

Parameters:
  • x (ndarray (n_x,)) – Grid x-coordinates (or longitude), increasing.

  • y (ndarray (n_y,)) – Grid y-coordinates (or latitude), increasing.

  • elevation (ndarray (n_y, n_x)) – Elevation surface, metres, sampled on the (y, x) meshgrid implied by x/y — the same row-major convention numpy.meshgrid(x, y) (default indexing="xy") produces.

Examples

>>> import numpy as np
>>> from pcsf.core.schema import TopographyRaster
>>> topo = TopographyRaster(x=[0.0, 10.0, 20.0], y=[0.0, 10.0],
...                         elevation=np.zeros((2, 3)))
>>> topo.validate()
kind: ClassVar[str] = 'raster'#
x: ndarray#
y: ndarray#
elevation: ndarray#
validate()#

Check the consistency of the arrays.

Raises:

GeometryError – If x or y is not 1-D or elevation does not have shape (len(y), len(x)).

Return type:

None

class pycsamt.format.PCSFModel(geometry, resistivity=None, resistivity_native=None, resistivity_native_encoding=None, uncertainty=None, sensitivity=None, resistivity_by_region=None, resistivity_by_node=None, stations=None, topography=None, survey=<factory>, history=<factory>, source_backend='generic', created_by='', created_at='', crs=None, description='', metadata=<factory>, boreholes=None)#

Bases: PCSFObject, MetadataMixin

Solver-neutral resistivity model; one PCSF file.

Parameters:
  • geometry (geometry object) – The model’s geometry, discriminated by geometry.kind: a Grid2DGeometry, Grid3DGeometry, UnstructuredMeshGeometry or MultilineGeometry.

  • resistivity (ndarray, optional) – Canonical linear ohm.m resistivity. Required for grid2d/grid3d/mesh_unstructured geometries; must be None for multiline (each line carries its own resistivity — see LineEntry).

  • resistivity_native (ndarray, optional) – Passthrough of the source backend’s own array, for provenance.

  • resistivity_native_encoding (str, optional) – Encoding of resistivity_native, a name from pcsf.core.encodings.known_encodings(). Required whenever resistivity_native is given; never assumed.

  • uncertainty (ndarray, optional) – Same shape as resistivity, when available from the source.

  • sensitivity (ndarray, optional) – Same shape as resistivity, when available from the source.

  • resistivity_by_region (ndarray, optional) – Per-region resistivity table (mesh_unstructured only), alongside the per-cell resistivity expanded from it.

  • resistivity_by_node (ndarray, optional) – Per-node resistivity table (mesh_unstructured only), shape (n_nodes,) – the natural output shape of a graph-based model (e.g. a GCN) that predicts one value per mesh vertex rather than per cell. Kept alongside the per-cell resistivity derived from it (see pcsf.algorithms.node_to_cell()).

  • stations (StationTable, optional)

  • topography (TopographyPerStation | TopographyRaster, optional)

  • survey (dict) – Free-form survey metadata. Adapters populate this from survey-metadata objects (SurveyMeta, BBox, ProvenanceMeta) via their own dict conversion; PCSF itself does not require a specific metadata class here.

  • history (dict of ndarray) – Optional per-iteration series (e.g. {"rms": ..., "lambda": ...}) from an InversionHistory-like source.

  • source_backend (str, default "generic") – "occam2d" | "modem3d" | "mare2dem" | "duhi" | "generic".

  • created_by (str) – Producing software and ISO 8601 creation time.

  • created_at (str) – Producing software and ISO 8601 creation time.

  • crs (str, optional) – A pyproj-compatible CRS string.

  • description (str) – Free text.

  • metadata (dict) – Free-form metadata, including the inversion record (metadata["inversion"]).

  • boreholes (dict or object, optional) – Borehole association, interpreted by the borehole companion format and stored as JSON.

See also

pcsf.read, pcsf.write, pcsf.validate

Notes

Arrays are converted to float64 on construction but not checked; call validate() (the writers do) to check shapes and encodings.

Examples

>>> import numpy as np
>>> import pcsf
>>> native = np.log10([[100.0, 300.0]])
>>> model = pcsf.PCSFModel(
...     geometry=pcsf.Grid2DGeometry(x=[0.0, 10.0], z=[5.0]),
...     resistivity=10.0**native,
...     resistivity_native=native,
...     resistivity_native_encoding="log10",
...     source_backend="occam2d",
... )
>>> model.validate()
>>> model.kind
'grid2d'
geometry: Grid2DGeometry | Grid3DGeometry | UnstructuredMeshGeometry | MultilineGeometry#
resistivity: ndarray | None = None#
resistivity_native: ndarray | None = None#
resistivity_native_encoding: str | None = None#
uncertainty: ndarray | None = None#
sensitivity: ndarray | None = None#
resistivity_by_region: ndarray | None = None#
resistivity_by_node: ndarray | None = None#
stations: StationTable | None = None#
topography: TopographyPerStation | TopographyRaster | None = None#
survey: dict[str, Any]#
history: dict[str, ndarray]#
source_backend: str = 'generic'#
created_by: str = ''#
created_at: str = ''#
crs: str | None = None#
description: str = ''#
metadata: dict[str, Any]#
boreholes: Any | None = None#
property kind: str#

Geometry kind, such as "grid2d".

validate()#

Check the consistency of the arrays.

Raises:
  • GeometryError – If the geometry is invalid or an array shape does not match it.

  • EncodingError – If source values are given without a known encoding.

  • TypeError – If boreholes is neither a dict nor an object with to_dict().

Return type:

None

pycsamt.format.read_pcsf(path)#

Read a PCSFModel back from a .pcsf (HDF5) file.

Parameters:

path (path-like) – Source file.

Returns:

Fully reconstructed and re-validated model.

Return type:

PCSFModel

Raises:
  • FormatError – If pcsf_version or the geometry group is missing, or the geometry kind is unknown.

  • VersionError – If pcsf_version is malformed or of another major version (specification, section 5).

  • GeometryError, EncodingError – If the reconstructed model fails PCSFModel.validate().

Warns:

UserWarning – If the file’s minor version is newer than this reader’s; fields added since then are ignored.

See also

write_pcsf

Inverse operation.

pcsf.read

Read either encoding.

pcsf.api.registry.register_format

Companion-format decoders.

Notes

The optional boreholes group is returned as the dictionary it stores, unless a companion format registered under the group’s kind attribute ("pcbh") provides a from_dict callable, in which case model.boreholes is its result.

Examples

See write_pcsf().

pycsamt.format.write_pcsf(model, path)#

Write a PCSFModel to a .pcsf (HDF5) file.

Parameters:
  • model (PCSFModel) – The model to serialize. Validated before anything is written.

  • path (path-like) – Destination file. Parent directories are created if missing.

Returns:

The path written to.

Return type:

pathlib.Path

Raises:

See also

read_pcsf

Inverse operation.

pcsf.core.text.write_pcsm

Text encoding.

Examples

>>> import os, tempfile
>>> from pcsf import Grid2DGeometry, PCSFModel
>>> from pcsf.core.hdf5 import read_pcsf, write_pcsf
>>> model = PCSFModel(
...     geometry=Grid2DGeometry(x=[0.0, 100.0], z=[10.0, 50.0]),
...     resistivity=[[100.0, 120.0], [50.0, 60.0]],
...     source_backend="occam2d",
... )
>>> with tempfile.TemporaryDirectory() as tmp:
...     path = write_pcsf(model, os.path.join(tmp, "m.pcsf"))
...     back = read_pcsf(path)
>>> bool((back.resistivity == model.resistivity).all())
True
pycsamt.format.read_pcsm(path)#

Read a PCSFModel back from a .pcsm (ASCII) file.

Parameters:

path (path-like) – Source file.

Returns:

Fully reconstructed and re-validated model.

Return type:

PCSFModel

Raises:
  • PCSMSyntaxError – If the text does not follow the grammar.

  • VersionError – If PCSM_VERSION is malformed or of another major version (specification, section 5).

  • GeometryError, EncodingError – If the reconstructed model fails PCSFModel.validate().

See also

write_pcsm

Inverse operation.

pcsf.read

Read either encoding.

Examples

See write_pcsm().

pycsamt.format.write_pcsm(model, path, *, log10_view=False)#

Write a PCSFModel to a .pcsm (ASCII) file.

The same model write_pcsf() would encode as HDF5, encoded instead as human-readable, hand-editable text. See the module docstring for the grammar.

Every resistivity block carries its own encoding as an inline comment right next to the data, not only in a separate header line – e.g. RESISTIVITY  # linear ohm.m (canonical, ...) – so a reader never has to guess or scroll elsewhere to tell linear from log10. The canonical RESISTIVITY field is always linear ohm.m (specification, section 2): this cannot be changed by an option, since a reader/consumer relies on that invariant unconditionally, and reversing a 10**log10(x) round-trip is not guaranteed bit-exact the way the rest of this format’s repr()-based float round-trip is.

Pass log10_view=True to additionally write a RESISTIVITY_LOG10 block (and, for a multiline file, one per line) alongside it – a convenience for reading resistivity in the log space many EM inversions (Occam2D among them) actually work in. This is a write-only, clearly-labelled derived view: read_pcsm() discards it, it never becomes part of the returned PCSFModel, and it never influences the canonical RESISTIVITY block. (An Occam2D-sourced model already carries its own real log10 array as RESISTIVITY_NATIVE whenever resistivity_native is set – that block is unaffected by this option and is written either way.)

A path ending in .gz (e.g. model.pcsm.gz) is written gzip-compressed. Large volumes (a native grid3d or a dense mesh_unstructured mesh) produce large plain-text files – the same trade-off ModEM’s own ASCII .rho format already accepts – and gzip substantially reduces that in practice (measured on the 590,400-cell ModEM volume of the accompanying paper: 19.7 MB plain, 3.9 MB gzipped, against 4.1 MB for the equivalent .pcsf; real inverted resistivity compresses far better than random test data). A gzipped file is no longer something to casually open in a text editor, so this stays opt-in rather than the default: PCSM’s purpose is hand-editability, which a compressed file gives up.

Parameters:
  • model (PCSFModel) – The model to serialize. Validated before anything is written.

  • path (path-like) – Destination file. Parent directories are created if missing. A .gz suffix writes a gzip-compressed file.

  • log10_view (bool, default False) – Also write a RESISTIVITY_LOG10 convenience block (see above). Off by default so existing files/output size are unaffected unless explicitly requested.

Returns:

The path written to.

Return type:

pathlib.Path

Raises:

See also

read_pcsm

Inverse operation.

pcsf.core.hdf5.write_pcsf

Binary encoding.

Examples

>>> import os, tempfile
>>> from pcsf import Grid2DGeometry, PCSFModel
>>> from pcsf.core.text import read_pcsm, write_pcsm
>>> model = PCSFModel(
...     geometry=Grid2DGeometry(x=[0.0, 100.0], z=[10.0, 50.0]),
...     resistivity=[[100.0, 120.0], [50.0, 60.0]],
...     source_backend="occam2d",
... )
>>> with tempfile.TemporaryDirectory() as tmp:
...     path = os.path.join(tmp, "m.pcsm.gz")
...     _ = write_pcsm(model, path, log10_view=True)
...     back = read_pcsm(path)
>>> print(back.resistivity)
[[100. 120.]
 [ 50.  60.]]
pycsamt.format.pcsf_to_pcsm(pcsf_path, pcsm_path, *, log10_view=False)#

Convert a .pcsf (HDF5) file to .pcsm text.

Parameters:
  • pcsf_path (path-like) – Source file.

  • pcsm_path (path-like) – Destination; a .gz suffix compresses it.

  • log10_view (bool, default False) – Passed to write_pcsm().

Returns:

The path written to.

Return type:

pathlib.Path

See also

pcsm_to_pcsf

Inverse conversion.

pcsf.convert

Conversion with content detection.

Examples

>>> import os, tempfile
>>> import pcsf
>>> from pcsf.core.text import pcsf_to_pcsm, pcsm_to_pcsf
>>> model = pcsf.PCSFModel(
...     geometry=pcsf.Grid2DGeometry(x=[0.0], z=[5.0]),
...     resistivity=[[100.0]],
... )
>>> with tempfile.TemporaryDirectory() as tmp:
...     a = pcsf.write(model, os.path.join(tmp, "a.pcsf"))
...     b = pcsf_to_pcsm(a, os.path.join(tmp, "b.pcsm"))
...     c = pcsm_to_pcsf(b, os.path.join(tmp, "c.pcsf"))
...     pcsf.read(c).resistivity.tolist()
[[100.0]]
pycsamt.format.pcsm_to_pcsf(pcsm_path, pcsf_path)#

Convert a .pcsm text file to .pcsf (HDF5).

Parameters:
  • pcsm_path (path-like) – Source file, plain or gzip-compressed.

  • pcsf_path (path-like) – Destination.

Returns:

The path written to.

Return type:

pathlib.Path

See also

pcsf_to_pcsm

Inverse conversion, with an example.

pycsamt.format.read_pcsf_or_pcsm(path)#

Read a PCSFModel from either encoding, by extension.

The extension is the only signal used; pcsf.read() detects the encoding from the content instead and is preferred in new code.

Parameters:

path (path-like) – A .pcsf (binary HDF5), .pcsm (ASCII), or .pcsm.gz (gzip-compressed ASCII) file.

Returns:

The model read.

Return type:

PCSFModel

Raises:

PCSMSyntaxError – If the extension is none of the three recognised forms.

See also

pcsf.read

Content-based detection.

Examples

>>> from pcsf.core.text import read_pcsf_or_pcsm
>>> read_pcsf_or_pcsm("model.txt")
Traceback (most recent call last):
...
pcsf.exceptions.PCSMSyntaxError: model.txt: unrecognised ...
pycsamt.format.peek_kind(path)#

Geometry kind of a file, without reading its arrays.

Only the geometry attribute of a .pcsf file or the GEOMETRY_KIND header of a .pcsm file is read, so that a file picker can label many files cheaply.

Parameters:

path (path-like) – A .pcsf, .pcsm or .pcsm.gz file.

Returns:

Geometry kind, such as "grid2d".

Return type:

str

Raises:

PCSMSyntaxError – If the extension is not recognised or the kind cannot be found (for instance in a truncated file).

Examples

>>> import os, tempfile
>>> import pcsf
>>> from pcsf.core.text import peek_kind
>>> model = pcsf.PCSFModel(
...     geometry=pcsf.Grid2DGeometry(x=[0.0], z=[5.0]),
...     resistivity=[[100.0]],
... )
>>> with tempfile.TemporaryDirectory() as tmp:
...     path = pcsf.write(model, os.path.join(tmp, "m.pcsm"))
...     peek_kind(path)
'grid2d'
pycsamt.format.build_multiline_pcsf(profiles, *, line_spacing=1.0, fallback_unit=1000.0, cache_derived_volume=True, topo=None, epsg=None, utm_zone=None, latlon=False, on_mismatch='raise', survey=None, source_backend='generic', created_by='', crs=None, description='')#

Build a multiline PCSFModel from a profiles dict.

Parameters:
  • profiles (mapping of str to mapping) – {line_name: {"x": (n_x,), "z": (n_z,), "rho": (n_z, n_x), ...}}, the exact shape map3d.py’s _profiles_from_pseudo/ _profiles_from_inversion_result already produce. rho must already be linear ohm.m (call _rho_log_to_ohm_m-equivalent conversion first, matching every other PCSF adapter’s canonical-linear convention). Optional per-line keys sta_x, sta_names, sta_elev, sta_lat, sta_lon populate PCSFModel.stations/ PCSFModel.topography when present. sta_lat/ sta_lon do double duty: line_offsets_from_stations() uses them (via pycsamt.map.geometry.survey_uv()) to compute each line’s real cross-strike offset when every line carries them, falling back to a synthetic index-based stack otherwise (see offset_kind below) – and the same values are also persisted into PCSFModel.stations’ lon/lat, so a loaded multiline file is self-sufficiently geo-referenced too, not just correctly spaced.

  • line_spacing (float) – Forwarded to stack_lines_to_common_grid() for the optional cached DerivedVolume (real per-line geometry itself never depends on these — only the synthetic offset fallback does).

  • fallback_unit (float) – Forwarded to stack_lines_to_common_grid() for the optional cached DerivedVolume (real per-line geometry itself never depends on these — only the synthetic offset fallback does).

  • cache_derived_volume (bool, default True) – When True and there are at least two lines, also cache a DerivedVolume (each line resampled onto a common grid) so a large multiline file does not need to re-resample on every render. Set False to keep the file smaller when that convenience volume is not needed.

  • topo (optional) – A “smart” real-coordinate source resolved via pycsamt.format.topo_source.resolve_topo() – see pycsamt.format.adapters.occam2d.occam2d_to_pcsf()’s identical parameter for the full description of accepted source types. Populates each line’s own sta_lat/sta_lon before the real-offset computation above runs, so passing topo is enough to get both a real cross-strike offset per line and a self-georeferenced file – no separate offset step is needed. Accepts either a single source matched by station name across every line combined (a .stn/.csv/Sites source covering the whole survey), or a {line_name: source} mapping / one-source-per-line sequence (in profiles’s own key order) for e.g. one .bln file per surveyed line. Takes precedence over any sta_lat/sta_lon already present in profiles for every station it resolves (with a UserWarning if both were supplied). If topo only partially covers a line’s stations, the resulting nan entries make line_offsets_from_stations() fall back to a synthetic offset for every line (mixing a real and a synthetic stack would look inconsistent – see that function’s own all-or-nothing behaviour) rather than silently using a partially-real one; the stations themselves still keep whatever real lon/lat topo did resolve. None (the default) leaves this function’s behaviour exactly as it was before topo existed.

  • epsg (int | None) – Forwarded to pycsamt.format.topo_source.resolve_topo(); see occam2d_to_pcsf’s identical parameters.

  • utm_zone (Any | None) – Forwarded to pycsamt.format.topo_source.resolve_topo(); see occam2d_to_pcsf’s identical parameters.

  • latlon (bool) – Forwarded to pycsamt.format.topo_source.resolve_topo(); see occam2d_to_pcsf’s identical parameters.

  • on_mismatch (str) – Forwarded to pycsamt.format.topo_source.resolve_topo(); see occam2d_to_pcsf’s identical parameters.

  • survey (Any | Mapping[str, Any] | None) – Passed straight through to PCSFModel.

  • source_backend (str) – Passed straight through to PCSFModel.

  • created_by (str) – Passed straight through to PCSFModel.

  • crs (str | None) – Passed straight through to PCSFModel.

  • description (str) – Passed straight through to PCSFModel.

Raises:

ValueError – If profiles is empty, or any line is missing x/z/rho.

Return type:

PCSFModel

Examples

>>> import numpy as np
>>> from pycsamt.format.multiline import build_multiline_pcsf
>>> profiles = {
...     "L1": {"x": np.array([0.0, 100.0]), "z": np.array([10.0, 50.0]),
...            "rho": np.array([[100.0, 110.0], [50.0, 55.0]])},
...     "L2": {"x": np.array([0.0, 100.0]), "z": np.array([10.0, 50.0]),
...            "rho": np.array([[200.0, 210.0], [90.0, 95.0]])},
... }
>>> model = build_multiline_pcsf(profiles, cache_derived_volume=False)
>>> model.kind
'multiline'
>>> [line.line_id for line in model.geometry.lines]
['L1', 'L2']
pycsamt.format.multiline_pcsf_to_profiles(model)#

Reconstruct a profiles dict from a multiline PCSFModel.

The exact inverse of build_multiline_pcsf()’s per-line conversion — the result is a drop-in alternate data source for map3d.py’s existing _build_fence_fig/_assemble_3d_grid/ _build_block_fig, which only need the {"x", "z", "rho", ...} shape, not any particular origin.

Parameters:

model (PCSFModel) – Must have geometry.kind == "multiline".

Returns:

{line_id: {"x", "z", "rho", "sta_x", "sta_names", "sta_elev", "sta_lat", "sta_lon"}}. Station keys are populated from PCSFModel.stations when present (matched to each line via StationTable.line_id); sta_lat/sta_lon come from StationTable.lat/.lon when the file has them (see build_multiline_pcsf()), else stay empty lists – an older file written before those fields existed round-trips the same way it always did.

Return type:

dict

Raises:

ValueError – If model is not a multiline geometry.

pycsamt.format.line_offsets_from_stations(profiles)#

Cross-strike offset (m) for each line, from real station lat/lon.

Same algorithm as map3d.py’s private _line_real_offsets (built on pycsamt.map.geometry.survey_uv()), so both the live-cache rendering path and this persisted-file path place lines identically. Requires every line to carry sta_lat/sta_lon/ sta_names of equal length; returns None otherwise so callers fall back to a synthetic index-based stack via resolve_offset().

Parameters:

profiles (Mapping[str, Mapping[str, Any]])

Return type:

dict[str, float] | None

pycsamt.format.stack_lines_to_common_grid(profiles, *, line_spacing=1.0, fallback_unit=1000.0)#

Resample every line onto the first line’s own (x, z) grid.

Same algorithm as map3d.py’s private _assemble_3d_grid: the first profile’s grid is the reference; other lines are resampled onto it via _resample_line_to_grid().

Returns:

  • x_arr, z_arr (ndarray) – The reference line’s own coordinates.

  • y_arr (ndarray, shape (n_lines,)) – Per-line cross-strike offset, from line_offsets_from_stations() when available, otherwise a synthetic idx * spacing * fallback_unit stack (see pycsamt.map.geometry.resolve_offset()).

  • rho_3d (ndarray, shape (n_lines, n_x, n_z))

Parameters:
Return type:

tuple[ndarray, ndarray, ndarray, ndarray]

pycsamt.format.topography_from_map_data(data)#

Build topography from a MapData’s own station elevations (typically real, EDI-derived values).

Parameters:

data (MapData) – Survey data, e.g. from pycsamt.map.load_lines().

Returns:

None when no station carries a finite elevation, so callers can leave PCSFModel.topography unset rather than persisting an all-nan table.

Return type:

TopographyPerStation or None

Examples

>>> from pycsamt.map import load_lines
>>> from pycsamt.format.topography import topography_from_map_data
>>> data = load_lines("data/AMT/WILLY_DATA", detect="folder")
>>> topo = topography_from_map_data(data)
pycsamt.format.topography_from_elevation_file(content, filename)#

Build topography from an uploaded elevation file.

Thin wrapper around pycsamt.map.topo.parse_elevation_file() (CSV / HDF5 / NPZ, flexible station-id and elevation column/array names) — the same parser the “Upload file” elevation source in pycsamt.app.web uses, so a file that works there also works here.

Parameters:
  • content (str or bytes) – A Dash dcc.Upload-style data URI ("data:...;base64,..."), raw base64 text, or raw bytes — anything parse_elevation_file() already accepts.

  • filename (str) – Used only for its extension (.csv/.h5/.hdf5/.npz).

Returns:

None when the file cannot be parsed (unrecognised format, missing id/elevation column) — matches parse_elevation_file()’s own best-effort, non-raising contract.

Return type:

TopographyPerStation or None

pycsamt.format.topography_to_elev_map(topo)#

Return {station_id: elevation}, the inverse of both builders.

The same shape pycsamt.map.topo.apply_elevations() and pycsamt.map.topo.parse_elevation_file() already use, so a PCSF file’s topography can be applied straight back onto a MapData with no extra conversion.

Parameters:

topo (TopographyPerStation)

Return type:

dict[str, float]

pycsamt.format.topography_from_grid(x, y, elevation)#

Build a gridded-DEM TopographyRaster.

Parameters:
  • x (ndarray (n_x,)) – Grid x-coordinates (or longitude), increasing.

  • y (ndarray (n_y,)) – Grid y-coordinates (or latitude), increasing.

  • elevation (ndarray (n_y, n_x)) – Elevation surface, metres, on the (y, x) meshgrid implied by x/y (numpy.meshgrid(x, y)’s default row-major convention).

Return type:

TopographyRaster

Examples

>>> import numpy as np
>>> from pycsamt.format.topography import topography_from_grid
>>> x = np.linspace(0.0, 500.0, 6)
>>> y = np.linspace(0.0, 300.0, 4)
>>> elevation = 100.0 + 0.01 * np.add.outer(y, x)
>>> topo = topography_from_grid(x, y, elevation)
>>> topo.elevation.shape
(4, 6)
pycsamt.format.topography_raster_to_grid(topo)#

Return (x, y, elevation), the inverse of topography_from_grid().

Parameters:

topo (TopographyRaster)

Return type:

tuple[ndarray, ndarray, ndarray]

class pycsamt.format.TopoTable(lon, lat, elevation=None, names=None, source='<unknown>')#

Bases: object

A parsed topo source, before it is matched to any station names.

Variables:
  • names (list of str, optional) – Station identity carried by the source itself. None for a positional-only source (e.g. a bare .bln).

  • lat (lon,) – WGS84 decimal degrees — already converted from easting/northing if the source needed that.

  • elevation (ndarray, shape (n,), optional) – Metres, nan where genuinely unknown.

  • source (str) – Human-readable provenance (file path, or a short description for an in-memory source), surfaced in error/warning messages.

Parameters:
lon: ndarray#
lat: ndarray#
elevation: ndarray | None = None#
names: list[str] | None = None#
source: str = '<unknown>'#
property n: int#
class pycsamt.format.TopoAttribution(lon=<factory>, lat=<factory>, elevation=<factory>, matched=<factory>, unmatched_stations=<factory>, source='none')#

Bases: object

Per-station real coordinates resolved from a topo source, ready to populate lon/lat (and merge into elevation).

Parameters:
lon: dict[str, float]#
lat: dict[str, float]#
elevation: dict[str, float]#
matched: list[str]#
unmatched_stations: list[str]#
source: str = 'none'#
pycsamt.format.read_topo_file(path, *, epsg=None, utm_zone=None, latlon=False)#

Parse a .bln/.csv/.stn topo file into a TopoTable.

Parameters:
  • path (path-like) – A .bln, .csv/.txt, or .stn file.

  • epsg (int, optional) – EPSG code of the source’s projected CRS, when it stores easting/northing rather than lat/lon. Takes precedence over utm_zone when both are given (matches pycsamt.gis.utils.to_ll()’s own precedence).

  • utm_zone (optional) – UTM zone designator (e.g. "32N"), an alternative to epsg.

  • latlon (bool, default False) – .bln only: set True when the file’s own x, y columns are already lon, lat (a .bln carries no CRS metadata to detect this from). Ignored for .csv/.stn, which are only treated as already-geographic when their own header says lat/lon.

Raises:

ValueError – Unrecognised extension, a malformed .bln header/body, no recognisable coordinate columns in a .csv/.stn file, or projected coordinates with neither epsg nor utm_zone.

Return type:

TopoTable

pycsamt.format.topo_from_sites(source)#

Extract lon/lat/elevation from an already-geo-located Sites/MapData/iterable-of-station-record object.

Duck-typed on purpose: works with anything iterable whose items (or whose .stations attribute’s items, for a MapData-like container) expose a station identifier (id/name/ station) plus longitude/latitude and, optionally, elevation – pycsamt.map._core.StationRecord and similar objects all qualify without any adapter code.

Raises:

ValueError – If no station in source carries a usable id + lon/lat pair.

Parameters:

source (Any)

Return type:

TopoTable

pycsamt.format.attribute_topo(topo, station_names, *, on_mismatch='raise')#

Match a parsed TopoTable onto station_names.

Name-based when topo.names is populated (exact match, then a normalized fallback); positional (in order, requiring an exact count match) otherwise. See the module docstring for the full rationale.

Parameters:
  • on_mismatch ({"raise", "warn"}, default "raise") – Only consulted for a positional (name-less) source. "raise" rejects a station-count mismatch outright; "warn" issues a UserWarning and attributes only the overlapping prefix (min(topo.n, len(station_names)) points, in order).

  • topo (TopoTable)

  • station_names (Sequence[str])

Return type:

TopoAttribution

pycsamt.format.resolve_topo(topo, station_names, *, epsg=None, utm_zone=None, latlon=False, on_mismatch='raise')#

Resolve any accepted topo= argument into a TopoAttribution against station_names.

Parameters:
  • topo (None, path-like, TopoTable, Sites/MapData-like, mapping, or sequence) –

    • None – returns an empty attribution (every adapter’s existing station_elevations/station_lonlat behaviour is unaffected).

    • a .bln/.csv/.stn path, or an already-parsed TopoTable.

    • a Sites/MapData/iterable-of-station-record object (see topo_from_sites()).

    • a plain {station_name: (lon, lat[, elevation])} mapping.

    • when station_names is a mapping (multiline, {line_id: [names, ...]}): a {line_id: <any of the above>} mapping, or a sequence with exactly one source per line, in the same order as station_names’s own keys. A single non-mapping, non-per-line-sequence source is instead matched by name across all lines’ stations combined – the natural choice for one combined .stn/.csv/Sites source covering a whole multiline survey.

  • station_names (sequence of str, or mapping of str to sequence of str) – The inversion’s own station names (flat), or {line_id: names} for a multiline build.

  • epsg (int | None) – Forwarded to read_topo_file()/attribute_topo() for every file-based source encountered.

  • utm_zone (Any | None) – Forwarded to read_topo_file()/attribute_topo() for every file-based source encountered.

  • latlon (bool) – Forwarded to read_topo_file()/attribute_topo() for every file-based source encountered.

  • on_mismatch (str) – Forwarded to read_topo_file()/attribute_topo() for every file-based source encountered.

Returns:

Empty (all fields blank, source="none") when topo is None.

Return type:

TopoAttribution

class pycsamt.format.PointCloud(x, y, z, value, label)#

Bases: object

Flat point cloud ready for a 3-D scatter view.

Variables:
  • z (x, y,) – Position, metres. z is elevation-like (positive up) — callers plotting depth sections see negative values below the surface, matching the sign convention already used by pycsamt.app.web.callbacks.map3d’s own 3-D views.

  • value (ndarray, shape (n,)) – \(\log_{10}(\rho / \Omega\mathrm{m})\).

  • label (str) – Short description of what was plotted (geometry kind + any subsampling applied), for a status bar / axis title.

Parameters:
x: ndarray#
y: ndarray#
z: ndarray#
value: ndarray#
label: str#
pycsamt.format.pcsf_to_point_cloud(model, *, max_points=200000, seed=0)#

Flatten any PCSFModel geometry into one 3-D point cloud.

Parameters:
  • model (PCSFModel) – Any geometry kind.

  • max_points (int, default 200_000) – Random (seeded, reproducible) subsample cap — a native grid3d/mesh_unstructured model can carry hundreds of thousands of cells, too many for an interactive scatter plot.

  • seed (int, default 0) – Subsampling RNG seed, for a reproducible view across renders.

Returns:

Non-finite values (masked cells, log of non-positive resistivity) are dropped, not zeroed.

Return type:

PointCloud

Raises:

ValueError – If model.geometry.kind is not one of GEOMETRY_KINDS.

Examples

>>> import numpy as np
>>> from pycsamt.format import Grid2DGeometry, PCSFModel
>>> from pycsamt.format.pointcloud import pcsf_to_point_cloud
>>> geometry = Grid2DGeometry(x=np.array([0.0, 100.0]), z=np.array([10.0, 50.0]))
>>> model = PCSFModel(geometry=geometry, resistivity=np.array([[100.0, 110.0], [50.0, 55.0]]))
>>> cloud = pcsf_to_point_cloud(model)
>>> cloud.x.shape
(4,)
class pycsamt.format.Point(id, name='', x=None, y=None, longitude=None, latitude=None, z=None, depth_top=None, depth_bottom=None, kind='poi', symbol='circle', color=None, note='', category='', properties=<factory>)#

Bases: PyCSAMTObject

One named position with an optional depth window.

Parameters:
id: str#
name: str = ''#
x: float | None = None#
y: float | None = None#
longitude: float | None = None#
latitude: float | None = None#
z: float | None = None#
depth_top: float | None = None#
depth_bottom: float | None = None#
kind: str = 'poi'#
symbol: str = 'circle'#
color: str | None = None#
note: str = ''#
category: str = ''#
properties: dict[str, Any]#
issues()#
Return type:

list[str]

class pycsamt.format.PointSet(document_id, created_at, created_by, crs, points, pcpt_version='0.1.0', title='', description='', metadata=<factory>)#

Bases: PyCSAMTObject, MetadataMixin

A validated flat list of points sharing one CRS.

Parameters:
document_id: str#
created_at: str#
created_by: str#
crs: str#
points: list[Point]#
pcpt_version: str = '0.1.0'#
title: str = ''#
description: str = ''#
metadata: dict[str, Any]#
issues()#
Return type:

list[str]

validate()#

Validate object state.

Subclasses can override this hook. The base implementation intentionally accepts all states.

Return type:

None

lonlat()#

Return {id: (lat, lon)} for every locatable point.

Return type:

dict[str, tuple[float, float]]

exception pycsamt.format.PointSetValidationError#

Bases: ValueError

Raised when a PCPT document fails validation.

pycsamt.format.read_points(path)#

Read a .pcpt.json file.

Parameters:

path (str | Path)

Return type:

PointSet

pycsamt.format.write_points(point_set, path)#

Write point_set as canonical .pcpt.json.

Parameters:
Return type:

Path

pycsamt.format.points_from_csv(path, *, columns=None, crs=None, document_id=None)#

Import a points CSV (one point per row).

Parameters:
Return type:

PointSet

pycsamt.format.points_from_xlsx(source, *, sheet=None, header_row=None, columns=None, crs=None, document_id=None)#

Import points from one worksheet of an .xlsx workbook.

Parameters:
Return type:

PointSet

pycsamt.format.point_set_to_dict(point_set)#

Return a canonical JSON-safe dict for point_set.

Parameters:

point_set (PointSet)

Return type:

dict[str, Any]

pycsamt.format.point_set_from_dict(payload)#

Build and validate a PointSet from a dict.

Parameters:

payload (dict[str, Any])

Return type:

PointSet

class pycsamt.format.GeologyLegend(document_id, created_at, created_by, db, pcgl_version='0.1.0', title='', description='', rho_unit='ohm.m', metadata=<factory>)#

Bases: PyCSAMTObject, MetadataMixin

A versioned, portable resistivity-to-geology legend document.

Parameters:
  • document_id (str)

  • created_at (str) – ISO-8601 timestamp.

  • created_by (str) – Creating application, workflow step, or person (e.g. "auto-suggest", "manual", a user name).

  • db (RockDatabase) – The legend table itself – resistivity ranges, colours, and pattern references. See pycsamt.geology.lithology. RockDatabase.

  • pcgl_version (str)

  • title (str)

  • description (str)

  • rho_unit (str) – Resistivity unit the ranges are expressed in. PCGL 0.1 only defines "ohm.m" (linear ohm-metres); readers MUST reject any other value rather than silently reinterpreting the ranges.

  • metadata (dict[str, Any])

document_id: str#
created_at: str#
created_by: str#
db: RockDatabase#
pcgl_version: str = '0.1.0'#
title: str = ''#
description: str = ''#
rho_unit: str = 'ohm.m'#
metadata: dict[str, Any]#
property entries: tuple[RockEntry, ...]#
classify(rho_ohm_m, method='nearest')#
Parameters:
Return type:

RockEntry

classmethod from_rock_database(db=None, *, document_id=None, created_by='pycsamt', title='', description='')#

Wrap an existing (or the built-in default) rock database as a PCGL document, ready to write or hand to Map View.

Parameters:
Return type:

GeologyLegend

classmethod from_csv(path, *, document_id=None, created_by='pycsamt CSV importer', title='')#

Load a legend from a CSV (see module docstring for columns).

Parameters:
Return type:

GeologyLegend

to_csv(path)#

Write the legend table as CSV (document metadata is dropped; use write_legend() to keep it).

Parameters:

path (str | Path)

Return type:

Path

issues()#
Return type:

list[str]

validate()#

Validate object state.

Subclasses can override this hook. The base implementation intentionally accepts all states.

Return type:

None

exception pycsamt.format.GeologyLegendValidationError#

Bases: ValueError

Raised when a PCGL document fails validation.

pycsamt.format.read_legend(path)#

Read a .pcgl.json file.

Parameters:

path (str | Path)

Return type:

GeologyLegend

pycsamt.format.write_legend(legend, path)#

Write legend as canonical .pcgl.json.

Parameters:
Return type:

Path

pycsamt.format.legend_from_csv(path, **kwargs)#

Module-level convenience alias for GeologyLegend.from_csv().

Parameters:
Return type:

GeologyLegend

pycsamt.format.legend_to_dict(legend)#

Return a canonical JSON-safe dict for legend.

Parameters:

legend (GeologyLegend)

Return type:

dict[str, Any]

pycsamt.format.legend_from_dict(payload)#

Build and validate a GeologyLegend from a dict.

Parameters:

payload (dict[str, Any])

Return type:

GeologyLegend

class pycsamt.format.StructModel(document_id, created_at, created_by, model, pcgs_version='0.1.0', title='', description='', metadata=<factory>)#

Bases: PyCSAMTObject, MetadataMixin

A versioned, portable structural-geology document.

Parameters:
document_id: str#
created_at: str#
created_by: str#
model: StructuralModel#
pcgs_version: str = '0.1.0'#
title: str = ''#
description: str = ''#
metadata: dict[str, Any]#
property planar#
property linear#
property faults#
classmethod from_structural_model(model=None, *, document_id=None, created_by='pycsamt', title='', description='')#
Parameters:
Return type:

StructModel

classmethod from_csv(*, planar_path=None, linear_path=None, faults_path=None, delimiter=',', document_id=None, created_by='pycsamt CSV importer', title='')#

Load a document from up to three CSV files – see pycsamt.geology.structural.StructuralModel.from_csv().

Parameters:
  • planar_path (str | Path | None)

  • linear_path (str | Path | None)

  • faults_path (str | Path | None)

  • delimiter (str)

  • document_id (str | None)

  • created_by (str)

  • title (str)

Return type:

StructModel

issues()#
Return type:

list[str]

validate()#

Validate object state.

Subclasses can override this hook. The base implementation intentionally accepts all states.

Return type:

None

exception pycsamt.format.StructModelValidationError#

Bases: ValueError

Raised when a PCGS document fails validation.

pycsamt.format.read_structure(path)#

Read a .pcgs.json file.

Parameters:

path (str | Path)

Return type:

StructModel

pycsamt.format.write_structure(doc, path)#

Write doc as canonical .pcgs.json.

Parameters:
Return type:

Path

pycsamt.format.structure_from_csv(**kwargs)#

Module-level convenience alias for StructModel.from_csv().

Parameters:

kwargs (Any)

Return type:

StructModel

pycsamt.format.structure_to_dict(doc)#

Return a canonical JSON-safe dict for doc.

Parameters:

doc (StructModel)

Return type:

dict[str, Any]

pycsamt.format.structure_from_dict(payload)#

Build and validate a StructModel from a dict.

Parameters:

payload (dict[str, Any])

Return type:

StructModel

class pycsamt.format.ModelProvenance(architecture='', framework='', framework_version='', checkpoint='', checkpoint_sha256='', training_data='', hyperparameters=<factory>, random_seed=None, git_commit='', authors=<factory>, contact='', notes='', extra=<factory>)#

Bases: PCSFObject

Describe the AI/DL model that produced a resistivity result.

Parameters:
  • architecture (str, optional) – Free-text model family/architecture, e.g. "UNet", "GCN", "ResNet18", or any third-party name.

  • framework (str, optional) – e.g. "pytorch"/"2.3.0", "tensorflow"/"2.16.1".

  • framework_version (str, optional) – e.g. "pytorch"/"2.3.0", "tensorflow"/"2.16.1".

  • checkpoint (str, optional) – Path or identifier of the trained weights used to produce the result (e.g. a filename, a model-hub id, a DOI).

  • checkpoint_sha256 (str, optional) – SHA-256 hex digest of the checkpoint file, so a reader can verify they are re-running the exact weights this result claims – see compute_checkpoint_hash().

  • training_data (str, optional) – Free-text reference to the training dataset (name, DOI, path).

  • hyperparameters (dict, default {}) – Free-form training/model hyperparameters.

  • random_seed (int, optional) – Seed used for training and/or inference, when reproducibility depends on it.

  • git_commit (str, optional) – Commit hash of the code that produced this result.

  • authors (list of str, default []) – Model authors/maintainers.

  • contact (str, optional) – Contact e-mail or URL for questions about this result.

  • notes (str, optional) – Free-text notes not covered by the fields above.

  • extra (dict, default {}) – Unmodelled provenance fields, retained losslessly.

Examples

>>> from pcsf.core.provenance import ModelProvenance
>>> prov = ModelProvenance(
...     architecture="UNet",
...     framework="pytorch",
...     framework_version="2.3.0",
...     checkpoint="unet_v3.pt",
...     random_seed=42,
... )
>>> prov.to_dict()["architecture"]
'UNet'
architecture: str = ''#
framework: str = ''#
framework_version: str = ''#
checkpoint: str = ''#
checkpoint_sha256: str = ''#
training_data: str = ''#
hyperparameters: dict[str, Any]#
random_seed: int | None = None#
git_commit: str = ''#
authors: list[str]#
contact: str = ''#
notes: str = ''#
extra: dict[str, Any]#
validate()#

Check field types.

Raises:

TypeError – If random_seed is neither an int nor None.

Return type:

None

to_dict()#

Plain dictionary form of the provenance.

Returns:

Every field, with containers copied; suitable for PCSFModel.metadata["model_provenance"].

Return type:

dict

pycsamt.format.compute_checkpoint_hash(path, *, chunk_size=1048576)#

SHA-256 of a model-checkpoint file, read in chunks.

Parameters:
  • path (path-like) – The checkpoint file to hash (e.g. a .pt/.h5/.onnx file).

  • chunk_size (int, default 1 MiB) – Read block size; large checkpoints are hashed without loading the whole file into memory.

Returns:

Lowercase hex digest, directly comparable to ModelProvenance.checkpoint_sha256.

Return type:

str

Examples

>>> from pcsf.core.provenance import compute_checkpoint_hash
>>> compute_checkpoint_hash("unet_v3.pt")
'3b1c...'
pycsamt.format.mesh_to_grid2d(model, *, nx=200, nz=150)#

Sample a triangular-mesh model on a regular grid2d.

Parameters:
  • model (PCSFModel) – Model of kind mesh_unstructured in plane "xz" with per-triangle resistivity of shape (n_triangles,). A per-region array must first be expanded onto each triangle’s region id.

  • nx (int, default 200 and 150) – Number of grid points along x and z. A mesh has no natural rectilinear resolution, so these are explicit, bounded defaults.

  • nz (int, default 200 and 150) – Number of grid points along x and z. A mesh has no natural rectilinear resolution, so these are explicit, bounded defaults.

Returns:

New grid2d model with nz by nx cells spanning the mesh bounding box. Points outside the triangulation are NaN. source_backend, created_by, crs and survey are carried over; description and metadata (keys synthesized, regridded_from, regrid_nx, regrid_nz) record that the model is synthesized.

Return type:

PCSFModel

Raises:

GeometryError – If model is not mesh_unstructured, its plane is not "xz", or its resistivity is not per triangle.

See also

pcsf.algorithms.sample_log10

Sample at arbitrary points.

Notes

Each grid point \(\mathbf{p}_{ij}\) takes the resistivity of the triangle \(t(\mathbf{p}_{ij})\) that contains it; no value is interpolated or extrapolated, so contrasts across region boundaries stay sharp at the cost of staircase edges of one grid step. The source values and the per-region table do not apply to the grid and are dropped.

Examples

>>> import numpy as np
>>> import pcsf
>>> from pcsf.algorithms import mesh_to_grid2d
>>> geometry = pcsf.UnstructuredMeshGeometry(
...     nodes=np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0],
...                     [1.0, 1.0]]),
...     connectivity=np.array([[0, 1, 2], [1, 3, 2]]),
...     region_ids=np.array([0, 1]),
... )
>>> model = pcsf.PCSFModel(geometry=geometry,
...                        resistivity=np.array([10.0, 20.0]))
>>> grid = mesh_to_grid2d(model, nx=5, nz=5)
>>> grid.kind, grid.resistivity.shape
('grid2d', (5, 5))
>>> grid.metadata["synthesized"]
True

2.23.2. Schema and serialization#

pycsamt.format.schema

In-memory PCSF schema: geometries, stations and topography.

pycsamt.format.io

Reading and writing .pcsf (HDF5) files.

pycsamt.format.text

Reading and writing .pcsm, the text encoding of PCSF.

2.23.3. Backend adapters#

The adapter namespace contains converters for supported inversion codes and generic constructors for classical, machine-learning, and deep-learning results that already expose their geometry and resistivity arrays.

pycsamt.format.adapters

Per-backend converters into pycsamt.format.schema.PCSFModel.

pycsamt.format.adapters.generic

Generic array-based -> PCSF adapter, for any AI/DL inversion result.

pycsamt.format.adapters.occam2d

Occam2D -> PCSF adapter (Phase 2 of the PCSF format plan).

pycsamt.format.adapters.modem3d

ModEM 3-D -> PCSF adapter (Phase 3 of the PCSF format plan).

pycsamt.format.adapters.mare2dem

MARE2DEM -> PCSF adapter (Phase 4 of the PCSF format plan).

2.23.4. Geometry and visualization support#

pycsamt.format.multiline

Multiline PCSF builder/reader — Phase 5 of the PCSF format plan.

pycsamt.format.pointcloud

Generic point-cloud extraction from any PCSFModel geometry kind.

pycsamt.format.regrid

Regridding of unstructured meshes onto 2D grids.

pycsamt.format.topography

Topography helpers — per_station and raster PCSF kinds.

pycsamt.format.topo_source

Attach real per-station spatial coordinates (and elevation) to a PCSF adapter's StationTable from an external topo source.

2.23.5. Provenance#

pycsamt.format.provenance

Provenance of models predicted by learned methods.

2.23.6. Points and interpretation exchange#

Small, versioned JSON documents (each with a plain-CSV sibling) that travel alongside a PCSF model: PCPT points/targets, the PCGL resistivity-to-geology legend, and PCGS field structural evidence.

pycsamt.format.pointset

PCPT - pyCSAMT Points: a tiny format for targets and points of interest.

pycsamt.format.geology

PCGL - pyCSAMT Common Geology Legend.

pycsamt.format.structure

PCGS - pyCSAMT Common Geological Structure.

2.23.7. Borehole exchange#

The pycsamt.format.borehole namespace contains PCBH schema objects, canonical JSON I/O, CSV/LAS adapters, trajectory derivation, PCSF association, and application-neutral 3-D render/export contracts.

pycsamt.format.borehole

PCBH - pyCSAMT Common Borehole Format.

pycsamt.format.borehole.schema

In-memory schema and semantic validation for PCBH 0.1.

pycsamt.format.borehole.jsonio

Canonical UTF-8 JSON reader and writer for PCBH 0.1.

pycsamt.format.borehole.csvio

Combined interval-CSV importer for PCBH 0.1.

pycsamt.format.borehole.xlsxio

Spreadsheet (.xlsx) importer for PCBH 0.1.

pycsamt.format.borehole.lasio

Loss-explicit LAS 2.0 subset import and export for PCBH.

pycsamt.format.borehole.relational

Manifest-driven relational CSV import and export for PCBH.

pycsamt.format.borehole.trajectory

Deterministic 3-D trajectory derivation for PCBH boreholes.

pycsamt.format.borehole.pcsf

PCBH association and coordinate alignment for PCSF models.

pycsamt.format.borehole.render

Viewer-neutral render models for PCBH boreholes.

pycsamt.format.borehole.exports

GeoJSON, VTP, and glTF exports for PCBH visualization subsets.