pygeostats.kriging¶
Kriging interpolation methods.
AnisotropicKriging
¶
Bases: BaseEstimator, RegressorMixin
Anisotropic kriging with elliptical distance calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variogram
|
Variogram
|
Fitted anisotropic variogram model with parameters: [nugget, sill, range_major, range_minor, rotation_angle] |
required |
fit
¶
fit(coordinates: Union[ndarray, GeoDataFrame, DataFrame], values: Union[ndarray, Series]) -> AnisotropicKriging
Fit the anisotropic kriging model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinates
|
(array - like, shape(n_samples, 2))
|
Known sample coordinates (must be 2D for anisotropic kriging). |
required |
values
|
(array - like, shape(n_samples))
|
Known sample values. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
AnisotropicKriging
|
Returns self for method chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the coordinates are not 2D, the variogram model is not exponential, spherical or Gaussian, or the kriging system is singular, as it is when two samples share a location. |
predict
¶
predict(coordinates: Union[ndarray, GeoDataFrame, DataFrame], return_variance: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]
Predict values at new locations using anisotropic kriging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinates
|
(array - like, shape(n_points, 2))
|
Coordinates to predict at. |
required |
return_variance
|
bool
|
If True, also return kriging variance. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
predictions |
(ndarray, shape(n_points))
|
Predicted values. |
variance |
(ndarray, shape(n_points), optional)
|
Kriging variance at each point. Only returned if return_variance=True. |
score
¶
Return the coefficient of determination R^2 of the prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinates
|
(array - like, shape(n_samples, 2))
|
Test coordinates. |
required |
values
|
(array - like, shape(n_samples))
|
True values. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
score |
float
|
R^2 score. |
get_anisotropy_info
¶
Return anisotropy parameters and derived statistics.
ParallelKrigingExecutor
¶
ParallelKrigingExecutor(n_workers: Optional[int] = None, execution_method: str = 'process', chunk_size: int = 1000, memory_limit_gb: float = 8.0, progress_callback: Optional[Callable] = None)
Parallel executor for large-scale kriging computations.
Provides various parallelization strategies for kriging predictions on large datasets.
Initialize parallel kriging executor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_workers
|
int
|
Number of worker processes/threads. Uses CPU count if None. |
None
|
execution_method
|
str
|
Execution method: "process", "thread", or "sequential". |
"process"
|
chunk_size
|
int
|
Size of prediction chunks. |
1000
|
memory_limit_gb
|
float
|
Memory limit per worker process. |
8.0
|
progress_callback
|
callable
|
Callback function for progress updates. |
None
|
predict_parallel
¶
predict_parallel(kriging_model, prediction_coordinates: ndarray, return_variance: bool = False, strategy: str = 'chunk') -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]
Perform parallel kriging predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kriging_model
|
object
|
Fitted kriging model with predict method. |
required |
prediction_coordinates
|
(ndarray, shape(n_pred, d))
|
Coordinates for prediction. |
required |
return_variance
|
bool
|
Whether to return prediction variance. |
False
|
strategy
|
str
|
Parallelization strategy: "chunk", "spatial", or "adaptive". |
"chunk"
|
Returns:
| Name | Type | Description |
|---|---|---|
predictions |
(ndarray, shape(n_pred))
|
Predicted values. |
variances |
(ndarray, shape(n_pred), optional)
|
Prediction variances if return_variance=True. |
Raises:
| Type | Description |
|---|---|
Exception
|
Whatever |
Notes
With execution_method="process", the model is pickled and sent to
worker processes, which are always spawned rather than forked. Call this
from code guarded by if __name__ == "__main__":.
estimate_computation_time
¶
estimate_computation_time(n_predictions: int, sample_size: int = 100, kriging_model=None) -> Dict[str, float]
Estimate computation time for different parallelization strategies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_predictions
|
int
|
Number of predictions to make. |
required |
sample_size
|
int
|
Sample size for timing estimation. |
100
|
kriging_model
|
object
|
Kriging model for accurate timing. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
estimates |
dict
|
Time estimates for different strategies in seconds. |
ApproximateNeighborIndex
¶
ApproximateNeighborIndex(method: str = 'auto', max_neighbors: int = 64, leaf_size: int = 30, algorithm: str = 'auto')
Approximate neighbor search index for large-scale kriging.
Provides efficient neighbor queries for datasets with millions of points using various spatial indexing strategies.
Initialize approximate neighbor index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Indexing method: "auto", "kdtree", "sklearn", "annoy". |
"auto"
|
max_neighbors
|
int
|
Maximum number of neighbors to retrieve. |
64
|
leaf_size
|
int
|
Leaf size for tree-based methods. |
30
|
algorithm
|
str
|
Algorithm for sklearn methods. |
"auto"
|
fit
¶
Build the neighbor index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinates
|
(ndarray, shape(n_points, d))
|
Coordinates to index. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
ApproximateNeighborIndex
|
Returns self for method chaining. |
query
¶
query(query_points: ndarray, k: Optional[int] = None, max_distance: Optional[float] = None, return_indices: bool = True) -> NeighborQueryResult
Query neighbors for given points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query_points
|
(ndarray, shape(n_queries, d))
|
Points to query neighbors for. |
required |
k
|
int
|
Number of neighbors to return. Uses max_neighbors if None. |
None
|
max_distance
|
float
|
Maximum distance for neighbors. |
None
|
return_indices
|
bool
|
Whether to return neighbor indices. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
result |
NeighborQueryResult
|
Query results with neighbor indices and distances. |
NeighborQueryResult
¶
Result of a neighbor query operation.
Initialize neighbor query result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
(ndarray, shape(n_queries, k))
|
Indices of k nearest neighbors for each query point. |
required |
distances
|
(ndarray, shape(n_queries, k))
|
Distances to k nearest neighbors for each query point. |
required |
query_indices
|
ndarray
|
Original indices of query points. |
None
|
OrdinaryKriging
¶
Bases: BaseEstimator, RegressorMixin
Ordinary kriging interpolation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variogram
|
Variogram
|
Fitted variogram model. |
required |
fit
¶
fit(coordinates: Union[ndarray, GeoDataFrame, DataFrame], values: Union[ndarray, Series]) -> OrdinaryKriging
Fit the kriging model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinates
|
(array - like, shape(n_samples, n_features))
|
Known sample coordinates. |
required |
values
|
(array - like, shape(n_samples))
|
Known sample values. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
self |
OrdinaryKriging
|
Returns self for method chaining. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the variogram is not fitted, or the kriging system is singular, as it is when two samples share a location. |
predict
¶
predict(coordinates: Union[ndarray, GeoDataFrame, DataFrame], return_variance: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]
Predict values at new locations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinates
|
(array - like, shape(n_points, n_features))
|
Coordinates to predict at. |
required |
return_variance
|
bool
|
If True, also return kriging variance. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
predictions |
(ndarray, shape(n_points))
|
Predicted values. |
variance |
(ndarray, shape(n_points), optional)
|
Kriging variance at each point. Only returned if return_variance=True. |
predict_parallel
¶
predict_parallel(coordinates: Union[ndarray, GeoDataFrame, DataFrame], *, neighbors: int = 64, backend: Optional[str] = None, search_k: Optional[int] = None, grid_shape: Optional[Tuple[int, int]] = None, halo: float = 0.0, chunk_size: int = 10000, checkpoint_path: Optional[Union[str, Path]] = None, checkpoint_interval: int = 5, resume: bool = False, progress: bool = True) -> np.ndarray
Deprecated: use :meth:predict, which computes targets in parallel.
This method never worked. It called ParallelKrigingExecutor,
ApproximateNeighborIndex and spatial_tiles with arguments they do not
accept, so it raised for any input. It now returns predict(coordinates)
and emits a FutureWarning, and it will be removed in a future release.
Neighbour search, tiling, checkpointing and resuming were never implemented. Their options are accepted so that existing calls do not fail, but they are ignored, and the warning names any that were given.
score
¶
Return the coefficient of determination R^2 of the prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coordinates
|
(array - like, shape(n_samples, n_features))
|
Test coordinates. |
required |
values
|
(array - like, shape(n_samples))
|
True values. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
score |
float
|
R^2 score. |
SimpleKriging
¶
Bases: BaseEstimator, RegressorMixin
Simple kriging interpolation with known mean.
fit
¶
fit(coordinates: Union[ndarray, GeoDataFrame, DataFrame], values: Union[ndarray, Series]) -> SimpleKriging
Store known samples and factorise the kriging system.
Raises ValueError if the variogram is not fitted, or the system is
singular, as it is when two samples share a location.
predict
¶
predict(coordinates: Union[ndarray, GeoDataFrame, DataFrame], return_variance: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]
Predict values at new locations.
With return_variance=True, also return the simple kriging variance at
each location, sill - w @ c for weights w and covariances c to
the samples, floored at zero. It used to be the ordinary kriging variance,
which is larger, because ordinary kriging estimates the mean.
score
¶
Coefficient of determination of the prediction.
UniversalKriging
¶
Bases: BaseEstimator, RegressorMixin
Universal kriging with automatic polynomial trend selection.
fit
¶
fit(coordinates: Union[ndarray, GeoDataFrame, DataFrame], values: Union[ndarray, Series]) -> UniversalKriging
Fit the universal kriging model and factorise its system.
Raises ValueError if the variogram is not fitted, or the system is
singular, as it is when two samples share a location.
predict
¶
predict(coordinates: Union[ndarray, GeoDataFrame, DataFrame], return_variance: bool = False) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]
Predict values at new locations.
With return_variance=True, also return the universal kriging variance
at each location, sill - w @ c - mu @ f for weights w, covariances
c to the samples, trend features f and Lagrange multipliers mu,
floored at zero. It used to be the ordinary kriging variance, which is
smaller, because it does not account for estimating the trend.
score
¶
Coefficient of determination of the prediction.
create_anisotropic_variogram_from_directional
¶
create_anisotropic_variogram_from_directional(directional_variogram, model: str = 'exponential') -> Variogram
Create an anisotropic variogram from directional variogram analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directional_variogram
|
DirectionalVariogram
|
Fitted directional variogram with anisotropy detection. |
required |
model
|
str
|
Variogram model type. |
"exponential"
|
Returns:
| Name | Type | Description |
|---|---|---|
variogram |
Variogram
|
Anisotropic variogram model ready for kriging. |
plot_anisotropy_ellipse
¶
Plot anisotropy ellipse showing spatial correlation structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kriging_model
|
AnisotropicKriging
|
Fitted anisotropic kriging model. |
required |
center
|
tuple
|
Center point for the ellipse. |
(0, 0)
|
scale
|
float
|
Scale factor for ellipse size. |
1.0
|
ax
|
matplotlib axes
|
Axes to plot on. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ax |
matplotlib axes
|
The axes object with the ellipse plot. |
chunk_indices
¶
Generate chunk index ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_items
|
int
|
Total number of items. |
required |
chunk_size
|
int
|
Size of each chunk. |
required |
Yields:
| Type | Description |
|---|---|
start, end : tuple of int
|
Start and end indices for each chunk. |
spatial_tiles
¶
spatial_tiles(bounds: Tuple[float, float, float, float], tile_size: Union[float, Tuple[float, float]], overlap: float = 0.1) -> List[Tuple[float, float, float, float]]
Generate spatial tiles for parallel processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds
|
tuple
|
Spatial bounds (xmin, ymin, xmax, ymax). |
required |
tile_size
|
float or tuple
|
Size of each tile. If float, assumes square tiles. Must be positive. |
required |
overlap
|
float
|
Overlap fraction between adjacent tiles. |
0.1
|
Returns:
| Name | Type | Description |
|---|---|---|
tiles |
list of tuples
|
List of tile bounds (xmin, ymin, xmax, ymax). Bounds with no width or height still give one row or column of tiles. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a tile size is not positive. |