krigekit.variogram_model#
Marginal variogram model, fitting, anisotropy, plotting, and transfer.
Classes#
Python-side variogram model with |
Module Contents#
- class krigekit.variogram_model.VariogramModel(structures=None)#
Bases:
krigekit.variogram_base._VariogramModelBasePython-side variogram model with
Kriging.set_vgm-style specs.The class is useful for fitting, plotting, and validating model choices before replaying the same structures into the Fortran solver. It supports additive nested structures and product structures using the same convention as
krigekit.Kriging.set_vgm(): a structure withproduct=Trueis multiplied with the immediately preceding structure in covariance space.Notes
covariance(h)andvariogram(h)evaluate lag distances directly. Usecalc_covariance()andcalc_variogram()to evaluate between coordinates with each structure’s anisotropy parameters applied.Create an empty marginal model or load
set_vgmspecifications.- calc_directional_average(rawvgm=None, store: bool = True, raw_kwargs=None, h_width=None, h_bins=15, cutoff=None, bandwidth=None, angle_tol=22.5, robust=False, include_minor2: bool = None, **kwargs)#
Average the raw cloud along the model’s fixed anisotropy axes.
The model orientation is taken from the stored structures. For 2D data, the output contains major and
minor1directions; for 3D data,minor2is included unlessinclude_minor2=False.
- set_params(params=None, *, sills=None, ranges=None, sill=None, a_major=None, range_=None, nugget=None, fit_nugget: bool = True)#
Manually update fitted variogram parameters.
paramsuses the same flat convention returned byfit():sill0, range0, sill1, range1, ..., [nugget]. For a single structure, the singular keywordssill,a_major/range_andnuggetare convenient alternatives.sillsandrangesmay be sequences with one value per stored structure.- Returns:
VariogramModel –
self, so manual adjustments can be chained before plotting or applying to kriging.
- fit(avgvgm=None, p0=None, x_col=('distance', 'mean'), y_col=('variogram', 'mean'), sigma_col=None, weight_col=None, weights=None, bounds=None, inplace: bool = False, makeplot: bool = False, fit_nugget: bool = True, raw_kwargs=None, avg_kwargs=None, **kwargs)#
Fit this model to an averaged variogram, returning a
FitResult.If
avgvgmis omitted, the cachedavg_variogram_is used when available, otherwise it is computed from observations supplied byset_obs(). The theoretical fit delegates toVgmStructure.fit(); this wrapper adds the empirical-data convenience and updates the analysis fit-state caches.- Returns:
FitResult –
.targetis this model (inplace=True) or a new fitted model;.params/.cov/.metricscarry the fit outputs and.summary()gives a labelled table.
- fit_aniso_angle(rawvgm=None, n_struct=None, set_ranges=True, raw_kwargs=None, **kwargs)#
Estimate the anisotropy orientation from the empirical cloud and apply it.
This is the first fitting step of the anisotropic workflow: run it before
fit_anisotropy()so the directional binning and the sill/range fit use the correct axes. A 3-D cloud uses the multi-started model-based profile fit (krigekit.fit_aniso_angle()); a 2-D cloud falls back to the fast PCA azimuth (estimate_aniso_angle()). The fittedazimuth/dip/plungeare written into every structure, and withset_ranges=Truethe minor ranges are seeded from the fitted anisotropy ratios.rawvgmdefaults to the cached cloud, otherwise it is computed from observations.n_structdefaults to the number of structures. Returnsselfso it can precede the rest of the workflow.
- calc_anisotropic_params(include_minor2: bool = False, fit_nugget: bool = True)#
Return the current anisotropic flat parameter vector.
- set_anisotropic_params(params, include_minor2: bool = False, fit_nugget: bool = True)#
Manually update sills and anisotropic ranges from a flat vector.
paramsfollows thefit_anisotropy()convention:sill, a_major, a_minor1for each structure, optionallya_minor2, followed by a trailing nugget whenfit_nugget=True.
- fit_anisotropy(directional=None, p0=None, axis_col='direction', x_col='lag', y_col='variogram', sigma_col=None, weight_col=None, weights=None, bounds=None, inplace: bool = False, makeplot: bool = False, fit_nugget: bool = True, include_minor2: bool = None, raw_kwargs=None, directional_kwargs=None, maxfev=9999, ax=None, xlabel='Lag', ylabel='Semivariogram', **kwargs)#
Fit sills and anisotropic ranges with fixed orientation.
The fitted parameter vector is
sill, a_major, a_minor1for each structure, optionallya_minor2for 3D fits, followed by a trailing nugget whenfit_nugget=True. Directional data can be supplied directly, or it is computed withcalc_directional_average()using the currentazimuth,dipandplungeas fixed axes.
- set_vgm(vtype: str, nugget: float = 0.0, sill: float = 1.0, a_major: float = 1.0, a_minor1: float = None, a_minor2: float = None, azimuth: float = 0.0, dip: float = 0.0, plunge: float = 0.0, append: bool = True, product: bool = False, name: str = None)#
Add one nested variogram structure.
Parameters mirror
krigekit.Kriging.set_vgm(), exceptivarandjvarare omitted because this object represents one variable-pair model. Passappend=Falseto clear existing structures before adding the new one. Passproduct=Trueto multiply this structure with the immediately preceding structure in covariance space.The stored ranges and rotation angles define theoretical-model evaluation, directional axes, fitting, plotting overlays, and transfer to kriging. They do not implicitly transform a raw empirical cloud; pass
anisotropy=...tocalc_experimental()when desired. This separation is necessary because nested structures may have different anisotropy parameters.- Returns:
VariogramModel –
self, so calls can be chained.
- set_structure_params(index: int = 0, **params)#
Manually update fields on one stored variogram structure.
- Parameters:
index (int, optional) – Zero-based structure index.
**params – Any
VgmComponentfield exceptappend. Use this for edits that do not fit in the flatset_paramsvector, such asa_minor1,azimuth,diporproduct.
- set_anisotropy(structures=None, *, a_minor1=None, a_minor2=None, ratio_minor1=None, ratio_minor2=None, anis1=None, anis2=None, azimuth=None, dip=None, plunge=None)#
Apply anisotropy parameters to one or more structures.
- Parameters:
structures (int or sequence of int, optional) – Zero-based structure indices to update. Defaults to all stored structures.
a_minor1 (float or sequence, optional) – Absolute minor-axis ranges. A sequence must have one value per selected structure.
a_minor2 (float or sequence, optional) – Absolute minor-axis ranges. A sequence must have one value per selected structure.
ratio_minor1 (float or sequence, optional) – Minor/major range ratios.
anis1andanis2are accepted as aliases for compatibility with the kriging search terminology.ratio_minor2 (float or sequence, optional) – Minor/major range ratios.
anis1andanis2are accepted as aliases for compatibility with the kriging search terminology.azimuth (float, optional) – Rotation angles in degrees.
dip (float, optional) – Rotation angles in degrees.
plunge (float, optional) – Rotation angles in degrees.
- Returns:
VariogramModel –
self.
- covariance(h)#
Evaluate the nested/product covariance model at lag distance
h.Delegates to
VgmStructure.covariance(); product groups are evaluated exactly like the Fortran engine.
- property cov0#
Covariance at zero lag, including nugget and product groups.
- variogram(h)#
Evaluate the semivariogram
gamma(h) = C(0) - C(h).
- calc_covariance(coord0, coord1, pairwise: bool = False)#
Evaluate covariance between coordinates, applying anisotropy.
- Parameters:
coord0 (array-like) – Coordinates with shape
(dim,)or(n, dim). By default, arrays with matching lengths are compared row-wise; if one side has one coordinate it is broadcast against the other side.coord1 (array-like) – Coordinates with shape
(dim,)or(n, dim). By default, arrays with matching lengths are compared row-wise; if one side has one coordinate it is broadcast against the other side.pairwise (bool, optional) – If true, return the full
(n0, n1)covariance matrix.
- Returns:
numpy.ndarray or scalar-like – Covariance value(s) from the nested/product model.
- calc_variogram(coord0, coord1, pairwise: bool = False)#
Evaluate semivariogram values between coordinates with anisotropy.
- plot(avgvgm=None, ax=None, x_col=('distance', 'mean'), y_col=('variogram', 'mean'), h=None, plot_data: bool = True, plot_model: bool = True, annotate: bool = True, plotkws_data=None, plotkws_model=None, xlabel='Lag', ylabel='Semivariogram')#
Plot cached/explicit averaged data and the current model curve.
If
avgvgmis omitted, the cached_avgtable fromcalc_average()is used when available. The curve is evaluated withvariogram(), so it represents the isotropic lag-distance model. Usecalc_variogram()for anisotropy-aware coordinate evaluation.
- plot_map(rawvgm=None, ax=None, angle_aniso='model', ellipse_aniso='model', estimate: bool = False, raw_kwargs=None, **kwargs)#
Plot a 2D variogram map from the cached raw cloud.
- Parameters:
rawvgm (pandas.DataFrame, optional) – Raw variogram cloud. If omitted, the cached
_rawtable is used, or computed from stored observations.angle_aniso ({"model", "estimate", None} or float, optional) – Angle overlay for maximum continuity.
"model"uses the first structure’s azimuth,"estimate"estimates the angle from the raw cloud, and a float uses that azimuth directly.ellipse_aniso ({"model", None} or tuple, optional) – Ellipse overlay.
"model"uses the first structure’s major and first minor range.estimate (bool, optional) – Shorthand for
angle_aniso="estimate".raw_kwargs (dict, optional) – Keyword arguments passed to
experimental()if a new raw cloud must be computed.**kwargs – Forwarded to
plot_vgm_map().
- Returns:
matplotlib.axes.Axes – Axis containing the variogram map.
- plot_map3d(rawvgm=None, ax=None, angle_aniso='model', estimate: bool = False, raw_kwargs=None, **kwargs)#
Plot a 3D variogram map as orthogonal fence sections.
Calls
plot_vgm_map3d(). By default (rotate_fences=False) fences align with the world X/Y/Z axes:Fence A — horizontal XY plane (azimuth pattern).
Fence B (
n_fences ≥ 2) — vertical XZ East–West section (dip).Fence C (
n_fences ≥ 3) — vertical YZ North–South section.
A red line is projected onto each fence showing the major axis direction so the fitted orientation can be compared with the empirical map. Pass
rotate_fences=Trueto rotate the fences to the model’s principal planes instead.- Parameters:
rawvgm (pandas.DataFrame, optional) – Raw 3D variogram cloud. If omitted the cached cloud is used, or computed from stored observations.
angle_aniso ({"model", "estimate", None} or float or tuple, optional) – Model orientation.
"model"reads(azimuth, dip, plunge)from the first fitted structure;"estimate"estimates the major direction from the raw cloud; a float is azimuth only; a tuple is(azimuth[, dip[, plunge]]).estimate (bool, optional) – Shorthand for
angle_aniso="estimate".raw_kwargs (dict, optional) – Forwarded to
calc_experimental()when the raw cloud must be computed.**kwargs – Forwarded to
plot_vgm_map3d()(e.g.n_fences,rotate_fences,dx,dz,cutoff,vmax,fill_nan).
- Returns:
matplotlib.axes.Axes – 3D axis containing the variogram map.
- to_kriging_specs(replace: bool = False)#
Return structures as dictionaries accepted by
Kriging.set_vgm.- Parameters:
replace (bool, optional) – If true, the first returned spec has
append=Falseand later specs haveappend=True. This is convenient when applying a complete model to a reusedkrigekit.Krigingobject.
- apply_to(kriging, ivar: int, jvar: int, replace: bool = True)#
Apply this model to a
krigekit.Krigingobject.The first structure clears any existing model for
(ivar, jvar)whenreplace=True. Setreplace=Falseto append all structures to an existing model.
- to_temporal_specs()#
Return structures accepted by
SpaceTimeKriging.set_vgm_temporal.The one-dimensional
a_majorvalue is renamed toat_k. Spatial anisotropy fields are intentionally omitted because temporal marginal structures are one-dimensional.
- apply_temporal_to(kriging, ivar: int, jvar: int)#
Append this model to a
SpaceTimeKrigingtemporal marginal.The target pair should not already contain temporal structures. The space-time API currently resets spatial and temporal marginals together, so this helper deliberately does not offer a replace mode.