Skip to content

BUG: nan segfault in KDTree, reject non-finite input #18230

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

Merged
merged 3 commits into from
May 21, 2023
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
3 changes: 3 additions & 0 deletions scipy/spatial/_ckdtree.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,9 @@ cdef class cKDTree:
if data.ndim != 2:
raise ValueError("data must be 2 dimensions")

if not np.isfinite(data).all():
raise ValueError("data must be finite, check for nan or inf values")

self.data = data
cself.n = data.shape[0]
cself.m = data.shape[1]
Expand Down
21 changes: 17 additions & 4 deletions scipy/spatial/tests/test_kdtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -1464,7 +1464,20 @@ def test_kdtree_nan():
vals = [1, 5, -10, 7, -4, -16, -6, 6, 3, -11]
n = len(vals)
data = np.concatenate([vals, np.full(n, np.nan)])[:, None]

query_with_nans = KDTree(data).query_pairs(2)
query_without_nans = KDTree(data[:n]).query_pairs(2)
assert query_with_nans == query_without_nans
with pytest.raises(ValueError, match="must be finite"):
KDTree(data)


def test_gh_18223():
rng = np.random.default_rng(12345)
coords = rng.uniform(size=(100, 3), low=0.0, high=0.1)
KDTree(coords, balanced_tree=False, compact_nodes=False)
coords[0, :] = np.nan
with pytest.raises(ValueError, match="must be finite"):
KDTree(coords, balanced_tree=True, compact_nodes=False)
with pytest.raises(ValueError, match="must be finite"):
KDTree(coords, balanced_tree=False, compact_nodes=True)
with pytest.raises(ValueError, match="must be finite"):
KDTree(coords, balanced_tree=True, compact_nodes=True)
with pytest.raises(ValueError, match="must be finite"):
KDTree(coords, balanced_tree=False, compact_nodes=False)