-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathtest_wsireader.py
2981 lines (2388 loc) · 101 KB
/
test_wsireader.py
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 for reading whole-slide images."""
from __future__ import annotations
import copy
import json
import logging
import re
import shutil
from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING, Callable
from unittest.mock import patch
import cv2
import glymur
import numpy as np
import pytest
import zarr
from click.testing import CliRunner
from packaging.version import Version
from skimage.filters import threshold_otsu
from skimage.metrics import peak_signal_noise_ratio, structural_similarity
from skimage.morphology import binary_dilation, disk, remove_small_objects
from skimage.registration import phase_cross_correlation
from tiatoolbox import cli, utils
from tiatoolbox.annotation import SQLiteStore
from tiatoolbox.utils import imread, tiff_to_fsspec
from tiatoolbox.utils.exceptions import FileNotSupportedError
from tiatoolbox.utils.magic import is_sqlite3
from tiatoolbox.utils.transforms import imresize, locsize2bounds
from tiatoolbox.utils.visualization import AnnotationRenderer
from tiatoolbox.wsicore import WSIReader, wsireader
from tiatoolbox.wsicore.wsireader import (
AnnotationStoreReader,
ArrayView,
DICOMWSIReader,
FsspecJsonWSIReader,
JP2WSIReader,
NGFFWSIReader,
OpenSlideWSIReader,
TIFFWSIReader,
VirtualWSIReader,
is_ngff,
is_zarr,
)
if TYPE_CHECKING: # pragma: no cover
from collections.abc import Iterable
import requests
from openslide import OpenSlide
from tiatoolbox.type_hints import IntBounds, IntPair
from tiatoolbox.wsicore.wsimeta import WSIMeta
# -------------------------------------------------------------------------------------
# Constants
# -------------------------------------------------------------------------------------
NDPI_TEST_TISSUE_BOUNDS = (30400, 11810, 30912, 12322)
NDPI_TEST_TISSUE_LOCATION = (30400, 11810)
NDPI_TEST_TISSUE_SIZE = (512, 512)
SVS_TEST_TISSUE_BOUNDS = (1000, 2000, 2000, 3000)
SVS_TEST_TISSUE_LOCATION = (1000, 2000)
SVS_TEST_TISSUE_SIZE = (1000, 1000)
JP2_TEST_TISSUE_BOUNDS = (0, 0, 1024, 1024)
JP2_TEST_TISSUE_LOCATION = (0, 0)
JP2_TEST_TISSUE_SIZE = (1024, 1024)
COLOR_DICT = {
0: (200, 0, 0, 255),
1: (0, 200, 0, 255),
2: (0, 0, 200, 255),
3: (155, 155, 0, 255),
4: (155, 0, 155, 255),
5: (0, 155, 155, 255),
}
RNG = np.random.default_rng() # Numpy Random Generator
# -------------------------------------------------------------------------------------
# Utility Test Functions
# -------------------------------------------------------------------------------------
def strictly_increasing(sequence: Iterable) -> bool:
"""Return True if sequence is strictly increasing.
Args:
sequence (Iterable): Sequence to check.
Returns:
bool: True if strictly increasing.
"""
return all(a < b for a, b in zip(sequence, sequence[1:]))
def strictly_decreasing(sequence: Iterable) -> bool:
"""Return True if sequence is strictly decreasing.
Args:
sequence (Iterable): Sequence to check.
Returns:
bool: True if strictly decreasing.
"""
return all(a > b for a, b in zip(sequence, sequence[1:]))
def read_rect_objective_power(wsi: WSIReader, location: IntPair, size: IntPair) -> None:
"""Read rect objective helper."""
for objective_power in [20, 10, 5, 2.5, 1.25]:
im_region = wsi.read_rect(
location,
size,
resolution=objective_power,
units="power",
)
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def read_bounds_mpp(
wsi: WSIReader,
bounds: IntBounds,
size: IntPair,
*,
jp2: bool,
) -> None:
"""Read bounds mpp helper."""
slide_mpp = wsi.info.mpp
for factor in range(1, 10):
mpp = slide_mpp * factor
downsample = mpp / slide_mpp
im_region = wsi.read_bounds(bounds, resolution=mpp, units="mpp")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
bounds_shape = np.array(size[::-1])
expected_output_shape = tuple((bounds_shape / downsample).round().astype(int))
if jp2:
assert im_region.shape[:2] == pytest.approx(expected_output_shape, abs=1)
else:
assert im_region.shape[:2] == expected_output_shape
assert im_region.shape[2] == 3
def read_bounds_objective_power(
wsi: WSIReader,
slide_power: float,
bounds: IntBounds,
size: IntPair,
*,
jp2: bool,
) -> None:
"""Read bounds objective power helper."""
for objective_power in [20, 10, 5, 2.5, 1.25]:
downsample = slide_power / objective_power
im_region = wsi.read_bounds(
bounds,
resolution=objective_power,
units="power",
)
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
bounds_shape = np.array(size[::-1])
expected_output_shape = tuple((bounds_shape / downsample).round().astype(int))
if jp2:
assert im_region.shape[:2] == pytest.approx(
expected_output_shape[:2],
abs=1,
)
else:
assert im_region.shape[:2] == expected_output_shape
assert im_region.shape[2] == 3
def read_bounds_level_consistency(wsi: WSIReader, bounds: IntBounds) -> None:
"""Read bounds level consistency helper.
Reads the same region at each stored resolution level and compares
the resulting image using phase cross correlation to check that they
are aligned.
"""
# Avoid testing very small levels (e.g. as in Omnyx JP2) because
# MSE for very small levels is noisy.
levels_to_test = [
n for n, downsample in enumerate(wsi.info.level_downsamples) if downsample <= 32
]
imgs = [wsi.read_bounds(bounds, level, "level") for level in levels_to_test]
smallest_size = imgs[-1].shape[:2][::-1]
resized = [cv2.resize(img, smallest_size) for img in imgs]
# Some blurring applied to account for changes in sharpness arising
# from interpolation when calculating the downsampled levels. This
# adds some tolerance for the comparison.
blurred = [cv2.GaussianBlur(img, (5, 5), cv2.BORDER_REFLECT) for img in resized]
as_float = [img.astype(np.float64) for img in blurred]
# Pair-wise check resolutions for mean squared error
for i, a in enumerate(as_float):
for b in as_float[i + 1 :]:
_, error, phase_diff = phase_cross_correlation(a, b, normalization=None)
assert phase_diff < 0.125
assert error < 0.125
# -------------------------------------------------------------------------------------
# Utility Test Classes & Functions
# -------------------------------------------------------------------------------------
_FSSPEC_WSI_CACHE = {}
def fsspec_wsi(sample_svs: Path, tmp_path: Path) -> FsspecJsonWSIReader:
"""Returns cached FsspecJsonWSIReader instance.
The reader instance opens CMU-1-Small-Region.svs image.
It's cached so the reader can be reused,
since loading the whole image using HTTP range requests from:
https://tiatoolbox.dcs.warwick.ac.uk/sample_wsis/CMU-1-Small-Region.svs
takes about 20 seconds.
"""
cache_key = "sample_svs"
if cache_key in _FSSPEC_WSI_CACHE:
return _FSSPEC_WSI_CACHE[cache_key] # Return cached instance
file_types = ("*.svs",)
files_all = utils.misc.grab_files_from_dir(
input_path=Path(sample_svs).parent,
file_types=file_types,
)
svs_file_path = str(files_all[0])
json_file_path = str(tmp_path / "fsspec.json")
final_url = (
"https://tiatoolbox.dcs.warwick.ac.uk/sample_wsis/CMU-1-Small-Region.svs"
)
tiff_to_fsspec.main(svs_file_path, json_file_path, final_url)
_FSSPEC_WSI_CACHE[cache_key] = wsireader.FsspecJsonWSIReader(json_file_path)
return _FSSPEC_WSI_CACHE[cache_key]
class DummyMutableOpenSlideObject:
"""Dummy OpenSlide object with mutable properties."""
def __init__(self: DummyMutableOpenSlideObject, openslide_obj: OpenSlide) -> None:
"""DummyMutableOpenSlideObject initialization."""
self.openslide_obj = openslide_obj
self._properties = dict(openslide_obj.properties)
def __getattr__(self: DummyMutableOpenSlideObject, name: str) -> object:
"""Catch references to OpenSlide object attributes."""
return getattr(self.openslide_obj, name)
@property
def properties(self: DummyMutableOpenSlideObject) -> object:
"""Return the fake properties."""
return self._properties
def relative_level_scales_baseline(wsi: WSIReader) -> None:
"""Relative level scales for pixels per baseline pixel."""
level_scales = wsi.info.relative_level_scales(0.125, "baseline")
level_scales = np.array(level_scales)
downsamples = np.array(wsi.info.level_downsamples)
expected = downsamples * 0.125
assert strictly_increasing(level_scales[:, 0])
assert strictly_increasing(level_scales[:, 1])
assert np.array_equal(level_scales[:, 0], level_scales[:, 1])
assert np.array_equal(level_scales[:, 0], expected)
# -------------------------------------------------------------------------------------
# Generic Tests
# -------------------------------------------------------------------------------------
def test_wsireader_slide_info(sample_svs: Path, tmp_path: Path) -> None:
"""Test for slide_info in WSIReader class as a python function."""
file_types = ("*.svs",)
files_all = utils.misc.grab_files_from_dir(
input_path=str(Path(sample_svs).parent),
file_types=file_types,
)
wsi = wsireader.OpenSlideWSIReader(files_all[0])
slide_param = wsi.info
out_path = tmp_path / slide_param.file_path.with_suffix(".yaml").name
utils.misc.save_yaml(slide_param.as_dict(), out_path)
def test_wsireader_slide_info_cache(sample_svs: Path) -> None:
"""Test for caching slide_info in WSIReader class as a python function."""
file_types = ("*.svs",)
files_all = utils.misc.grab_files_from_dir(
input_path=str(Path(sample_svs).parent),
file_types=file_types,
)
wsi = wsireader.OpenSlideWSIReader(files_all[0])
info = wsi.info
cached_info = wsi.info
assert info.as_dict() == cached_info.as_dict()
# -------------------------------------------------------------------------------------
# Class-Specific Tests
# -------------------------------------------------------------------------------------
def test_relative_level_scales_openslide_baseline(sample_ndpi: Path) -> None:
"""Test openslide relative level scales for pixels per baseline pixel."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
relative_level_scales_baseline(wsi)
def test_relative_level_scales_jp2_baseline(sample_jp2: Path) -> None:
"""Test jp2 relative level scales for pixels per baseline pixel."""
wsi = wsireader.JP2WSIReader(sample_jp2)
relative_level_scales_baseline(wsi)
def test_relative_level_scales_openslide_mpp(sample_ndpi: Path) -> None:
"""Test openslide calculation of relative level scales for mpp."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
level_scales = wsi.info.relative_level_scales(0.5, "mpp")
level_scales = np.array(level_scales)
assert strictly_increasing(level_scales[:, 0])
assert strictly_increasing(level_scales[:, 1])
assert all(level_scales[0] == wsi.info.mpp / 0.5)
def test_relative_level_scales_jp2_mpp(sample_jp2: Path) -> None:
"""Test jp2 calculation of relative level scales for mpp."""
wsi = wsireader.JP2WSIReader(sample_jp2)
level_scales = wsi.info.relative_level_scales(0.5, "mpp")
level_scales = np.array(level_scales)
assert strictly_increasing(level_scales[:, 0])
assert strictly_increasing(level_scales[:, 1])
assert all(level_scales[0] == wsi.info.mpp / 0.5)
def relative_level_scales_power(wsi: WSIReader) -> None:
"""Calculation of relative level scales for objective power."""
level_scales = wsi.info.relative_level_scales(wsi.info.objective_power, "power")
level_scales = np.array(level_scales)
assert strictly_increasing(level_scales[:, 0])
assert strictly_increasing(level_scales[:, 1])
assert np.array_equal(level_scales[0], [1, 1])
downsamples = np.array(wsi.info.level_downsamples)
assert np.array_equal(level_scales[:, 0], level_scales[:, 1])
assert np.array_equal(level_scales[:, 0], downsamples)
def test_relative_level_scales_openslide_power(sample_ndpi: Path) -> None:
"""Test openslide calculation of relative level scales for objective power."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
relative_level_scales_power(wsi)
def test_relative_level_scales_jp2_power(sample_jp2: Path) -> None:
"""Test jp2 calculation of relative level scales for objective power."""
wsi = wsireader.JP2WSIReader(sample_jp2)
relative_level_scales_power(wsi)
def relative_level_scales_level(wsi: WSIReader) -> None:
"""Calculation of relative level scales for level."""
level_scales = wsi.info.relative_level_scales(3, "level")
level_scales = np.array(level_scales)
assert np.array_equal(level_scales[3], [1, 1])
downsamples = np.array(wsi.info.level_downsamples)
expected = downsamples / downsamples[3]
assert np.array_equal(level_scales[:, 0], level_scales[:, 1])
assert np.array_equal(level_scales[:, 0], expected)
def test_relative_level_scales_openslide_level(sample_ndpi: Path) -> None:
"""Test openslide calculation of relative level scales for level."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
relative_level_scales_level(wsi)
def test_relative_level_scales_jp2_level(sample_jp2: Path) -> None:
"""Test jp2 calculation of relative level scales for level."""
wsi = wsireader.JP2WSIReader(sample_jp2)
relative_level_scales_level(wsi)
def relative_level_scales_float(wsi: WSIReader) -> None:
"""Calculation of relative level scales for fractional level."""
level_scales = wsi.info.relative_level_scales(1.5, "level")
level_scales = np.array(level_scales)
assert level_scales[0] == pytest.approx([1 / 3, 1 / 3])
downsamples = np.array(wsi.info.level_downsamples)
expected = downsamples / downsamples[0] * (1 / 3)
assert np.array_equal(level_scales[:, 0], level_scales[:, 1])
assert np.array_equal(level_scales[:, 0], expected)
def test_relative_level_scales_openslide_level_float(sample_ndpi: Path) -> None:
"""Test openslide calculation of relative level scales for fractional level."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
relative_level_scales_float(wsi)
def test_relative_level_scales_jp2_level_float(sample_jp2: Path) -> None:
"""Test jp2 calculation of relative level scales for fractional level."""
wsi = wsireader.JP2WSIReader(sample_jp2)
relative_level_scales_float(wsi)
def test_relative_level_scales_invalid_units(sample_svs: Path) -> None:
"""Test relative_level_scales with invalid units."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
with pytest.raises(ValueError, match="Invalid units"):
wsi.info.relative_level_scales(1.0, "gibberish")
def test_relative_level_scales_no_mpp() -> None:
"""Test relative_level_scales objective when mpp is None."""
class DummyWSI:
"""Mock WSIReader for testing."""
@property
def info(self: DummyWSI) -> WSIMeta:
return wsireader.WSIMeta((100, 100), axes="YXS")
wsi = DummyWSI()
with pytest.raises(ValueError, match="MPP is None"):
wsi.info.relative_level_scales(1.0, "mpp")
def test_relative_level_scales_no_objective_power() -> None:
"""Test relative_level_scales objective when objective power is None."""
class DummyWSI:
"""Mock WSIReader for testing."""
@property
def info(self: DummyWSI) -> WSIMeta:
return wsireader.WSIMeta((100, 100), axes="YXS")
wsi = DummyWSI()
with pytest.raises(ValueError, match="Objective power is None"):
wsi.info.relative_level_scales(10, "power")
def test_relative_level_scales_level_too_high(sample_svs: Path) -> None:
"""Test relative_level_scales levels set too high."""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
with pytest.raises(ValueError, match="levels"):
wsi.info.relative_level_scales(100, "level")
def test_find_optimal_level_and_downsample_openslide_interpolation_warning(
sample_ndpi: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test finding optimal level for mpp read with scale > 1.
This tests the case where the scale is found to be > 1 and interpolation
will be applied to the output. A UserWarning should be raised in this case.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
_, _ = wsi._find_optimal_level_and_downsample(0.1, "mpp")
assert (
"Read: Scale > 1.This means that the desired resolution is higher"
in caplog.text
)
def test_find_optimal_level_and_downsample_jp2_interpolation_warning(
sample_jp2: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test finding optimal level for mpp read with scale > 1.
This tests the case where the scale is found to be > 1 and interpolation
will be applied to the output. A UserWarning should be raised in this case.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
_, _ = wsi._find_optimal_level_and_downsample(0.1, "mpp")
assert (
"Read: Scale > 1.This means that the desired resolution is higher"
in caplog.text
)
def test_find_optimal_level_and_downsample_mpp(sample_ndpi: Path) -> None:
"""Test finding optimal level for mpp read."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
mpps = [0.5, 10]
expected_levels = [0, 4]
expected_scales = [[0.91282519, 0.91012514], [0.73026016, 0.72810011]]
for mpp, expected_level, expected_scale in zip(
mpps,
expected_levels,
expected_scales,
):
read_level, post_read_scale_factor = wsi._find_optimal_level_and_downsample(
mpp,
"mpp",
)
assert read_level == expected_level
assert post_read_scale_factor == pytest.approx(expected_scale)
def test_find_optimal_level_and_downsample_power(sample_ndpi: Path) -> None:
"""Test finding optimal level for objective power read."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
objective_powers = [20, 10, 5, 2.5, 1.25]
expected_levels = [0, 1, 2, 3, 4]
for objective_power, expected_level in zip(objective_powers, expected_levels):
read_level, post_read_scale_factor = wsi._find_optimal_level_and_downsample(
objective_power,
"power",
)
assert read_level == expected_level
assert np.array_equal(post_read_scale_factor, [1.0, 1.0])
def test_find_optimal_level_and_downsample_level(sample_ndpi: Path) -> None:
"""Test finding optimal level for level read.
For integer levels, the returned level should always be the same as
the input level.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
for level in range(wsi.info.level_count):
read_level, post_read_scale_factor = wsi._find_optimal_level_and_downsample(
level,
"level",
)
assert read_level == level
assert np.array_equal(post_read_scale_factor, [1.0, 1.0])
def test_convert_resolution_units(
sample_ndpi: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the resolution unit conversion code."""
wsi = wsireader.WSIReader.open(sample_ndpi)
# test for invalid input and output units
with pytest.raises(ValueError, match=r".*Invalid input_unit.*"):
wsi.convert_resolution_units(0, input_unit="invalid")
with pytest.raises(ValueError, match=r".*Invalid output_unit.*"):
wsi.convert_resolution_units(0, input_unit="level", output_unit="level")
# Test functionality: Assuming a baseline_mpp to be 0.25 at 40x mag
gt_mpp = wsi.info.mpp
gt_power = wsi.info.objective_power
gt_dict = {"mpp": 2 * gt_mpp, "power": gt_power / 2, "baseline": 0.5}
# convert input_unit == "mpp" to other formats
output = wsi.convert_resolution_units(2 * gt_mpp, input_unit="mpp")
assert output["power"] == gt_dict["power"]
# convert input_unit == "power" to other formats
output = wsi.convert_resolution_units(
gt_power / 2,
input_unit="power",
output_unit="mpp",
)
assert all(output == gt_dict["mpp"])
# convert input_unit == "level" to other formats
output = wsi.convert_resolution_units(1, input_unit="level")
assert all(output["mpp"] == gt_dict["mpp"])
# convert input_unit == "baseline" to other formats
output = wsi.convert_resolution_units(0.5, input_unit="baseline")
assert output["power"] == gt_dict["power"]
# Test for missing information
org_info = wsi.info
# test when mpp is missing
_info = deepcopy(org_info)
_info.mpp = None
wsi._m_info = _info
with pytest.raises(ValueError, match=r".*Missing 'mpp'.*"):
wsi.convert_resolution_units(0, input_unit="mpp")
_ = wsi.convert_resolution_units(0, input_unit="power")
# test when power is missing
_info = deepcopy(org_info)
_info.objective_power = None
wsi._m_info = _info
with pytest.raises(ValueError, match=r".*Missing 'objective_power'.*"):
wsi.convert_resolution_units(0, input_unit="power")
_ = wsi.convert_resolution_units(0, input_unit="mpp")
# test when power and mpp are missing
_info = deepcopy(org_info)
_info.objective_power = None
_info.mpp = None
wsi._m_info = _info
_ = wsi.convert_resolution_units(0, input_unit="baseline")
_ = wsi.convert_resolution_units(0, input_unit="level", output_unit="mpp")
assert "output_unit is returned as None." in caplog.text
def test_find_read_rect_params_power(sample_ndpi: Path) -> None:
"""Test finding read rect parameters for objective power."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
location = NDPI_TEST_TISSUE_LOCATION
size = NDPI_TEST_TISSUE_SIZE
# Test a range of objective powers
for target_scale in [1.25, 2.5, 5, 10, 20]:
(level, _, read_size, post_read_scale, _) = wsi.find_read_rect_params(
location=location,
size=size,
resolution=target_scale,
units="power",
)
assert level >= 0
assert level < wsi.info.level_count
# Check that read_size * scale == size
post_read_downscaled_size = np.round(read_size * post_read_scale).astype(int)
assert np.array_equal(post_read_downscaled_size, np.array(size))
def test_find_read_rect_params_mpp(sample_ndpi: Path) -> None:
"""Test finding read rect parameters for objective mpp."""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
location = NDPI_TEST_TISSUE_LOCATION
size = NDPI_TEST_TISSUE_SIZE
# Test a range of MPP
for target_scale in range(1, 10):
(level, _, read_size, post_read_scale, _) = wsi.find_read_rect_params(
location=location,
size=size,
resolution=target_scale,
units="mpp",
)
assert level >= 0
assert level < wsi.info.level_count
# Check that read_size * scale == size
post_read_downscaled_size = np.round(read_size * post_read_scale).astype(int)
assert np.array_equal(post_read_downscaled_size, np.array(size))
def test_read_rect_openslide_baseline(sample_ndpi: Path) -> None:
"""Test openslide read rect at baseline.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
location = NDPI_TEST_TISSUE_LOCATION
size = NDPI_TEST_TISSUE_SIZE
im_region = wsi.read_rect(location, size, resolution=0, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_read_rect_jp2_baseline(sample_jp2: Path) -> None:
"""Test jp2 read rect at baseline.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
location = JP2_TEST_TISSUE_LOCATION
size = JP2_TEST_TISSUE_SIZE
im_region = wsi.read_rect(location, size, resolution=0, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_read_rect_tiffreader_svs_baseline(sample_svs: Path) -> None:
"""Test TIFFWSIReader.read_rect with an SVS file at baseline."""
wsi = wsireader.TIFFWSIReader(sample_svs)
location = SVS_TEST_TISSUE_LOCATION
size = SVS_TEST_TISSUE_SIZE
im_region = wsi.read_rect(location, size, resolution=0, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_read_rect_tiffreader_ome_tiff_baseline(sample_ome_tiff: Path) -> None:
"""Test TIFFWSIReader.read_rect with an OME-TIFF file at baseline."""
wsi = wsireader.TIFFWSIReader(sample_ome_tiff)
location = SVS_TEST_TISSUE_LOCATION
size = SVS_TEST_TISSUE_SIZE
im_region = wsi.read_rect(location, size, resolution=0, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_is_tiled_tiff(source_image: Path) -> None:
"""Test if source_image is a tiled tiff."""
source_image.replace(source_image.with_suffix(".tiff"))
assert wsireader.is_tiled_tiff(source_image.with_suffix(".tiff")) is False
source_image.with_suffix(".tiff").replace(source_image)
def test_read_rect_openslide_levels(sample_ndpi: Path) -> None:
"""Test openslide read rect with resolution in levels.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
location = NDPI_TEST_TISSUE_LOCATION
size = NDPI_TEST_TISSUE_SIZE
for level in range(wsi.info.level_count):
im_region = wsi.read_rect(location, size, resolution=level, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_read_rect_jp2_levels(sample_jp2: Path) -> None:
"""Test jp2 read rect with resolution in levels.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
location = (0, 0)
size = JP2_TEST_TISSUE_SIZE
width, height = size
for level in range(wsi.info.level_count):
level_width, level_height = wsi.info.level_dimensions[level]
im_region = wsi.read_rect(
location,
size,
resolution=level,
units="level",
pad_mode=None,
)
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == pytest.approx(
(
min(height, level_height),
min(width, level_width),
3,
),
abs=1,
)
def read_rect_mpp(wsi: WSIReader, location: IntPair, size: IntPair) -> None:
"""Read rect with resolution in microns per pixel."""
for factor in range(1, 10):
mpp = wsi.info.mpp * factor
im_region = wsi.read_rect(location, size, resolution=mpp, units="mpp")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_read_rect_openslide_mpp(sample_ndpi: Path) -> None:
"""Test openslide read rect with resolution in microns per pixel.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
location = NDPI_TEST_TISSUE_LOCATION
size = NDPI_TEST_TISSUE_SIZE
read_rect_mpp(wsi, location, size)
def test_read_rect_jp2_mpp(sample_jp2: Path) -> None:
"""Test jp2 read rect with resolution in microns per pixel.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
location = JP2_TEST_TISSUE_LOCATION
size = JP2_TEST_TISSUE_SIZE
read_rect_mpp(wsi, location, size)
def test_read_rect_openslide_objective_power(sample_ndpi: Path) -> None:
"""Test openslide read rect with resolution in objective power.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
location = NDPI_TEST_TISSUE_LOCATION
size = NDPI_TEST_TISSUE_SIZE
read_rect_objective_power(wsi, location, size)
def test_read_rect_jp2_objective_power(sample_jp2: Path) -> None:
"""Test jp2 read rect with resolution in objective power.
Location coordinate is in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
location = JP2_TEST_TISSUE_LOCATION
size = JP2_TEST_TISSUE_SIZE
read_rect_objective_power(wsi, location, size)
def test_read_bounds_openslide_baseline(sample_ndpi: Path) -> None:
"""Test openslide read bounds at baseline.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
bounds = NDPI_TEST_TISSUE_BOUNDS
size = NDPI_TEST_TISSUE_SIZE
im_region = wsi.read_bounds(bounds, resolution=0, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_read_bounds_jp2_baseline(sample_jp2: Path) -> None:
"""Test JP2 read bounds at baseline.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
bounds = JP2_TEST_TISSUE_BOUNDS
size = JP2_TEST_TISSUE_SIZE
im_region = wsi.read_bounds(bounds, resolution=0, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape == (*size[::-1], 3)
def test_read_bounds_openslide_levels(sample_ndpi: Path) -> None:
"""Test openslide read bounds with resolution in levels.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
bounds = NDPI_TEST_TISSUE_BOUNDS
width, height = NDPI_TEST_TISSUE_SIZE
for level, downsample in enumerate(wsi.info.level_downsamples):
im_region = wsi.read_bounds(bounds, resolution=level, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
expected_output_shape = tuple(
np.round([height / downsample, width / downsample, 3]).astype(int),
)
assert im_region.shape == expected_output_shape
def test_read_bounds_jp2_levels(sample_jp2: Path) -> None:
"""Test jp2 read bounds with resolution in levels.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
bounds = JP2_TEST_TISSUE_BOUNDS
width, height = JP2_TEST_TISSUE_SIZE
for level, downsample in enumerate(wsi.info.level_downsamples):
im_region = wsi.read_bounds(bounds, resolution=level, units="level")
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
expected_output_shape = tuple(
np.round([height / downsample, width / downsample]),
)
assert im_region.shape[:2] == pytest.approx(expected_output_shape, abs=1)
assert im_region.shape[2] == 3
def test_read_bounds_openslide_mpp(sample_ndpi: Path) -> None:
"""Test openslide read bounds with resolution in microns per pixel.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
bounds = NDPI_TEST_TISSUE_BOUNDS
size = NDPI_TEST_TISSUE_SIZE
read_bounds_mpp(wsi, bounds, size, jp2=False)
def test_read_bounds_jp2_mpp(sample_jp2: Path) -> None:
"""Test jp2 read bounds with resolution in microns per pixel.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
bounds = JP2_TEST_TISSUE_BOUNDS
size = JP2_TEST_TISSUE_SIZE
read_bounds_mpp(wsi, bounds, size, jp2=True)
def test_read_bounds_openslide_objective_power(sample_ndpi: Path) -> None:
"""Test openslide read bounds with resolution in objective power.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_ndpi)
bounds = NDPI_TEST_TISSUE_BOUNDS
size = NDPI_TEST_TISSUE_SIZE
slide_power = wsi.info.objective_power
read_bounds_objective_power(wsi, slide_power, bounds, size, jp2=False)
def test_read_bounds_jp2_objective_power(sample_jp2: Path) -> None:
"""Test jp2 read bounds with resolution in objective power.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.JP2WSIReader(sample_jp2)
bounds = JP2_TEST_TISSUE_BOUNDS
size = JP2_TEST_TISSUE_SIZE
slide_power = wsi.info.objective_power
read_bounds_objective_power(wsi, slide_power, bounds, size, jp2=True)
def test_read_bounds_interpolated(sample_svs: Path) -> None:
"""Test openslide read bounds with interpolated output.
Coordinates in baseline (level 0) reference frame.
"""
wsi = wsireader.OpenSlideWSIReader(sample_svs)
bounds = SVS_TEST_TISSUE_BOUNDS
size = SVS_TEST_TISSUE_SIZE
im_region = wsi.read_bounds(
bounds,
resolution=0.1,
units="mpp",
)
assert wsi.info.mpp[0] > 0.1
assert wsi.info.mpp[1] > 0.1
assert isinstance(im_region, np.ndarray)
assert im_region.dtype == "uint8"
assert im_region.shape[2] == 3
assert all(np.array(im_region.shape[:2]) > size)
def test_read_bounds_level_consistency_openslide(sample_ndpi: Path) -> None:
"""Test read_bounds produces the same visual field across resolution levels.