Inversion Module#

Core Inversion Classes#

Single-time ERT inversion functionality.

PyHydroGeophysX.inversion.ert_inversion.ERROR_SOURCES = ('file', 'estimate', 'max')#

How err is chosen. file trusts the err column the instrument wrote and only estimates where it is missing; estimate always recomputes from relative_error/absolute_error; max takes the larger of the two per datum, which is the conservative reading when the file’s errors look optimistic. file is the default because silently discarding measured errors makes chi2 report on an error model the data never had.

class PyHydroGeophysX.inversion.ert_inversion.ERTInversion(data_file: str, mesh: pygimli.Mesh | None = None, **kwargs)[source]#

Bases: InversionBase

Single-time ERT inversion class.

run(initial_model: ndarray | None = None, reference_model: ndarray | None = None) InversionResult[source]#

Run ERT inversion.

Parameters:
  • initial_model – Initial model parameters (if None, a homogeneous model is used)

  • reference_model – Model the regularization pulls toward. Defaults to the initial model, which is the usual smoothness-from-homogeneous setup. Pass it explicitly when continuing an interrupted run. Leaving it to default makes the restart point the new reference, so the penalty becomes roughness of the change since the restart rather than roughness of the model; accumulated structure then goes unpenalized and the run drifts steadily under-regularized. Measured on the Ashton line over a 20 to 0.3 lambda ladder, that reached chi2 5.72 where the same ladder with the reference pinned reached 6.38.

Returns:

InversionResult with inversion results

setup()[source]#

Set up ERT inversion (create operators, matrices, etc.)

class PyHydroGeophysX.inversion.ert_inversion.ERTRun(lam: float, chi2: float, iterations: int, stop: str, convergence: ~typing.List[float], model: ~numpy.ndarray, response: ~numpy.ndarray, mesh: ~typing.Any, coverage: ~numpy.ndarray | None = None, manager: ~typing.Any = None, metrics: ~typing.Dict[str, ~typing.Any] = <factory>)[source]#

Bases: object

One inversion at one lambda, described the same way by either engine.

chi2: float#
convergence: List[float]#
coverage: ndarray | None = None#
iterations: int#
lam: float#
manager: Any = None#
mesh: Any#
metrics: Dict[str, Any]#
model: ndarray#
response: ndarray#
property result#

A manager-like handle for the viewer and the VTK export.

stop: str#
PyHydroGeophysX.inversion.ert_inversion.GEOMETRIC_FACTOR_POLICIES = ('off', 'check', 'fix')#

What to do about geometric factors before anything else touches the data. fix validates and, if the check fails, recomputes k numerically on the inversion mesh and rebuilds rhoa from the measured transfer resistance.

PyHydroGeophysX.inversion.ert_inversion.MESH_SUFFIXES = ('.bms', '.msh', '.vtk', '.vtu', '.poly')#

Mesh formats a user can hand the inversion. .bms is PyGIMLi’s own, .msh is Gmsh (the usual route for a complex 3D domain), and the rest are what PyGIMLi’s loader recognises.

class PyHydroGeophysX.inversion.ert_inversion.ModelResult(mesh, model, response=None, coverage=None, velocity=None)[source]#

Bases: object

Manager-shaped view of an inverted model, so both engines feed one viewer.

MeshResultView and the VTK export ask for paraDomain, model and an optional coverage(); the in-house engine returns arrays rather than a PyGIMLi manager, so this wraps them in the same shape.

velocity is set only by travel time, where a PyGIMLi manager exposes it under that name. It stays None for ERT, because a velocity attribute that quietly returned resistivity would be worse than a missing one.

coverage()[source]#
PyHydroGeophysX.inversion.ert_inversion.ensure_geometric_factors(container, mesh, *, policy: str = 'fix', tolerance: float = 0.05, rho0: float = 100.0, log: ~typing.Callable[[str], None] = <function noop>) Dict[str, Any][source]#

Validate k before the data are used, and repair it when asked.

A repair is kept only if it actually makes the check pass; otherwise the original factors are restored, because a failed repair is worse than a reported problem. Either way the caller is told what happened.

PyHydroGeophysX.inversion.ert_inversion.load_inversion_mesh(mesh_path: str | ~pathlib.Path, data=None, log: ~typing.Callable[[str], None] = <function noop>)[source]#

Load a user-supplied inversion mesh and check it can hold this survey.

Building a mesh from the electrode line is fine for a 2D profile and hopeless for a 3D domain with topography, boreholes or known structure, so those are meshed externally (usually in Gmsh) and brought in here.

An imported mesh fails in ways a generated one cannot: electrodes outside the domain, or every cell marked background so nothing is inverted. Both surface deep inside the forward solver as errors that name nothing useful, so they are checked here where the message can say what is wrong.

PyHydroGeophysX.inversion.ert_inversion.repair_geometric_factors(container, mesh, log: ~typing.Callable[[str], None] = <function noop>) Dict[str, Any][source]#

Recompute k numerically on the inversion mesh and rebuild rhoa from R.

The transfer resistance R = rhoa/k is what the instrument actually measured; k and rhoa are both derived from it. So the repair keeps R fixed, takes k from a forward run on the mesh the inversion will use, and rebuilds rhoa = R * k. Numerical factors also carry the topography that the analytic half-space formula cannot.

R has to be recovered with the factors that formed rhoa, which is the file’s own k_file when the loader kept it, and only otherwise the container’s k. Dividing by the wrong one would bake the discrepancy into R and leave the section scaled after the repair rather than before it.

Modifies container in place and returns what changed.

PyHydroGeophysX.inversion.ert_inversion.run_ert_manager_inversion(data_path: str | ~pathlib.Path, output_dir: str | ~pathlib.Path, *, relative_error: float = 0.03, absolute_error: float = 0.0, error_source: str = 'file', error_floor: float = 0.005, mesh_quality: float = 34.0, para_depth: float = 0.0, para_max_cell_size: float = 0.0, mesh_file: str = '', lam: float = 50.0, max_iterations: int = 20, plateau_tolerance: float = 0.005, max_total_iterations: int = 60, engine: str = 'pyhydro', model_constraints: ~typing.Tuple[float, float] = (0.01, 100000.0), solver: str = 'cgls', geometric_factor_policy: str = 'fix', geometric_factor_tolerance: float = 0.05, instrument: str | None = None, reject_outliers: bool = False, outlier_threshold: float = 3.0, outlier_passes: int = 2, min_data_fraction: float = 0.5, auto_lambda: bool = False, target_chi2: float = 1.0, chi2_tolerance: float = 0.2, max_lambda_trials: int = 6, lambda_bounds: ~typing.Tuple[float, float] = (0.001, 100000.0), lambda_warm_start: bool = True, lambda_cold_retry_chi2: float = 15.0, log: ~typing.Callable[[str], None] = <function noop>) Dict[str, Any][source]#

Invert one ERT dataset, in the order that actually lowers chi2.

The stages run back to back, each optional:

  1. Geometric factors (geometric_factor_policy). A homogeneous forward run must return the model resistivity; if it does not, k disagrees with the geometry being modelled and the whole section is scaled by that factor with no trace in chi2. fix recomputes k numerically on the inversion mesh and rebuilds rhoa from the measured transfer resistance.

  2. Error model. error_source decides whether the file’s own err column is trusted, recomputed from relative_error/absolute_error, or combined. Overwriting a measured error with an assumed one makes chi2 report on an error model the data never had.

  3. Inversion at the requested lambda, iterated to a plateau. A run that exhausts max_iterations is continued (up to max_total_iterations) rather than being judged where it stopped. This run is always kept, under fixed_lambda.

  4. Outlier rejection (reject_outliers). Measurements the converged model cannot explain are dropped and the inversion repeated, at most outlier_passes times and never below min_data_fraction of the data.

  5. Lambda search (auto_lambda). Only now, with a plateaued misfit on the cleaned data, is lambda allowed to move; every trial is itself iterated to a plateau before its chi2 counts. With lambda_warm_start each trial continues from the nearest lambda already solved rather than restarting from a homogeneous model, which is why lam should start on the smooth side: the sweep is then a relaxation from an over-regularized model down to the data, the direction in which continuation is stable.

engine selects the solver: "pyhydro" for the in-house Gauss-Newton inversion (ERTInversion), "pygimli" for ert.ERTManager, or "adtlert" for the optional differentiable ADTLERT 2.5D backend when Torch, CuPy CUDA 12 and cuDSS are available. Linux and Windows both use cuDSS; ADTLERT’s slower SciPy forward solver is intentionally disabled. Linux remains the recommended platform for the best performance. Without CUDA 12 or cuDSS, "adtlert" falls back to "pyhydro".

ADTLERT matches the published real-data branch: fast normal sensitivity, no Robin-boundary derivative, line search, a maximum log step of one, and GPU CGLS when CUDA is available.

PyHydroGeophysX.inversion.ert_inversion.validate_geometric_factors(container, mesh, *, rho0: float = 100.0, tolerance: float = 0.05, log: ~typing.Callable[[str], None] = <function noop>) Dict[str, Any][source]#

Check k by forward-modelling a homogeneous half space.

A homogeneous model of resistivity rho0 must return rho0 as the apparent resistivity of every configuration. The forward response is (U/I) * k, so the returned ratio is exactly k / k_true for the geometry actually being modelled, and it is independent of the field data.

This catches what chi2 cannot. A geometric factor that is uniformly wrong by a factor X forces the inversion to scale the model by 1/X to fit the same apparent resistivities, so the section is wrong by X while the fit looks perfect. Topography, wrong electrode spacing, and half-space versus full-space convention errors all show up here.

Returns the ratio statistics, an ok flag, and a message naming the likely cause and the consequence.

Seismic Refraction Tomography (SRT) inversion functionality.

Uses PyGIMLi’s TravelTimeManager for forward modeling and Jacobian computation. Provides custom Gauss-Newton inversion with the same architecture as ERTInversion but for travel-time data.

class PyHydroGeophysX.inversion.srt_inversion.SRTInversion(data_file: str, mesh: pygimli.Mesh | None = None, **kwargs: Any)[source]#

Bases: InversionBase

Seismic Refraction Tomography inversion class.

Inverts travel-time data for subsurface velocity via log-slowness, and uses a Gauss-Newton optimization loop.

run(initial_model: ndarray | None = None) InversionResult[source]#

Abstract method to run the main inversion loop.

Derived classes must implement this to perform the iterative optimization process. The method should populate and return an InversionResult (or subclass) object.

Returns:

An object containing the results of the inversion.

Return type:

InversionResult

setup() None[source]#

Abstract method to set up the inversion specifics.

This should be implemented by derived classes to prepare everything needed for the inversion, such as: - Creating or validating the mesh if not already done. - Initializing forward modeling operators. - Preparing data weighting and model regularization matrices. - Setting up initial models.

PyHydroGeophysX.inversion.srt_inversion.build_srt_mesh(data, *, mesh_quality: float = 32.0, para_depth: float = 0.0, para_max_cell_size: float = 0.0, log: ~typing.Callable[[str], None] = <function noop>)[source]#

Build the travel-time inversion mesh, mirroring the ERT pipeline.

PyGIMLi sizes the parameter domain from the array length when paraDepth is left at 0. For refraction that reaches well past where any ray turns, so the deep cells are unconstrained and only slow the run down; capping the depth removes them. Cell size and quality trade resolution against cost the same way they do for ERT.

PyHydroGeophysX.inversion.srt_inversion.run_srt_manager_inversion(travel_time_path: str | ~pathlib.Path, output_dir: str | ~pathlib.Path, *, engine: str = 'pygimli', lam: float = 50.0, max_iterations: int = 20, plateau_tolerance: float = 0.005, max_total_iterations: int = 60, mesh_quality: float = 32.0, para_depth: float = 0.0, para_max_cell_size: float = 0.0, secondary_nodes: int = 3, auto_lambda: bool = False, target_chi2: float = 1.0, chi2_tolerance: float = 0.2, max_lambda_trials: int = 6, lambda_warm_start: bool = True, log: ~typing.Callable[[str], None] = <function noop>) Dict[str, Any][source]#

Invert one travel-time dataset for velocity.

With auto_lambda the same machinery as the ERT pipeline applies: each lambda is iterated to a plateau before its chi2 counts, the sweep relaxes from the requested lambda downward, and each trial continues from the nearest lambda already solved. engine="pyhydro" uses the in-house Gauss-Newton solver, which is what the search can drive; "pygimli" runs TravelTimeManager once and is the historical default.

The mesh is built once here and handed to whichever engine runs, so the two invert the same domain. para_depth and para_max_cell_size take 0 to mean “let PyGIMLi size it from the array”; secondary_nodes refines the ray tracing without adding unknowns.

Time-lapse ERT inversion functionality.

class PyHydroGeophysX.inversion.time_lapse.TimeLapseERTInversion(data_files: List[str], measurement_times: List[float], mesh: pygimli.Mesh | None = None, **kwargs)[source]#

Bases: InversionBase

Time-lapse ERT inversion class.

run(initial_model: ndarray | None = None) TimeLapseInversionResult[source]#

Run time-lapse ERT inversion.

Parameters:

initial_model – Initial model parameters (if None, a homogeneous model is used)

Returns:

TimeLapseInversionResult with inversion results

setup()[source]#

Set up time-lapse ERT inversion (load data, create operators, matrices, etc.)

Time-lapse Seismic Refraction Tomography (SRT) inversion functionality.

Jointly inverts multiple travel-time datasets with spatial and temporal regularization using log-slowness parameterization.

class PyHydroGeophysX.inversion.srt_time_lapse.TimeLapseSRTInversion(data_files: List[str], measurement_times: List[float], mesh: pygimli.Mesh | None = None, **kwargs: Any)[source]#

Bases: InversionBase

Time-lapse Seismic Refraction Tomography inversion.

Architecture mirrors TimeLapseERTInversion while using TravelTimeManager and log-slowness model parameters.

run(initial_model: ndarray | None = None) TimeLapseInversionResult[source]#

Abstract method to run the main inversion loop.

Derived classes must implement this to perform the iterative optimization process. The method should populate and return an InversionResult (or subclass) object.

Returns:

An object containing the results of the inversion.

Return type:

InversionResult

setup() None[source]#

Abstract method to set up the inversion specifics.

This should be implemented by derived classes to prepare everything needed for the inversion, such as: - Creating or validating the mesh if not already done. - Initializing forward modeling operators. - Preparing data weighting and model regularization matrices. - Setting up initial models.

Windowed time-lapse ERT inversion for handling large temporal datasets.

class PyHydroGeophysX.inversion.windowed.WindowedTimeLapseERTInversion(data_dir: str, ert_files: List[str], measurement_times: List[float], window_size: int = 3, mesh: pygimli.Mesh | str | None = None, engine: str = 'pyhydro', log: Callable[[str], None] | None = None, **kwargs)[source]#

Bases: object

Class for windowed time-lapse ERT inversion to handle large temporal datasets.

run(window_parallel: bool = False, max_window_workers: int | None = None) TimeLapseInversionResult[source]#

Run windowed time-lapse ERT inversion.

Parameters:
  • window_parallel – Whether to process windows in parallel

  • max_window_workers – Maximum number of parallel workers (None for auto)

Returns:

TimeLapseInversionResult with stitched results

EM Inversion#

Inversion utilities for Time-Domain Electromagnetic (TDEM) data.

This module provides classes for 1D TDEM inversion using SimPEG, with support for both L2 and sparse (IRLS) regularization.

class PyHydroGeophysX.inversion.tdem_inversion.TDEMInversion(times: ndarray, dobs: ndarray, uncertainties: ndarray, source_radius: float = 10.0, source_location: ndarray | None = None, receiver_location: ndarray | None = None, n_layers: int = 25, min_thickness: float = 1.0, max_thickness: float = 30.0, **kwargs)[source]#

Bases: object

Class for 1D TDEM inversion using SimPEG.

This class provides functionality for inverting TDEM sounding data to recover 1D layered Earth conductivity models.

Example

>>> # Load or create data
>>> times = np.logspace(-5, -2, 31)
>>> dobs = ...  # observed data
>>> uncertainties = ...  # data uncertainties
>>>
>>> # Create inversion
>>> inv = TDEMInversion(
...     times=times,
...     dobs=dobs,
...     uncertainties=uncertainties,
...     source_radius=10.0
... )
>>>
>>> # Run inversion
>>> result = inv.run()
plot_result(result: TDEMInversionResult, true_model: Tuple[ndarray, ndarray] | None = None, save_path: str | None = None) None[source]#

Plot inversion results.

Parameters:
  • result – TDEMInversionResult from run()

  • true_model – Tuple of (thicknesses, conductivity) for true model

  • save_path – Path to save figure (optional)

run(starting_model: ndarray | None = None) TDEMInversionResult[source]#

Run TDEM inversion.

Parameters:

starting_model – Initial log-conductivity model (optional)

Returns:

TDEMInversionResult with inversion results

setup() None[source]#

Set up inversion components (survey, mesh, simulation).

class PyHydroGeophysX.inversion.tdem_inversion.TDEMInversionResult(recovered_model: ndarray = None, recovered_conductivity: ndarray = None, l2_model: ndarray = None, l2_conductivity: ndarray = None, predicted_data: ndarray = None, mesh: discretize.TensorMesh = None, thicknesses: ndarray = None, chi2: float = None, iterations: int = 0, convergence_history: List[float] = <factory>)[source]#

Bases: object

Container for TDEM inversion results.

recovered_model#

Final recovered model (log-conductivity)

Type:

numpy.ndarray

recovered_conductivity#

Recovered conductivity (S/m)

Type:

numpy.ndarray

l2_model#

L2 model before IRLS (log-conductivity)

Type:

numpy.ndarray

l2_conductivity#

L2 conductivity (S/m)

Type:

numpy.ndarray

predicted_data#

Predicted data from recovered model

Type:

numpy.ndarray

mesh#

TensorMesh used for inversion

Type:

discretize.TensorMesh

thicknesses#

Layer thicknesses used in inversion

Type:

numpy.ndarray

chi2#

Final chi-squared misfit

Type:

float

iterations#

Number of iterations

Type:

int

convergence_history#

History of data misfit per iteration

Type:

List[float]

chi2: float = None#
convergence_history: List[float]#
iterations: int = 0#
l2_conductivity: ndarray = None#
l2_model: ndarray = None#
mesh: discretize.TensorMesh = None#
predicted_data: ndarray = None#
recovered_conductivity: ndarray = None#
recovered_model: ndarray = None#
thicknesses: ndarray = None#
PyHydroGeophysX.inversion.tdem_inversion.run_tdem_inversion(times: ndarray, dobs: ndarray, uncertainties: ndarray, source_radius: float = 10.0, n_layers: int = 25, use_irls: bool = True, verbose: bool = True, **kwargs) TDEMInversionResult[source]#

Convenience function to run TDEM inversion.

Parameters:
  • times – Time channels (s)

  • dobs – Observed data (T)

  • uncertainties – Data uncertainties (T)

  • source_radius – Loop radius (m)

  • n_layers – Number of inversion layers

  • use_irls – Use IRLS for sparse inversion

  • verbose – Print progress

  • **kwargs – Additional parameters for TDEMInversion

Returns:

TDEMInversionResult with inversion results

Inversion utilities for Frequency-Domain Electromagnetic (FDEM) data.

Provides 1D layered-earth FDEM inversion using SimPEG.

class PyHydroGeophysX.inversion.fdem_inversion.FDEMInversion(frequencies: ndarray, dobs: ndarray, uncertainties: ndarray, thicknesses: ndarray | None = None, source_location: ndarray | None = None, source_radius: float = 10.0, receiver_location: ndarray | None = None, receiver_orientation: str = 'z', receiver_component: str = 'secondary', waveform_type: str = 'dipole', n_layers: int = 25, min_thickness: float = 1.0, max_thickness: float = 30.0, **kwargs)[source]#

Bases: object

1D FDEM inversion using SimPEG.

Follows the same pattern used in TDEMInversion.

run(starting_model: ndarray | None = None) FDEMInversionResult[source]#
setup() None[source]#
class PyHydroGeophysX.inversion.fdem_inversion.FDEMInversionResult(recovered_model: ndarray = None, recovered_conductivity: ndarray = None, l2_model: ndarray = None, l2_conductivity: ndarray = None, predicted_data: ndarray = None, mesh: Any = None, thicknesses: ndarray = None, chi2: float = None, frequencies: ndarray = None)[source]#

Bases: object

Container for FDEM inversion results.

chi2: float = None#
frequencies: ndarray = None#
l2_conductivity: ndarray = None#
l2_model: ndarray = None#
mesh: Any = None#
predicted_data: ndarray = None#
recovered_conductivity: ndarray = None#
recovered_model: ndarray = None#
thicknesses: ndarray = None#

Joint and Multi-Method Inversion#

Joint ERT-SRT inversion with structural and geostatistical constraints.

This module integrates the legacy alternating inversion strategy from cg_joint_inversion_hang into the package architecture.

class PyHydroGeophysX.inversion.joint_ert_srt.JointERTSRTInversion(ert_data: str | PathLike | pygimli.DataContainer, srt_data: str | PathLike | pygimli.DataContainer, mesh: pygimli.Mesh | None = None, **kwargs: Any)[source]#

Bases: InversionBase

Joint ERT-SRT inversion using alternating Gauss-Newton updates.

  • ERT model parameter: log-resistivity

  • SRT model parameter: log-slowness

  • Coupling: linearized cross-gradient terms (B1, B2)

  • Regularization: smoothness or geostatistical

RCM: ndarray | None#
Wd_ert: scipy.sparse.csr_matrix | None#
Wd_srt: scipy.sparse.csr_matrix | None#
Wm_ert: scipy.sparse.csr_matrix | None#
Wm_srt: scipy.sparse.csr_matrix | None#
X: ndarray | None#
dobs_ert: ndarray | None#
dobs_srt: ndarray | None#
ert_grid: pygimli.Mesh | None#
mr: ndarray | None#
mr_ref: ndarray | None#
mv: ndarray | None#
mv_ref: ndarray | None#
run() JointERTSRTResult[source]#

Abstract method to run the main inversion loop.

Derived classes must implement this to perform the iterative optimization process. The method should populate and return an InversionResult (or subclass) object.

Returns:

An object containing the results of the inversion.

Return type:

InversionResult

setup() None[source]#

Abstract method to set up the inversion specifics.

This should be implemented by derived classes to prepare everything needed for the inversion, such as: - Creating or validating the mesh if not already done. - Initializing forward modeling operators. - Preparing data weighting and model regularization matrices. - Setting up initial models.

class PyHydroGeophysX.inversion.joint_ert_srt.JointERTSRTResult(ert_log_resistivity: ndarray | None = None, srt_log_slowness: ndarray | None = None, ert_resistivity: ndarray | None = None, srt_velocity: ndarray | None = None, ert_predicted: ndarray | None = None, srt_predicted: ndarray | None = None, ert_coverage: ndarray | None = None, srt_coverage: ndarray | None = None, chi2_ert: float | None = None, chi2_srt: float | None = None, iteration_history: list = <factory>, mesh: Any = None, meta: Dict[str, ~typing.Any]=<factory>)[source]#

Bases: object

Container for joint ERT-SRT inversion outputs.

chi2_ert: float | None = None#
chi2_srt: float | None = None#
ert_coverage: ndarray | None = None#
ert_log_resistivity: ndarray | None = None#
ert_predicted: ndarray | None = None#
ert_resistivity: ndarray | None = None#
iteration_history: list#
mesh: Any = None#
meta: Dict[str, Any]#
srt_coverage: ndarray | None = None#
srt_log_slowness: ndarray | None = None#
srt_predicted: ndarray | None = None#
srt_velocity: ndarray | None = None#

Unified multi-method geophysical inversion interface.

class PyHydroGeophysX.inversion.multi_method.GeophysicalInversion(method: str, **kwargs)[source]#

Bases: object

Unified factory for multi-method geophysical inversion.

Dispatches to the correct inversion engine.

SUPPORTED = {'ert', 'fdem', 'joint', 'joint_ert_srt', 'srt', 'tdem'}#
property engine#
run(**kwargs)[source]#
setup(**kwargs)[source]#

Cross-Constraint Utilities#

Cross-method constraint utilities for joint/cooperative inversion.

These utilities enable information sharing between geophysical methods and provide hydrology-to-geophysics coupling helpers.

class PyHydroGeophysX.inversion.cross_constraints.PetrophysicalCoupling[source]#

Bases: object

Coupling helpers from hydrological state to multi-method geophysics.

static compare_inversions_to_hydro(hydro_wc, ert_result, srt_result=None, em_result=None, petro_params=None)[source]#

Compare inversion products back to hydrological water content.

Returns misfit statistics for available methods.

static water_content_to_all_geophysics(water_content, porosity, **params)[source]#

Convert water content to resistivity, velocity, and conductivity.

Uses existing petrophysical functions in the package.

class PyHydroGeophysX.inversion.cross_constraints.StructuralConstraint[source]#

Bases: object

Build structural constraint terms from one method for another.

static apply_structural_weights_to_Wm(Wm, boundary_weights)[source]#

Modify an existing smoothness matrix Wm to respect boundaries.

static build_cross_gradient_operator(mesh, model_a, model_b)[source]#

Build a cross-gradient operator surrogate.

Returns a diagonal sparse matrix weighted by local cross-gradient magnitude, where small values indicate better structural agreement.

static build_linearized_cross_gradient_blocks(RCM: ndarray, X: ndarray, model_a: ndarray, model_b: ndarray, mode: str = 'direct') Tuple[ndarray, ndarray][source]#

Build linearized cross-gradient blocks B1 and B2.

B1 multiplies model_a and B2 multiplies model_b. The resulting penalty terms are ||B1 m_a||^2 and ||B2 m_b||^2.

static build_local_design_matrix(mesh) ndarray[source]#

Build the local design matrix X=[x, z, 1] used by cross-gradient.

This mirrors the legacy xyzpos[:, 2] = 1 construction.

static build_neighborhood_matrix(mesh, Wm: Any | None = None, source: str = 'smoothness', correlation_lengths: Sequence[float] = (4.0, 4.0), threshold: float = 0.01, binarize: bool = True) ndarray[source]#

Build the neighborhood/correlation matrix used by cross-gradient.

Parameters:
  • mesh – Mesh object.

  • Wm – Smoothness matrix. Required when source='smoothness'.

  • source – One of 'smoothness' (legacy direct mode) or 'covariance' (legacy spatial mode).

  • correlation_lengths – Correlation lengths passed to pg.utils.covarianceMatrix when source='covariance'.

  • threshold – Entries with absolute value below this threshold are zeroed.

  • binarize – If True, convert nonzero entries to 1.

static from_conductivity_model(conductivity, mesh, gradient_threshold: float = 0.3)[source]#

Extract structural boundaries from an EM conductivity model.

static from_velocity_model(velocity_model, mesh, gradient_threshold: float = 0.3)[source]#

Extract structural boundaries from an SRT velocity model.

Returns a pairwise-boundary weight map that can reduce smoothing across detected structural interfaces.

Base Classes#

Base classes for geophysical inversion frameworks.

This module defines:

  • InversionResult: A base class to store and manage common results from an inversion process, including final model, predicted data, convergence history, and plotting utilities.

  • TimeLapseInversionResult: A specialized version of InversionResult for time-lapse studies, handling multiple models over time and providing time-slice plotting and animation.

  • InversionBase: An abstract base class outlining the common structure and interface for various geophysical inversion methods (e.g., ERT, SRT). It handles data, mesh, and basic parameter management.

class PyHydroGeophysX.inversion.base.InversionBase(data: pygimli.DataContainer, mesh: pygimli.Mesh | None = None, **kwargs: Any)[source]#

Bases: object

Abstract base class for geophysical inversion methods.

This class provides a foundational structure for specific inversion techniques (e.g., ERT, SRT). It manages observed data, mesh, common inversion parameters, and an InversionResult object. Subclasses must implement methods for setting up the inversion, running the inversion loop, computing Jacobians, and evaluating the objective function.

compute_jacobian(model: ndarray) ndarray[source]#

Abstract method to compute the Jacobian matrix (sensitivity matrix).

The Jacobian J_ij = ∂d_i / ∂m_j relates changes in model parameters (m_j) to changes in observed data (d_i).

Parameters:

model (np.ndarray) – The current model parameter vector for which to compute the Jacobian.

Returns:,

np.ndarray: The computed Jacobian matrix, typically of shape (n_data, n_model_params).

data: pygimli.DataContainer#
mesh: pygimli.Mesh | None#
objective_function(model: ndarray, data_to_fit: ndarray | None = None) float[source]#

Abstract method to compute the value of the objective function.

The objective function typically includes a data misfit term and one or more regularization terms: Φ(m) = Φ_d(m) + λ * Φ_m(m).

Parameters:
  • model (np.ndarray) – The current model parameter vector.

  • data_to_fit (Optional[np.ndarray], optional) – The observed data to fit. If None, self.data (from DataContainer) is typically used. Defaults to None.

Returns:

The calculated value of the objective function.

Return type:

float

parameters: Dict[str, Any]#
result: InversionResult#
run() InversionResult[source]#

Abstract method to run the main inversion loop.

Derived classes must implement this to perform the iterative optimization process. The method should populate and return an InversionResult (or subclass) object.

Returns:

An object containing the results of the inversion.

Return type:

InversionResult

setup() None[source]#

Abstract method to set up the inversion specifics.

This should be implemented by derived classes to prepare everything needed for the inversion, such as: - Creating or validating the mesh if not already done. - Initializing forward modeling operators. - Preparing data weighting and model regularization matrices. - Setting up initial models.

class PyHydroGeophysX.inversion.base.InversionResult[source]#

Bases: object

Base class to store, save, load, and plot results from a geophysical inversion.

final_model#

The final inverted model parameters (e.g., resistivity, velocity). Typically a 1D array corresponding to mesh cells.

Type:

Optional[np.ndarray]

predicted_data#

The data predicted by the forward model using the final_model.

Type:

Optional[np.ndarray]

coverage#

Coverage or sensitivity values for the model parameters, often derived from the Jacobian or resolution matrix.

Type:

Optional[np.ndarray]

mesh#

The PyGIMLi mesh object used in the inversion.

Type:

Optional[pg.Mesh]

iteration_models#

A list storing the model parameters at each iteration of the inversion.

Type:

List[np.ndarray]

iteration_data_errors#

A list storing the data misfit (e.g., residuals) at each iteration.

Type:

List[np.ndarray]

iteration_chi2#

A list storing the chi-squared (χ²) value or a similar misfit metric at each iteration.

Type:

List[float]

meta#

A dictionary to store any additional metadata about the inversion run (e.g., inversion parameters, timings, comments).

Type:

Dict[str, Any]

coverage: ndarray | None#
final_model: ndarray | None#
iteration_chi2: List[float]#
iteration_data_errors: List[ndarray]#
iteration_models: List[ndarray]#
classmethod load(filename: str) InversionResult[source]#

Load inversion results from a file previously saved by the save method.

Parameters:

filename (str) – The base path to the saved results file. If saved as name.pkl and name.bms, provide name.pkl or name.

Returns:

An instance of InversionResult (or a subclass if called on one)

populated with the loaded data.

Return type:

InversionResult

Raises:
  • FileNotFoundError – If the main data file or associated mesh file (if referenced) is not found.

  • IOError – If there’s an error during file reading.

  • pickle.UnpicklingError – If the file cannot be unpickled.

mesh: pygimli.Mesh | None#
meta: Dict[str, Any]#
plot_convergence(ax: Axes | None = None, **kwargs: Any) Tuple[Figure, Axes][source]#

Plot the convergence curve (chi-squared misfit vs. iteration number).

Parameters:
  • ax (Optional[plt.Axes], optional) – A matplotlib Axes object to plot on. If None, a new figure and axes are created. Defaults to None.

  • **kwargs (Any) – Additional keyword arguments passed directly to ax.plot (e.g., color, marker, linestyle).

Returns:

The matplotlib Figure and Axes objects of the plot.

Return type:

Tuple[plt.Figure, plt.Axes]

Raises:

ValueError – If self.iteration_chi2 is empty (no convergence data).

plot_model(ax: Axes | None = None, cmap: str = 'viridis', coverage_threshold: float | None = None, **kwargs: Any) Tuple[Figure, Axes][source]#

Plot the final inverted model on its associated mesh.

Parameters:
  • ax (Optional[plt.Axes], optional) – A matplotlib Axes object to plot on. If None, a new figure and axes are created. Defaults to None.

  • cmap (str, optional) – The colormap to use for visualizing model values. Defaults to ‘viridis’.

  • coverage_threshold (Optional[float], optional) – If provided, cells with coverage values below this threshold will be masked (made transparent or semi-transparent) in the plot. Requires self.coverage to be populated. Defaults to None (no masking).

  • **kwargs (Any) – Additional keyword arguments passed directly to pygimli.show (e.g., cMin, cMax, orientation, logScale).

Returns:

The matplotlib Figure and Axes objects of the plot.

Return type:

Tuple[plt.Figure, plt.Axes]

Raises:

ValueError – If self.final_model or self.mesh is None.

predicted_data: ndarray | None#
save(filename: str) None[source]#

Save the inversion results to a file using Python’s pickle format. If a mesh is present, it is saved separately as a PyGIMLi binary mesh file (.bms).

Parameters:

filename (str) – The base path (including filename without extension) to save the results. The main data will be saved as filename.pkl (or just filename if user includes .pkl). The mesh will be saved as filename.bms or filename.pkl.bms. It’s recommended to provide filename without .pkl.

Raises:
  • IOError – If there’s an error during file writing.

  • pickle.PicklingError – If an object cannot be pickled.

class PyHydroGeophysX.inversion.base.TimeLapseInversionResult[source]#

Bases: InversionResult

Specialized class to store and manage results from time-lapse inversions. Inherits from InversionResult and adds attributes specific to time-lapse data.

final_models#

A 2D NumPy array where each column represents the inverted model for a specific timestep (shape: num_cells x num_timesteps).

Type:

Optional[np.ndarray]

timesteps#

An array or list of time values (e.g., hours, days) corresponding to each model slice in final_models.

Type:

Optional[np.ndarray]

all_coverage#

A list where each element is the coverage array for the corresponding timestep’s model.

Type:

List[np.ndarray]

all_chi2#

A list where each element is a list of chi-squared values per iteration for the inversion of that specific timestep or window. (Note: Original was List[float], if chi2 is per window, might need adjustment)

Type:

List[Any]

all_chi2: List[Any]#
all_coverage: List[ndarray]#
create_time_lapse_animation(output_filename: str, cmap: str = 'viridis', coverage_threshold: float | None = None, dpi: int = 100, fps: int = 2, **kwargs: Any) None[source]#

Create and save an animation (e.g., MP4 video) of the time-lapse inversion results.

Requires ffmpeg or another Matplotlib-supported animation writer to be installed.

Parameters:
  • output_filename (str) – The filename for the output animation (e.g., ‘timelapse_animation.mp4’).

  • cmap (str, optional) – Colormap for model values. Defaults to ‘viridis’.

  • coverage_threshold (Optional[float], optional) – Threshold for coverage masking. Defaults to None.

  • dpi (int, optional) – Dots Per Inch for the output animation. Defaults to 100.

  • fps (int, optional) – Frames Per Second for the animation. Defaults to 2.

  • **kwargs (Any) – Additional keyword arguments passed to plot_time_slice for each frame.

Raises:
  • ValueError – If final_models or mesh is missing.

  • ImportError – If matplotlib.animation cannot be imported.

final_models: ndarray | None#
classmethod load(filename: str) TimeLapseInversionResult[source]#

Load time-lapse inversion results. Overrides base class load.

plot_time_slice(timestep_idx: int, ax: Axes | None = None, cmap: str = 'viridis', coverage_threshold: float | None = None, **kwargs: Any) Tuple[Figure, Axes][source]#

Plot a single time slice (inverted model at a specific timestep) from the results.

Parameters:
  • timestep_idx (int) – The zero-based index of the timestep to plot.

  • ax (Optional[plt.Axes], optional) – Matplotlib Axes to plot on. If None, creates new.

  • cmap (str, optional) – Colormap for model values. Defaults to ‘viridis’.

  • coverage_threshold (Optional[float], optional) – Threshold for coverage masking. Defaults to None.

  • **kwargs (Any) – Additional arguments passed to pg.show.

Returns:

The matplotlib Figure and Axes objects.

Return type:

Tuple[plt.Figure, plt.Axes]

Raises:

ValueError – If models or mesh are missing, or if timestep_idx is out of range.

save(filename: str) None[source]#

Save time-lapse inversion results. Overrides base class save.

timesteps: ndarray | None#