krigekit.variogram#

Compatibility facade for krigekit’s variogram analysis API.

Implementation is split by responsibility:

variogram_kernels

Engine-compatible covariance kernels and components.

variogram_geometry

Lag vectors, anisotropic distances, and rotations.

variogram_empirical

Variogram clouds, binning, and directional analysis.

variogram_fitting

Generic marginal fitting.

variogram_plotting

Curve, map, polar, and 3-D plots.

variogram_model

Marginal VariogramModel.

variogram_st

Composed SpaceTimeVariogramModel.

variogram_system

Multivariable VariogramSystem.

Imports from krigekit.variogram remain supported.

Classes#

VgmComponent

One nested variogram component.

VgmStructure

An ordered set of nested variogram components for one variable pair.

VgmStructureST

Theoretical space-time variogram: spatial/temporal structures + coupling.

ObservationSet

Observation data and search configuration for one variable.

vgm

Backwards-compatible namespace for theoretical model functions.

VariogramModel

Python-side variogram model with Kriging.set_vgm-style specs.

SpaceTimeVariogramModel

Joint model composed from spatial and temporal marginal models.

VariogramSystem

Multivariable variogram system for cokriging workflows.

IndicatorVariogramSystem

Variogram system for K mutually exclusive categorical indicators.

Functions#

avg_vgm(rawvgm[, h_col, t_col, cutoff, t_cutoff, ...])

Bin a variogram cloud and average it.

cross_vgm(coordsA, valsA, coordsB, valsB[, cutoff, ...])

Cross-variogram cloud between two co-located variables A and B.

directional_vgm(rawvgm, directions[, h_width, h_bins, ...])

Experimental directional variograms along arbitrary (2D/3D) axes.

distance_pnt_line(dx, dy, azimuth)

Perpendicular distance from offset vectors (dx, dy) to a line through

estimate_angle_angular_profile(rawvgm[, angle, dist, ...])

Mean variogram as a function of azimuth, within a near-origin radius.

estimate_aniso_angle(rawvgm[, x, y, dist, vgm, r_max, ...])

Estimate anisotropy directions from a variogram cloud via weighted PCA.

fit_aniso_angle(rawvgm[, n_struct, x, y, z, dist, ...])

Fit the 3-D anisotropy orientation by a model-based profile search.

filter_vgm(dx, dy, azimuth, azimuth_anis[, bandwidth, ...])

Boolean mask selecting pairs aligned with azimuth_anis.

raw_cross_vgm(coords, valsA, valsB[, cutoff, times, ...])

Traditional (LMC) cross-variogram cloud on collocated data.

raw_vgm(coords, vals[, cutoff, times, t_cutoff, ...])

Compute the raw empirical variogram cloud (all admissible pairs).

fit_vgm(avgvgm[, x_col, y_col, sigma_col, weight_col, ...])

Least-squares fit of a (nested) variogram model to averaged data.

azimuth_dip_to_vector(azimuth[, dip])

Unit vector for an azimuth (deg, clockwise from +Y/North) and dip

calc_anisotropic_lag(lag, *[, anis1, anis2, azimuth, ...])

Calculate engine-compatible equivalent major-axis lag distance.

calc_lag_vectors(coord0, coord1[, pairwise])

Return signed lag vectors coord1 - coord0.

rotation_matrix_3d([azimuth, dip, rake])

Right-handed 3D rotation whose columns are the principal axes.

calc_cov(vtype, d[, psill, rng])

Evaluate an engine-compatible covariance model.

calc_vgm(vtype, d[, psill, rng, nugget])

Evaluate a semivariogram model.

resolve_model(name)

Return the 3-letter canonical model key for name.

vgmfunc(models, h, *params)

Evaluate a (possibly nested) variogram model at lags h.

plot_vgm(avgvgm[, x_col, y_col, models, parameters, ...])

Plot an averaged variogram and/or a fitted model curve.

plot_vgm_anisotropy3d(eigenvalues, eigenvectors[, ax])

Plot the three principal anisotropy axes as 3D arrows scaled by their

plot_vgm_map(rawvgm[, x, y, dist, dx, dy, cutoff, ax, ...])

2D variogram map (pcolormesh) with optional anisotropy overlays.

plot_vgm_map3d(rawvgm[, x, y, z, dist, dx, dy, dz, ...])

3D variogram map shown as orthogonal fence sections.

plot_vgm_map_polar(rawvgm[, angle, dist, da, dr, ...])

Variogram map in polar coordinates (azimuth vs lag distance).

contrast_basis(ncat)

Return an orthonormal (K, K-1) basis Q of the contrast space.

encode_indicator_matrix(values, categories)

Return the (nobs, K) one-hot indicator matrix for raw values.

indicator_covariance(proportions)

Return the closed zero-lag indicator covariance diag(p) - p p^T.

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_width and t_width may 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 legacy h_bins and t_bins arguments use the same edge convention.

Directional filtering follows variogram-axis symmetry. If only angleh is supplied, azimuths angleh and angleh + 180 are treated as the same horizontal axis. If both angleh and anglev are 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 statistics mean, std and count. The averaged semivariogram is available as result[(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 residual is 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-variogram 0.5 * E[(A(x) - A(x+h)) * (B(x) - B(x+h))]. Its sill mixes var(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, derive cov(A, B) from collocated hard-data pairs instead.

n_jobs=None adaptively selects up to four pair-chunk workers after subsampling and cutoff candidate generation. 1 is sequential and -1 uses all available CPUs.

max_memory_fraction defaults to 0.8 and raises MemoryError when the estimated final cloud exceeds that fraction of available RAM. Pass None to 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_tol of that axis (and within the perpendicular bandwidth) are selected and binned by lag distance – the multi-dimensional analogue of the gstools vario_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 as max_proj / h_bins, where max_proj is 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_width is None.

  • 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), variogram and count.

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 of angle, dist and vgm.

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 z slab) is still resolved rather than collapsing under a single horizontal-scale spacing. Pass dx / dy / dz to 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. Sweeping r_max to 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_deg is the compass azimuth (0 = North, 90 = East) of the major

  • (maximum-continuity) axis, dip_deg its tilt below the horizontal plane

  • (positive downward), and plunge_deg the twist of the minor axes about

  • the major axis – exactly the azimuth / dip / plunge convention of

  • the model and the Fortran engine, so the angles feed straight into

  • VariogramModel.set_vgm(). anis1 and anis2 are the

  • minor1/major and minor2/major axis-length ratios (the same meaning as the

  • engine’s anis1 / anis2 minor-axis ratios), estimated from the

  • eigenvalue spectrum. plunge is folded into (-90, 90] and is the

  • least 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_struct spherical 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 the estimate_aniso_angle() seed.

Returns ((azimuth, dip, plunge), (anis1, anis2)) – the same shape as estimate_aniso_angle() – but anis1 / anis2 are 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/z and a vgm value 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_tol of the target axis, treating azimuth_anis and azimuth_anis + 180 as equivalent. If bandwidth is given, the pair must also fall within bandwidth / 2 of 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 variogram column. Unlike the pseudo estimator in cross_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 into avg_vgm(), estimate_aniso_angle(), directional_vgm() and the variogram-map plots. Calling it with valsB is valsA reproduces 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=None adaptively selects up to four pair-chunk workers after maxobs and cutoff candidate generation. 1 is sequential and -1 uses all available CPUs.

max_memory_fraction defaults to 0.8 and raises MemoryError when the estimated final cloud exceeds that fraction of available RAM. Pass None to 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; dim may 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 (and angle_v in 3D) for each pair.

  • maxobs (int, optional) – Randomly subsample to at most maxobs points 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 the distance lag and cutoff.

  • anisotropy (dict, optional) – Arguments accepted by calc_anisotropic_lag(). When supplied, cutoff is applied to the equivalent major-axis lag and the cloud includes an anisotropic_distance column. The physical Euclidean lag remains available as distance.

  • n_jobs (int, optional) – Number of worker threads for vectorized pair chunks. None (default) chooses adaptively from the post-maxobs candidate-pair count, up to four workers. 1 is sequential and -1 uses 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). None disables 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.

models may be a sequence of model names, a sequence of VariogramModel.set_vgm-style dictionaries, or a VariogramModel template. String-only models preserve the legacy additive fitting path. Dictionary/model templates also preserve product=True flags, so product structures can be fitted and returned as a Python-side model.

p0 is the initial guess as sill0, range0, ..., [nugget]. sigma_col gives SciPy-style observation standard deviations. Use weights or weight_col for weighted least squares, where larger values carry more influence; internally these are converted to sigma = 1 / sqrt(weight). Returns (params, covariance) by default; when return_model=True the fitted VariogramModel is appended to the return tuple. When makeplot is 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 internal vgm_aniso type after transfer.

validate()#

Validate finite parameters and strictly positive ranges.

copy(**changes)#

Return a validated copy, optionally replacing selected fields.

property display_name#

the name if 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.

anis1 and anis2 are 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 name metadata).

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() (without ivar and jvar). Pass append=False to clear existing components first, or product=True to multiply this component with the preceding one in covariance space.

set_structure_params(index=0, **params)#

Update fields on one component, with validation.

index is a zero-based component position. Accepts any VgmComponent field; the component is rebuilt and revalidated.

set_anisotropy(index=None, **params)#

Update anisotropy on one, several, or all components.

index accepts None (all components), one zero-based integer, or a sequence of integers. Keyword arguments are forwarded to VgmComponent.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.

coord0 and coord1 have shape (dim,) or (n, dim). By default matching rows are compared and a single point is broadcast; pairwise=True returns 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, and name are preserved. kind selects the fit; only the "isotropic" path (default "auto" for a distance/variogram table) is implemented here – use VariogramModel.fit_anisotropy for directional fits.

to_kriging_specs(replace=False)#

Return flat specs accepted by Kriging.set_vgm.

With replace=True the first spec carries append=False so 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_major value is renamed to at_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.Kriging object.

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"). Use set_product_sum() or set_sum_metric() to populate it, then calc_variogram() to evaluate and to_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.

params is (a, b, p, spatial_range, temporal_range) with unit-sill marginals; a valid covariance conversion requires p <= 0, a + p > 0 and b + p > 0. cs/ct are rebuilt as single-component structures whose sills are a + p and b + 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.

spatial and temporal are VgmStructure marginal shapes, and params is (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 nobs#

Number of observation rows (zero before set()).

property ndim#

Spatial dimension (zero before set()).

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/value are required. times, variance and drift are per-observation and replace any previous values (None clears them). sk_mean is updated only when provided, so it survives a data-only re-set().

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.

anis1 and anis2 are 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. With pairwise=True the 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 model plunge) rotates the minor axes about the major axis. Useful for building anisotropic search/model coordinate frames or directional axis sets for directional_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, flipping minor2 to 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-likepsill * 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 through krigekit.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. Raises KeyError with 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._VariogramModelBase

Python-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 with product=True is multiplied with the immediately preceding structure in covariance space.

Notes

covariance(h) and variogram(h) evaluate lag distances directly. Use calc_covariance() and calc_variogram() to evaluate between coordinates with each structure’s anisotropy parameters applied.

Create an empty marginal model or load set_vgm specifications.

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 minor1 directions; for 3D data, minor2 is included unless include_minor2=False.

calc_params(fit_nugget: bool = True)#

Return the current flat (sill, range, ..., [nugget]) vector.

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.

params uses the same flat convention returned by fit(): sill0, range0, sill1, range1, ..., [nugget]. For a single structure, the singular keywords sill, a_major/range_ and nugget are convenient alternatives. sills and ranges may be sequences with one value per stored structure.

Returns:

VariogramModelself, 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 avgvgm is omitted, the cached avg_variogram_ is used when available, otherwise it is computed from observations supplied by set_obs(). The theoretical fit delegates to VgmStructure.fit(); this wrapper adds the empirical-data convenience and updates the analysis fit-state caches.

Returns:

FitResult.target is this model (inplace=True) or a new fitted model; .params/.cov/.metrics carry 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 fitted azimuth / dip / plunge are written into every structure, and with set_ranges=True the minor ranges are seeded from the fitted anisotropy ratios.

rawvgm defaults to the cached cloud, otherwise it is computed from observations. n_struct defaults to the number of structures. Returns self so 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.

params follows the fit_anisotropy() convention: sill, a_major, a_minor1 for each structure, optionally a_minor2, followed by a trailing nugget when fit_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_minor1 for each structure, optionally a_minor2 for 3D fits, followed by a trailing nugget when fit_nugget=True. Directional data can be supplied directly, or it is computed with calc_directional_average() using the current azimuth, dip and plunge as 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(), except ivar and jvar are omitted because this object represents one variable-pair model. Pass append=False to clear existing structures before adding the new one. Pass product=True to 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=... to calc_experimental() when desired. This separation is necessary because nested structures may have different anisotropy parameters.

Returns:

VariogramModelself, 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 VgmComponent field except append. Use this for edits that do not fit in the flat set_params vector, such as a_minor1, azimuth, dip or product.

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. anis1 and anis2 are accepted as aliases for compatibility with the kriging search terminology.

  • ratio_minor2 (float or sequence, optional) – Minor/major range ratios. anis1 and anis2 are 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:

VariogramModelself.

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 avgvgm is omitted, the cached _avg table from calc_average() is used when available. The curve is evaluated with variogram(), so it represents the isotropic lag-distance model. Use calc_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 _raw table 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=True to 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=False and later specs have append=True. This is convenient when applying a complete model to a reused krigekit.Kriging object.

apply_to(kriging, ivar: int, jvar: int, replace: bool = True)#

Apply this model to a krigekit.Kriging object.

The first structure clears any existing model for (ivar, jvar) when replace=True. Set replace=False to append all structures to an existing model.

to_temporal_specs()#

Return structures accepted by SpaceTimeKriging.set_vgm_temporal.

The one-dimensional a_major value is renamed to at_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 SpaceTimeKriging temporal 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=True to 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. dy is accepted for API compatibility but is ignored; use dx only.

  • dy (float, optional) – Reference horizontal bin size. Defaults to cutoff / 10. dy is accepted for API compatibility but is ignored; use dx only.

  • 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 when rotate_fences=True (or to label the title). None estimates the horizontal azimuth from the cloud with estimate_aniso_angle().

  • rotate_fences (bool, optional) – If False (default) fences align with the world X/Y/Z axes. If True fences are rotated to the model anisotropy axes defined by angle_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. Default False.

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._VariogramModelBase

Joint model composed from spatial and temporal marginal models.

This mirrors the Fortran vgm_struct_st layout: spatial corresponds to cs, temporal corresponds to ct, 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, use spacetime_params_ from fit_spacetime_product_sum() or set_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.

anis1 and anis2 are 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.

params is (a, b, p, spatial_range, temporal_range). Valid covariance conversion requires p <= 0, a + p > 0 and b + 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:

VariogramModelself with spacetime_params_, spacetime_fit_result_ and spacetime_fit_results_ populated.

calc_spacetime_sum_metric_variogram(spatial_lag, temporal_lag, params=None)#

Evaluate a fitted sum-metric space-time semivariogram.

params contains spatial_scale, temporal_scale, one joint sill per spatial structure, and the joint temporal scale at.

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.

model selects the coupling form:

  • "product_sum" fits the constrained a*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 scale at.

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 are NaN.

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 a VgmStructure, while fit_lmc() fits all requested pairs together with positive-semidefinite coregionalization matrices.

Create an empty multivariable variogram system.

nvar=None selects dynamic mode: the variable count grows to the largest referenced 1-based index. An explicit nvar is 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 containing ivar.

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 no jvar), the cloud is computed for every pair that has a variogram model configured via set_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 estimator raw_cross_vgm() when the observations are collocated. Set cross="pseudo" to force cross_vgm(), or cross="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 via fit_lmc(); method="pair" fits one variable pair independently via fit_pair() and requires ivar (with optional jvar). Subclasses extend this facade – IndicatorVariogramSystem adds method="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 by pairs (all configured pairs by default, since an LMC shares one orientation). set_ranges=True also seeds the minor ranges from the fitted ratios. Returns self.

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.T during optimization, so every fitted coregionalization matrix is positive semidefinite. Ranges are shared across all pairs. Use sigma_col for uncertainty-style residual scaling or weight_col for 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]. If None it is estimated from the collocated observations of the two variables (which must share coordinates; otherwise pass corr explicitly).

  • 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 kriging without leaving it partially configured. Raises on the first problem and mutates nothing; this is the validate-first half of apply().

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 leaves kriging unchanged. 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.VariogramSystem

Variogram system for K mutually exclusive categorical indicators.

Create an indicator system from category labels or a count.

Provide categories (an ordered label list) or ncat. The system has exactly K variables (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 categories using labels.

set_categorical_obs(coord, categories, *, category_labels=None, variance=None)#

Encode raw categories into K indicator datasets and store them.

category_labels (or the constructor categories) 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^2 indicator pairs with one shared model shape.

sill_strategy sets the auto (diagonal) partial sills:

  • "theoretical"p_k (1 - p_k) from category proportions;

  • "uniform" – the given sill for every category.

cross_strategy sets 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 given sill.

Legacy configurations map directly: old cross="same" is sill_strategy="uniform", cross_strategy="uniform"; old cross="independent"/"proportional" pair with sill_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^T with Q the contrast basis, guaranteeing positive semidefiniteness and closure (B 1 = 0) at every fitted lag. Ranges are shared across pairs when shared_ranges=True. Returns a FitResult whose target is 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 exceeding tol in magnitude.

fit(*, method='closure', **kwargs)#

Fit the indicator system; method="closure" is the default.

"closure" runs fit_indicator_lmc(); "lmc" and "pair" fall through to the unconstrained VariogramSystem facade.

apply(kriging, observations=True, variograms=True, replace=True, pairs=None)#

Transfer indicators and structures, checking ncat agreement.

krigekit.variogram.contrast_basis(ncat)#

Return an orthonormal (K, K-1) basis Q of the contrast space.

Columns of Q are orthonormal and orthogonal to the all-ones vector, so B = Q L L^T Q^T is positive semidefinite and closed (B 1 = 0) for any lower-triangular L.

krigekit.variogram.encode_indicator_matrix(values, categories)#

Return the (nobs, K) one-hot indicator matrix for raw values.

categories is the ordered list of K labels; column k is the binary indicator values == 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 p summing to one this is positive semidefinite with row sums of zero, giving auto variances p_k (1 - p_k) and cross covariances -p_k p_l.