Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
11 changes: 7 additions & 4 deletions LoopStructural/modelling/features/_geological_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,13 @@ def evaluate_value(
if fillnan == 'nearest':
from scipy import spatial

nanmask = np.isnan(v)
tree = spatial.cKDTree(evaluation_points[~nanmask, :])
_d, i = tree.query(evaluation_points[nanmask, :])
v[nanmask] = v[~nanmask][i]
known = ~np.isnan(v)
# A point with a NaN coordinate has no nearest point, so its value stays NaN.
nanmask = ~known & np.all(np.isfinite(evaluation_points), axis=1)
if np.any(nanmask) and np.any(known):
tree = spatial.cKDTree(evaluation_points[known, :])
_d, i = tree.query(evaluation_points[nanmask, :])
v[nanmask] = v[known][i]
return v

def evaluate_gradient(
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/modelling/test_geological_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,36 @@ def test_tojson():
test_tojson()
print("All tests passed")
sys.exit(0)


def test_fillnan_nearest_keeps_nan_for_points_with_a_nan_coordinate():
"""fillnan='nearest' fills a finite point and leaves a NaN-coordinate point NaN.

Since a point with a NaN coordinate gives NaN, the KD-tree query got NaN
points and raised "'x' must be finite" (seen in fault gradients near faults).
"""

class LinearInterpolator:
def evaluate_value(self, points):
return points[:, 0] + 2.0 * points[:, 1]

feature = GeologicalFeature(
"field",
builder=None,
# The region removes x > 0.5, so that point needs a nearest value.
regions=[lambda points: ~(points[:, 0] > 0.5)],
interpolator=LinearInterpolator(),
)
points = np.array([[0.0, 1.0, 0.0], [0.6, 1.0, 0.0], [np.nan, 1.0, 0.0]])
values = feature.evaluate_value(points, fillnan="nearest")
np.testing.assert_allclose(values, [2.0, 2.0, np.nan], equal_nan=True)


def test_fillnan_nearest_without_known_values_gives_nan():
class NanInterpolator:
def evaluate_value(self, points):
return np.full(points.shape[0], np.nan)

feature = GeologicalFeature("field", builder=None, regions=[], interpolator=NanInterpolator())
values = feature.evaluate_value(np.zeros((3, 3)), fillnan="nearest")
assert np.all(np.isnan(values))
Loading