-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ Introduce pyiem.grid.util.grid_smear
Fill in masked data by shifting grid four times refs akrherz/iem#923
- Loading branch information
Showing
3 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |