0
# Utilities
1
2
Utility functions provide essential support for geostatistical workflows including VTK export, geometric operations, field transformations, data normalization, and spatial analysis tools.
3
4
## Capabilities
5
6
### VTK Export Functions
7
8
Functions for exporting spatial fields to VTK format for visualization in ParaView, VisIt, and other scientific visualization software.
9
10
```python { .api }
11
def vtk_export(filename, pos, fields, fieldnames=None):
12
"""
13
Export spatial fields to VTK format.
14
15
Parameters:
16
- filename (str): Output VTK filename (without extension)
17
- pos (array-like): Spatial positions, shape (dim, n_points)
18
- fields (array-like): Field values, shape (n_fields, n_points) or (n_points,)
19
- fieldnames (list): Names for field variables (default: auto-generate)
20
21
Returns:
22
- None: Writes VTK file to disk
23
"""
24
25
def vtk_export_structured(filename, pos, fields, fieldnames=None):
26
"""
27
Export structured grid fields to VTK format.
28
29
Parameters:
30
- filename (str): Output VTK filename
31
- pos (list): Grid coordinate arrays [x, y, z]
32
- fields (array-like): Field values on structured grid
33
- fieldnames (list): Field variable names
34
35
Returns:
36
- None: Writes structured VTK file
37
"""
38
39
def vtk_export_unstructured(filename, pos, fields, fieldnames=None):
40
"""
41
Export unstructured point data to VTK format.
42
43
Parameters:
44
- filename (str): Output VTK filename
45
- pos (array-like): Point positions
46
- fields (array-like): Field values at points
47
- fieldnames (list): Field variable names
48
49
Returns:
50
- None: Writes unstructured VTK file
51
"""
52
53
def to_vtk(pos, fields, fieldnames=None):
54
"""
55
Convert spatial fields to VTK data structure.
56
57
Parameters:
58
- pos (array-like): Spatial positions
59
- fields (array-like): Field values
60
- fieldnames (list): Field variable names
61
62
Returns:
63
- VTK data structure for direct use with PyVista
64
"""
65
66
def to_vtk_structured(pos, fields, fieldnames=None):
67
"""Convert structured grid to VTK format."""
68
69
def to_vtk_unstructured(pos, fields, fieldnames=None):
70
"""Convert unstructured data to VTK format."""
71
```
72
73
### Geometric Functions
74
75
Functions for coordinate system operations, grid generation, and spatial transformations.
76
77
```python { .api }
78
def generate_grid(x, y=None, z=None, **kwargs):
79
"""
80
Generate coordinate grid for field evaluation.
81
82
Parameters:
83
- x (array-like): X-coordinate values or grid specification
84
- y (array-like): Y-coordinate values (default: None for 1D)
85
- z (array-like): Z-coordinate values (default: None for 2D)
86
- **kwargs: Additional grid parameters
87
88
Returns:
89
- Grid coordinate arrays for structured field generation
90
"""
91
92
def generate_st_grid(space_grid, time_grid, **kwargs):
93
"""
94
Generate spatio-temporal coordinate grid.
95
96
Parameters:
97
- space_grid (list): Spatial coordinate arrays [x, y, z]
98
- time_grid (array-like): Temporal coordinate values
99
- **kwargs: Additional grid parameters
100
101
Returns:
102
- Spatio-temporal coordinate arrays
103
"""
104
105
def rotated_main_axes(dim, angles):
106
"""
107
Calculate rotated coordinate system main axes.
108
109
Parameters:
110
- dim (int): Spatial dimension (2 or 3)
111
- angles (float or array-like): Rotation angles
112
113
Returns:
114
- Rotation matrix for coordinate transformation
115
"""
116
117
def matrix_rotate(dim, angles):
118
"""Create rotation matrix."""
119
120
def matrix_isometrize(dim, anis, angles):
121
"""Create isometrization matrix for anisotropic scaling."""
122
123
def matrix_anisometrize(dim, anis, angles):
124
"""Create anisometrization matrix."""
125
```
126
127
### Transformation Functions
128
129
Field transformation functions for converting between different statistical distributions and applying nonlinear transformations.
130
131
```python { .api }
132
def apply(method, field, **kwargs):
133
"""
134
Apply transformation to field values.
135
136
Parameters:
137
- method (str): Transformation method name
138
- field (array-like): Input field values
139
- **kwargs: Method-specific parameters
140
141
Returns:
142
- Transformed field values
143
"""
144
145
def apply_function(function, field, **kwargs):
146
"""Apply custom function to field values."""
147
148
def binary(field, threshold=0.0, upper=1.0, lower=0.0):
149
"""
150
Binary transformation based on threshold.
151
152
Parameters:
153
- field (array-like): Input field values
154
- threshold (float): Threshold value
155
- upper (float): Value for field > threshold
156
- lower (float): Value for field <= threshold
157
158
Returns:
159
- Binary field values
160
"""
161
162
def discrete(field, values, thresholds):
163
"""
164
Discrete transformation using multiple thresholds.
165
166
Parameters:
167
- field (array-like): Input field values
168
- values (array-like): Output discrete values
169
- thresholds (array-like): Threshold boundaries
170
171
Returns:
172
- Discretized field values
173
"""
174
175
def boxcox(field, lmbda, shift=0.0):
176
"""Box-Cox power transformation."""
177
178
def zinnharvey(field, conn='high'):
179
"""Zinn & Harvey transformation for connectivity."""
180
181
def normal_force_moments(field, mean=0.0, var=1.0):
182
"""Force field to have specified moments."""
183
184
def normal_to_lognormal(field, mean=1.0, var=1.0):
185
"""Transform normal field to log-normal distribution."""
186
187
def normal_to_uniform(field, a=0.0, b=1.0):
188
"""Transform normal field to uniform distribution."""
189
190
def normal_to_arcsin(field, a=0.0, b=1.0):
191
"""Transform normal field to arcsine distribution."""
192
193
def normal_to_uquad(field, a=0.0, b=1.0):
194
"""Transform normal field to U-quadratic distribution."""
195
```
196
197
### Special Mathematical Functions
198
199
Specialized mathematical functions used in geostatistical computations.
200
201
```python { .api }
202
def confidence_scaling(dim, nugget, var, len_scale, anis, alpha):
203
"""Calculate confidence scaling for kriging variance."""
204
205
def inc_gamma(s, x):
206
"""
207
Incomplete gamma function.
208
209
Parameters:
210
- s (float): Shape parameter
211
- x (array-like): Input values
212
213
Returns:
214
- Incomplete gamma function values
215
"""
216
217
def inc_gamma_low(s, x):
218
"""Lower incomplete gamma function."""
219
220
def exp_int(s, x):
221
"""Exponential integral function."""
222
223
def inc_beta(a, b, x):
224
"""Incomplete beta function."""
225
226
def tplstable_cor(r, len_scale, hurst, alpha):
227
"""TPL stable correlation function."""
228
229
def tpl_exp_spec_dens(k, len_scale, hurst, len_low):
230
"""TPL exponential spectral density."""
231
232
def tpl_gau_spec_dens(k, len_scale, hurst, len_low):
233
"""TPL Gaussian spectral density."""
234
```
235
236
### Normalization Classes
237
238
Classes for data normalization and distribution transformation.
239
240
```python { .api }
241
class Normalizer:
242
"""
243
Base class for data normalization.
244
245
Methods:
246
- normalize(data): Transform data to normalized form
247
- denormalize(data): Transform back to original scale
248
- fit(data): Fit normalization parameters to data
249
"""
250
def normalize(self, data): ...
251
def denormalize(self, data): ...
252
def fit(self, data): ...
253
254
class LogNormal(Normalizer):
255
"""Log-normal distribution normalizer."""
256
257
class BoxCox(Normalizer):
258
"""Box-Cox transformation normalizer."""
259
260
class BoxCoxShift(Normalizer):
261
"""Box-Cox transformation with shift parameter."""
262
263
class YeoJohnson(Normalizer):
264
"""Yeo-Johnson transformation normalizer."""
265
266
class Modulus(Normalizer):
267
"""Modulus transformation normalizer."""
268
269
class Manly(Normalizer):
270
"""Manly transformation normalizer."""
271
272
def apply_mean_norm_trend(field, mean, normalizer, trend, pos):
273
"""Apply mean, normalization, and trend to field."""
274
275
def remove_trend_norm_mean(field, mean, normalizer, trend, pos):
276
"""Remove trend, normalization, and mean from field."""
277
```
278
279
### Constants
280
281
Important physical and mathematical constants used in geostatistical calculations.
282
283
```python { .api }
284
EARTH_RADIUS: float = 6371.0
285
"""Earth radius in kilometers for geographic coordinate calculations."""
286
287
KM_SCALE: float = 6371.0
288
"""Kilometer scaling factor for geographic projections."""
289
290
DEGREE_SCALE: float = 57.29577951308232
291
"""Conversion factor from radians to degrees (180/π)."""
292
293
RADIAN_SCALE: float = 1.0
294
"""Radian scaling factor (identity)."""
295
```
296
297
### Random Number Generation
298
299
Classes for random number generation and seeding control.
300
301
```python { .api }
302
class RNG:
303
"""
304
Random number generator with seed control.
305
306
Parameters:
307
- seed (int): Random seed for reproducibility
308
- **kwargs: Additional RNG parameters
309
"""
310
def __init__(self, seed=None, **kwargs): ...
311
312
class MasterRNG:
313
"""Master random number generator for coordinated seeding."""
314
315
def dist_gen(dist, **kwargs):
316
"""Distribution generator factory function."""
317
```
318
319
### Configuration Variables
320
321
Global configuration settings for GSTools behavior.
322
323
```python { .api }
324
NUM_THREADS: int = None
325
"""Number of threads for parallel computation (None = auto-detect)."""
326
327
USE_GSTOOLS_CORE: bool = True
328
"""Whether to use GSTools core library for acceleration."""
329
```
330
331
## Usage Examples
332
333
### VTK Export
334
335
```python
336
import gstools as gs
337
import numpy as np
338
339
# Generate field data
340
model = gs.Gaussian(dim=2, var=1.0, len_scale=10.0)
341
srf = gs.SRF(model, seed=12345)
342
343
# Structured grid export
344
x = np.arange(0, 50, 1.0)
345
y = np.arange(0, 30, 1.0)
346
field = srf.structured([x, y])
347
348
gs.vtk_export_structured('field_structured', [x, y], field, ['temperature'])
349
350
# Unstructured point export
351
pos = np.random.rand(2, 1000) * 50
352
field = srf.unstructured(pos)
353
354
gs.vtk_export_unstructured('field_points', pos, field, ['temperature'])
355
```
356
357
### Grid Generation
358
359
```python
360
# Simple 1D grid
361
x = gs.generate_grid(np.linspace(0, 100, 101))
362
363
# 2D structured grid
364
x = np.arange(0, 50, 1.0)
365
y = np.arange(0, 30, 1.0)
366
grid_2d = gs.generate_grid(x, y)
367
368
# 3D grid
369
z = np.arange(0, 20, 1.0)
370
grid_3d = gs.generate_grid(x, y, z)
371
372
# Spatio-temporal grid
373
time = np.linspace(0, 10, 11)
374
st_grid = gs.generate_st_grid([x, y], time)
375
```
376
377
### Coordinate Transformations
378
379
```python
380
# 2D rotation matrix
381
angles = np.pi/4 # 45 degrees
382
rot_matrix = gs.rotated_main_axes(2, angles)
383
384
# Transform coordinates
385
coords = np.array([[1, 0], [0, 1]]) # Unit vectors
386
rotated_coords = rot_matrix @ coords.T
387
388
# Anisotropic transformation
389
anis = [1.0, 0.5] # Anisotropy ratios
390
angles = np.pi/6 # 30 degrees
391
anis_matrix = gs.matrix_isometrize(2, anis, angles)
392
```
393
394
### Field Transformations
395
396
```python
397
# Import transform functions
398
from gstools.transform import normal_to_lognormal, binary, boxcox
399
# Or: import gstools.transform as gst
400
401
# Generate normal field
402
field = srf.structured([x, y])
403
404
# Log-normal transformation
405
lognormal_field = normal_to_lognormal(field, mean=2.0, var=1.0)
406
407
# Binary transformation
408
binary_field = binary(field, threshold=0.5)
409
410
# Box-Cox transformation
411
boxcox_field = boxcox(field, lmbda=0.5)
412
413
# Custom transformation using normalizer
414
from gstools.normalizer import LogNormal
415
normalizer = LogNormal()
416
normalizer.fit(field)
417
normalized = normalizer.normalize(field)
418
denormalized = normalizer.denormalize(normalized)
419
```
420
421
### Discrete Field Generation
422
423
```python
424
# Generate categorical field
425
categories = ['sand', 'clay', 'rock']
426
thresholds = [-0.5, 0.5]
427
428
from gstools.transform import discrete
429
categorical = discrete(
430
field,
431
values=categories,
432
thresholds=thresholds
433
)
434
435
# Count category frequencies
436
unique, counts = np.unique(categorical, return_counts=True)
437
for cat, count in zip(unique, counts):
438
print(f"{cat}: {count} ({100*count/len(field):.1f}%)")
439
```
440
441
### Special Functions
442
443
```python
444
# Incomplete gamma function for Matérn covariance
445
nu = 1.5
446
distances = np.linspace(0.1, 10, 100)
447
gamma_values = gs.tools.inc_gamma(nu, distances)
448
449
# Exponential integral
450
exp_int_values = gs.tools.exp_int(1, distances)
451
452
# TPL correlation function
453
tpl_corr = gs.tools.tplstable_cor(
454
distances, len_scale=5.0, hurst=0.5, alpha=1.5
455
)
456
```
457
458
### Parallel Configuration
459
460
```python
461
# Set number of threads globally
462
gs.config.NUM_THREADS = 4
463
464
# Use GSTools core for acceleration
465
gs.config.USE_GSTOOLS_CORE = True
466
467
# Check current configuration
468
print(f"Threads: {gs.config.NUM_THREADS}")
469
print(f"Use core: {gs.config.USE_GSTOOLS_CORE}")
470
```
471
472
### Geographic Calculations
473
474
```python
475
# Work with lat/lon coordinates
476
lat = np.linspace(40, 45, 50)
477
lon = np.linspace(-75, -70, 60)
478
479
# Use Earth radius for distance calculations
480
earth_radius_km = gs.EARTH_RADIUS
481
degree_to_km = earth_radius_km * np.pi / 180
482
483
# Convert degrees to kilometers
484
lat_km = lat * degree_to_km
485
lon_km = lon * degree_to_km
486
487
# Geographic field generation
488
geo_model = gs.Exponential(
489
dim=2,
490
var=1.0,
491
len_scale=100.0, # 100 km correlation length
492
latlon=True
493
)
494
geo_srf = gs.SRF(geo_model)
495
geo_field = geo_srf.structured([lon, lat])
496
```
497
498
### Advanced Transformations
499
500
```python
501
# Import transform functions
502
from gstools.transform import normal_force_moments, zinnharvey, apply_function
503
504
# Force specific moments
505
field_moments = normal_force_moments(
506
field, mean=5.0, var=2.0
507
)
508
509
# Zinn-Harvey connectivity transformation
510
connected_field = zinnharvey(field, conn='high')
511
512
# Apply custom function
513
def custom_transform(x):
514
return np.exp(x) / (1 + np.exp(x)) # Sigmoid
515
516
transformed = apply_function(custom_transform, field)
517
```
518
519
## Integration Examples
520
521
### Complete Workflow
522
523
```python
524
# Complete geostatistical workflow using utilities
525
import gstools as gs
526
import numpy as np
527
528
# 1. Generate synthetic data
529
model = gs.Matern(dim=2, var=2.0, len_scale=15.0, nu=1.5)
530
srf = gs.SRF(model, seed=42)
531
532
# 2. Create evaluation grid
533
x = np.arange(0, 100, 2.0)
534
y = np.arange(0, 80, 2.0)
535
field = srf.structured([x, y])
536
537
# 3. Apply transformation
538
from gstools.transform import normal_to_lognormal
539
log_field = normal_to_lognormal(field, mean=3.0, var=1.0)
540
541
# 4. Export for visualization
542
gs.vtk_export_structured(
543
'workflow_result',
544
[x, y],
545
[field, log_field],
546
['original', 'lognormal']
547
)
548
549
# 5. Generate summary statistics
550
print(f"Original field - Mean: {np.mean(field):.2f}, Std: {np.std(field):.2f}")
551
print(f"Log-normal field - Mean: {np.mean(log_field):.2f}, Std: {np.std(log_field):.2f}")
552
```
553
554
This comprehensive utilities documentation covers all major utility functions, constants, and classes available in GSTools for supporting geostatistical workflows.