wbspatialstats 0.1.1

Unified spatial statistics library: kriging, spatial autocorrelation, spatial regression, point process analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# wbgeostats Usage Examples

Complete, runnable examples demonstrating kriging workflows in Python, R, and Rust.

## Table of Contents
- [Python Examples]#python-examples
- [R Examples]#r-examples
- [Rust Examples]#rust-examples

---

## Python Examples

### Example 1: Simple Kriging Prediction

```python
from wbgeostats import VariogramModel, OrdinaryKriging

# Training data: (x, y) coordinates and observed values
coords = [
    (0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0),
    (5.0, 5.0), (15.0, 5.0), (5.0, 15.0)
]
values = [1.0, 2.5, 1.5, 3.0, 2.2, 3.5, 2.8]

# Define variogram (spherical model)
vario = VariogramModel(
    family="spherical",
    nugget=0.1,
    partial_sill=2.0,
    range=10.0
)

# Create kriging model
ok = OrdinaryKriging(coords, values, vario)

# Predict at a single location
result = ok.predict(5.0, 5.0)
print(f"Prediction: {result.prediction:.3f}")
print(f"Std Error: {result.std_error:.3f}")
print(f"95% CI: [{result.ci_lower:.3f}, {result.ci_upper:.3f}]")
```

**Output**:
```
Prediction: 2.201
Std Error: 0.315
95% CI: [1.583, 2.819]
```

---

### Example 2: Empirical Variogram Estimation

```python
from wbgeostats import estimate_variogram, fit_variogram

# Generate synthetic data with spatial structure
import random
random.seed(42)

coords = [(random.uniform(0, 100), random.uniform(0, 100)) for _ in range(50)]
# Create values with spatial trend
values = [x + 0.5*y + random.gauss(0, 0.5) for x, y in coords]

# Estimate empirical variogram
vario_dict = estimate_variogram(
    x=[c[0] for c in coords],
    y=[c[1] for c in coords],
    values=values,
    lag_distance=10.0,
    max_lag_count=10
)

print(f"Analyzed {vario_dict['max_lag']:.1f} max lag distance")
print(f"Number of lag bins: {len(vario_dict['distances'])}")

# Fit theoretical model
fitted_vario = fit_variogram(
    distances=vario_dict['distances'],
    semivariances=vario_dict['semivariances'],
    pair_counts=vario_dict['pair_counts'],
    model_family="exponential"
)

print(f"\nFitted Variogram (Exponential):")
print(f"  Nugget: {fitted_vario.nugget:.3f}")
print(f"  Partial Sill: {fitted_vario.partial_sill:.3f}")
print(f"  Range: {fitted_vario.range:.3f}")
```

**Output**:
```
Analyzed 95.0 max lag distance
Number of lag bins: 10

Fitted Variogram (Exponential):
  Nugget: 0.253
  Partial Sill: 1.847
  Range: 28.435
```

---

### Example 3: Cross-Validation & Model Assessment

```python
from wbgeostats import (
    VariogramModel, OrdinaryKriging, 
    cross_validate_kriging, estimate_variogram, fit_variogram
)

# Load or generate data
# ... (data preparation code) ...

# Step 1: Estimate empirical variogram
vario_dict = estimate_variogram(x, y, values, lag_distance=8.0)

# Step 2: Fit theoretical models and compare
models = {}
for family in ["spherical", "exponential", "gaussian"]:
    fitted_vario = fit_variogram(
        vario_dict['distances'],
        vario_dict['semivariances'],
        vario_dict['pair_counts'],
        model_family=family
    )
    
    # Cross-validate model
    cv_metrics = cross_validate_kriging(x, y, values, fitted_vario)
    
    models[family] = {
        'vario': fitted_vario,
        'metrics': cv_metrics
    }
    
    print(f"\n{family.upper()} Model:")
    print(f"  RMSE: {cv_metrics['rmse']:.4f}")
    print(f"  RMSSE: {cv_metrics['rmsse']:.4f}")
    print(f"  Correlation: {cv_metrics['correlation']:.4f}")
    print(f"  Well-calibrated: {cv_metrics['is_well_calibrated']}")

# Choose best model (e.g., lowest RMSE)
best_family = min(
    models.keys(),
    key=lambda f: models[f]['metrics']['rmse']
)
print(f"\nBest model: {best_family}")

# Use best model for predictions
best_vario = models[best_family]['vario']
ok = OrdinaryKriging(list(zip(x, y)), values, best_vario)
```

---

### Example 4: Grid Prediction (Vectorized)

```python
from wbgeostats import VariogramModel, OrdinaryKriging

# Training data
coords = [(x, y) for x in range(0, 101, 20) for y in range(0, 101, 20)]
values = [x + 0.5*y for x, y in coords]

# Kriging model
vario = VariogramModel("spherical", nugget=5.0, partial_sill=50.0, range=40.0)
ok = OrdinaryKriging(coords, values, vario)

# Create prediction grid
grid_coords = [
    (x, y) for x in range(0, 101, 5) for y in range(0, 101, 5)
]

# Predict all grid points (parallelized)
results = ok.predict_batch(grid_coords)

# Extract results
predictions = [r.prediction for r in results]
variances = [r.variance for r in results]

print(f"Grid predictions: {len(predictions)} points")
print(f"Mean prediction: {sum(predictions)/len(predictions):.2f}")
print(f"Mean variance: {sum(variances)/len(variances):.2f}")

# Convert to grid structure for visualization
import numpy as np
n = 21  # sqrt(len(grid_coords))
pred_grid = np.array(predictions).reshape(n, n)
var_grid = np.array(variances).reshape(n, n)

# Plot (requires matplotlib)
# import matplotlib.pyplot as plt
# plt.contourf(pred_grid); plt.colorbar(); plt.show()
```

---

## R Examples

### Example 1: Simple Kriging Prediction

```r
library(wbgeostats)

# Training data
coords_x <- c(0, 10, 0, 10, 5, 15, 5)
coords_y <- c(0, 0, 10, 10, 5, 5, 15)
values <- c(1.0, 2.5, 1.5, 3.0, 2.2, 3.5, 2.8)

# Single prediction
result <- kriging_predict(
  train_x = coords_x,
  train_y = coords_y,
  train_values = values,
  pred_x = 5.0,
  pred_y = 5.0,
  family = "spherical",
  nugget = 0.1,
  psill = 2.0,
  range = 10.0
)

cat("Prediction:", result$prediction, "\n")
cat("Std Error:", result$std_error, "\n")
cat("95% CI: [", result$ci_lower, ",", result$ci_upper, "]\n")
```

**Output**:
```
Prediction: 2.201
Std Error: 0.315
95% CI: [ 1.583 , 2.819 ]
```

---

### Example 2: Empirical Variogram in R

```r
library(wbgeostats)

# Sample data (e.g., from sp or sf package)
data(meuse)  # Built-in dataset from gstat package

# Estimate empirical variogram
vario_emp <- estimate_variogram(
  x = meuse$x,
  y = meuse$y,
  values = meuse$zinc,
  lag_distance = 100,
  max_lag_count = 15
)

# Plot empirical variogram
plot(vario_emp$distances, vario_emp$semivariances,
     xlab = "Distance (m)", ylab = "Semivariance",
     main = "Empirical Variogram - Meuse Zinc",
     pch = 16)

# Fit theoretical model
vario_fit <- fit_variogram(
  distances = vario_emp$distances,
  semivariances = vario_emp$semivariances,
  pair_counts = vario_emp$pair_counts,
  model_family = "exponential"
)

cat("Fitted model parameters:\n")
print(vario_fit)
```

---

### Example 3: Grid Kriging & Cross-Validation

```r
library(wbgeostats)
library(sf)  # For grid creation

# Training data
coords_x <- c(0, 10, 0, 10, 5, 15, 5)
coords_y <- c(0, 0, 10, 10, 5, 5, 15)
values <- c(1.0, 2.5, 1.5, 3.0, 2.2, 3.5, 2.8)

# Cross-validation
cv_result <- kriging_cross_validate(
  x = coords_x,
  y = coords_y,
  values = values,
  family = "spherical",
  nugget = 0.1,
  psill = 2.0,
  range = 10.0
)

cat("Cross-validation metrics:\n")
cat("  RMSE:", cv_result$rmse, "\n")
cat("  RMSSE:", cv_result$rmsse, "\n")
cat("  Well-calibrated:", cv_result$is_well_calibrated, "\n")

# Create prediction grid
grid_x <- rep(seq(0, 15, by=1), 16)
grid_y <- rep(seq(0, 15, by=1), each=16)

# Grid predictions (vectorized)
grid_results <- kriging_predict_grid(
  train_x = coords_x,
  train_y = coords_y,
  train_values = values,
  pred_x = grid_x,
  pred_y = grid_y,
  family = "spherical",
  nugget = 0.1,
  psill = 2.0,
  range = 10.0
)

# Combine results
grid_df <- data.frame(
  x = grid_x,
  y = grid_y,
  prediction = grid_results$prediction,
  std_error = grid_results$std_error
)

# Visualize
library(ggplot2)
ggplot(grid_df, aes(x=x, y=y, fill=prediction)) +
  geom_raster() +
  scale_fill_viridis_c() +
  coord_fixed() +
  theme_minimal() +
  labs(title="Kriging Predictions")
```

---

## Rust Examples

### Example 1: Basic Kriging (Pure Rust)

```rust
use wbgeostats::variogram::VariogramModel;
use wbgeostats::kriging::OrdinaryKriging;
use wbgeostats::variogram::VariogramModelFamily;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Training data
    let coords = vec![
        (0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0),
        (5.0, 5.0), (15.0, 5.0), (5.0, 15.0)
    ];
    let values = vec![1.0, 2.5, 1.5, 3.0, 2.2, 3.5, 2.8];
    
    // Define variogram
    let vario = VariogramModel {
        family: VariogramModelFamily::Spherical,
        nugget: 0.1,
        partial_sill: 2.0,
        range: 10.0,
        wrss: 0.0,
        condition_number: 1.0,
    };
    
    // Create kriging model
    let ok = OrdinaryKriging::new(coords, values, vario)?;
    
    // Single prediction
    let result = ok.predict((5.0, 5.0))?;
    println!("Prediction: {:.3}", result.prediction);
    println!("Std Error: {:.3}", result.std_error);
    
    Ok(())
}
```

---

### Example 2: Batch Prediction with Rayon Parallelization

```rust
use wbgeostats::variogram::VariogramModel;
use wbgeostats::kriging::OrdinaryKriging;
use wbgeostats::variogram::VariogramModelFamily;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Training data
    let coords = vec![
        (0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0),
        (5.0, 5.0), (15.0, 5.0), (5.0, 15.0)
    ];
    let values = vec![1.0, 2.5, 1.5, 3.0, 2.2, 3.5, 2.8];
    
    let vario = VariogramModel {
        family: VariogramModelFamily::Exponential,
        nugget: 0.15,
        partial_sill: 1.8,
        range: 12.0,
        wrss: 0.0,
        condition_number: 1.0,
    };
    
    let ok = OrdinaryKriging::new(coords, values, vario)?;
    
    // Create prediction grid
    let grid: Vec<(f64, f64)> = (0..=20)
        .flat_map(|x| (0..=20).map(move |y| (x as f64, y as f64)))
        .collect();
    
    // Batch predictions (parallelized)
    let results = ok.predict_batch(&grid)?;
    
    println!("Predicted {} grid points", results.len());
    println!("Mean prediction: {:.3}", 
        results.iter().map(|r| r.prediction).sum::<f64>() / results.len() as f64);
    
    Ok(())
}
```

---

### Example 3: Variogram Fitting & Cross-Validation

```rust
use wbgeostats::variogram::{
    EmpiricalVariogramBuilder, VariogramFitter, VariogramModelFamily, LagBin
};
use wbgeostats::cv::LeaveOneOutCV;
use wbgeostats::kriging::OrdinaryKriging;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Sample data
    let coords = vec![/* ... */];
    let values = vec![/* ... */];
    
    // Step 1: Estimate empirical variogram
    let builder = EmpiricalVariogramBuilder::default()
        .lag_distance(10.0)
        .max_lag_count(15);
    
    let emp_vario = builder.build(&coords, &values)?;
    println!("Estimated {} lag bins", emp_vario.lags.len());
    
    // Step 2: Fit theoretical model (try multiple families)
    for family in [VariogramModelFamily::Spherical, VariogramModelFamily::Exponential] {
        let fitted = VariogramFitter::fit(&emp_vario.lags, family)?;
        
        // Step 3: Cross-validate
        let cv_metrics = LeaveOneOutCV::validate(&coords, &values, &fitted)?;
        
        println!("\n{:?} Model:", family);
        println!("  RMSE: {:.4}", cv_metrics.rmse);
        println!("  RMSSE: {:.4}", cv_metrics.rmsse);
        println!("  Well-calibrated: {}", cv_metrics.is_well_calibrated());
    }
    
    Ok(())
}
```

---

## Workflow Comparison

### Python Workflow
1. `estimate_variogram()` → fit parameters from data
2. `fit_variogram()` → get VariogramModel
3. `cross_validate_kriging()` → assess model quality
4. `OrdinaryKriging()` + `predict_batch()` → grid interpolation

### R Workflow
1. `estimate_variogram()` → fit parameters from data
2. `fit_variogram()` → get fitted model parameters
3. `kriging_cross_validate()` → assess model quality
4. `kriging_predict_grid()` → vectorized grid interpolation

### Rust Workflow
1. `EmpiricalVariogramBuilder` → empirical variogram
2. `VariogramFitter::fit()` → fit theoretical model
3. `LeaveOneOutCV::validate()` → CV metrics
4. `OrdinaryKriging` + `predict_batch()` → predictions

---

## Performance Tips

- **Batch prediction**: Always use `predict_batch()` instead of repeated single predictions
- **Large grids**: Use 1000-5000 points per batch for optimal parallelization
- **LOOCV**: Cache variogram fitting; only refits if model changes
- **Memory**: Pre-allocate coordinate vectors for large datasets
- **I/O**: Use raster templates to define grids; avoids redundant coordinate generation