Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a function to fill NaNs in grids by interpolation #440

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions verde/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,22 @@
meshgrid_to_1d,
parse_engine,
partition_by_sum,
fill_nans
)


def test_fill_nans():
"""
This function tests the fill_nans function.
Phssilva marked this conversation as resolved.
Show resolved Hide resolved
"""

grid = np.array([[1, np.nan, 3],
[4, 5, np.nan],
[np.nan, 7, 8]])
filled_grid = fill_nans(grid)
assert np.isnan(filled_grid).sum() == 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function is supposed to take an xarray.DataArray but the test gives it a numpy array. The test should match the expected use of the function. Please make the grid into a DataArray.

It would also be good to check if the final grid has the correct values in the NaNs. Right now, this only checks that the NaNs aren't there but the values could be completely wrong and we'd never know.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Leo!
A DataArray was added to the test function, and a check was made on the filled values in the DataArray. Could you please verify if the changes made are correct? Thank you for your attention.

Phssilva marked this conversation as resolved.
Show resolved Hide resolved


def test_parse_engine():
"Check that it works for common input"
assert parse_engine("numba") == "numba"
Expand Down
31 changes: 31 additions & 0 deletions verde/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import pandas as pd
import xarray as xr
from scipy.spatial import cKDTree
from sklearn.impute import KNNImputer
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please use verde.KNeighbors instead.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used the KNeighbors class and used the predict and fit methods to fill in the values of the data array.


try:
from pykdtree.kdtree import KDTree as pyKDTree
Expand Down Expand Up @@ -681,6 +682,36 @@ def kdtree(coordinates, use_pykdtree=True, **kwargs):
return tree


def fill_nans(grid, n_neighbors=1):
"""
This methos is responsible for fill the NaN values in the grid using the KNN algorithm.
Phssilva marked this conversation as resolved.
Show resolved Hide resolved
Phssilva marked this conversation as resolved.
Show resolved Hide resolved

Parameters
----------
grid : :class:`xarray.Dataset` or :class:`xarray.DataArray`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be only a DataArray and not a Dataset.

A 2D grid with one or more data variables.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
A 2D grid with one or more data variables.
A 2D grid with missing values (NaNs).

n_neighbors : int
Number of nearest neighbors to use to fill the NaN values in the grid.
The greater the quantity, the longer the processing time, depending on the size of the matrix
Phssilva marked this conversation as resolved.
Show resolved Hide resolved

Returns
-------
grid : :class:`xarray.Dataset` or :class:`xarray.DataArray`
A 2D grid with the NaN values filled.
"""

not_nan_values = np.argwhere(~np.isnan(grid)).reshape(-1, 1)
unknown_indices = np.argwhere(np.isnan(grid))

knn_imputer = KNNImputer(n_neighbors=n_neighbors)
knn_imputer.fit(not_nan_values)

predicted_values = knn_imputer.transform(not_nan_values)
for i, idx in enumerate(unknown_indices):
grid[tuple(idx)] = predicted_values[i]

return grid
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The output grid should be a copy of the input grid. We want to avoid changing the input values in-place. The code above will actually alter the input and could cause problems for users since their original grid with NaNs is now gone.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used a copy of the grid in the variable filled_grid, which is returned at the end of the function.


def partition_by_sum(array, parts):
"""
Partition an array into parts of approximately equal sum.
Expand Down
Loading