krigekit.variogram#
Compatibility facade for krigekit’s variogram analysis API.
Implementation is split by responsibility:
variogram_kernelsEngine-compatible covariance kernels and components.
variogram_geometryLag vectors, anisotropic distances, and rotations.
variogram_empiricalVariogram clouds, binning, and directional analysis.
variogram_fittingGeneric marginal fitting.
variogram_plottingCurve, map, polar, and 3-D plots.
variogram_modelMarginal
VariogramModel.variogram_stComposed
SpaceTimeVariogramModel.variogram_systemMultivariable
VariogramSystem.
Imports from krigekit.variogram remain supported.
Classes#
One nested variogram component. |
|
An ordered set of nested variogram components for one variable pair. |
|
Theoretical space-time variogram: spatial/temporal structures + coupling. |
|
Observation data and search configuration for one variable. |
|
Backwards-compatible namespace for theoretical model functions. |
|
Python-side variogram model with |
|
Joint model composed from spatial and temporal marginal models. |
|
Multivariable variogram system for cokriging workflows. |
|
Variogram system for |
Functions#
|
Bin a variogram cloud and average it. |
|
Cross-variogram cloud between two co-located variables A and B. |
|
Experimental directional variograms along arbitrary (2D/3D) axes. |
|
Perpendicular distance from offset vectors |
|
Mean variogram as a function of azimuth, within a near-origin radius. |
|
Estimate anisotropy directions from a variogram cloud via weighted PCA. |
|
Fit the 3-D anisotropy orientation by a model-based profile search. |
|
Boolean mask selecting pairs aligned with azimuth_anis. |
|
Traditional (LMC) cross-variogram cloud on collocated data. |
|
Compute the raw empirical variogram cloud (all admissible pairs). |
|
Least-squares fit of a (nested) variogram model to averaged data. |
|
Unit vector for an azimuth (deg, clockwise from +Y/North) and dip |
|
Calculate engine-compatible equivalent major-axis lag distance. |
|
Return signed lag vectors |
|
Right-handed 3D rotation whose columns are the principal axes. |
|
Evaluate an engine-compatible covariance model. |
|
Evaluate a semivariogram model. |
|
Return the 3-letter canonical model key for name. |
|
Evaluate a (possibly nested) variogram model at lags h. |
|
Plot an averaged variogram and/or a fitted model curve. |
|
Plot the three principal anisotropy axes as 3D arrows scaled by their |
|
2D variogram map (pcolormesh) with optional anisotropy overlays. |
|
3D variogram map shown as orthogonal fence sections. |
|
Variogram map in polar coordinates (azimuth vs lag distance). |
|
Return an orthonormal |
|
Return the |
|
Return the closed zero-lag indicator covariance |
Module Contents#
- krigekit.variogram.avg_vgm(rawvgm, h_col='distance', t_col=None, cutoff=None, t_cutoff=None, h_width=None, t_width=None, h_bins=None, t_bins=None, tor_hori=None, tor_vert=None, angleh=None, anglev=None, angleh_tor=15, anglev_tor=10, robust=None, estimator='matheron', vgm_col='variogram')#
Bin a variogram cloud and average it.
Supports distance (and optional time) binning, directional and bandwidth filtering, and either the classic (Matheron) mean or the robust Cressie–Hawkins estimator (
estimator="cressie"), Dowd ("dowd"), or Genton.h_widthandt_widthmay be positive scalars for fixed-width bins or one-dimensional arrays of explicit bin edges. Edge-array bins are left-closed and right-open, except that the final edge is included; lags outside the edge range are omitted. Arrays passed through the legacyh_binsandt_binsarguments use the same edge convention.Directional filtering follows variogram-axis symmetry. If only
anglehis supplied, azimuthsanglehandangleh + 180are treated as the same horizontal axis. If bothanglehandanglevare supplied, the same 3D axis is represented by(angleh, anglev)and the reversed lag vector(angleh + 180, -anglev).- Returns:
pandas.DataFrame – Grouped variogram table whose columns are a
(variable, statistic)MultiIndex with statisticsmean,stdandcount. The averaged semivariogram is available asresult[(vgm_col, "mean")].
- krigekit.variogram.cross_vgm(coordsA, valsA, coordsB, valsB, cutoff=np.inf, residual=True, timesA=None, timesB=None, t_cutoff=np.inf, calc_angle=False, maxobs=None, maxobsA=None, maxobsB=None, seed=None, verbose=True, anisotropy=None, n_jobs=None, max_memory_fraction=0.8)#
Cross-variogram cloud between two co-located variables A and B.
Pairs are formed across the two data sets (every A vs every B). When
residualis True the means are removed first so the result is a cross-covariance-style estimator.Warning
This is the pseudo cross-variogram
0.5 * E[(A(x) - B(x+h))**2], not the linear-model-of-coregionalisation (LMC) cross-variogram0.5 * E[(A(x) - A(x+h)) * (B(x) - B(x+h))]. Its sill mixesvar(A) + var(B) - 2*cov(A, B), so do not read an LMC cross-sill directly off it. For heterotopic data (A and B at different locations) the true cross-variogram is not computable and this pseudo form is a reasonable substitute; for a cokriging cross-sill, derivecov(A, B)from collocated hard-data pairs instead.n_jobs=Noneadaptively selects up to four pair-chunk workers after subsampling and cutoff candidate generation.1is sequential and-1uses all available CPUs.max_memory_fractiondefaults to 0.8 and raisesMemoryErrorwhen the estimated final cloud exceeds that fraction of available RAM. PassNoneto disable the guard.
- krigekit.variogram.directional_vgm(rawvgm, directions, h_width=None, h_bins=15, bandwidth=None, angle_tol=22.5, dist='distance', vgm='variogram', robust=False, dim=None)#
Experimental directional variograms along arbitrary (2D/3D) axes.
For each direction the pairs whose lag vector falls within
angle_tolof that axis (and within the perpendicularbandwidth) are selected and binned by lag distance – the multi-dimensional analogue of the gstoolsvario_estimate(direction=...)workflow.- Parameters:
rawvgm (DataFrame) – Variogram cloud with
d0..d{dim-1}lag components.directions (array-like, shape (n_dir, dim)) – Direction vectors (need not be normalised). Use
rotation_matrix_3d()to obtain a rotated orthonormal axis set.h_width (float, optional) – Fixed bin width applied to every direction. When
None(default) the width is computed per direction asmax_proj / h_bins, wheremax_projis the largest projected lag along that axis. This gives equal resolution across all axes regardless of range, which matters for strongly anisotropic data where a single cutoff-derived width would leave the short-range axes with very few bins.h_bins (int) – Number of bins per direction when
h_widthisNone.bandwidth (float, optional) – Maximum perpendicular distance from the directional line.
angle_tol (float, optional) – Angular tolerance (degrees) between a lag and the direction.
- Returns:
DataFrame – Long format with columns
direction(axis index),lag(mean projected lag in the bin),variogramandcount.
- krigekit.variogram.distance_pnt_line(dx, dy, azimuth)#
Perpendicular distance from offset vectors
(dx, dy)to a line through the origin with the given azimuth (degrees, clockwise from +Y).
- krigekit.variogram.estimate_angle_angular_profile(rawvgm, angle='angle_h', dist='distance', r_profile=None, da=10, a_tol=2.5, close=False, vgm='variogram', dim3d=False)#
Mean variogram as a function of azimuth, within a near-origin radius.
Sweeps the azimuth in steps of da degrees (overlapping by
a_tol) and returns the per-sector mean ofangle,distandvgm.
- krigekit.variogram.estimate_aniso_angle(rawvgm, x='d0', y='d1', dist='distance', vgm='variogram', r_max=None, z='d2', dim3d=False, robust=False, get_eigens=False, dx=None, dy=None, dz=None)#
Estimate anisotropy directions from a variogram cloud via weighted PCA.
Near-origin lags are grouped into cells, each cell weighted inversely by its (normalised) mean variogram – low variogram means strong continuity – and an eigen-decomposition of the weighted second moment about the origin yields the principal axes. Each cell contributes its mean lag vector (not the bin edge), so the estimate is insensitive to the bin size. Bins are sized per axis from each axis’s own lag extent, so a thin or short axis (e.g. a shallow
zslab) is still resolved rather than collapsing under a single horizontal-scale spacing. Passdx/dy/dzto override the spacing per axis.The estimate is sensitive to
r_max: too small and a gridded cloud is dominated by axis-aligned lags (the sampling lattice – which can throw the azimuth off by tens of degrees), too large and it mixes nested structures. A good choice is roughly half the shortest structure’s range. Sweepingr_maxto find a stable value does not help reliably – there is no clean plateau – so prefer one principled near-origin radius. This is an approximate orientation estimate (a few degrees at best), best used to seed a fixed-orientation fit (VariogramModel.fit_anisotropy()), not as a final answer.- Returns:
If ``get_eigens`` is True (
(eigvals, eigvecs)sorted descending.)If ``dim3d`` is False (
((azimuth_deg,), (anis1,)).)If ``dim3d`` is True (
((azimuth_deg, dip_deg, plunge_deg), (anis1, anis2)).)azimuth_degis the compass azimuth (0 = North, 90 = East) of the major(maximum-continuity) axis,
dip_degits tilt below the horizontal plane(positive downward), and
plunge_degthe twist of the minor axes aboutthe major axis – exactly the
azimuth/dip/plungeconvention ofthe model and the Fortran engine, so the angles feed straight into
VariogramModel.set_vgm().anis1andanis2are theminor1/major and minor2/major axis-length ratios (the same meaning as the
engine’s
anis1/anis2minor-axis ratios), estimated from theeigenvalue spectrum.
plungeis folded into(-90, 90]and is theleast well-determined angle from sparse clouds.
- krigekit.variogram.fit_aniso_angle(rawvgm, n_struct=1, x='d0', y='d1', z='d2', dist='distance', vgm='variogram', n_bins=16, starts=None, use_seed=True, max_nfev=500)#
Fit the 3-D anisotropy orientation by a model-based profile search.
Unlike
estimate_aniso_angle()(a fast PCA of the lag cloud), this fits the model to the data: for each candidate orientation,n_structspherical structures’ sills and anisotropic ranges are fitted with the orientation held fixed, against a denoised binned cloud, and the orientation giving the lowest residual is kept. The objective is multi-modal, so the search is multi-started over a coarse(azimuth, dip)grid plus theestimate_aniso_angle()seed.Returns
((azimuth, dip, plunge), (anis1, anis2))– the same shape asestimate_aniso_angle()– butanis1/anis2are the fitted minor/major range ratios of the strongest structure (true ratios, not the PCA spread proxy).This is far more robust on scattered, strongly anisotropic clouds, where the PCA seed can be tens of degrees wrong, at a higher cost. It is not immune to a regular sampling lattice: on gridded clouds the lattice biases the residual, and the near-origin PCA seed may be better. Spherical structures are used as the orientation probe regardless of the eventual model type.
- Parameters:
rawvgm (pandas.DataFrame) – Raw variogram cloud with signed lag columns
x/y/zand avgmvalue column.n_struct (int) – Number of nested spherical structures to fit while probing orientation.
n_bins (int) – Cells per cutoff radius for the denoising bins (lag cells use the cell mean lag vector, so the result is insensitive to the exact bin size).
starts (sequence of (azimuth, dip, plunge), optional) – Override the default coarse start grid.
use_seed (bool) – Also start from the
estimate_aniso_angle()PCA estimate.
- krigekit.variogram.filter_vgm(dx, dy, azimuth, azimuth_anis, bandwidth=None, angle_tol=10)#
Boolean mask selecting pairs aligned with azimuth_anis.
This is a 2D/horizontal-axis helper. A pair is kept when its azimuth is within
angle_tolof the target axis, treatingazimuth_anisandazimuth_anis + 180as equivalent. Ifbandwidthis given, the pair must also fall withinbandwidth / 2of the directional line.For 3D azimuth+dip filtering, use
avg_vgm(), which flips the sign of dip for the reversed azimuth.
- krigekit.variogram.raw_cross_vgm(coords, valsA, valsB, cutoff=np.inf, times=None, t_cutoff=np.inf, calc_angle=False, maxobs=None, nmax=None, metric=None, seed=None, verbose=True, anisotropy=None, n_jobs=None, max_memory_fraction=0.8)#
Traditional (LMC) cross-variogram cloud on collocated data.
Both variables are measured at the same
coords(isotopic data). Pairs are formed within the single point set and the cross-semivariance:gamma_AB(h) = 0.5 * (A_i - A_j) * (B_i - B_j)
is stored in the
variogramcolumn. Unlike the pseudo estimator incross_vgm(), this is symmetric in A/B, its sill is the LMC cross-sill you can feed into cokriging, and it costs O(n**2 / 2) rather than O(nA*nB).The returned cloud has exactly the same columns as
raw_vgm(), so it flows straight intoavg_vgm(),estimate_aniso_angle(),directional_vgm()and the variogram-map plots. Calling it withvalsB is valsAreproduces the direct variogram of A.For heterotopic data (A and B at different locations) the true cross-variogram is not computable; use
cross_vgm()(pseudo estimator) or restrict to a collocated subset before calling this function.n_jobs=Noneadaptively selects up to four pair-chunk workers aftermaxobsand cutoff candidate generation.1is sequential and-1uses all available CPUs.max_memory_fractiondefaults to 0.8 and raisesMemoryErrorwhen the estimated final cloud exceeds that fraction of available RAM. PassNoneto disable the guard.
- krigekit.variogram.raw_vgm(coords, vals, cutoff=np.inf, times=None, t_cutoff=np.inf, calc_angle=False, maxobs=None, nmax=None, metric=None, seed=None, verbose=True, great_circle=False, anisotropy=None, n_jobs=None, max_memory_fraction=0.8)#
Compute the raw empirical variogram cloud (all admissible pairs).
- Parameters:
coords (array-like, shape (n, dim)) – Sample coordinates;
dimmay be 1, 2 or 3.vals (array-like, shape (n,)) – Sample values.
cutoff (float, optional) – Maximum spatial lag
|h|to keep (default: no cutoff).times (array-like, optional) – Per-sample time stamps for a space-time variogram.
t_cutoff (float, optional) – Maximum absolute time lag to keep.
calc_angle (bool, optional) – Also compute
angle_h(andangle_vin 3D) for each pair.maxobs (int, optional) – Randomly subsample to at most
maxobspoints before pairing.seed (int, optional) – Random seed for the subsampling.
verbose (bool, optional) – Print a progress indicator.
great_circle (bool, optional) – Treat 2D coordinates as
(lon, lat)in degrees and use the great-circle distance (km) for thedistancelag andcutoff.anisotropy (dict, optional) – Arguments accepted by
calc_anisotropic_lag(). When supplied,cutoffis applied to the equivalent major-axis lag and the cloud includes ananisotropic_distancecolumn. The physical Euclidean lag remains available asdistance.n_jobs (int, optional) – Number of worker threads for vectorized pair chunks.
None(default) chooses adaptively from the post-maxobscandidate-pair count, up to four workers.1is sequential and-1uses all available CPUs.max_memory_fraction (float or None, optional) – Refuse clouds whose estimated final numeric columns exceed this fraction of currently available RAM (default 0.8).
Nonedisables the safety check.
- Returns:
pandas.DataFrame – The variogram cloud (see module docstring for the columns).
- krigekit.variogram.fit_vgm(avgvgm, x_col=('distance', 'mean'), y_col=('variogram', 'mean'), sigma_col=None, weight_col=None, weights=None, models=('exponential',), p0=(), makeplot=False, maxfev=9999, ax=None, xlabel='Lag', ylabel='Semivariogram', bounds=None, return_model=False, return_metrics=False)#
Least-squares fit of a (nested) variogram model to averaged data.
modelsmay be a sequence of model names, a sequence ofVariogramModel.set_vgm-style dictionaries, or aVariogramModeltemplate. String-only models preserve the legacy additive fitting path. Dictionary/model templates also preserveproduct=Trueflags, so product structures can be fitted and returned as a Python-side model.p0is the initial guess assill0, range0, ..., [nugget].sigma_colgives SciPy-style observation standard deviations. Useweightsorweight_colfor weighted least squares, where larger values carry more influence; internally these are converted tosigma = 1 / sqrt(weight). Returns(params, covariance)by default; whenreturn_model=Truethe fittedVariogramModelis appended to the return tuple. Whenmakeplotis true, the Matplotlib axis is also appended.
- class krigekit.variogram.VgmComponent#
One nested variogram component.
The public representation deliberately matches the flat arguments accepted by
krigekit.Kriging.set_vgm(). The Fortran engine groups the anisotropy fields into its internalvgm_anisotype after transfer.- validate()#
Validate finite parameters and strictly positive ranges.
- copy(**changes)#
Return a validated copy, optionally replacing selected fields.
- property display_name#
the
nameif set, otherwise the model type.- Type:
Human-readable label
- set_anisotropy(*, a_major=None, a_minor1=None, a_minor2=None, ratio_minor1=None, ratio_minor2=None, anis1=None, anis2=None, azimuth=None, dip=None, plunge=None)#
Update ranges and angles in place.
anis1andanis2are aliases for the minor/major ratios used by the kriging search API.
- anisotropy_dict()#
Return ranges, ratios, and angles used by geometry helpers.
- calc_anisotropic_distance(lag)#
Return equivalent major-axis distance for lag vector(s).
- calc_covariance(distance)#
Evaluate this component’s covariance at scalar lag distance(s).
- calc_covariance_lag(lag)#
Evaluate covariance for coordinate lag vector(s), with anisotropy.
- property cov0#
Covariance at zero lag, including this component’s nugget.
- calc_variogram(distance)#
Evaluate
gamma(h) = C(0) - C(h)at scalar lag distance(s).
- calc_variogram_lag(lag)#
Evaluate the semivariogram for coordinate lag vector(s).
- to_flat_dict()#
Return the flat engine representation (excludes the
namemetadata).
- classmethod from_flat_dict(spec)#
Construct a component from a strict flat engine-style mapping.
- class krigekit.variogram.VgmStructure(components=None, name=None)#
An ordered set of nested variogram components for one variable pair.
Create a structure from components or flat component specs.
- property ncomponent#
Number of nested components (always
len(self.components)).
- copy()#
Return an independent copy with copied components.
- clear()#
Remove all components and return
self.
- validate()#
Validate every component and return
self.
- set_vgm(vtype, nugget=0.0, sill=1.0, a_major=1.0, a_minor1=None, a_minor2=None, azimuth=0.0, dip=0.0, plunge=0.0, append=True, product=False, name=None)#
Add one nested component.
Parameters mirror
krigekit.Kriging.set_vgm()(withoutivarandjvar). Passappend=Falseto clear existing components first, orproduct=Trueto multiply this component with the preceding one in covariance space.
- set_structure_params(index=0, **params)#
Update fields on one component, with validation.
indexis a zero-based component position. Accepts anyVgmComponentfield; the component is rebuilt and revalidated.
- set_anisotropy(index=None, **params)#
Update anisotropy on one, several, or all components.
indexacceptsNone(all components), one zero-based integer, or a sequence of integers. Keyword arguments are forwarded toVgmComponent.set_anisotropy()(a_minor1,ratio_minor1/anis1,azimuth, …).
- covariance(distance)#
Evaluate the nested/product covariance at scalar lag distance(s).
- property cov0#
Covariance at zero lag, including nugget and product groups.
- variogram(distance)#
Evaluate
gamma(h) = C(0) - C(h)at scalar lag distance(s).
- calc_covariance(coord0, coord1, pairwise=False)#
Evaluate covariance between coordinates, applying anisotropy.
coord0andcoord1have shape(dim,)or(n, dim). By default matching rows are compared and a single point is broadcast;pairwise=Truereturns the full(n0, n1)matrix.
- calc_variogram(coord0, coord1, pairwise=False)#
Evaluate semivariogram values between coordinates with anisotropy.
- fit(data, *, kind='auto', p0=None, x_col=('distance', 'mean'), y_col=('variogram', 'mean'), sigma_col=None, weight_col=None, weights=None, bounds=None, fit_nugget=True, inplace=True, **kwargs)#
Fit sills, major ranges, and nugget to an averaged variogram.
Returns a
krigekit.variogram_fitting.FitResult. Fitted values are written into copies of the current components, so model type, anisotropy, andnameare preserved.kindselects the fit; only the"isotropic"path (default"auto"for a distance/variogram table) is implemented here – useVariogramModel.fit_anisotropyfor directional fits.
- to_kriging_specs(replace=False)#
Return flat specs accepted by
Kriging.set_vgm.With
replace=Truethe first spec carriesappend=Falseso it clears any existing model for the pair; later specs append.
- to_temporal_specs()#
Return specs accepted by
SpaceTimeKriging.set_vgm_temporal.The one-dimensional
a_majorvalue is renamed toat_k; spatial anisotropy fields are omitted because temporal marginals are 1-D.
- apply_to(kriging, ivar, jvar, replace=True)#
Apply this structure to a
krigekit.Krigingobject.
- class krigekit.variogram.VgmStructureST(spatial=None, temporal=None, *, name=None)#
Theoretical space-time variogram: spatial/temporal structures + coupling.
The active coupling form is named by
model("product_sum"or"sum_metric"). Useset_product_sum()orset_sum_metric()to populate it, thencalc_variogram()to evaluate andto_kriging_specs()to emit engine-ready dictionaries.Create an empty structure or wrap existing marginal structures.
- property cs#
Alias for the spatial structure, matching
vgm_struct_st%cs.
- property ct#
Alias for the temporal structure, matching
vgm_struct_st%ct.
- property ncomponent_spatial#
Number of nested spatial components.
- property ncomponent_temporal#
Number of nested temporal components.
- copy()#
Return an independent copy of this structure and its parameters.
- set_product_sum(params, *, spatial_vtype, temporal_vtype, anisotropy=None)#
Populate a product-sum coupling and rebuild
cs/ct.paramsis(a, b, p, spatial_range, temporal_range)with unit-sill marginals; a valid covariance conversion requiresp <= 0,a + p > 0andb + p > 0.cs/ctare rebuilt as single-component structures whose sills area + pandb + p.
- set_sum_metric(spatial, temporal, params, *, transform, time_nugget=0.0, time_sill=1.0)#
Populate a sum-metric coupling from fitted marginal structures.
spatialandtemporalareVgmStructuremarginal shapes, andparamsis(spatial_scale, temporal_scale, *joint_sills, at)with one joint sill per spatial component.
- validate()#
Validate the active coupling parameters and return
self.
- calc_variogram(spatial_lag, temporal_lag)#
Evaluate the active space-time semivariogram at lag arrays.
- to_kriging_specs(**kwargs)#
Return engine-ready specs for the active coupling model.
- class krigekit.variogram.ObservationSet#
Observation data and search configuration for one variable.
- property configured#
True once valid coordinates and values are present.
- property ndrift#
Number of external-drift columns (zero when drift is absent).
- set(coord, value, times=None, variance=None, sk_mean=None, drift=None)#
Set observation data, validating shapes.
coord/valueare required.times,varianceanddriftare per-observation and replace any previous values (Noneclears them).sk_meanis updated only when provided, so it survives a data-only re-set().
- set_search(nmax=None, maxdist=None, anis1=1.0, anis2=1.0, azimuth=0.0, dip=0.0, plunge=0.0, sector_search=False, time_at=None)#
Configure neighbour search (stored for transfer to the engine).
- clear()#
Reset all data and search configuration to defaults.
- validate(ndim=None)#
Validate configured data; optionally require a spatial dimension.
- is_collocated_with(other)#
Return true when two variables share coordinates and times.
- apply_to(kriging, ivar)#
Transfer observations (and drift) to a kriging object for
ivar.
- krigekit.variogram.azimuth_dip_to_vector(azimuth, dip=0.0)#
Unit vector for an azimuth (deg, clockwise from +Y/North) and dip (deg below horizontal, positive down). Returns a length-3 array
[x, y, z].
- krigekit.variogram.calc_anisotropic_lag(lag, *, anis1=1.0, anis2=1.0, azimuth=0.0, dip=0.0, plunge=0.0)#
Calculate engine-compatible equivalent major-axis lag distance.
anis1andanis2are the first and second minor/major range ratios. Isotropic input therefore uses both ratios equal to one. The returned lag remains in coordinate units; dividing it by the major range gives the reduced lag used by the variogram kernels.
- krigekit.variogram.calc_lag_vectors(coord0, coord1, pairwise=False)#
Return signed lag vectors
coord1 - coord0.Coordinates may be single points or
(n, dim)arrays. By default, matching rows are compared and a single point is broadcast. Withpairwise=Truethe result has shape(n0, n1, dim).
- krigekit.variogram.rotation_matrix_3d(azimuth=0.0, dip=0.0, rake=0.0)#
Right-handed 3D rotation whose columns are the principal axes.
The major axis points along
azimuth/dip; rake (the modelplunge) rotates the minor axes about the major axis. Useful for building anisotropic search/model coordinate frames or directional axis sets fordirectional_vgm().The axes are taken from the engine-consistent
_engine_rotation(): its rows are the data-space principal directions in model-axis order(minor1, major, minor2), which are reordered to(major, minor1, minor2)columns here, flippingminor2to keep the frame right-handed.
- krigekit.variogram.calc_cov(vtype, d, psill=1.0, rng=1.0)#
Evaluate an engine-compatible covariance model.
- Parameters:
vtype (str) – Variogram/covariance model code or alias accepted by
resolve_model().d (array-like) – Lag distance(s) in the same units as
rng.psill (float, optional) – Partial sill multiplier for the unit correlation function.
rng (float, optional) – Practical range / period parameter. Must be positive.
- Returns:
numpy.ndarray or scalar-like –
psill * rho(d / rng)using the same model shapes as the Fortran engine. Nugget handling here mirrors a standalone model evaluation:"nug"is one at zero lag and zero otherwise. In kriging matrix assembly, per-structure nugget terms are added on the diagonal by the engine.
- krigekit.variogram.calc_vgm(vtype, d, psill=1.0, rng=1.0, nugget=0.0)#
Evaluate a semivariogram model.
The returned value is
psill * (1 - rho(d / rng)) + nugget. This helper is intended for experimental variogram fitting and plotting, so the nugget is added uniformly to the curve. Kriging matrix assembly handles nugget terms separately throughkrigekit.Kriging.set_vgm().
- krigekit.variogram.resolve_model(name)#
Return the 3-letter canonical model key for name.
Accepts canonical keys (
"exp"), full names ("exponential") or any unambiguous prefix. RaisesKeyErrorwith a helpful message otherwise.
- class krigekit.variogram.vgm#
Backwards-compatible namespace for theoretical model functions.
- krigekit.variogram.vgmfunc(models, h, *params)#
Evaluate a (possibly nested) variogram model at lags h.
- Parameters:
models (sequence of str) – One model name per nested structure.
*params – Flattened
(sill, range)pairs, one pair per model, optionally followed by a single trailing nugget when an odd number of values is given:sill0, range0, sill1, range1, ..., [nugget].
- Returns:
numpy.ndarray – Sum of the requested nested variogram structures at the supplied lags.
- class krigekit.variogram.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.
- krigekit.variogram.plot_vgm(avgvgm, x_col=('distance', 'mean'), y_col=('variogram', 'mean'), models=('exponential',), parameters=(1, 100, 0), plot_data=True, plot_model=True, annotate=True, ax=None, plotkws_data=None, plotkws_model=None, xlabel='Lag', ylabel='Semivariogram')#
Plot an averaged variogram and/or a fitted model curve.
- krigekit.variogram.plot_vgm_anisotropy3d(eigenvalues, eigenvectors, ax=None)#
Plot the three principal anisotropy axes as 3D arrows scaled by their eigenvalues, annotating the azimuth and dip of the major axis.
- krigekit.variogram.plot_vgm_map(rawvgm, x='d0', y='d1', dist='distance', dx=None, dy=None, cutoff=None, ax=None, angle_aniso=None, ellipse_aniso=None, r_profile=None, angle=None, cmap='viridis_r', vmin=None, vmax=None, vgm='variogram', kws_cbar=None, title='Variogram Map', show_cbar=True, show_title=True)#
2D variogram map (pcolormesh) with optional anisotropy overlays.
- krigekit.variogram.plot_vgm_map3d(rawvgm, x='d0', y='d1', z='d2', dist='distance', dx=None, dy=None, dz=None, cutoff=None, ax=None, angle_aniso=None, rotate_fences=False, vgm='variogram', cmap='viridis_r', vmin=None, vmax=None, bandwidth_factor=2.0, n_fences=2, fill_nan=False, kws_cbar=None, title='3D Variogram Map', show_cbar=True, show_title=True)#
3D variogram map shown as orthogonal fence sections.
Up to three mutually orthogonal fences are drawn. By default they are aligned with the world coordinate axes (XY, XZ, YZ), which makes the anisotropy angles easy to read off the plot. Set
rotate_fences=Trueto align the fences with the fitted model axes instead.World-axis-aligned fences (
rotate_fences=False, default):Fence A (always) — horizontal XY plane.
Fence B (
n_fences >= 2) — vertical XZ (East–West) plane.Fence C (
n_fences >= 3) — vertical YZ (North–South) plane.
Model-axis-aligned fences (
rotate_fences=True):Fence A — minor1 × minor2 plane (normal = major axis).
Fence B (
n_fences >= 2) — major × minor2 plane (dip section).Fence C (
n_fences >= 3) — major × minor1 plane (plunge section).
- Parameters:
dx (float, optional) – Reference horizontal bin size. Defaults to
cutoff / 10.dyis accepted for API compatibility but is ignored; usedxonly.dy (float, optional) – Reference horizontal bin size. Defaults to
cutoff / 10.dyis accepted for API compatibility but is ignored; usedxonly.dz (float, optional) – Reference vertical bin size. Defaults to the 90th-percentile of
|d2|divided by 10, which naturally tracks the (typically finer) vertical sampling scale.angle_aniso (None, float, or tuple, optional) – Model orientation. A scalar is interpreted as azimuth (degrees); a 2-tuple as
(azimuth, dip); a 3-tuple as(azimuth, dip, plunge). Only used whenrotate_fences=True(or to label the title).Noneestimates the horizontal azimuth from the cloud withestimate_aniso_angle().rotate_fences (bool, optional) – If
False(default) fences align with the world X/Y/Z axes. IfTruefences are rotated to the model anisotropy axes defined byangle_aniso.bandwidth_factor (float, optional) – Each fence selects pairs within
bandwidth_factor× (normal-axis bin size) of the fence plane. Default 2.n_fences ({1, 2, 3}, optional) – Number of orthogonal fences to draw (A only, A+B, or A+B+C). Default 2. Three fences can be informative but crowded.
fill_nan (bool, optional) – If
True, empty bins are filled with their nearest valid neighbour before rendering, but only inside the cutoff/max-lag radius. Useful when data are sparse and bins patchy. DefaultFalse.
- krigekit.variogram.plot_vgm_map_polar(rawvgm, angle='angle_h', dist='distance', da=None, dr=None, cutoff=None, angle_aniso=None, r_profile=None, cmap='viridis', vmin=None, vmax=None, vgm='variogram', kws_cbar=None)#
Variogram map in polar coordinates (azimuth vs lag distance).
- class krigekit.variogram.SpaceTimeVariogramModel(spatial=None, temporal=None)#
Bases:
krigekit.variogram_base._VariogramModelBaseJoint model composed from spatial and temporal marginal models.
This mirrors the Fortran
vgm_struct_stlayout:spatialcorresponds tocs,temporalcorresponds toct, and this object owns only full space-time observations, coupling parameters, and transfer metadata.Create a space-time model from optional marginal models.
- set_vgm(*args, **kwargs)#
Add a structure to the spatial marginal and return
self.
- set_vgm_temporal(vtype, nugget=0.0, sill=1.0, at_k=1.0, product=False, **kwargs)#
Add a structure to the temporal marginal and return
self.
- experimental(store=True, **kwargs)#
Calculate the full space-time cloud with stored spatial anisotropy.
- calc_spacetime_variogram(spatial_lag, temporal_lag, params=None)#
Evaluate the fitted product-sum space-time semivariogram.
- Parameters:
spatial_lag (array-like) – Broadcastable spatial and temporal lag arrays.
temporal_lag (array-like) – Broadcastable spatial and temporal lag arrays.
params (array-like, optional) –
(a, b, p, spatial_range, temporal_range). If omitted, usespacetime_params_fromfit_spacetime_product_sum()orset_spacetime_params().
- calc_spacetime_variogram_between(coord0, coord1, time0, time1, *, pairwise=False, params=None)#
Evaluate the space-time variogram between coordinates.
Spatial lag vectors are rotated and scaled using the anisotropy stored by
set_spacetime_anisotropy(). The resulting distance is the equivalent lag along the major axis, in the original coordinate units.
- set_spacetime_anisotropy(*, anis1=1.0, anis2=1.0, azimuth=0.0, dip=0.0, plunge=0.0)#
Set spatial anisotropy for product-sum fitting and evaluation.
anis1andanis2are minor/major range ratios, matching the Fortran engine. Angles use the engine convention: azimuth clockwise from north and dip positive downward.
- set_spacetime_params(params, *, spatial_vtype=None, temporal_vtype=None)#
Manually set product-sum space-time parameters.
paramsis(a, b, p, spatial_range, temporal_range). Valid covariance conversion requiresp <= 0,a + p > 0andb + p > 0.
- fit_spacetime_product_sum(avgvgm=None, *, spatial_vtype='sph', temporal_vtype='gau', starts=None, bounds=None, spatial_col=None, temporal_col=('time_lag', 'mean'), variogram_col=('variogram', 'mean'), count_col=('variogram', 'count'), weight_cap_quantile=0.9, min_marginal_sill=0.0001, options=None, avg_kwargs=None)#
Fit a constrained product-sum model to averaged space-time bins.
The fitted form is
a*g_s(h_s) + b*g_t(h_t) + p*g_s(h_s)*g_t(h_t),where both marginal variograms have unit sill. Multiple starting points are fitted with SLSQP; the successful result with the smallest weighted objective is stored.
- Returns:
VariogramModel –
selfwithspacetime_params_,spacetime_fit_result_andspacetime_fit_results_populated.
- calc_spacetime_sum_metric_variogram(spatial_lag, temporal_lag, params=None)#
Evaluate a fitted sum-metric space-time semivariogram.
paramscontainsspatial_scale, temporal_scale, one joint sill per spatial structure, and the joint temporal scaleat.
- fit_spacetime_sum_metric(spatial_model=None, temporal_model=None, avgvgm=None, *, transform='lin', time_nugget=0.0, time_sill=1.0, p0=None, bounds=None, spatial_col=('distance', 'mean'), temporal_col=('time_lag', 'mean'), variogram_col=('variogram', 'mean'), count_col=('variogram', 'count'), weight_cap_quantile=0.9, max_nfev=20000, avg_kwargs=None)#
Fit sum-metric coupling while retaining fitted marginal shapes.
The fit estimates a spatial marginal scale, temporal marginal scale, one non-negative joint sill per spatial structure, and the joint temporal scale
at. Allowing the two marginal scales to adjust avoids forcing separately fitted boundary marginals to explain the entire interior space-time lag surface.
- fit(avgvgm=None, *, model='product_sum', **kwargs)#
Fit a space-time coupling model, returning a
FitResult.modelselects the coupling form:"product_sum"fits the constraineda*g_s(h_s) + b*g_t(h_t) + p*g_s(h_s)*g_t(h_t)model; its parameters are(a, b, p, spatial_range, temporal_range)."sum_metric"fits a spatial marginal scale, a temporal marginal scale, one joint sill per spatial structure, and the joint temporal scaleat.
Remaining keyword arguments are forwarded to the underlying fitter, and the fitted parameters are stored on the model for
to_spacetime_kriging_specs()/to_sum_metric_kriging_specs().FitResult.summary()reports the labelled parameter table; variance and p-values are not estimated for these constrained/weighted joint fits, so those columns areNaN.
- to_sum_metric_kriging_specs()#
Return fitted sum-metric marginal, coupling, and search parameters.
- to_spacetime_kriging_specs(*, z_scale=None, spatial_nugget=0.0, temporal_nugget=0.0)#
Convert fitted product-sum parameters to engine-ready dictionaries.
- class krigekit.variogram.VariogramSystem(nvar=None)#
Multivariable variogram system for cokriging workflows.
The system stores observations and variogram structures by 1-based variable pair
(ivar, jvar). Each pair is aVgmStructure, whilefit_lmc()fits all requested pairs together with positive-semidefinite coregionalization matrices.Create an empty multivariable variogram system.
nvar=Noneselects dynamic mode: the variable count grows to the largest referenced 1-based index. An explicitnvaris a strict upper bound and access beyond it raises.- set_obs(ivar, coord, value, times=None, variance=None, sk_mean=None, drift=None)#
Store observations for variable
ivar(ergonomic wrapper).Delegates to
self.obs[ivar].set(...)and invalidates cached empirical variograms for any pair containingivar.
- set_search(ivar, *, nmax=None, maxdist=None, anis1=1.0, anis2=1.0, azimuth=0.0, dip=0.0, plunge=0.0, sector_search=False, time_at=None)#
Configure per-variable neighbour search, transferred by
apply().Search settings are stored on the variable’s
ObservationSet; the Fortran engine performs the actual neighbour selection.
- set_vgm(ivar, jvar, vtype, **kwargs)#
Add one nested structure to the model for
(ivar, jvar).
- set_raw_vgm(ivar, jvar, rawvgm)#
Store an externally computed raw variogram cloud for a pair.
- set_avg_vgm(ivar, jvar, avgvgm)#
Store an externally computed averaged variogram for a pair.
- calc_experimental(ivar=None, jvar=None, cross='auto', store=True, **kwargs)#
Compute a raw empirical variogram cloud for one or all pairs.
With
ivar=None(and nojvar), the cloud is computed for every pair that has a variogram model configured viaset_vgm()(vgm.configured_pairs()), returning a{(ivar, jvar): cloud}dict. Otherwise a single pair is computed and returned.Direct pairs use
raw_vgm(). Cross pairs use the LMC cross-variogram estimatorraw_cross_vgm()when the observations are collocated. Setcross="pseudo"to forcecross_vgm(), orcross="lmc"to require collocated observations.
- calc_empirical(*args, **kwargs)#
Alias for
calc_experimental().
- calc_average(ivar=None, jvar=None, rawvgm=None, store=True, raw_kwargs=None, **kwargs)#
Average one pair, or all cached raw variograms when no pair is given.
- fit_pair(ivar, jvar=None, avgvgm=None, inplace=True, **kwargs)#
Fit one variable-pair model independently.
This is convenient for direct variograms, but
fit_lmc()is the safer choice for cokriging because it constrains cross-pair sills.
- fit(*, method='lmc', ivar=None, jvar=None, pairs=None, **kwargs)#
Fit the system, returning a
FitResult(method facade).method="lmc"(default) fits a joint linear model of coregionalization viafit_lmc();method="pair"fits one variable pair independently viafit_pair()and requiresivar(with optionaljvar). Subclasses extend this facade –IndicatorVariogramSystemaddsmethod="closure".
- fit_aniso_angle(ivar=1, jvar=None, pairs=None, n_struct=None, set_ranges=True, raw_kwargs=None, **kwargs)#
Fit the anisotropy orientation from one pair and apply it system-wide.
Run this before
fit_lmc()/fit_pair(): the orientation is estimated from the(ivar, jvar)pair’s empirical cloud (the primary auto-variogram by default) with the model-based profile fit (krigekit.fit_aniso_angle(), 3-D) or the PCA azimuth (estimate_aniso_angle(), 2-D), then written into the structures selected bypairs(all configured pairs by default, since an LMC shares one orientation).set_ranges=Truealso seeds the minor ranges from the fitted ratios. Returnsself.
- fit_lmc(pairs=None, x_col=('distance', 'mean'), y_col=('variogram', 'mean'), sigma_col=None, weight_col=None, fit_ranges=True, fit_nugget=True, inplace=False, raw_kwargs=None, avg_kwargs=None, max_nfev=20000, **kwargs)#
Fit an additive linear model of coregionalization.
The sill matrix for each nested structure is parameterized as
L @ L.Tduring optimization, so every fitted coregionalization matrix is positive semidefinite. Ranges are shared across all pairs. Usesigma_colfor uncertainty-style residual scaling orweight_colfor weighted least squares.
- get_lmc_matrices(include_nugget=True)#
Return fitted/coregionalization matrices from current pair models.
- set_markov_cross(primary, secondary, corr=None, structure='secondary', cross_nugget=0.0)#
Build the
(primary, secondary)cross variogram by the Markov Model 1 (MM1) collocated-cokriging assumption.For a sparsely sampled primary and a densely sampled secondary the cross-covariance cannot be fit from the primary’s (often nugget-dominated) structure – a joint
fit_lmc()would drive it to zero. MM1 instead transfers it through the collocated correlation: the cross adopts the nested structure of one variable (structure="secondary"by default – the dense covariate that carries the spatial continuity), and each cross partial sill is\[b_{ps}^{(k)} = \rho \, \sqrt{b_{pp}^{(k)} \, b_{ss}^{(k)}}\]which is positive-semidefinite per structure for
|rho| <= 1, so the coregionalization is valid by construction (no clamping needed). This is the appropriate model for sparse-hard + dense-soft cokriging (Almeida & Journel, 1994; Goovaerts, 1997). Markov Model 2 is not yet implemented.- Parameters:
primary (int) – 1-based indices; both auto-models must already be set via
set_vgm()and share the same nested-structure count.secondary (int) – 1-based indices; both auto-models must already be set via
set_vgm()and share the same nested-structure count.corr (float, optional) – Collocated cross-correlation in
[-1, 1]. IfNoneit is estimated from the collocated observations of the two variables (which must share coordinates; otherwise passcorrexplicitly).structure ({"secondary", "primary"}) – Which variable’s structure shapes/ranges the cross adopts.
cross_nugget (float) – Cross nugget partial sill (default 0).
- validate_for(kriging, observations=True, variograms=True, pairs=None)#
Check that this system can be applied to
krigingwithout leaving it partially configured. Raises on the first problem and mutates nothing; this is the validate-first half ofapply().
- apply_observations(kriging)#
Transfer configured observations (and drift) in ascending order.
- apply_variograms(kriging, replace=True, pairs=None)#
Transfer configured pair structures in canonical upper-triangle order.
- apply(kriging, observations=True, variograms=True, replace=True, pairs=None)#
Validate, then transfer observations and/or variograms to
kriging.Validation (
validate_for()) completes before any mutation, so a failure leaveskrigingunchanged. Observations are applied in ascending variable order (drift immediately after each base observation), then configured variograms in canonical upper-triangle order.
- class krigekit.variogram.IndicatorVariogramSystem(categories=None, ncat=None)#
Bases:
krigekit.variogram_system.VariogramSystemVariogram system for
Kmutually exclusive categorical indicators.Create an indicator system from category labels or a count.
Provide
categories(an ordered label list) orncat. The system has exactlyKvariables (ivar = 1..K); secondary co-variates are out of scope here – configure those on the kriging object directly.- property ncat#
Number of categories
K(always the system’s variable count).
- encode_indicators(categories)#
Return the one-hot indicator matrix for
categoriesusing labels.
- set_categorical_obs(coord, categories, *, category_labels=None, variance=None)#
Encode raw categories into
Kindicator datasets and store them.category_labels(or the constructorcategories) fixes the label order; otherwise sorted unique values are used. Proportions are computed from the encoded indicators.
- calc_proportions()#
Compute and store category proportions from configured indicators.
- initial_indicator_covariance()#
Return the closed zero-lag covariance
diag(p) - p p^T.
- set_indicator_vgm(vtype='sph', nugget=0.0, sill=1.0, a_major=1.0, a_minor1=None, a_minor2=None, azimuth=0.0, dip=0.0, plunge=0.0, sill_strategy='theoretical', cross_strategy='closure', proportions=None)#
Configure all
K^2indicator pairs with one shared model shape.sill_strategysets the auto (diagonal) partial sills:"theoretical"–p_k (1 - p_k)from category proportions;"uniform"– the givensillfor every category.
cross_strategysets the off-diagonal partial sills:"closure"(recommended) –-p_k p_l, the closed indicator covariance off-diagonal;"independent"– zero (no co-kriging);"proportional"–sqrt(s_k s_l)from the auto sills;"uniform"– the givensill.
Legacy configurations map directly: old
cross="same"issill_strategy="uniform", cross_strategy="uniform"; oldcross="independent"/"proportional"pair withsill_strategy="theoretical".
- fit_indicator_lmc(pairs=None, shared_ranges=True, x_col=('distance', 'mean'), y_col=('variogram', 'mean'), sigma_col=None, weight_col=None, fit_nugget=True, inplace=False, raw_kwargs=None, avg_kwargs=None, max_nfev=20000, **kwargs)#
Fit a closed, PSD linear model of coregionalization for indicators.
Each nested coregionalization matrix is parameterized as
B = Q L L^T Q^TwithQthe contrast basis, guaranteeing positive semidefiniteness and closure (B 1 = 0) at every fitted lag. Ranges are shared across pairs whenshared_ranges=True. Returns aFitResultwhosetargetis the fitted indicator system.
- validate_closure(tol=1e-06, include_nugget=True)#
Check that every fitted coregionalization matrix is closed.
Raises if any matrix (sill structures, plus the nugget when
include_nugget) has a row sum exceedingtolin magnitude.
- fit(*, method='closure', **kwargs)#
Fit the indicator system;
method="closure"is the default."closure"runsfit_indicator_lmc();"lmc"and"pair"fall through to the unconstrainedVariogramSystemfacade.
- apply(kriging, observations=True, variograms=True, replace=True, pairs=None)#
Transfer indicators and structures, checking
ncatagreement.
- krigekit.variogram.contrast_basis(ncat)#
Return an orthonormal
(K, K-1)basisQof the contrast space.Columns of
Qare orthonormal and orthogonal to the all-ones vector, soB = Q L L^T Q^Tis positive semidefinite and closed (B 1 = 0) for any lower-triangularL.
- krigekit.variogram.encode_indicator_matrix(values, categories)#
Return the
(nobs, K)one-hot indicator matrix for rawvalues.categoriesis the ordered list ofKlabels; columnkis the binary indicatorvalues == categories[k]as floats.
- krigekit.variogram.indicator_covariance(proportions)#
Return the closed zero-lag indicator covariance
diag(p) - p p^T.For a probability vector
psumming to one this is positive semidefinite with row sums of zero, giving auto variancesp_k (1 - p_k)and cross covariances-p_k p_l.