core.grid.grid_resampling
Grid resampling
- exception gridr.core.grid.grid_resampling.GridMetricsError(message='grid metrics error')[source]
Exception raised when grid metrics computation was not possible
- class gridr.core.grid.grid_resampling.ResamplingMaskStrategy(mask_kind: str | None, safe_region: ndarray | None, needs_mask_alloc: bool, pad_fill: Any | None, boundary_condition: str | None)[source]
Result of mask strategy resolution.
-
boundary_condition:
Optional[str] Alias for field number 4
-
mask_kind:
Optional[str] One of
'none','safe_region'or'binary'.
-
needs_mask_alloc:
bool Whether a mask buffer must be allocated (only when no user mask is provided).
-
pad_fill:
Optional[Any] Alias for field number 3
-
safe_region:
Optional[ndarray] The safe window [[row_min, row_max], [col_min, col_max]] (inclusives boundaries) or None.
-
boundary_condition:
- gridr.core.grid.grid_resampling.STANDALONE_SAFECHECK_SOURCE_BOUNDARIES = True
Parameter activating an additional validation of the grid source boundaries to ensure topological consistency in standalone mode.
This check computes the source boundaries from all valid grid data within the current computed region, verifying that the source boundaries extracted from grid metrics align with the hull border. When using grid metrics only, we assumes that points inside the source hull correspond to points within the target hull, maintaining topological integrity. If this assumption is violated, the read window may be insufficient, potentially causing a Rust panic when attempting to access out-of-bounds indices.
This safety check helps prevent such runtime errors by proactively extending boundary conditions if required.
- gridr.core.grid.grid_resampling.apply_mask_strategy(array_in_mask, pad, array_in_shape, strategy)[source]
Build the final mask buffer ready to pass to the Rust core.
Executes the strategy produced by
resolve_mask_strategy, performing validation, optional allocation, and optional padding.Behaviour per
mask_kind:'none': returnsNone– no mask is passed to Rust.'binary': padsarray_in_maskwithstrategy.pad_fill(andstrategy.boundary_conditionif set) when padding is present; otherwise returns it as-is.'safe_region':needs_mask_alloc=True: allocates a new buffer filled withstrategy.pad_fill, then marks the safe region asValidity.VALID.needs_mask_alloc=False: padsarray_in_maskwithstrategy.pad_fillwhen padding is present; otherwise returns it as-is.
- Parameters:
array_in_mask (np.ndarray or None) – The original (pre-padded) input mask, or
None. Required whenstrategy.mask_kindis not'none'andstrategy.needs_mask_allocisFalse.pad (np.ndarray, shape (2, 2)) – Padding amounts
[[top, bottom], [left, right]].array_in_shape (tuple of int) – Shape of the original (pre-padded) input array, as
(nvar, nrow, ncol)or(nrow, ncol). Used to compute the padded mask shape whenneeds_mask_allocisTrue.strategy (ResamplingMaskStrategy) – Strategy produced by
resolve_mask_strategy. Validated bycheck_mask_strategybefore execution.
- Returns:
The final mask buffer (uint8, 2D, C-contiguous) to pass to the Rust interpolation core, or
Nonewhen no mask is needed.- Return type:
np.ndarray or None
- Raises:
ValueError – If
strategyis internally inconsistent (viacheck_mask_strategy), or if a requiredarray_in_maskis missing.
See also
resolve_mask_strategyBuilds the strategy.
check_mask_strategyValidates the strategy.
- gridr.core.grid.grid_resampling.array_grid_resampling(interp, array_in, grid_row, grid_col, grid_resolution, array_out, array_out_win=None, nodata_out=0, array_in_origin=(0.0, 0.0), win=None, array_in_mask=None, array_in_mask_safe_win=None, grid_mask=None, grid_mask_valid_value=1, grid_nodata=None, array_out_mask=None, check_boundaries=True, interp_kwargs=None, standalone=True, boundary_condition=None, trust_padding=True, logger_msg_prefix=None, logger=None)[source]
Resamples an input array based on target grid coordinates, applying an optional bilinear interpolation for low resolution grids.
The method uses target grid coordinates (grid_row and grid_col) that may represent a lower resolution than the input array. Bilinear interpolation is applied internally to compute missing target coordinates. The oversampling factor is specified by the grid_resolution parameter, where a value of 1 indicates full resolution.
The interpolation method is set through the interp parameter.
This method wraps a Rust function (py_array1_grid_resampling_*) for efficient resampling. The underlying Rust implementation requires that:
All target positions in array_in referenced by grid coordinates must be accessible, along with their neighborhoods needed for interpolation and preprocessing (e.g., B-spline prefiltering).
Any required preprocessing (e.g., B-spline prefiltering) must be completed before interpolation.
Execution Modes
The method supports two execution modes controlled by the standalone parameter:
Standalone Mode (standalone=True):
Handles all preprocessing automatically, making the function fully self-contained:
Automatic Padding: If array_in is too small to satisfy interpolation requirements (e.g., neighborhood access for the interpolator or grid coordinates falling near boundaries), the array is automatically padded according to boundary_condition.
Mask Handling: If array_in_mask is provided, it is padded consistently with array_in:
With boundary_condition set: Padded mask values are extrapolated from the original mask according to the boundary condition (e.g., ‘edge’ repeats boundary mask values, ‘reflect’ mirrors them without including the edge).
With boundary_condition=None: Padded regions are marked as invalid (typically set to 0).
If no mask is provided and boundary_condition=None: A mask is created with padded regions marked as invalid.
Preprocessing: All required preprocessing steps (e.g., B-spline coefficient calculation) are performed automatically.
Use this mode when calling the function independently or when you want the function to handle all edge cases automatically.
Integrated Mode (standalone=False):
Assumes preprocessing has been handled externally, offering maximum performance:
No Padding: Assumes array_in is already large enough to satisfy all interpolation requirements. The caller is responsible for ensuring adequate array dimensions.
No Mask Preprocessing: Assumes array_in_mask (if provided) is already properly sized and formatted.
No Preprocessing: Assumes all required preprocessing (e.g., B-spline prefiltering) has been completed externally.
Use this mode within tiled processing pipelines where padding and preprocessing are managed at a higher level to avoid redundant operations across tiles.
- Parameters:
interp (InterpolatorIdentifier) –
The interpolator identifier. It can be:
A string representing the interpolator name (e.g., “nearest”, “linear” , “cubic”, etc.).
A PyInterpolatorType enum value.
An instance of an interpolator class.
See gridr.core.interp.interpolator for further details
array_in (is padded using the same boundary condition as) – The input array to be resampled. It must be a contiguous 2D (nrow, ncol) or 3D (nvar, nrow, ncol) array.
grid_row (np.ndarray) – A 2D array representing the row coordinates of the target grid, with the same shape as grid_col. The coordinates target row positions in the array_in input array.
grid_col (np.ndarray) – A 2D array representing the column coordinates of the target grid, with the same shape as grid_row. The coordinates target column positions in the array_in input array.
grid_resolution (Tuple[int, int]) – A tuple specifying the oversampling factor for the grid for rows and columns. The resolution value of 1 represents full resolution, and higher values indicate lower resolution grids.
array_out (Optional[np.ndarray]) – The output array where the resampled values will be stored. If None, a new array will be allocated. The shape of the output array is either determined based on the resolution and the input grid or by the optional win parameter.
array_out_win (Optional[np.ndarray], default None) – An optional np.ndarray that designates the specific area in array_out to receive the resampled data. If None, the method will populate a default rectangular region starting from array_out’s top-left corner. This argument is only considered when array_out is passed, requiring array_out to be large enough to contain array_out_win.
nodata_out (Optional[Union[int, float]], default 0) – The value to be assigned to “NoData” in the output array. This value is used to fill in missing values where no valid resampling could occur or where a mask flag is set.
array_in_origin (Optional[Tuple[float, float]], default (0., 0.)) – Bias to respectively apply to the grid_row and grid_col coordinates. The operation is performed by the wrapped Rust function. Its primary use cases include aligning with alternative grid origin conventions or handling situations where the provided array_in array corresponds to a subregion of the complete source raster.
win (Optional[np.ndarray], default None) – A window (or sub-region) of the full resolution grid to limit the resampling to a specific target region. The window is defined as a list of tuples containing the first and last indices for each dimension. If None, the entire grid is processed.
array_in_mask (Optional[np.ndarray], default None) – A mask for the input array that indicates which parts of array_in are valid for resampling. If not provided, the entire input array is considered valid.
array_in_mask_safe_win (Optional[np.ndarray], shape (2, 2), default None) – Known all-valid sub-region within
array_in_mask, expressed as[[row_start, row_end], [col_start, col_end]]with inclusive boundaries in the original (pre-padded) array coordinate system. When provided, promotes the mask strategy from'binary'to'safe_region', allowing the Rust core to skip per-pixel mask checks for stencils that fall entirely within this zone. Only meaningful whenarray_in_maskis also provided and has real invalids. Ignored in integrated mode (standalone=False).grid_mask (Optional[np.ndarray], default None) – An optional integer mask array for the grid. Grid cells corresponding to grid_mask_valid_value are considered valid; all other values indicate invalid cells and will result in nodata_out in the output array. If not provided, the entire grid is considered valid. The grid mask must have the same shape as grid_row and grid_col.
grid_mask_valid_value (Optional[int], default 1) – The value in grid_mask that designates a valid grid cell. All values in grid_mask that differ from this will be treated as invalid. This parameter is required if grid_mask is provided.
grid_nodata (Optional[float], default None) – The value in grid_row and grid_col to consider as invalid cells. Please note this option is exclusive with grid_mask. The exclusivity is managed within the bound core method.
array_out_mask (Optional[Union[np.ndarray, bool]], default None) – A mask for the output array that indicates where the resampled values should be stored. If True, a new array will be allocated and initially filled with 0. The shape of this output mask array is consistent with the array_out shape. If None or not True, the entire output array is assumed to be valid.
check_boundaries (bool, default True) – Force a check at each iteration to ensure that the required data to perform interpolation is available in the source data. This parameter adresses the core Rust function and can be set to False for performance gain if you are sure that all the required data is available.
interp_kwargs (Optional[dict], default=None) – Optional keyword parameters that will be passed to the get_interpolator function for interpolator creation. Used when interp is of type str or PyInterpolatorType.
standalone (bool, default=True) –
Controls the execution mode:
True: Standalone mode - Performs all preprocessing automatically, including padding, mask handling, and any required interpolator-specific preprocessing (e.g., B-spline prefiltering). Use when calling this function independently.
False: Integrated mode - Assumes all preprocessing has been handled externally. Offers maximum performance for tiled processing pipelines. The caller must ensure array_in is adequately sized and preprocessed.
boundary_condition (Optional[str], default=None) –
Defines how to handle boundary conditions when padding is required in standalone mode. Ignored when standalone=False. Available modes :
- ’constant’ (0)
Pads with a constant value (0).
- -‘edge’
Pads with the edge values of array.
- ’reflect’
Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.
- ’symmetric’
Pads with the reflection of the vector mirrored along the edge of the array.
- ’wrap’
Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.
NoneZero padding is applied. If insufficient data is available for interpolation, those regions will be marked as invalid in the mask. The behaviour is different from constant : with that mode, the padded zone can be either trusted or not.
The boundary condition applies to
array_in. For the mask, the behaviour depends ontrust_padding:If
trust_padding=Trueand a boundary condition is set, the padded mask zone is marked asValidity.VALID— the extrapolated data is considered exploitable.If
trust_padding=Falseorboundary_condition=None, the padded mask zone is marked asValidity.INVALIDregardless of howarray_inwas padded.
invalids (When array_in_mask is provided and contains real)
it
array_in
with
above. (the fill value determined by trust_padding as)
trust_padding (bool, default True) – Controls how the padded zone is marked in the mask when padding is applied in standalone mode. If
Trueand aboundary_conditionis set, the padded zone is considered valid (Validity.VALID) and no mask check is enforced there. IfFalse, the padded zone is always marked asValidity.INVALIDregardless of the boundary condition, ensuring conservative behaviour. Ignored whenstandalone=False.logger_msg_prefix (Optional[str], default=None) – A prefix to add to all log messages generated by this function.
logger (Optional[logging.Logger], default=None) – A logger instance for outputting diagnostic messages.
- Returns:
A tuple containing:
The resampled array. If array_out was provided, this will be None (as the result is written in-place).
The resampled output mask. If array_out_mask was False or None, this will be None.
- Return type:
Tuple[Union[np.ndarray, NoReturn], Union[np.ndarray, NoReturn]]
- Raises:
ValueError – If incompatible parameters are provided (e.g., both array_in_origin and standalone=True).
AssertionError – If input arrays are not C-contiguous.
AssertionError – If grid-related arrays have mismatched shapes.
AssertionError – If optional array_in_mask shape is not consistent with array_in.
Exception – If the py_array_grid_resampling_* function (the underlying Rust binding) is not available for the provided input types.
Notes
This method is designed for resampling raster-like data using a grid of target coordinates.
With integrated mode (standalone=False) this method is designed to be embedded in code that works on tiles, supporting both tiled inputs and outputs.
For correct results, ensure that the grid_row and grid_col values represent the desired target grid coordinates within the full resolution grid system.
When standalone=True, the function may allocate temporary arrays internally, which may increase memory usage.
If the grid metrics calculation fails, the method emits a warning, sets the output array’s values to the designated nodata value, and marks the mask array as a masked-invalid region. When array_out_win is provided, nodata substitution, and masking are applied only to that window; all other portions of the output remain unchanged.
Limitations
The method assumes that all input arrays (array_in, grid_row, grid_col, etc.) are C-contiguous. If any are not, the method may raise an assertion error.
The method assumes that the grid-related arrays (grid_row, grid_col, grid_mask) have the same shapes. Mismatched shapes will raise an assertion error.
The win parameter, if provided, must be compatible with the resolution of the grid. If win exceeds the bounds of the grid, an error may occur.
For large grids or arrays, performance may degrade. Users should test the method’s efficiency for their specific data sizes before using it in production.
This method assumes that the input grid is in a “full resolution” grid coordinate system. If the coordinate system is different, the resampling may produce incorrect results.
Example
Standalone mode with automatic padding:
>>> array_in = np.random.rand(100, 100) >>> grid_row = np.linspace(0, 99, 50) >>> grid_col = np.linspace(0, 99, 50) >>> grid_resolution = (2, 2) >>> result, mask = array_grid_resampling( ... interp="cubic", ... array_in=array_in, ... grid_row=grid_row, ... grid_col=grid_col, ... grid_resolution=grid_resolution, ... array_out=None, ... standalone=True, ... boundary_condition='reflect' ... )
Integrated mode for tiled processing:
>>> # Assume array_in is already padded and preprocessed >>> updated_array = preprocess(interp, array_in) # External function >>> result, mask = array_grid_resampling( ... interp="cubic", ... array_in=updated_array, ... grid_row=grid_row, ... grid_col=grid_col, ... grid_resolution=grid_resolution, ... array_out=None, ... standalone=False ... )
- gridr.core.grid.grid_resampling.calculate_source_extent(interp, array_in, grid_row, grid_col, grid_resolution, grid_nodata, grid_mask, grid_mask_valid_value=1, win=None, safecheck_src_boundaries=True, logger_msg_prefix=None, logger=None)[source]
Calculate the source array read window with margins for interpolation.
This function computes the minimal read window from the source array required to resample data onto the target grid. It accounts for interpolation margins and handles boundary cases where the required window extends beyond the source array bounds.
The calculation proceeds in three steps:
Compute grid metrics from valid grid coordinates
Apply interpolation margins to determine the required source extent
Adjust for boundary conditions and compute necessary padding
Warning : the padding does not guarantee that all the grid target coordinates lie within the final array. It only guarantee that target points that exist in the source image domain will have a sufficient neighborhood to perform interpolation.
- Parameters:
interp (Interpolator) – Interpolator instance that defines the required margins for interpolation. See gridr.core.interp.interpolator for details.
array_in (np.ndarray) – Source array to be resampled. Must be a C-contiguous 3D array with shape (nvar, nrow, ncol) or 2D array with shape (nrow, ncol).
grid_row (np.ndarray) – 2D array of row coordinates in the source array coordinate system. Must have the same shape as grid_col.
grid_col (np.ndarray) – 2D array of column coordinates in the source array coordinate system. Must have the same shape as grid_row.
grid_resolution (tuple of int) – Oversampling factor as (row_resolution, col_resolution). Value of 1 indicates full resolution; higher values indicate coarser grids.
grid_nodata (int or float, optional) – Value in grid_row and grid_col indicating invalid cells. Mutually exclusive with grid_mask (exclusivity enforced in core method).
grid_mask (np.ndarray, optional) – Integer mask array for the grid. Cells matching grid_mask_valid_value are considered valid. Must have the same shape as grid_row and grid_col.
grid_mask_valid_value (int, default=1) – Value in grid_mask that designates valid grid cells. Required if grid_mask is provided.
win (np.ndarray, optional) – Target window in full-resolution grid coordinates, shape (2, 2):
[[row_start, row_end], [col_start, col_end]]. If None, processes the entire grid.safecheck_src_boundaries (bool, default=True) – If True, computes the source boundaries from all valid grid data.
logger_msg_prefix (str, optional) – Prefix for log messages generated by this function.
logger (logging.Logger, optional) – Logger instance for diagnostic messages.
- Returns:
array_src_win_read (np.ndarray, shape (2, 2)) – Final source read window adjusted for margins and boundary constraints. Format:
[[row_start, row_end], [col_start, col_end]]. Use this window for raster IO operations.array_src_win_marged (np.ndarray, shape (2, 2)) – Desired read window with margins applied, before boundary correction. Format:
[[row_start, row_end], [col_start, col_end]].pad (np.ndarray, shape (2, 2)) – Padding required if the marged window extends outside the source array. Format:
[[top_pad, bottom_pad], [left_pad, right_pad]].grid_metrics (Union[PyGeometryBoundsF64, None]) – A structure containing the computed boundaries (PyGeometryBoundsF64) or None if no valid boundaries can be computed (e.g., empty grid).
Notes
If no valid grid points are found, returns None for all outputs
The safecheck_src_boundaries option is useful to detect grid topology issues that could cause panic
Padding may be required when the grid extends beyond source boundaries, which should be filled using appropriate boundary conditions
See also
array_compute_resampling_grid_geometriesComputes grid metrics from
coordinates,metrics
- gridr.core.grid.grid_resampling.check_mask_strategy(pad, strategy)[source]
Validate the internal consistency of a
ResamplingMaskStrategy.Acts as a safety guard between
resolve_mask_strategy(which builds the strategy) andapply_mask_strategy(which executes it). Catches any combination of fields that would lead to incorrect mask construction or silent data corruption.The validation enforces four groups of invariants:
mask_kind constraints – each kind imposes requirements on the other fields:
'none': all other fields must be neutral (None/False).'safe_region':safe_regionmust be set;needs_mask_allocandboundary_conditionare mutually exclusive (cannot allocate a new mask and pad an existing one).'binary':needs_mask_allocmust beFalse(the caller provides the mask).
safe_region coherence –
safe_regionis notNoneiffmask_kind == 'safe_region'.Padding constraints – when no padding is applied,
pad_fillandboundary_conditionmust beNone(nothing to fill). When padding is applied and a mask is needed,pad_fillmust beValidity.VALIDorValidity.INVALID.Allocation constraints –
needs_mask_allocrequiresmask_kind == 'safe_region'and a concretepad_fillvalue.
- Parameters:
pad (np.ndarray, shape (2, 2)) – Padding amounts
[[top, bottom], [left, right]].strategy (ResamplingMaskStrategy) – The strategy to validate.
- Raises:
ValueError – If any invariant is violated, with a message identifying the incompatible fields.
See also
resolve_mask_strategyBuilds the strategy.
apply_mask_strategyExecutes the strategy (calls this first).
- gridr.core.grid.grid_resampling.get_array_padded_shape(array_src, pad)[source]
Compute padded array shape and source window slice for padding operations.
This utility function calculates the shape of an array after padding and generates slice objects to position the original data within the padded array.
- Parameters:
array_src (np.ndarray) – Source array to be padded. Must be 2D (nrow, ncol) or 3D (nvar, nrow, ncol).
pad (tuple of tuple of int) – Padding amounts as
((top, bottom), (left, right)).
- Return type:
(
Tuple[int],Tuple[slice])- Returns:
array_padded_shape (tuple of int) – Shape of the padded array:
For 3D input: (nvar, nrow + top + bottom, ncol + left + right)
For 2D input: (nrow + top + bottom, ncol + left + right)
source_window (tuple of slice) – Slice objects to position the original array within the padded array:
For 3D: (slice(None), slice(top, top+nrow), slice(left, left+ncol))
For 2D: (slice(top, top+nrow), slice(left, left+ncol))
- Raises:
ValueError – If input array has neither 2 nor 3 dimensions.
Notes
This function does not allocate or modify arrays; it only computes metadata for padding operations. Use source_extent_pad to apply actual padding.
Examples
>>> import numpy as np >>> from gridr import get_array_padded_shape >>> >>> # For a 2D array >>> arr = np.ones((100, 100)) >>> pad = ((5, 5), (10, 10)) >>> shape, window = get_array_padded_shape(arr, pad) >>> print(shape) # (110, 120) >>> print(window) # (slice(5, 105), slice(10, 110)) >>> >>> # For a 3D array >>> arr = np.ones((3, 100, 100)) >>> shape, window = get_array_padded_shape(arr, pad) >>> print(shape) # (3, 110, 120) >>> print(window) # (slice(None), slice(5, 105), slice(10, 110))
- gridr.core.grid.grid_resampling.resolve_mask_strategy(interp, pad, array_in_mask, boundary_condition, trust_padding=True, array_in_shape=None, array_in_mask_safe_win=None)[source]
Determine how to prepare the input mask before passing it to the Rust interpolation core.
Based on the input configuration (padding, boundary condition, mask content, interpolator type), this function decides whether a mask buffer must be allocated, how to fill the padded zone, and whether a safe region can be identified to optimize mask checks.
This function must be called from both the standalone and IO code paths to guarantee consistent behaviour. Its output drives
apply_mask_strategywhich builds the actual mask buffer.Decision tree
mask has real invalids? | +-- yes | +-- safe_win provided? | | +-- yes -> safe_region (shifted by pad) | | +-- no -> binary | | | +-- pad > 0? | +-- yes + BC + trust -> pad_fill=VALID, BC propagated | +-- yes + otherwise -> pad_fill=INVALID | +-- no -> pad_fill=None | +-- no (mask is None or full-valid) | +-- pad = 0? | +-- bspline -> safe_region (full array, alloc mask) | +-- other -> none | +-- pad > 0 | +-- BC + trust? | +-- bspline -> safe_region (full padded, alloc if no mask) | +-- other -> none | +-- otherwise (not trusted) +-----------> safe_region (data zone only, alloc if no mask)- type interp:
Any- param interp:
The interpolator instance. Used to determine whether B-spline prefiltering applies.
- type interp:
Interpolator
- type pad:
ndarray- param pad:
Padding amounts
[[top, bottom], [left, right]].- type pad:
np.ndarray, shape (2, 2)
- type array_in_mask:
Optional[ndarray]- param array_in_mask:
Optional input mask (uint8, 2D). If provided and not full-valid, the strategy accounts for scattered invalids. A full-valid mask is treated as no mask.
- type array_in_mask:
np.ndarray or None
- type boundary_condition:
Optional[str]- param boundary_condition:
Boundary condition used to fill the padded zone. Available modes :
- ‘constant’ (0)
Pads with a constant value (0).
- -‘edge’
Pads with the edge values of array.
- ‘reflect’
Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.
- ‘symmetric’
Pads with the reflection of the vector mirrored along the edge of the array.
- ‘wrap’
Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.
Nonemeans the padded zone contains zeros but is considered asnon trusted data. The behaviour is different from constant : with that mode, the padded zone can be either trusted or not.
- type boundary_condition:
str or None
- type trust_padding:
bool- param trust_padding:
If
Trueand a not None boundary condition was applied, the extrapolated padding data is considered numerically valid. WhenFalse, the padded zone is treated as suspect regardless of the boundary condition.- type trust_padding:
bool, default True
- type array_in_shape:
Optional[Tuple[int,...]]- param array_in_shape:
Shape of the original (pre-padded) input array, as
(nvar, nrow, ncol)or(nrow, ncol). Required whenever the strategy may be'safe_region'.- type array_in_shape:
tuple of int
- type array_in_mask_safe_win:
Optional[ndarray]- param array_in_mask_safe_win:
Caller-provided safe region within the input mask, as
[[row_start, row_end], [col_start, col_end]]with inclusive boundaries, in pre-padded coordinates. When provided with a mask that has real invalids, promotes the strategy from'binary'to'safe_region'. The region is automatically shifted to account for padding. Ignored when no real invalids are present in the mask.- type array_in_mask_safe_win:
np.ndarray, shape (2, 2), optional
- returns:
Named tuple with fields:
mask_kind:'none','safe_region', or'binary'.safe_region: window array (inclusive boundaries in post-padded coordinates) orNone.needs_mask_alloc: whether a structural mask buffer must be allocated.pad_fill: fill value for the padded zone in the mask (Validity.VALID,Validity.INVALID, orNone).boundary_condition: boundary condition to apply when padding the mask, orNone.
- rtype:
ResamplingMaskStrategy
- gridr.core.grid.grid_resampling.source_extent_pad(array_src, pad, boundary_condition, fill=None)[source]
Apply padding to a source array with specified boundary conditions.
This function creates a padded version of the input array, optionally filling the padded regions using boundary conditions (edge, reflect, symmetric, wrap) or a constant fill value.
- Parameters:
array_src (np.ndarray) – Source array to pad. Must be 2D (nrow, ncol) or 3D (nvar, nrow, ncol), C-contiguous.
pad (tuple of tuple of int) – Padding amounts as
((top, bottom), (left, right)).boundary_condition (str, optional) –
Boundary condition mode for padding the margins. If None, padded regions are left uninitialized (except if fill is provided). Available modes:
- ’constant’ (0)
Pads with a constant value (0).
- -‘edge’
Pads with the edge values of array.
- ’reflect’
Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.
- ’symmetric’
Pads with the reflection of the vector mirrored along the edge of the array.
- ’wrap’
Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.
fill (scalar, optional) – Value to initialize padded regions before applying boundary conditions. If None, array is allocated uninitialized (faster but contains garbage values in padded regions if boundary_condition is None).
- Returns:
array_padded – Padded array with the same dtype as array_src. Shape:
For 3D input: (nvar, nrow + top + bottom, ncol + left + right)
For 2D input: (nrow + top + bottom, ncol + left + right)
- Return type:
np.ndarray
Notes
The original data is always copied into the center of the padded array
If both boundary_condition and fill are provided, fill is applied first, then the boundary condition overwrites the padded regions
Uses an optimized in-place padding implementation (pad_inplace)
The returned array is always C-contiguous
See also
get_array_padded_shapeComputes padded shape without allocation
pad_inplaceLow-level in-place padding function
Examples
>>> import numpy as np >>> from gridr import source_extent_pad >>> >>> # Pad with edge replication >>> arr = np.arange(9).reshape(3, 3) >>> padded = source_extent_pad(arr, pad=((1, 1), (1, 1)), ... boundary_condition='edge') >>> print(padded.shape) # (5, 5) >>> >>> # Pad with constant fill value >>> padded = source_extent_pad(arr, pad=((2, 2), (2, 2)), ... boundary_condition=None, fill=-999) >>> >>> # Pad 3D array with reflection >>> arr_3d = np.random.rand(3, 100, 100) >>> padded_3d = source_extent_pad(arr_3d, pad=((5, 5), (5, 5)), ... boundary_condition='reflect')
- gridr.core.grid.grid_resampling.standalone_preprocessing(interp, array_in, array_in_shape, array_in_origin, grid_row, grid_col, grid_resolution, grid_nodata, grid_mask, grid_mask_valid_value, win, array_in_mask, array_in_mask_safe_win, boundary_condition, trust_padding, check_boundaries, logger_msg_prefix, logger)[source]
Perform all preprocessing steps required before the Rust resampling call in standalone mode.
This function is the single entry point for standalone preprocessing. It sequentially handles source extent computation, data padding, mask preparation, and B-spline prefiltering.
Processing steps
Validate that
array_in_originis zero (shifting is not supported in standalone mode).Initialize the interpolator (required for B-spline).
Compute the minimal source read window and required padding via
calculate_source_extent.Pad
array_inif needed, updatearray_in_shapeandarray_in_originaccordingly.Prepare the mask (resolve and apply the mask strategy)
If the interpolator is a B-spline, run prefiltering in place on
array_inandarray_in_mask.
- type interp:
Any- param interp:
Initialised interpolator instance.
- type interp:
Interpolator
- type array_in:
ndarray- param array_in:
Source data array (2D or 3D, C-contiguous).
- type array_in:
np.ndarray
- type array_in_shape:
Tuple[int,...]- param array_in_shape:
Shape of
array_inas(nvar, nrow, ncol)(always 3D).- type array_in_shape:
tuple of int
- type array_in_origin:
Optional[Tuple[float,float]]- param array_in_origin:
Must be
Noneor(0.0, 0.0)in standalone mode.- type array_in_origin:
tuple of float or None
- type grid_row:
ndarray- param grid_row:
Row coordinates of the target grid.
- type grid_row:
np.ndarray
- type grid_col:
ndarray- param grid_col:
Column coordinates of the target grid.
- type grid_col:
np.ndarray
- type grid_resolution:
Tuple[int,int]- param grid_resolution:
Oversampling factor
(row_resolution, col_resolution).- type grid_resolution:
tuple of int
- type grid_nodata:
Optional[float]- param grid_nodata:
NoData value in the grid coordinate arrays.
- type grid_nodata:
float or None
- type grid_mask:
Optional[ndarray]- param grid_mask:
Optional validity mask for the grid.
- type grid_mask:
np.ndarray or None
- type grid_mask_valid_value:
Optional[int]- param grid_mask_valid_value:
Value in
grid_maskdesignating valid cells.- type grid_mask_valid_value:
int or None
- type win:
Optional[ndarray]- param win:
Target sub-window within the full-resolution grid.
- type win:
np.ndarray or None
- type array_in_mask:
Optional[ndarray]- param array_in_mask:
Optional input validity mask for
array_in(uint8, 2D).- type array_in_mask:
np.ndarray or None
- type array_in_mask_safe_win:
Optional[ndarray]- param array_in_mask_safe_win:
Caller-provided safe region within
array_in_mask, in pre-padded coordinates. Forwarded toprepare_mask.- type array_in_mask_safe_win:
np.ndarray or None
- type boundary_condition:
Optional[str]- param boundary_condition:
Boundary condition used to fill the padded zone. Available modes :
- ‘constant’ (0)
Pads with a constant value (0).
- -‘edge’
Pads with the edge values of array.
- ‘reflect’
Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis.
- ‘symmetric’
Pads with the reflection of the vector mirrored along the edge of the array.
- ‘wrap’
Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning.
Nonemeans the padded zone contains zeros but is considered asnon trusted data. The behaviour is different from constant : with that mode, the padded zone can be either trusted or not.
- type boundary_condition:
str or None
- type trust_padding:
Optional[bool]- param trust_padding:
If
Trueand a not None boundary condition was applied, the extrapolated padding data is considered numerically valid. WhenFalse, the padded zone is treated as suspect regardless of the boundary condition.- type trust_padding:
bool, default True
- type check_boundaries:
bool- param check_boundaries:
Passed through unchanged to the return value.
- type check_boundaries:
bool
- type logger_msg_prefix:
Optional[str]- param logger_msg_prefix:
Prefix for log messages.
- type logger_msg_prefix:
str or None
- type logger:
Optional[Logger]- param logger:
Logger instance.
- type logger:
logging.Logger or None
- rtype:
Tuple[ndarray,Tuple[int,...],Optional[Tuple[float,float]],Optional[ndarray],bool]- returns:
array_in (np.ndarray) – Padded (and prefiltered if B-spline) data array.
array_in_shape (tuple of int) – Updated shape of the padded
array_inas(nvar, nrow, ncol).array_in_origin (tuple of float or None) – Updated coordinate origin accounting for padding offset.
array_in_mask (np.ndarray or None) – Final mask buffer ready to pass to the Rust core, or
Nonewhen no mask is needed.safe_region (np.ndarray or None) – Safe region window within the padded array (
[[row_start, row_end], [col_start, col_end]], inclusive), orNoneif unavailable.check_boundaries (bool) – Passed through from input unchanged.
- raises ValueError:
If
array_in_originis non-zero in standalone mode.
See also
resolve_mask_strategyBuilds the strategy.
apply_mask_strategyExecutes the strategy.
calculate_source_extentSource window and padding computation.