Source code for PyHydroGeophysX.analysis.sensitivity

"""Sensitivity and resolution analysis utilities."""

from typing import Any, Dict, Optional, Tuple

import numpy as np

from PyHydroGeophysX.solvers.linear_solvers import spd_solve, symmetrize


def _as_matrix(weights, size: Optional[int] = None) -> np.ndarray:
    arr = np.asarray(weights)
    if arr.ndim == 1:
        return np.diag(arr)
    if arr.ndim == 2:
        return arr
    if size is None:
        raise ValueError("Cannot infer matrix size from scalar weights without `size`.")
    return np.eye(size) * float(arr)


[docs] def compute_resolution_matrix( J: Any, Wd: Any, Wm: Any, lam: Any, ) -> Any: """ Compute model resolution matrix: R = (J^T Wd^T Wd J + lam Wm^T Wm)^(-1) J^T Wd^T Wd J ``Wd`` whitens the data, so the data term is ``(Wd J)^T (Wd J)``. A whitening matrix need not be symmetric (the inverse Cholesky factor of a data covariance is triangular), and ``J^T Wd Wd J`` is then a different matrix; for a symmetric or diagonal ``Wd`` the two are the same. ``lhs`` is the Gauss-Newton normal matrix, which is symmetric positive definite, so the inverse is applied as a Cholesky solve rather than formed with a pseudo-inverse, which is an SVD and much slower for the same result. """ J = np.asarray(J, dtype=float) Wd_mat = _as_matrix(Wd, J.shape[0]) Wm_mat = _as_matrix(Wm, J.shape[1]) wd_j = Wd_mat @ J jt_wdwd_j = wd_j.T @ wd_j reg_term = float(lam) * (Wm_mat.T @ Wm_mat) lhs = symmetrize(jt_wdwd_j + reg_term) return spd_solve(lhs, jt_wdwd_j, what="the regularized normal matrix")
[docs] def compute_depth_of_investigation( inv_class: Any, data: Any, mesh: Any, scale_low: float = 0.8, scale_high: float = 1.2, reference_resistivity: Optional[float] = None, ) -> Tuple[np.ndarray, Dict[str, np.ndarray]]: """ Estimate DOI using two inversions with different reference/initial models. This follows the Oldenburg-Li style idea of quantifying model sensitivity to reference-model choice. The two starting models are ``reference_resistivity * scale_low`` and ``reference_resistivity * scale_high``; when ``reference_resistivity`` is None it is taken as the median apparent resistivity of ``data`` so the perturbation brackets the survey's actual background instead of an arbitrary absolute value. The index is only as meaningful as the inversion's use of its reference. ``ERTInversion`` regularizes with first-order smoothness, which ignores a homogeneous reference, so give it a ``reference_weight`` for this (a smallness term, as Oldenburg and Li (1999) use). Let both runs converge as well: a run stopped at its target misfit keeps its starting model wherever the data are weak, and the index then reflects where each run stopped. A cell that follows its reference completely scores ``(scale_high - scale_low) / (scale_high + scale_low)``; dividing by it gives Oldenburg and Li's index, from 0 to 1. """ if hasattr(mesh, "cellCount"): n_cells = int(mesh.cellCount()) else: raise ValueError("mesh must expose cellCount() for DOI estimation.") if reference_resistivity is None: try: rhoa = np.asarray(data["rhoa"], dtype=float).ravel() rhoa = rhoa[np.isfinite(rhoa) & (rhoa > 0)] reference_resistivity = float(np.median(rhoa)) if rhoa.size else 100.0 except Exception: reference_resistivity = 100.0 base = np.ones(n_cells, dtype=float) * float(reference_resistivity) result_low = inv_class.run(initial_model=base * scale_low) result_high = inv_class.run(initial_model=base * scale_high) model_low = np.asarray(result_low.final_model, dtype=float).ravel() model_high = np.asarray(result_high.final_model, dtype=float).ravel() if model_low.size != model_high.size: raise ValueError("DOI models are incompatible in size.") doi = np.abs(model_high - model_low) / (np.abs(model_high) + np.abs(model_low) + 1e-12) doi = np.clip(doi, 0.0, 1.0) return doi, {"model_low": model_low, "model_high": model_high}
[docs] def compute_cumulative_sensitivity( J: Any, ) -> Any: """Compute cumulative sensitivity as absolute column sums of the Jacobian.""" J = np.asarray(J, dtype=float) if J.ndim != 2: raise ValueError("J must be a 2D matrix.") return np.sum(np.abs(J), axis=0)
[docs] def plot_sensitivity_map( sensitivity: Any, mesh: Any, ax: Any = None, ) -> Any: """Plot a sensitivity map on a mesh (or as a simple line plot fallback).""" import matplotlib.pyplot as plt sens = np.asarray(sensitivity, dtype=float).ravel() if ax is None: fig, ax = plt.subplots(figsize=(8, 4)) else: fig = ax.figure # Try mesh-based plotting first when PyGIMLi mesh plotting is available. mesh_plot_ok = False try: import pygimli as pg if mesh is not None and hasattr(mesh, "cellCount") and mesh.cellCount() == sens.size: pg.show(mesh, data=sens, ax=ax, cMap="viridis", label="Sensitivity") ax.set_title("Sensitivity Map") mesh_plot_ok = True except Exception: mesh_plot_ok = False if not mesh_plot_ok: ax.plot(np.arange(sens.size), sens, "k-") ax.set_xlabel("Cell Index") ax.set_ylabel("Sensitivity") ax.set_title("Cumulative Sensitivity") ax.grid(True, alpha=0.3) return fig, ax