0
# Kriging
1
2
Kriging provides optimal spatial interpolation methods for estimating values at unobserved locations based on covariance models and observed data. GSTools implements comprehensive kriging variants with uncertainty quantification.
3
4
## Capabilities
5
6
### Universal Kriging Interface
7
8
Swiss-army-knife kriging class supporting all major kriging variants through unified interface.
9
10
```python { .api }
11
class Krige:
12
"""
13
Universal kriging interface supporting all kriging variants.
14
15
Parameters:
16
- model (CovModel): Covariance model defining spatial correlation
17
- cond_pos (array-like): Positions of conditioning points
18
- cond_val (array-like): Values at conditioning points
19
- drift_functions (list): Drift functions for Universal Kriging (default: None)
20
- ext_drift (array-like): External drift values (default: None)
21
- mean (float or callable): Known mean value or function (default: None)
22
- normalizer (Normalizer): Data normalization method (default: None)
23
- trend (callable): Additional trend function (default: None)
24
- unbiased (bool): Ensure unbiased estimates (default: True)
25
- exact (bool): Honor conditioning values exactly (default: False)
26
- cond_err (str or array-like): Conditioning error specification (default: 'nugget')
27
- pseudo_inv (bool): Use pseudo-inverse for numerical stability (default: True)
28
- pseudo_inv_type (str or callable): Pseudo-inverse method (default: 'pinv')
29
- fit_normalizer (bool): Fit normalizer to data (default: False)
30
- fit_variogram (bool): Fit variogram to data (default: False)
31
"""
32
def __init__(self, model, cond_pos, cond_val, drift_functions=None,
33
ext_drift=None, mean=None, normalizer=None, trend=None,
34
unbiased=True, exact=False, cond_err='nugget', pseudo_inv=True,
35
pseudo_inv_type='pinv', fit_normalizer=False, fit_variogram=False): ...
36
37
def __call__(self, pos, mesh_type='unstructured', chunk_size=None,
38
only_mean=False, return_var=False, store=True):
39
"""
40
Perform kriging at specified positions.
41
42
Parameters:
43
- pos (array-like): Target positions for interpolation
44
- mesh_type (str): Mesh type ('structured', 'unstructured')
45
- chunk_size (int): Process data in chunks to manage memory
46
- only_mean (bool): Return only kriging mean, skip variance
47
- return_var (bool): Return kriging variance in addition to mean
48
- store (bool): Store results in class instance
49
50
Returns:
51
- Kriging estimates (and variance if return_var=True)
52
"""
53
54
def structured(self, pos, **kwargs):
55
"""
56
Perform kriging on structured grid.
57
58
Parameters:
59
- pos (list): Grid coordinate arrays [x, y, z]
60
- **kwargs: Additional kriging parameters
61
62
Returns:
63
- Kriging estimates on structured grid
64
"""
65
66
def unstructured(self, pos, **kwargs):
67
"""
68
Perform kriging at unstructured points.
69
70
Parameters:
71
- pos (array-like): Point coordinates
72
- **kwargs: Additional kriging parameters
73
74
Returns:
75
- Kriging estimates at points
76
"""
77
78
def get_mean(self, pos=None, mesh_type='unstructured', chunk_size=None):
79
"""
80
Get kriging mean estimates.
81
82
Parameters:
83
- pos (array-like): Target positions (default: use stored positions)
84
- mesh_type (str): Mesh type
85
- chunk_size (int): Chunk size for processing
86
87
Returns:
88
- Kriging mean values
89
"""
90
91
def get_variance(self, pos=None, mesh_type='unstructured', chunk_size=None):
92
"""
93
Get kriging variance estimates.
94
95
Parameters:
96
- pos (array-like): Target positions (default: use stored positions)
97
- mesh_type (str): Mesh type
98
- chunk_size (int): Chunk size for processing
99
100
Returns:
101
- Kriging variance values
102
"""
103
```
104
105
### Specialized Kriging Classes
106
107
Pre-configured kriging classes for specific applications and simplified usage.
108
109
```python { .api }
110
class Simple:
111
"""
112
Simple Kriging with known mean.
113
114
Parameters:
115
- model (CovModel): Covariance model
116
- cond_pos (array-like): Conditioning positions
117
- cond_val (array-like): Conditioning values
118
- mean (float): Known mean value (default: 0.0)
119
- normalizer (Normalizer): Data normalization method (default: None)
120
- trend (callable): Trend function (default: None)
121
- exact (bool): Honor conditioning values exactly (default: False)
122
- cond_err (str or array-like): Conditioning error (default: 'nugget')
123
- pseudo_inv (bool): Use pseudo-inverse (default: True)
124
- pseudo_inv_type (str): Pseudo-inverse method (default: 'pinv')
125
- fit_normalizer (bool): Fit normalizer to data (default: False)
126
- fit_variogram (bool): Fit variogram to data (default: False)
127
"""
128
def __init__(self, model, cond_pos, cond_val, mean=0.0, normalizer=None,
129
trend=None, exact=False, cond_err='nugget', pseudo_inv=True,
130
pseudo_inv_type='pinv', fit_normalizer=False, fit_variogram=False): ...
131
132
class Ordinary:
133
"""
134
Ordinary Kriging with estimated mean.
135
136
Parameters:
137
- model (CovModel): Covariance model
138
- cond_pos (array-like): Conditioning positions
139
- cond_val (array-like): Conditioning values
140
- **kwargs: Additional kriging parameters
141
"""
142
def __init__(self, model, cond_pos, cond_val, **kwargs): ...
143
144
class Universal:
145
"""
146
Universal Kriging with drift functions.
147
148
Parameters:
149
- model (CovModel): Covariance model
150
- cond_pos (array-like): Conditioning positions
151
- cond_val (array-like): Conditioning values
152
- drift_functions (list): List of drift functions
153
- **kwargs: Additional kriging parameters
154
"""
155
def __init__(self, model, cond_pos, cond_val, drift_functions, **kwargs): ...
156
157
class ExtDrift:
158
"""
159
External Drift Kriging with auxiliary variable.
160
161
Parameters:
162
- model (CovModel): Covariance model
163
- cond_pos (array-like): Conditioning positions
164
- cond_val (array-like): Conditioning values
165
- ext_drift (array-like): External drift values at conditioning points
166
- **kwargs: Additional kriging parameters
167
"""
168
def __init__(self, model, cond_pos, cond_val, ext_drift, **kwargs): ...
169
170
class Detrended:
171
"""
172
Detrended Kriging with trend removal.
173
174
Parameters:
175
- model (CovModel): Covariance model
176
- cond_pos (array-like): Conditioning positions
177
- cond_val (array-like): Conditioning values
178
- trend (callable): Trend function to remove
179
- **kwargs: Additional kriging parameters
180
"""
181
def __init__(self, model, cond_pos, cond_val, trend, **kwargs): ...
182
```
183
184
## Usage Examples
185
186
### Simple Kriging
187
188
```python
189
import gstools as gs
190
import numpy as np
191
192
# Conditioning data
193
cond_pos = [[0, 10, 20], [0, 5, 15]] # (x, y) coordinates
194
cond_val = [1.0, 2.5, 1.8] # Observed values
195
known_mean = 2.0
196
197
# Define covariance model
198
model = gs.Exponential(dim=2, var=1.5, len_scale=10.0)
199
200
# Simple kriging with known mean
201
sk = gs.krige.Simple(model, cond_pos, cond_val, mean=known_mean)
202
203
# Interpolate on grid
204
x = np.arange(0, 30, 1.0)
205
y = np.arange(0, 20, 1.0)
206
sk_mean, sk_var = sk.structured([x, y], return_var=True)
207
```
208
209
### Ordinary Kriging
210
211
```python
212
# Ordinary kriging (estimates mean from data)
213
ok = gs.krige.Ordinary(model, cond_pos, cond_val)
214
215
# Perform interpolation
216
ok_mean = ok.structured([x, y])
217
ok_var = ok.get_variance([x, y], mesh_type='structured')
218
```
219
220
### Universal Kriging
221
222
```python
223
# Define drift functions (e.g., linear trend)
224
def drift_linear_x(x, y):
225
return x
226
227
def drift_linear_y(x, y):
228
return y
229
230
drift_functions = [drift_linear_x, drift_linear_y]
231
232
# Universal kriging with drift
233
uk = gs.krige.Universal(model, cond_pos, cond_val, drift_functions)
234
uk_mean = uk.structured([x, y])
235
```
236
237
### External Drift Kriging
238
239
```python
240
# External variable at conditioning points
241
ext_cond = [100, 150, 120] # e.g., elevation values
242
243
# External variable at prediction locations
244
X, Y = np.meshgrid(x, y)
245
ext_pred = 100 + 2*X + Y # External drift field
246
247
# External drift kriging
248
edk = gs.krige.ExtDrift(model, cond_pos, cond_val, ext_cond)
249
edk_mean = edk.structured([x, y], ext_drift=ext_pred)
250
```
251
252
### Advanced Kriging Options
253
254
```python
255
# Kriging with measurement errors
256
measurement_errors = [0.1, 0.2, 0.15] # Error variances
257
krige = gs.Krige(
258
model,
259
cond_pos,
260
cond_val,
261
cond_err=measurement_errors, # Specify conditioning errors
262
exact=False, # Allow inexact interpolation
263
pseudo_inv=True # Use pseudo-inverse for stability
264
)
265
266
# Chunked processing for large datasets
267
krige_mean = krige.structured([x, y], chunk_size=10000)
268
```
269
270
### Uncertainty Quantification
271
272
```python
273
# Get both mean and variance
274
ok = gs.krige.Ordinary(model, cond_pos, cond_val)
275
mean, variance = ok.structured([x, y], return_var=True)
276
277
# Calculate confidence intervals (assuming Gaussian distribution)
278
std_dev = np.sqrt(variance)
279
ci_lower = mean - 1.96 * std_dev # 95% confidence interval
280
ci_upper = mean + 1.96 * std_dev
281
282
# Probability of exceedance
283
threshold = 3.0
284
prob_exceed = 1 - scipy.stats.norm.cdf(threshold, mean, std_dev)
285
```
286
287
### Cross-Validation
288
289
```python
290
# Leave-one-out cross-validation
291
n_points = len(cond_val)
292
cv_residuals = []
293
294
for i in range(n_points):
295
# Remove point i
296
cv_pos = [np.delete(cond_pos[0], i), np.delete(cond_pos[1], i)]
297
cv_val = np.delete(cond_val, i)
298
299
# Krige at removed point
300
cv_krige = gs.krige.Ordinary(model, cv_pos, cv_val)
301
pred = cv_krige.unstructured([[cond_pos[0][i]], [cond_pos[1][i]]])
302
303
# Calculate residual
304
cv_residuals.append(cond_val[i] - pred[0])
305
306
# Calculate validation statistics
307
rmse = np.sqrt(np.mean(np.array(cv_residuals)**2))
308
mae = np.mean(np.abs(cv_residuals))
309
```
310
311
## Kriging System and Linear Algebra
312
313
### Kriging System Components
314
315
The kriging system solves the linear system:
316
317
```
318
[C + N] [λ] = [c]
319
[1ᵀ ] [μ] [1]
320
```
321
322
Where:
323
- **C**: Covariance matrix between conditioning points
324
- **N**: Nugget/error matrix
325
- **λ**: Kriging weights
326
- **μ**: Lagrange multiplier for unbiasedness constraint
327
- **c**: Covariance vector between conditioning and prediction points
328
329
### Numerical Considerations
330
331
```python
332
# Handle numerical instability
333
krige = gs.Krige(
334
model,
335
cond_pos,
336
cond_val,
337
pseudo_inv=True, # Use SVD pseudo-inverse
338
cond_err='nugget' # Add nugget for regularization
339
)
340
341
# Check condition number of kriging matrix
342
krige_matrix = krige._get_krige_matrix() # Internal method
343
cond_number = np.linalg.cond(krige_matrix)
344
print(f"Condition number: {cond_number}")
345
```
346
347
## Error Handling and Validation
348
349
Common kriging errors and solutions:
350
351
- **LinAlgError**: Singular kriging matrix - increase nugget or use pseudo_inv=True
352
- **ValueError**: Incompatible dimensions - check pos and val array shapes
353
- **RuntimeError**: Convergence issues - check model parameters and data quality
354
355
```python
356
try:
357
krige = gs.Krige(model, cond_pos, cond_val)
358
result = krige.structured([x, y])
359
except np.linalg.LinAlgError:
360
# Handle singular matrix
361
krige = gs.Krige(model, cond_pos, cond_val, pseudo_inv=True)
362
result = krige.structured([x, y])
363
```
364
365
## Properties and Methods
366
367
Kriging objects provide:
368
369
**Properties**:
370
- **model**: Covariance model
371
- **cond_pos**: Conditioning positions
372
- **cond_val**: Conditioning values
373
- **mean**: Kriging mean field
374
- **krige_var**: Kriging variance field
375
- **pos**: Prediction positions
376
377
**Key Methods**:
378
- **Interpolation**: `__call__()`, `structured()`, `unstructured()`
379
- **Estimation**: `get_mean()`, `get_variance()`
380
- **Validation**: Cross-validation capabilities
381
- **Export**: `vtk_export()`, plotting methods