Skip to content

core

py3dinterpolations.core

Core data structures and grid definitions.

Grid3D(x, y, z)

Bases: ABC

Abstract base class for 3D interpolation grids.

Parameters:

Name Type Description Default
x GridAxis

X axis definition.

required
y GridAxis

Y axis definition.

required
z GridAxis

Z axis definition.

required
Source code in py3dinterpolations/core/grid3d.py
47
48
49
50
51
def __init__(self, x: GridAxis, y: GridAxis, z: GridAxis):
    self._x = x
    self._y = y
    self._z = z
    self._result: InterpolationResult | None = None

grid property

1D grid arrays per axis.

normalized_grid property

Min-max normalized 1D grid arrays per axis.

gridres property

Grid resolution; scalar if uniform, dict otherwise.

mesh property

3D meshgrid arrays.

normalized_mesh property

Normalized 3D meshgrid arrays.

get_axis(axis)

Get a grid axis by name.

Parameters:

Name Type Description Default
axis str | Axis

Axis name ("X", "Y", "Z") or Axis enum.

required

Raises:

Type Description
ValueError

If axis name is invalid.

Source code in py3dinterpolations/core/grid3d.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def get_axis(self, axis: str | Axis) -> GridAxis:
    """Get a grid axis by name.

    Args:
        axis: Axis name ("X", "Y", "Z") or Axis enum.

    Raises:
        ValueError: If axis name is invalid.
    """
    axis = Axis(axis)
    match axis:
        case Axis.X:
            return self._x
        case Axis.Y:
            return self._y
        case Axis.Z:
            return self._z

prediction_points() abstractmethod

Return (N, 3) array of points at which to predict.

Source code in py3dinterpolations/core/grid3d.py
138
139
140
141
@abstractmethod
def prediction_points(self) -> np.ndarray:
    """Return (N, 3) array of points at which to predict."""
    ...

GridAxis(name, min, max, res) dataclass

A single axis of a 3D grid.

Parameters:

Name Type Description Default
name Axis

Axis identifier.

required
min float

Minimum value.

required
max float

Maximum value.

required
res float

Resolution (step size).

required

grid property

1D array of evenly spaced values along this axis.

IrregularGrid3D(x_min, x_max, x_res, y_min, y_max, y_res, z_min, z_max, z_res, hull=None)

Bases: Grid3D

3D grid with per-axis resolution and optional convex hull filtering.

Parameters:

Name Type Description Default
x_min float

Minimum X value.

required
x_max float

Maximum X value.

required
x_res float

X axis resolution.

required
y_min float

Minimum Y value.

required
y_max float

Maximum Y value.

required
y_res float

Y axis resolution.

required
z_min float

Minimum Z value.

required
z_max float

Maximum Z value.

required
z_res float

Z axis resolution.

required
hull BaseGeometry | None

Optional convex hull geometry for XY filtering.

None
Source code in py3dinterpolations/core/grid3d.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def __init__(
    self,
    x_min: float,
    x_max: float,
    x_res: float,
    y_min: float,
    y_max: float,
    y_res: float,
    z_min: float,
    z_max: float,
    z_res: float,
    hull: BaseGeometry | None = None,
):
    super().__init__(
        x=GridAxis(Axis.X, x_min, x_max, x_res),
        y=GridAxis(Axis.Y, y_min, y_max, y_res),
        z=GridAxis(Axis.Z, z_min, z_max, z_res),
    )
    self._hull = hull

prediction_points()

Return grid points filtered by convex hull if available.

Source code in py3dinterpolations/core/grid3d.py
223
224
225
226
227
228
229
230
231
232
233
def prediction_points(self) -> np.ndarray:
    """Return grid points filtered by convex hull if available."""
    m = self.mesh
    points = np.column_stack([m["X"].ravel(), m["Y"].ravel(), m["Z"].ravel()])
    if self._hull is not None:
        from shapely import Point

        mask = np.array([self._hull.contains(Point(p[0], p[1])) for p in points])
        filtered: np.ndarray = points[mask]
        return filtered
    return points

RegularGrid3D(x_min, x_max, y_min, y_max, z_min, z_max, gridres)

Bases: Grid3D

Regular 3D grid with equal spacing in all axes.

Parameters:

Name Type Description Default
x_min float

Minimum X value.

required
x_max float

Maximum X value.

required
y_min float

Minimum Y value.

required
y_max float

Maximum Y value.

required
z_min float

Minimum Z value.

required
z_max float

Maximum Z value.

required
gridres float

Uniform grid resolution.

required
Source code in py3dinterpolations/core/grid3d.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def __init__(
    self,
    x_min: float,
    x_max: float,
    y_min: float,
    y_max: float,
    z_min: float,
    z_max: float,
    gridres: float,
):
    super().__init__(
        x=GridAxis(Axis.X, x_min, x_max, gridres),
        y=GridAxis(Axis.Y, y_min, y_max, gridres),
        z=GridAxis(Axis.Z, z_min, z_max, gridres),
    )

prediction_points()

Return all grid points as (N, 3) array.

Source code in py3dinterpolations/core/grid3d.py
181
182
183
184
def prediction_points(self) -> np.ndarray:
    """Return all grid points as (N, 3) array."""
    m = self.mesh
    return np.column_stack([m["X"].ravel(), m["Y"].ravel(), m["Z"].ravel()])

GridData(data, *, ID='ID', X='X', Y='Y', Z='Z', V='V', preprocessing_params=None)

Container for 3D grid data with spatial coordinates and values.

Standardizes input DataFrames into a canonical format with MultiIndex (ID, X, Y, Z) and a single column V.

Parameters:

Name Type Description Default
data DataFrame

Source DataFrame with spatial data.

required
ID str

Column name for point identifier.

'ID'
X str

Column name for X coordinate.

'X'
Y str

Column name for Y coordinate.

'Y'
Z str

Column name for Z coordinate.

'Z'
V str

Column name for value.

'V'
preprocessing_params PreprocessingParams | None

Parameters from preprocessing applied to this data.

None
Source code in py3dinterpolations/core/griddata.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def __init__(
    self,
    data: pd.DataFrame,
    *,
    ID: str = "ID",
    X: str = "X",
    Y: str = "Y",
    Z: str = "Z",
    V: str = "V",
    preprocessing_params: PreprocessingParams | None = None,
):
    self.preprocessing_params = preprocessing_params
    self.columns = {"ID": ID, "X": X, "Y": Y, "Z": Z, "V": V}
    self.data = self._set_data(data)

specs property

Compute spatial and value extent statistics.

numpy_data property

Return X, Y, Z, V as a numpy array.

hull property

Convex hull of XY coordinates as a shapely geometry.

GridDataSpecs(xmin, xmax, ymin, ymax, zmin, zmax, vmin, vmax) dataclass

Precomputed spatial and value extent statistics.

Computed once from a DataFrame rather than re-reading on every access.

from_dataframe(data) classmethod

Compute specs from a canonical GridData DataFrame.

Source code in py3dinterpolations/core/griddata.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@classmethod
def from_dataframe(cls, data: pd.DataFrame) -> "GridDataSpecs":
    """Compute specs from a canonical GridData DataFrame."""
    df = data.reset_index()
    return cls(
        xmin=float(df["X"].min()),
        xmax=float(df["X"].max()),
        ymin=float(df["Y"].min()),
        ymax=float(df["Y"].max()),
        zmin=float(df["Z"].min()),
        zmax=float(df["Z"].max()),
        vmin=float(df["V"].min()),
        vmax=float(df["V"].max()),
    )

Axis

Bases: StrEnum

Spatial axis identifier.

DownsamplingParams(resolution) dataclass

Downsampling parameters.

DownsamplingStatistic

Bases: StrEnum

Supported downsampling statistics.

GridResolution(x, y, z) dataclass

Grid resolution per axis.

Use uniform() for equal resolution on all axes, or from_input() to accept either float or per-axis dict.

uniform(resolution) classmethod

Create uniform resolution across all axes.

Source code in py3dinterpolations/core/types.py
95
96
97
98
@classmethod
def uniform(cls, resolution: float) -> "GridResolution":
    """Create uniform resolution across all axes."""
    return cls(x=resolution, y=resolution, z=resolution)

from_input(resolution) classmethod

Create from either a uniform float or per-axis dict.

Source code in py3dinterpolations/core/types.py
100
101
102
103
104
105
106
107
108
109
110
111
112
@classmethod
def from_input(cls, resolution: float | dict[str, float]) -> "GridResolution":
    """Create from either a uniform float or per-axis dict."""
    if isinstance(resolution, (int, float)):
        return cls.uniform(float(resolution))
    if isinstance(resolution, dict):
        return cls(
            x=float(resolution["X"]),
            y=float(resolution["Y"]),
            z=float(resolution["Z"]),
        )
    msg = f"resolution must be float or dict, got {type(resolution)}"
    raise TypeError(msg)

InterpolationResult(interpolated, variance=None, probability=None) dataclass

Result of an interpolation run.

ModelType

Bases: StrEnum

Supported interpolation model types.

NormalizationParams(min, max) dataclass

Min/max normalization parameters for a single axis.

PreprocessingParams(downsampling=None, normalization=None, standardization=None) dataclass

Collected preprocessing parameters from a preprocessing run.

SklearnClassifier

Bases: SklearnEstimator, Protocol

Structural type for sklearn classifiers with predict_proba.

SklearnEstimator

Bases: Protocol

Structural type for sklearn-compatible estimators.

StandardizationParams(mean, std) dataclass

Mean/std standardization parameters.

create_grid(griddata, resolution)

Factory to create the appropriate Grid3D from data and resolution.

Parameters:

Name Type Description Default
griddata GridData

Source data to derive grid extents from.

required
resolution float | dict[str, float]

Uniform float for RegularGrid3D, or per-axis dict for IrregularGrid3D.

required

Returns:

Type Description
Grid3D

A Grid3D subclass instance.

Raises:

Type Description
TypeError

If resolution type is unsupported.

Source code in py3dinterpolations/core/grid3d.py
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
def create_grid(
    griddata: GridData,
    resolution: float | dict[str, float],
) -> Grid3D:
    """Factory to create the appropriate Grid3D from data and resolution.

    Args:
        griddata: Source data to derive grid extents from.
        resolution: Uniform float for RegularGrid3D,
            or per-axis dict for IrregularGrid3D.

    Returns:
        A Grid3D subclass instance.

    Raises:
        TypeError: If resolution type is unsupported.
    """
    specs = griddata.specs
    res = GridResolution.from_input(resolution)

    if isinstance(resolution, (int, float)):
        return RegularGrid3D(
            x_min=specs.xmin,
            x_max=specs.xmax,
            y_min=specs.ymin,
            y_max=specs.ymax,
            z_min=specs.zmin,
            z_max=specs.zmax,
            gridres=res.x,
        )
    if isinstance(resolution, dict):
        return IrregularGrid3D(
            x_min=specs.xmin,
            x_max=specs.xmax,
            x_res=res.x,
            y_min=specs.ymin,
            y_max=specs.ymax,
            y_res=res.y,
            z_min=specs.zmin,
            z_max=specs.zmax,
            z_res=res.z,
            hull=griddata.hull,
        )
    msg = f"resolution must be float or dict, got {type(resolution)}"
    raise TypeError(msg)