uncertainty package#

Submodules#

PyHydroGeophysX.uncertainty.posterior module#

Posterior covariance and uncertainty propagation helpers.

PyHydroGeophysX.uncertainty.posterior.POSTERIOR_MAX_CELLS = 12000#

Most cells regularized_posterior_std() forms the covariance for. The posterior precision is built, factored and inverted in one dense n x n buffer, 8 n^2 bytes: 1.15 GB at 12,000 cells, 1.4 GB with the Jacobian’s copies, what 6000 cells took when five such matrices were held at once.

PyHydroGeophysX.uncertainty.posterior.linearized_posterior(J: Any, Cd: Any, Cm_prior: Any) → Any[source]#

Compute linearized Gaussian posterior covariance:

Cm_post = (J^T Cd^-1 J + Cm_prior^-1)^-1

None of the three inverses in that expression is formed. Each is applied as a Cholesky solve instead, and the result is symmetrized before it is returned. This is a correctness matter, not a speed one: a posterior built from chained pseudo-inverses is not a covariance when the Jacobian is ill-conditioned (it comes out asymmetric, with negative eigenvalues), and sampling from it in propagate_petro_uncertainty below would be invalid.

PyHydroGeophysX.uncertainty.posterior.model_resolution_spread(R: Any) → Any[source]#

Return diagonal resolution spread metrics from a resolution matrix.

PyHydroGeophysX.uncertainty.posterior.propagate_petro_uncertainty(rho: Any, rho_cov: Any, petro_func: Callable[[ndarray], ndarray], n_samples: int = 500, seed: int | None = None) → Dict[str, ndarray][source]#

Propagate resistivity uncertainty through a petrophysical transform.

Uses Monte Carlo sampling by default. "cov" is always a 2-D (outputs, outputs) matrix, (1, 1) for one cell or a scalar output.

A diagonal covariance - one variance per cell, given as a vector or as a diagonal matrix - draws each cell on its own, rho + sqrt(var) z: no n x n matrix is formed or factored (multivariate_normal’s SVD took 10 s and 1 GB at 4000 cells), and a zero variance gives the cell’s value exactly, where the SVD’s round-off leaked other cells’ draws into it.

PyHydroGeophysX.uncertainty.posterior.regularized_posterior_std(J: Any, data_weights: Any, Wm: Any, lam: float, alpha: float = 0.0, free: Any | None = None) → ndarray[source]#

Per-cell standard deviation of a regularised Gauss-Newton model, linearised.

Reading the data weights as Gaussian data errors and the regularisation as a Gaussian prior, the model’s covariance at the final iterate is

C = (J^T Wd^2 J + lambda (Wm^T Wm + alpha I))^-1

(Tarantola, 2005, Inverse Problem Theory, SIAM, eq. 3.38; Aster, Borchers and Thurber, 2018, Parameter Estimation and Inverse Problems, ch. 11). Returned is sqrt(diag C), in the units of the model parameter (for an inversion in log resistivity, a standard deviation of ln rho).

What it leaves out: the error of the regularisation itself. A smoothness prior cannot describe a sharp layer boundary, so where the truth is blocky the real error exceeds this: the result is a lower bound there, most of all at depth and where coverage is low.

Parameters:
  • J (array_like) – Jacobian at the final model, data x cells, in the inversion’s own parameterisation (log data against log model for ERT).

  • data_weights (array_like) – Diagonal of Wd, one per datum (1 / the data error).

  • Wm (array_like or sparse matrix) – Model weighting (constraint) matrix, rows x cells.

  • lam (float) – Regularisation weight lambda, as in the objective above.

  • alpha (float) – Smallness weight relative to the smoothness (0 for none).

  • free (array_like of bool, optional) – Cells the inversion updated; held cells get a standard deviation of 0.

Returns:

One standard deviation per cell.

Return type:

numpy.ndarray

Raises:

ValueError – When more than POSTERIOR_MAX_CELLS free cells would have to be formed, the shapes disagree, or the posterior precision is not positive definite.

Examples

>>> J = np.array([[1.0, 0.0], [0.0, 1.0]])
>>> regularized_posterior_std(J, [10.0, 10.0], np.zeros((1, 2)), 1.0, alpha=1.0).round(4)
array([0.0995, 0.0995])
>>> regularized_posterior_std([[1, 0]], [1], [[0, 0]], 1, alpha=0)
Traceback (most recent call last):
    ...
ValueError: The posterior is improper: some cells are constrained neither by the data nor by the regularisation.

Module contents#

Posterior and uncertainty quantification helpers.

PyHydroGeophysX.uncertainty.interval_coverage(truth: Any, mean: Any, std: Any, groups: Any = None, *, p10: Any = None, p90: Any = None, weights: Any = None) → Dict[str, Any][source]#

How often an estimate’s mean +/- k standard deviations holds the truth.

A calibrated Gaussian error bar holds the truth in 68.3 % of cells at one standard deviation and 95.4 % at two, z = (truth - mean) / std has mean 0 and standard deviation 1, and p10-p90 holds it in 80 %. A band that passes the counts with z off-centre and narrow is wide, not calibrated: read the z figures and the per-group numbers (depth bins, units, coverage terciles), not only the totals. When the Monte Carlo draws one parameter set per unit, the cells of a unit are correlated, so the fractions are not binomial proportions and move with the seed.

Parameters:
  • truth (array_like) – True value, estimated mean and standard deviation per cell, one size.

  • mean (array_like) – True value, estimated mean and standard deviation per cell, one size.

  • std (array_like) – True value, estimated mean and standard deviation per cell, one size.

  • groups (array_like, optional) – One label per cell; every label gets the same figures under groups.

  • p10 (array_like, optional) – Percentiles of the estimate; add within_p10_p90.

  • p90 (array_like, optional) – Percentiles of the estimate; add within_p10_p90.

  • weights (array_like, optional) – Cell weights, such as cell areas, so small shallow cells do not dominate.

Returns:

overall and, with groups, groups (label -> the same block), each with n, within_1sigma, within_2sigma, within_p10_p90 (when given), z_mean, z_std, z_median, z_robust_std (1.4826 x MAD), rmse, bias (mean - truth), mean_std, rms_std, rmse_over_rms_std and zero_std (cells with a standard deviation of zero: covered only where the mean is the truth, and left out of z); plus excluded, the cells with a non-finite input or a negative standard deviation.

Return type:

dict

Raises:

ValueError – When the inputs differ in size.

Examples

>>> r = interval_coverage([0.10, 0.20, 0.30, 0.40], [0.10, 0.25, 0.20, 0.40], [0.05] * 4)
>>> round(r["overall"]["within_1sigma"], 2), r["overall"]["within_2sigma"]
(0.75, 1.0)
>>> round(r["overall"]["bias"], 4)
-0.0125
>>> by_depth = interval_coverage([0.1, 0.2], [0.1, 0.4], [0.05, 0.05], groups=["0-1 m", "1-3 m"])
>>> by_depth["groups"]["1-3 m"]["within_2sigma"]
0.0
PyHydroGeophysX.uncertainty.linearized_posterior(J: Any, Cd: Any, Cm_prior: Any) → Any[source]#

Compute linearized Gaussian posterior covariance:

Cm_post = (J^T Cd^-1 J + Cm_prior^-1)^-1

None of the three inverses in that expression is formed. Each is applied as a Cholesky solve instead, and the result is symmetrized before it is returned. This is a correctness matter, not a speed one: a posterior built from chained pseudo-inverses is not a covariance when the Jacobian is ill-conditioned (it comes out asymmetric, with negative eigenvalues), and sampling from it in propagate_petro_uncertainty below would be invalid.

PyHydroGeophysX.uncertainty.model_resolution_spread(R: Any) → Any[source]#

Return diagonal resolution spread metrics from a resolution matrix.

PyHydroGeophysX.uncertainty.propagate_petro_uncertainty(rho: Any, rho_cov: Any, petro_func: Callable[[ndarray], ndarray], n_samples: int = 500, seed: int | None = None) → Dict[str, ndarray][source]#

Propagate resistivity uncertainty through a petrophysical transform.

Uses Monte Carlo sampling by default. "cov" is always a 2-D (outputs, outputs) matrix, (1, 1) for one cell or a scalar output.

A diagonal covariance - one variance per cell, given as a vector or as a diagonal matrix - draws each cell on its own, rho + sqrt(var) z: no n x n matrix is formed or factored (multivariate_normal’s SVD took 10 s and 1 GB at 4000 cells), and a zero variance gives the cell’s value exactly, where the SVD’s round-off leaked other cells’ draws into it.

PyHydroGeophysX.uncertainty.regularized_posterior_std(J: Any, data_weights: Any, Wm: Any, lam: float, alpha: float = 0.0, free: Any | None = None) → ndarray[source]#

Per-cell standard deviation of a regularised Gauss-Newton model, linearised.

Reading the data weights as Gaussian data errors and the regularisation as a Gaussian prior, the model’s covariance at the final iterate is

C = (J^T Wd^2 J + lambda (Wm^T Wm + alpha I))^-1

(Tarantola, 2005, Inverse Problem Theory, SIAM, eq. 3.38; Aster, Borchers and Thurber, 2018, Parameter Estimation and Inverse Problems, ch. 11). Returned is sqrt(diag C), in the units of the model parameter (for an inversion in log resistivity, a standard deviation of ln rho).

What it leaves out: the error of the regularisation itself. A smoothness prior cannot describe a sharp layer boundary, so where the truth is blocky the real error exceeds this: the result is a lower bound there, most of all at depth and where coverage is low.

Parameters:
  • J (array_like) – Jacobian at the final model, data x cells, in the inversion’s own parameterisation (log data against log model for ERT).

  • data_weights (array_like) – Diagonal of Wd, one per datum (1 / the data error).

  • Wm (array_like or sparse matrix) – Model weighting (constraint) matrix, rows x cells.

  • lam (float) – Regularisation weight lambda, as in the objective above.

  • alpha (float) – Smallness weight relative to the smoothness (0 for none).

  • free (array_like of bool, optional) – Cells the inversion updated; held cells get a standard deviation of 0.

Returns:

One standard deviation per cell.

Return type:

numpy.ndarray

Raises:

ValueError – When more than POSTERIOR_MAX_CELLS free cells would have to be formed, the shapes disagree, or the posterior precision is not positive definite.

Examples

>>> J = np.array([[1.0, 0.0], [0.0, 1.0]])
>>> regularized_posterior_std(J, [10.0, 10.0], np.zeros((1, 2)), 1.0, alpha=1.0).round(4)
array([0.0995, 0.0995])
>>> regularized_posterior_std([[1, 0]], [1], [[0, 0]], 1, alpha=0)
Traceback (most recent call last):
    ...
ValueError: The posterior is improper: some cells are constrained neither by the data nor by the regularisation.