Skip to content

idw

py3dinterpolations.modelling.models.idw

Vectorized Inverse Distance Weighting (IDW) model.

IDWModel(power=1.0, threshold=1e-10)

Bases: BaseModel

Vectorized IDW interpolation.

Uses numpy broadcasting instead of Python loops for ~1000x speedup on typical workloads. Batches computation for memory safety.

Parameters:

Name Type Description Default
power float

Power parameter controlling distance decay. Higher values give more weight to nearby points.

1.0
threshold float

Distance below which a point is treated as coincident with a training point (exact interpolation).

1e-10
Source code in py3dinterpolations/modelling/models/idw.py
25
26
27
28
29
def __init__(self, power: float = 1.0, threshold: float = 1e-10):
    self._power = power
    self._threshold = threshold
    self._points: np.ndarray | None = None
    self._values: np.ndarray | None = None

fit(x, y, z, v)

Store training data.

Source code in py3dinterpolations/modelling/models/idw.py
31
32
33
34
def fit(self, x: np.ndarray, y: np.ndarray, z: np.ndarray, v: np.ndarray) -> None:
    """Store training data."""
    self._points = np.column_stack([x, y, z])
    self._values = v

predict(grid_x, grid_y, grid_z, **kwargs)

Predict on a regular grid defined by 1D arrays.

Returns:

Type Description
InterpolationResult

InterpolationResult with shape (len(grid_z), len(grid_y), len(grid_x))

InterpolationResult

to match pykrige's output convention.

Source code in py3dinterpolations/modelling/models/idw.py
 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
def predict(
    self,
    grid_x: np.ndarray,
    grid_y: np.ndarray,
    grid_z: np.ndarray,
    **kwargs: object,
) -> InterpolationResult:
    """Predict on a regular grid defined by 1D arrays.

    Returns:
        InterpolationResult with shape (len(grid_z), len(grid_y), len(grid_x))
        to match pykrige's output convention.
    """
    if self._points is None:
        msg = "Model must be fit before predicting"
        raise RuntimeError(msg)

    # Build meshgrid in ij (XYZ) indexing for computation
    mx, my, mz = np.meshgrid(grid_x, grid_y, grid_z, indexing="ij")
    query_points = np.column_stack([mx.ravel(), my.ravel(), mz.ravel()])

    # Batch processing for memory safety
    n_points = len(query_points)
    result = np.empty(n_points)
    for start in range(0, n_points, _BATCH_SIZE):
        end = min(start + _BATCH_SIZE, n_points)
        result[start:end] = self._predict_batch(query_points[start:end])

    # Reshape to (X, Y, Z) then transpose to (Z, Y, X) to match pykrige
    interpolated = result.reshape(mx.shape)
    interpolated = np.einsum("xyz->zyx", interpolated)

    return InterpolationResult(interpolated=interpolated, variance=None)