Skip to content

Commit 5d62a09

Browse files
authored
fix(data): cast SlidingPatchWSIDataset locations to int for numpy 2.x (#9136)
Fixes #9135. ### Description `SlidingPatchWSIDataset` builds `ProbMapKeys.LOCATION` with `np.round(...)` and never casts back to int, so `ProbMapProducer` indexes the probability map with floats and numpy 2.x raises `IndexError: only integers ... are valid indices`. Cast at the source so the metadata matches `MaskedPatchWSIDataset`, which already calls `.astype(int)`, and keep a defensive coercion in the handler for datasets that still supply floats. The existing tests only supply integer locations; add a float-location variant of each, which reproduces the error without the handler change. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [x] New tests added to cover the changes. --------- Signed-off-by: Patel, Nilaykumar K <nilapate@amd.com>
1 parent e660018 commit 5d62a09

4 files changed

Lines changed: 32 additions & 7 deletions

File tree

‎monai/data/wsi_datasets.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def _evaluate_patch_locations(self, sample):
306306
)
307307
)
308308
# convert locations to mask_location
309-
mask_locations = np.round((patch_locations + patch_size_0 // 2) / float(mask_ratio))
309+
mask_locations = np.round((patch_locations + patch_size_0 // 2) / float(mask_ratio)).astype(int)
310310

311311
# fill out samples with location and metadata
312312
sample[WSIPatchKeys.SIZE.value] = patch_size

‎monai/handlers/probability_maps.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,9 @@ def __call__(self, engine: Engine) -> None:
108108
locs = engine.state.batch[CommonKeys.IMAGE].meta[ProbMapKeys.LOCATION]
109109
probs = engine.state.output[self.prob_key]
110110
for name, loc, prob in zip(names, locs, probs):
111-
self.prob_map[name][tuple(loc)] = prob
111+
# numpy 2.x rejects non-integer array indices, so coerce here for datasets that
112+
# still supply float locations. The bundled WSI datasets already emit integers.
113+
self.prob_map[name][tuple(int(i) for i in loc)] = prob
112114
with self.lock:
113115
self.counter[name] -= 1
114116
if self.counter[name] == 0:

‎tests/data/test_sliding_patch_wsi_dataset.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from parameterized import parameterized
2222

2323
from monai.data import SlidingPatchWSIDataset
24-
from monai.utils import WSIPatchKeys, optional_import, set_determinism
24+
from monai.utils import ProbMapKeys, WSIPatchKeys, optional_import, set_determinism
2525
from tests.test_utils import download_url_or_skip_test, testing_data_config
2626

2727
set_determinism(0)
@@ -250,6 +250,9 @@ def test_read_patches_large(self, input_parameters, expected):
250250
steps = [round(expected[i]["ratio"] * s) for s in expected[i]["patch_size"]]
251251
expected_location = tuple(expected[i]["step_loc"][j] * steps[j] for j in range(len(steps)))
252252
assert_array_equal(sample["image"].meta[WSIPatchKeys.LOCATION], expected_location)
253+
# `ProbMapProducer` uses these as probability-map indices, which numpy 2.x
254+
# only accepts as integers.
255+
self.assertTrue(np.issubdtype(sample["image"].meta[ProbMapKeys.LOCATION].dtype, np.integer))
253256

254257

255258
@skipUnless(has_cucim, "Requires cucim")

‎tests/handlers/test_handler_prob_map_producer.py‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,21 @@ def __getitem__(self, index):
6565
return {"image": MetaTensor(x=image, meta=metadata), "pred": index + 1}
6666

6767

68+
class FloatLocationDataset(TestDataset):
69+
"""A test fixture whose probability-map locations are floats.
70+
71+
The bundled WSI datasets emit integer locations, so this stands in for a third-party
72+
dataset that does not, which the handler still has to index the probability map with.
73+
"""
74+
75+
__test__ = False # indicate to pytest that this class is not intended for collection
76+
77+
def __init__(self, name, size):
78+
super().__init__(name, size)
79+
for sample in self.data:
80+
sample[ProbMapKeys.LOCATION.value] = sample[ProbMapKeys.LOCATION.value].astype(float)
81+
82+
6883
class TestEvaluator(Evaluator):
6984
__test__ = False # indicate to pytest that this class is not intended for collection
7085

@@ -73,10 +88,7 @@ def _iteration(self, engine, batchdata):
7388

7489

7590
class TestHandlerProbMapGenerator(unittest.TestCase):
76-
@parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2])
77-
def test_prob_map_generator(self, name, size):
78-
# set up dataset
79-
dataset = TestDataset(name, size)
91+
def run_and_check(self, dataset, name, size):
8092
batch_size = 2
8193
data_loader = DataLoader(dataset, batch_size=batch_size)
8294

@@ -106,6 +118,14 @@ def inference(engine, batch):
106118
self.assertListEqual(np.vstack(prob_map.nonzero()).T.tolist(), [[i, i + 1] for i in range(size)])
107119
self.assertListEqual(prob_map[prob_map.nonzero()].tolist(), [i + 1 for i in range(size)])
108120

121+
@parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2])
122+
def test_prob_map_generator(self, name, size):
123+
self.run_and_check(TestDataset(name, size), name, size)
124+
125+
@parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2])
126+
def test_prob_map_generator_float_locations(self, name, size):
127+
self.run_and_check(FloatLocationDataset(name, size), name, size)
128+
109129

110130
if __name__ == "__main__":
111131
unittest.main()

0 commit comments

Comments
 (0)