Skip to content

Commit bec6188

Browse files
Clip searchsorted result to valid range
When np.searchsorted doesn't find an index, it returns N, where N is the length of the array being searched. This causes indexing errors. The `valid` mask ensures we're not using invalid values where pos >= len(keys), however, since pos is still used in other indexing operations, we clip to avoid oob indexing errors
1 parent fb62f43 commit bec6188

1 file changed

Lines changed: 5 additions & 1 deletion

File tree

parcels/spatialhash.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,11 @@ def query(self, y, x):
339339
pos = np.searchsorted(keys, query_codes) # pos is shape (num_queries,)
340340

341341
# Valid hits: inside range with finite query coordinates and query codes give exact morton code match.
342-
valid = (pos < len(keys)) & np.isfinite(x) & np.isfinite(y) & (query_codes == keys[pos])
342+
valid = (pos < len(keys)) & np.isfinite(x) & np.isfinite(y)
343+
# Clip pos to valid range to avoid out-of-bounds indexing
344+
pos = np.clip(pos, 0, len(keys) - 1)
345+
# Further filter out false positives from searchsorted by checking for exact code match
346+
valid[valid] &= query_codes[valid] == keys[pos[valid]]
343347

344348
# Pre-allocate i and j indices of the best match for each query
345349
# Default values to -1 (no match case)

0 commit comments

Comments
 (0)