-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathtest_multi_task_segmentor.py
More file actions
1845 lines (1540 loc) · 60.1 KB
/
test_multi_task_segmentor.py
File metadata and controls
1845 lines (1540 loc) · 60.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Test MultiTaskSegmentor."""
from __future__ import annotations
import json
import shutil
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, Final
from unittest.mock import MagicMock
import dask.array as da
import numpy as np
import psutil
import pytest
import torch
import zarr
from click.testing import CliRunner
from shapely import Point, STRtree
from tqdm.auto import tqdm
from zarr.storage import LocalStore
from tiatoolbox import cli
from tiatoolbox.annotation import SQLiteStore
from tiatoolbox.models import IOSegmentorConfig
from tiatoolbox.models.architecture import fetch_pretrained_weights
from tiatoolbox.models.engine.multi_task_segmentor import (
DaskDelayedJSONStore,
MultiTaskSegmentor,
_clear_zarr,
_get_sel_indices_margin_lines,
_post_save_json_store,
_process_instance_predictions,
_save_multitask_vertical_to_cache,
merge_multitask_vertical_chunkwise,
)
from tiatoolbox.utils import download_data, imwrite
from tiatoolbox.utils import env_detection as toolbox_env
from tiatoolbox.wsicore import WSIReader
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Sequence
OutputType = dict[str, Any] | Any
device = "cuda" if toolbox_env.has_gpu() else "cpu"
def test_mtsegmentor_init() -> None:
"""Tests MultiTaskSegmentor initialization."""
segmentor = MultiTaskSegmentor(model="hovernetplus-oed", device=device)
assert isinstance(segmentor, MultiTaskSegmentor)
assert isinstance(segmentor.model, torch.nn.Module)
def test_mtsegmentor_patches(remote_sample: Callable, track_tmp_path: Path) -> None:
"""Tests MultiTaskSegmentor on image patches."""
mtsegmentor = MultiTaskSegmentor(
model="hovernetplus-oed", batch_size=32, verbose=False, device=device
)
mini_wsi_svs = Path(remote_sample("wsi4_1k_1k_svs"))
mini_wsi = WSIReader.open(mini_wsi_svs)
size = (256, 256)
resolution = 0.50
units: Final = "mpp"
patch1 = mini_wsi.read_rect(
location=(0, 0), size=size, resolution=resolution, units=units
)
patch2 = mini_wsi.read_rect(
location=(512, 512), size=size, resolution=resolution, units=units
)
patch3 = np.zeros_like(patch1)
patches = np.stack([patch1, patch2, patch3], axis=0)
assert not mtsegmentor.patch_mode
output_dict = mtsegmentor.run(
images=patches,
return_probabilities=True,
return_labels=False,
device=device,
patch_mode=True,
return_predictions=(True, True),
)
expected_counts_nuclei = [95, 33, 0]
assert_output_lengths(
output_dict["nuclei_segmentation"],
expected_counts_nuclei,
fields=["box", "centroid", "contours", "prob", "type"],
)
assert_predictions_and_boxes(
output_dict["nuclei_segmentation"], expected_counts_nuclei, is_zarr=False
)
expected_counts_layer = [1, 1, 0]
assert_output_lengths(
output_dict["layer_segmentation"],
expected_counts_layer,
fields=["contours", "type"],
)
assert_predictions_and_boxes(
output_dict["layer_segmentation"], expected_counts_layer, is_zarr=False
)
# Zarr output comparison
processed_predictions = convert_to_dask(output_dict)
output_zarr = mtsegmentor.save_predictions(
processed_predictions=processed_predictions.copy(),
output_type="zarr",
save_path=track_tmp_path / "patch_output_zarr" / "output.zarr",
return_probabilities=False,
return_predictions=(True, True),
)
output_zarr_ = zarr.open(output_zarr, mode="r")
assert_output_lengths(
output_zarr_["nuclei_segmentation"],
expected_counts_nuclei,
fields=["box", "centroid", "contours", "prob", "type"],
)
assert_output_lengths(
output_zarr_["layer_segmentation"],
expected_counts_layer,
fields=["contours", "type"],
)
assert_output_equal(
output_zarr_["nuclei_segmentation"],
output_dict["nuclei_segmentation"],
fields=["box", "centroid", "contours", "prob", "type"],
indices_a=[0, 1, 2],
indices_b=[0, 1, 2],
)
assert_output_equal(
output_zarr_["layer_segmentation"],
output_dict["layer_segmentation"],
fields=["contours", "type"],
indices_a=[0, 1, 2],
indices_b=[0, 1, 2],
)
# AnnotationStore output comparison
output_ann = mtsegmentor.save_predictions(
processed_predictions=processed_predictions.copy(),
output_type="annotationstore",
save_path=track_tmp_path
/ "patch_output_annotationstore"
/ (output_zarr.stem + "_ann.db"),
return_probabilities=False,
return_predictions=(True, True),
)
assert len(output_ann) == 6
fields_nuclei = ["box", "centroid", "contours", "prob", "type"]
fields_layer = ["contours", "type"]
for task_name in mtsegmentor.tasks:
fields = fields_nuclei if task_name == "nuclei_segmentation" else fields_layer
output_ann_ = [p for p in output_ann if p.name.endswith(f"{task_name}.db")]
expected_counts = (
expected_counts_nuclei
if task_name == "nuclei_segmentation"
else expected_counts_layer
)
assert_annotation_store_patch_output(
inputs=patches,
output_ann=output_ann_,
output_dict=output_dict[task_name],
track_tmp_path=track_tmp_path,
fields=fields,
expected_counts=expected_counts,
task_name=task_name,
class_dict=mtsegmentor._get_model_attr("class_dict"),
)
# QuPath JSON does not have fields
fields_nuclei = ["contours", "prob", "type"]
# QuPath output comparison
output_json = mtsegmentor.save_predictions(
processed_predictions=processed_predictions.copy(),
output_type="qupath",
save_path=track_tmp_path
/ "patch_output_qupath"
/ (output_zarr.stem + "_qupath.db"),
return_probabilities=False,
return_predictions=(True, True),
)
assert len(output_json) == 6
for task_name in mtsegmentor.tasks:
fields = fields_nuclei if task_name == "nuclei_segmentation" else fields_layer
output_json_ = [p for p in output_json if p.name.endswith(f"{task_name}.json")]
expected_counts = (
expected_counts_nuclei
if task_name == "nuclei_segmentation"
else expected_counts_layer
)
assert_qupath_json_patch_output(
inputs=patches,
output_json=output_json_,
output_dict=output_dict[task_name],
track_tmp_path=track_tmp_path,
fields=fields,
expected_counts=expected_counts,
task_name=task_name,
)
def test_mtsegmentor_tiles_no_metadata(track_tmp_path: Path) -> None:
"""Tests MultiTaskSegmentor on a tile with no metadata."""
img_file_name = track_tmp_path / "tcga_hnscc.png"
download_data(
"https://huggingface.co/datasets/TIACentre/TIAToolBox_Remote_Samples/resolve/main/sample_imgs/tcga_hnscc.png",
img_file_name,
)
# Tile prediction
multi_segmentor = MultiTaskSegmentor(
model="hovernetplus-oed",
num_workers=0,
batch_size=4,
)
tile_output = multi_segmentor.run(
[img_file_name],
save_dir=track_tmp_path / "sample_tile_results",
patch_mode=False,
device=device,
auto_get_mask=False,
wsireader_kwargs={"mpp": 0.25}, # use this mpp to run test faster
return_predictions=(True, True),
)
assert tile_output[img_file_name].exists()
output_zarr = zarr.open(tile_output[img_file_name], mode="r")
assert "nuclei_segmentation" in output_zarr
assert "layer_segmentation" in output_zarr
assert "predictions" in output_zarr["layer_segmentation"]
assert "predictions" in output_zarr["nuclei_segmentation"]
fields_layer = ["contours", "type"]
assert (field in output_zarr["layer_segmentation"] for field in fields_layer)
fields_nuclei = ["box", "centroid", "contours", "prob", "type"]
assert (field in output_zarr["nuclei_segmentation"] for field in fields_nuclei)
assert len(output_zarr["layer_segmentation"]["contours"][:]) == 12
assert len(output_zarr["nuclei_segmentation"]["contours"][:]) == 1299
def test_single_task_mtsegmentor(
remote_sample: Callable,
track_tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Tests MultiTaskSegmentor on single task output."""
mtsegmentor = MultiTaskSegmentor(
model="hovernet_fast-pannuke", batch_size=32, verbose=False, device=device
)
mini_wsi_svs = Path(remote_sample("wsi4_1k_1k_svs"))
mini_wsi = WSIReader.open(mini_wsi_svs)
size = (256, 256)
resolution = 0.25
units: Final = "mpp"
patch1 = mini_wsi.read_rect(
location=(0, 0), size=size, resolution=resolution, units=units
)
patch2 = mini_wsi.read_rect(
location=(512, 512), size=size, resolution=resolution, units=units
)
patch3 = np.zeros_like(patch1)
imwrite(track_tmp_path / "patch1.png", patch1)
imwrite(track_tmp_path / "patch2.png", patch2)
imwrite(track_tmp_path / "patch3.png", patch3)
inputs = [
track_tmp_path / "patch1.png",
track_tmp_path / "patch2.png",
track_tmp_path / "patch3.png",
]
assert not mtsegmentor.patch_mode
output_dict = mtsegmentor.run(
images=inputs,
return_probabilities=True,
return_labels=False,
device=device,
patch_mode=True,
)
expected_counts_nuclei = [41, 17, 0]
assert_output_lengths(
output_dict,
expected_counts_nuclei,
fields=["box", "centroid", "contours", "prob", "type"],
)
assert_predictions_and_boxes(output_dict, expected_counts_nuclei, is_zarr=False)
assert next(iter(mtsegmentor.tasks)) == "nuclei_segmentation"
assert len(mtsegmentor.tasks) == 1
# Zarr output comparison
processed_predictions = convert_to_dask_single_task(
output_dict=output_dict,
task_name="nuclei_segmentation",
)
_ = zarr.open(str(track_tmp_path / "patch_output_zarr" / "output.zarr"), mode="w")
output_zarr = zarr.open(
mtsegmentor.save_predictions(
processed_predictions=processed_predictions.copy(),
output_type="zarr",
save_path=track_tmp_path / "patch_output_zarr" / "output.zarr",
return_probabilities=False,
return_predictions=(True, True),
),
mode="r",
)
assert_output_lengths(
output_zarr,
expected_counts_nuclei,
fields=["box", "centroid", "contours", "prob", "type"],
)
assert_output_equal(
output_zarr,
output_dict,
fields=["box", "centroid", "contours", "prob", "type"],
indices_a=[0, 1, 2],
indices_b=[0, 1, 2],
)
# AnnotationStore output comparison
mtsegmentor.drop_keys = []
# Triggers Return Coordinates for patch inference
output_ann = mtsegmentor.run(
images=inputs,
return_probabilities=True,
return_labels=False,
device=device,
patch_mode=True,
save_dir=track_tmp_path / "patch_output_annotationstore",
return_predictions=(True,),
output_type="annotationstore",
)
assert len(output_ann) == 3
class_dict_ = mtsegmentor._get_model_attr("class_dict")
assert_annotation_store_patch_output(
inputs=inputs,
output_ann=output_ann,
output_dict=output_dict,
track_tmp_path=track_tmp_path,
fields=["box", "centroid", "contours", "prob", "type"],
expected_counts=expected_counts_nuclei,
task_name=None,
class_dict=class_dict_["nuclei_segmentation"],
)
assert (track_tmp_path / "patch_output_annotationstore" / "output.zarr").exists()
zarr_group = zarr.open(
str(track_tmp_path / "patch_output_annotationstore" / "output.zarr"),
mode="r",
)
assert "probabilities" in zarr_group
assert "predictions" in zarr_group
fields = ["box", "centroid", "contours", "prob", "type"]
for field in fields:
assert field not in zarr_group
assert "Probability maps cannot be saved as AnnotationStore or JSON" in caplog.text
# QuPath output comparison
mtsegmentor.drop_keys = []
output_json = mtsegmentor.run(
images=inputs,
return_probabilities=True,
return_labels=False,
device=device,
patch_mode=True,
save_dir=track_tmp_path / "patch_output_qupath",
return_predictions=(False,),
output_type="qupath",
)
assert len(output_json) == 3
assert_qupath_json_patch_output(
inputs=inputs,
output_json=output_json,
output_dict=output_dict,
track_tmp_path=track_tmp_path,
fields=["box", "centroid", "contours", "prob", "type"],
expected_counts=expected_counts_nuclei,
task_name=None,
)
assert (track_tmp_path / "patch_output_qupath" / "output.zarr").exists()
zarr_group = zarr.open(
str(track_tmp_path / "patch_output_qupath" / "output.zarr"),
mode="r",
)
assert "probabilities" in zarr_group
fields = ["box", "centroid", "contours", "prob", "type", "predictions"]
for field in fields:
assert field not in zarr_group
assert "Probability maps cannot be saved as AnnotationStore or JSON" in caplog.text
def test_wsi_mtsegmentor_correct_nonsquare_shape(
remote_sample: Callable,
track_tmp_path: Path,
) -> None:
"""Test MultiTaskSegmentor output shape for non-square WSIs with zarr output."""
# Using this image to check for non-square output.
svs_1_small = remote_sample("svs-1-small")
# masking the image for shorter runtime
svs_1_small = WSIReader.open(svs_1_small)
mask = np.zeros(
svs_1_small.slide_dimensions(resolution=1.25, units="power")[::-1],
dtype=np.uint8,
)
mask[150:160, 50:75] = 1
mtsegmentor = MultiTaskSegmentor(
model="hovernetplus-oed",
batch_size=64,
verbose=False,
num_workers=1,
)
ioconfig = mtsegmentor.ioconfig
# Return Probabilities is True
output_full = mtsegmentor.run(
# Use rectangular (not square) to test output shape
images=[svs_1_small],
masks=[mask],
return_probabilities=True,
return_labels=False,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_out_full",
batch_size=2,
output_type="zarr",
ioconfig=ioconfig,
return_predictions=(True, True), # True for both tasks.
)
output_full_ = zarr.open(output_full[svs_1_small.input_path], mode="r")
assert 0.24 < np.mean(output_full_["nuclei_segmentation"]["predictions"][:]) < 0.26
assert 0.03 < np.mean(output_full_["layer_segmentation"]["predictions"][:]) < 0.04
assert "probabilities" in output_full_
assert "canvas" not in output_full_["nuclei_segmentation"]
assert "count" not in output_full_["nuclei_segmentation"]
assert "canvas" not in output_full_["layer_segmentation"]
assert "count" not in output_full_["layer_segmentation"]
# Verify output shape
expected_shape = svs_1_small.slide_dimensions(
**mtsegmentor.ioconfig.highest_input_resolution
)[::-1]
assert np.all(
output_full_["nuclei_segmentation"]["predictions"][:].shape == expected_shape
)
assert np.all(
output_full_["layer_segmentation"]["predictions"][:].shape == expected_shape
)
# Redefine tile size to force tile-based processing.
# 350 x 350 forces tile mode 3 (overlap)
ioconfig.tile_shape = (500, 500)
mtsegmentor.drop_keys = []
# Return Probabilities is False
output_tile = mtsegmentor.run(
# Use rectangular (not square) to test output shape
images=[svs_1_small],
masks=[mask],
return_probabilities=False,
return_labels=False,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_out_tile",
batch_size=2,
output_type="zarr",
ioconfig=ioconfig,
return_predictions=(True, True), # True for both tasks.
)
output_tile_ = zarr.open(output_tile[svs_1_small.input_path], mode="r")
assert 0.23 < np.mean(output_tile_["nuclei_segmentation"]["predictions"][:]) < 0.25
assert 0.03 < np.mean(output_tile_["layer_segmentation"]["predictions"][:]) < 0.04
assert "probabilities" not in output_tile_
assert "canvas" not in output_tile_["nuclei_segmentation"]
assert "count" not in output_tile_["nuclei_segmentation"]
assert "canvas" not in output_tile_["layer_segmentation"]
assert "count" not in output_tile_["layer_segmentation"]
# Verify output shape
expected_shape = svs_1_small.slide_dimensions(
**mtsegmentor.ioconfig.highest_input_resolution
)[::-1]
assert np.all(
output_tile_["nuclei_segmentation"]["predictions"][:].shape == expected_shape
)
assert np.all(
output_tile_["layer_segmentation"]["predictions"][:].shape == expected_shape
)
def test_wsi_mtsegmentor_zarr(
remote_sample: Callable,
track_tmp_path: Path,
) -> None:
"""Test MultiTaskSegmentor for WSIs with zarr output."""
wsi4_1k_1k_svs = remote_sample("wsi4_1k_1k_svs")
mtsegmentor = MultiTaskSegmentor(
model="hovernetplus-oed",
batch_size=64,
verbose=False,
num_workers=1,
)
ioconfig = mtsegmentor.ioconfig
# Force calculation without tile-based processing.
ioconfig.tile_shape = (1200, 1200)
# Return Probabilities is False
output_full = mtsegmentor.run(
images=[wsi4_1k_1k_svs],
return_probabilities=False,
return_labels=False,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_out_full",
batch_size=2,
output_type="zarr",
ioconfig=ioconfig,
return_predictions=(True, True), # True for both tasks.
)
output_full_ = zarr.open(output_full[wsi4_1k_1k_svs], mode="r")
assert 64 < np.mean(output_full_["nuclei_segmentation"]["predictions"][:]) < 68
assert 0.88 < np.mean(output_full_["layer_segmentation"]["predictions"][:]) < 0.92
assert "probabilities" not in output_full_
assert "canvas" not in output_full_["nuclei_segmentation"]
assert "count" not in output_full_["nuclei_segmentation"]
assert "canvas" not in output_full_["layer_segmentation"]
assert "count" not in output_full_["layer_segmentation"]
assert np.all(
output_full_["nuclei_segmentation"]["predictions"][:].shape == (504, 504)
)
assert np.all(
output_full_["layer_segmentation"]["predictions"][:].shape == (504, 504)
)
# Redefine tile size to force tile-based processing.
# 350 x 350 forces tile mode 3 (overlap)
ioconfig.tile_shape = (350, 350)
mtsegmentor.drop_keys = []
# Return predictions is False
output_tile = mtsegmentor.run(
images=[wsi4_1k_1k_svs],
return_probabilities=False,
return_labels=False,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_out_tile_based",
batch_size=2,
output_type="zarr",
memory_threshold=0, # Memory threshold forces tile_mode
ioconfig=ioconfig,
# HoVerNet does not return predictions once
# contours have been calculated in original implementation.
# It's also not straight forward to keep track of instances
# Prediction masks can be tracked and saved as for layer segmentation in
# HoVerNet Plus.
return_predictions=(False, True),
verbose=False,
)
output_tile_ = zarr.open(output_tile[wsi4_1k_1k_svs], mode="r")
assert "predictions" not in output_tile_["nuclei_segmentation"]
assert 0.87 < np.mean(output_tile_["layer_segmentation"]["predictions"][:]) < 0.91
predictions_tile = output_tile_["layer_segmentation"]["predictions"][:]
predictions_full = output_full_["layer_segmentation"]["predictions"][:]
overlap_pct = np.mean(predictions_full == predictions_tile) * 100
assert overlap_pct > 99
assert len(output_full_["layer_segmentation"]["contours"][:]) == len(
output_tile_["layer_segmentation"]["contours"][:]
)
assert (
len(output_tile_["nuclei_segmentation"]["contours"][:])
/ len(output_full_["nuclei_segmentation"]["contours"][:])
> 0.9
)
def test_multi_input_wsi_mtsegmentor_zarr(
remote_sample: Callable,
track_tmp_path: Path,
) -> None:
"""Test MultiTaskSegmentor for multiple WSIs with zarr output."""
wsi4_512_512_svs = Path(remote_sample("wsi4_512_512_svs"))
wsi4_512_512_svs_2 = wsi4_512_512_svs.parent / (
wsi4_512_512_svs.stem + "_2" + wsi4_512_512_svs.suffix
)
wsi4_512_512_svs_2 = Path(
shutil.copy(str(wsi4_512_512_svs), str(wsi4_512_512_svs_2))
)
# Return Probabilities is True
# Add multi-input test
# Use single task output from hovernet
mtsegmentor = MultiTaskSegmentor(
model="hovernet_fast-pannuke",
batch_size=64,
verbose=False,
num_workers=1,
)
output = mtsegmentor.run(
images=[wsi4_512_512_svs_2, wsi4_512_512_svs],
return_probabilities=True,
return_labels=False,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "return_probabilities_check",
batch_size=2,
output_type="zarr",
stride_shape=(160, 160),
verbose=True,
return_predictions=(True,),
)
output_ = zarr.open(output[wsi4_512_512_svs], mode="r")
assert 37 < np.mean(output_["predictions"][:]) < 41
assert "probabilities" in output_
assert "canvas" not in output_
assert "count" not in output_
output_ = zarr.open(output[wsi4_512_512_svs_2], mode="r")
assert 37 < np.mean(output_["predictions"][:]) < 41
assert "probabilities" in output_
assert "canvas" not in output_
assert "count" not in output_
def test_wsi_segmentor_annotationstore(
remote_sample: Callable, track_tmp_path: Path
) -> None:
"""Test MultiTaskSegmentor for WSIs with AnnotationStore output."""
wsi4_512_512_svs = remote_sample("wsi4_512_512_svs")
# testing different configuration for hovernet.
# kumar only has two probability maps
model_name = "hovernet_original-kumar"
mtsegmentor = MultiTaskSegmentor(
model=model_name,
batch_size=32,
verbose=False,
)
class_dict = mtsegmentor._get_model_attr("class_dict")
# Return Probabilities is False
output = mtsegmentor.run(
images=[wsi4_512_512_svs],
return_probabilities=False,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_out_check",
verbose=True,
output_type="annotationstore",
class_dict=class_dict,
memory_threshold=0,
)
for output_ in output[wsi4_512_512_svs]:
assert output_.suffix != ".zarr"
store_file_name = f"{wsi4_512_512_svs.stem}.db"
store_file_path = track_tmp_path / "wsi_out_check" / store_file_name
assert store_file_path.exists()
assert store_file_path == output[wsi4_512_512_svs][0]
def test_wsi_segmentor_qupath(remote_sample: Callable, track_tmp_path: Path) -> None:
"""Test MultiTaskSegmentor for WSIs with AnnotationStore output."""
wsi4_512_512_svs = remote_sample("wsi4_512_512_svs")
# testing different configuration for hovernet.
# kumar only has two probability maps
# Need to test Null values in JSON output.
model_name = "hovernet_original-kumar"
mtsegmentor = MultiTaskSegmentor(
model=model_name,
batch_size=32,
verbose=False,
)
class_dict = mtsegmentor.model.class_dict
# Return Probabilities is False
output = mtsegmentor.run(
images=[wsi4_512_512_svs],
return_probabilities=False,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_out_check",
verbose=True,
output_type="qupath",
class_dict=class_dict,
memory_threshold=0,
)
for output_ in output[wsi4_512_512_svs]:
assert output_.suffix != ".zarr"
json_file_name = f"{wsi4_512_512_svs.stem}.json"
json_file_name = track_tmp_path / "wsi_out_check" / json_file_name
assert json_file_name.exists()
assert json_file_name == output[wsi4_512_512_svs][0]
# Weights not used after this test
weights_path = Path(fetch_pretrained_weights(model_name=model_name))
weights_path.unlink()
def test_wsi_segmentor_annotationstore_probabilities(
remote_sample: Callable, track_tmp_path: Path, caplog: pytest.CaptureFixture
) -> None:
"""Test MultiTaskSegmentor with AnnotationStore and probabilities output."""
wsi4_512_512_svs = remote_sample("wsi4_512_512_svs")
# Return Probabilities is True
mtsegmentor = MultiTaskSegmentor(
model="hovernetplus-oed",
batch_size=32,
verbose=False,
)
output = mtsegmentor.run(
images=[wsi4_512_512_svs],
return_probabilities=True,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_prob_out_check",
verbose=True,
output_type="annotationstore",
)
assert "Probability maps cannot be saved as AnnotationStore or JSON." in caplog.text
zarr_group = zarr.open(output[wsi4_512_512_svs][0], mode="r")
assert "probabilities" in zarr_group
for task_name in mtsegmentor.tasks:
store_file_name = f"{wsi4_512_512_svs.stem}_{task_name}.db"
store_file_path = track_tmp_path / "wsi_prob_out_check" / store_file_name
assert store_file_path.exists()
assert store_file_path in output[wsi4_512_512_svs]
assert task_name not in zarr_group
def test_raise_value_error_return_labels_wsi(
remote_sample: Callable,
track_tmp_path: Path,
) -> None:
"""Tests MultiTaskSegmentor return_labels error."""
wsi4_512_512_svs = remote_sample("wsi4_512_512_svs")
mtsegmentor = MultiTaskSegmentor(model="hovernetplus-oed", device=device)
with pytest.raises(
ValueError,
match=r".*return_labels` is not supported for MultiTaskSegmentor.",
):
_ = mtsegmentor.run(
images=[wsi4_512_512_svs],
return_probabilities=False,
return_labels=True,
device=device,
patch_mode=False,
save_dir=track_tmp_path / "wsi_out_check",
batch_size=2,
output_type="zarr",
)
# inst_dict must contain boxes
inst_dict = {
1: {"box": np.array([81, 0, 96, 9])},
2: {"box": np.array([138, 0, 151, 8])},
}
invalid_tile_mode = 99 # not in [0,1,2,3]
ioconfig = mtsegmentor.ioconfig
ioconfig.margin = 128
with pytest.raises(ValueError, match=r".*Unknown tile mode.*"):
_get_sel_indices_margin_lines(
ioconfig=ioconfig,
tile_shape=(492, 492),
tile_flag=(0, 1, 0, 1),
tile_mode=invalid_tile_mode,
tile_tl=(0, 0),
inst_dict=inst_dict,
)
def test_clear_zarr() -> None:
"""Test _clear_zarr working appropriately.
This test only covers scenarios which are not feasible to run on GitHub Actions.
"""
store = zarr.storage.MemoryStore()
root = zarr.group(store=store)
# Create a dummy zarr array for probabilities_zarr
probabilities_zarr = root.create_array(
"probabilities",
data=np.zeros((5, 3, 3)),
)
idx = 2
chunk_shape = (1,)
probabilities_shape = (3, 3)
result = _clear_zarr(
probabilities_zarr=probabilities_zarr,
probabilities_da=None,
zarr_group=root,
idx=idx,
chunk_shape=chunk_shape,
probabilities_shape=probabilities_shape,
)
# Ensure the keys still exist but the specific index was removed
assert "canvas" not in root
assert "count" not in root
assert isinstance(result, da.Array)
result_ = _clear_zarr(
probabilities_zarr=None,
probabilities_da=result,
zarr_group=root,
idx=idx,
chunk_shape=chunk_shape,
probabilities_shape=probabilities_shape,
)
assert np.all(result_.compute() == result.compute())
def test_vertical_save_branch_without_patch(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test saving to cache if memory threshold is breached for vertical merge."""
idx = 0
class FakeVM:
"""Fake psutil.virtual_memory() with extremely low free memory."""
available = 0 # force used_percent > memory_threshold
monkeypatch.setattr(psutil, "virtual_memory", FakeVM)
# --- Real dask array ---
da_arr = da.from_array(np.array([[1, 2, 3]]), chunks=(1, 3))
probabilities_da = [da_arr]
# --- probabilities_zarr slot is None to trigger the branch ---
probabilities_zarr = [None]
# --- Real numpy array for shape/dtype ---
probabilities = np.zeros((1, 3))
tqdm_loop = tqdm(
range(1),
)
# --- Call function ---
new_zarr, new_da, zarr_group = _save_multitask_vertical_to_cache(
probabilities_zarr=probabilities_zarr,
probabilities_da=probabilities_da,
zarr_group=None,
probabilities=probabilities,
idx=idx,
tqdm_loop=tqdm_loop,
save_path=tmp_path / "cache.zarr",
chunk_shape=(1,),
memory_threshold=0, # ensure branch triggers
)
# probabilities_da must be set to None
assert new_da[idx] is None
# new_zarr must be a real zarr array
assert isinstance(new_zarr[idx], zarr.Array)
assert zarr_group is not None
# Data was written correctly
assert np.array_equal(new_zarr[idx][:], np.array([[1, 2, 3]]))
def test_multitask_vertical_merge_continues_after_zarr_spill(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test multitask vertical merge appends all chunks after spilling to Zarr."""
class FakeVM:
"""Fake psutil.virtual_memory() with extremely low available memory."""
available = 1
monkeypatch.setattr(psutil, "virtual_memory", FakeVM)
values = np.arange(8 * 3, dtype=np.float32).reshape(8, 3, 1)
canvas = [da.from_array(values, chunks=(2, 3, 1))]
count = [da.from_array(np.ones_like(values), chunks=(2, 3, 1))]
output_locs_y = np.array([[0, 2], [2, 4], [4, 6], [6, 8]])
result = merge_multitask_vertical_chunkwise(
canvas=canvas,
count=count,
output_locs_y_=output_locs_y,
zarr_group=None,
save_path=tmp_path / "vertical.zarr",
memory_threshold=0,
output_shape=(8, 3),
verbose=False,
)
assert result[0].shape == values.shape
assert np.array_equal(result[0].compute(), values)
def test_qupath_feature_class_dict_lookup_fails() -> None:
"""Test qupath_feature_class_dict lookup fails."""
qupath_json = DaskDelayedJSONStore.__new__(DaskDelayedJSONStore)
qupath_json._contours = [np.array([[0, 0], [1, 0], [1, 1]])]
qupath_json._processed_predictions = {"type": np.array([5], dtype=object)}
class_dict = {0: "A", 1: "B"} # does NOT contain 5
class_colors = {0: [255, 0, 0], 1: [0, 255, 0]} # also does NOT contain 5
feat = qupath_json._build_single_qupath_feature(
i=0,
class_dict=class_dict,
origin=(0, 0),
scale_factor=(1, 1),
class_colors=class_colors,
)
# type should fall back to raw value (5)
assert feat["properties"]["type"] == 5
# classification block should NOT appear
assert "classification" not in feat["properties"]
def test_qupath_feature_classification_block_skipped() -> None:
"""Test qupath_feature_classification_block_skipped fails."""
qupath_json = DaskDelayedJSONStore.__new__(DaskDelayedJSONStore)
qupath_json._contours = [np.array([[0, 0], [1, 0], [1, 1]])]
qupath_json._processed_predictions = {"type": np.array([1], dtype=object)}
class_dict = {1: "Tumor"}
class_colors = {0: [255, 0, 0]} # does NOT contain 1
feat = qupath_json._build_single_qupath_feature(
i=0,
class_dict=class_dict,
origin=(0, 0),
scale_factor=(1, 1),
class_colors=class_colors,
)
assert feat["properties"]["type"] == "Tumor"
assert "classification" not in feat["properties"]
def test_compute_qupath_json_valid_ids_not_empty(track_tmp_path: Path) -> None:
"""Test compute_qupath_json valid ids not empty."""
store = DaskDelayedJSONStore.__new__(DaskDelayedJSONStore)
# One simple contour
store._contours = [np.array([[0, 0], [10, 0], [10, 10], [0, 10]])]
# Mixed type array → valid_ids = [1, 2]
store._processed_predictions = {"type": np.array([1, None, 2], dtype=object)}