Skip to content

Commit

Permalink
✨ Introduce pyiem.grid.util.grid_smear
Browse files Browse the repository at this point in the history
Fill in masked data by shifting grid four times
refs akrherz/iem#923
  • Loading branch information
akrherz committed Sep 4, 2024
1 parent aee03c1 commit b2a2691
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ All notable changes to this library are documented in this file.

- Add `_check_dueling_tropics` VTEC check looking for TR+HU overlap (#930).
- Add IEMRE DOMAINS to support upcoming expansion.
- Add `pyiem.grid.util.grid_smear` to shift masked data to fill in missing.
- Allow `iemapp(memcachexpire)` to be a callable, called back with environ.
- Cross check WCNs against watch database storage for PDS status (#925).
- For `iemapp` if the `memcachekey=` callable returns `None`, the check of
Expand Down
34 changes: 34 additions & 0 deletions src/pyiem/grid/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""pyIEM grid utilities."""

import numpy as np


def grid_smear(grid: np.ndarray, pad: int = 4) -> np.ndarray:
"""Smear data around to fill in masked values (likely near coastlines).
Args:
grid: 2D numpy array
pad: number of pixels to smear the data around by in each direction
Returns:
2D numpy array with smeared data
"""
# Pad grid
padded = np.ma.masked_all(
(grid.shape[0] + pad * 2, grid.shape[1] + pad * 2)
)
# set values from inbound grid
padded[pad:-pad, pad:-pad] = grid

# shift the grid by 4 pixels in each direction to fill in the padded region
for xorigin in [0, pad * 2]:
for yorigin in [0, pad * 2]:
xslice = slice(xorigin, xorigin + grid.shape[0])
yslice = slice(yorigin, yorigin + grid.shape[1])
padded[xslice, yslice] = np.ma.where(
np.logical_and(padded[xslice, yslice].mask, ~grid.mask),
grid,
padded[xslice, yslice],
)

return padded[pad:-pad, pad:-pad]
14 changes: 14 additions & 0 deletions tests/grid/test_util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""Test pyiem.grid.util"""

import numpy as np

from pyiem.grid.util import grid_smear


def test_grid_smear():
"""Test the smearing."""
grid = np.ma.ones((10, 10)) * np.arange(10)
# set value at 8,8 to missing
grid[8, 8] = np.ma.masked
grid2 = grid_smear(grid)
assert grid2[8, 8] == 4

0 comments on commit b2a2691

Please sign in to comment.