-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest_frame.py
More file actions
2697 lines (2183 loc) · 91.7 KB
/
test_frame.py
File metadata and controls
2697 lines (2183 loc) · 91.7 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
"""
Tests cosmicqc CytoDataFrame module
"""
import logging
import pathlib
import re
import sys
import types
import warnings
from collections import OrderedDict
from contextlib import nullcontext
from importlib.machinery import ModuleSpec
import imageio.v2 as imageio
import ipywidgets as widgets
import numpy as np
import pandas as pd
import pytest
import tifffile
from _pytest.monkeypatch import MonkeyPatch
from pyarrow import parquet
from cytodataframe.frame import (
FILTER_SLIDER_LABEL_WIDTH_PX,
FILTER_SLIDER_READOUT_WIDTH_PX,
FILTER_SLIDER_TOTAL_WIDTH_PX,
MAX_FILTER_SLIDER_STOPS,
CytoDataFrame,
)
from tests.utils import (
cytodataframe_image_display_contains_pixels,
)
def test_to_ome_parquet_adds_arrow_column(
tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
) -> None:
image_dir = tmp_path / "images"
image_dir.mkdir()
image_path = image_dir / "sample.tiff"
imageio.imwrite(image_path, np.zeros((10, 10), dtype=np.uint8))
data = pd.DataFrame(
{
"Image_FileName_DNA": [image_path.name],
"Image_PathName_DNA": [str(image_dir)],
"Cells_AreaShape_BoundingBoxMinimum_X": [0],
"Cells_AreaShape_BoundingBoxMinimum_Y": [0],
"Cells_AreaShape_BoundingBoxMaximum_X": [10],
"Cells_AreaShape_BoundingBoxMaximum_Y": [10],
}
)
cdf = CytoDataFrame(data=data)
class TestOMEArrow:
def __init__(self, data: str): # noqa: ANN204
self.data = data
test_module = types.SimpleNamespace(
OMEArrow=TestOMEArrow,
__version__="test",
__spec__=types.SimpleNamespace(loader=None),
)
monkeypatch.setitem(sys.modules, "ome_arrow", test_module)
captured: dict = {}
def fake_write_table(table, file_path, **kwargs): # noqa: ANN001, ANN202, ANN003
captured["df"] = table.to_pandas()
captured["file_path"] = file_path
captured["kwargs"] = kwargs
captured["metadata"] = table.schema.metadata or {}
monkeypatch.setattr("pyarrow.parquet.write_table", fake_write_table, raising=False)
output_path = tmp_path / "out.parquet"
cdf.to_ome_parquet(output_path)
composite_col = "Image_FileName_DNA_OMEArrow_COMP"
orig_col = "Image_FileName_DNA_OMEArrow_ORIG"
mask_col = "Image_FileName_DNA_OMEArrow_LABL"
for column in (composite_col, orig_col, mask_col):
assert column in captured["df"].columns
comp_value = captured["df"].loc[0, composite_col]
orig_value = captured["df"].loc[0, orig_col]
mask_value = captured["df"].loc[0, mask_col]
assert isinstance(comp_value, str) and comp_value.endswith(".tiff")
assert isinstance(orig_value, str) and orig_value.endswith(".tiff")
assert mask_value is None
assert captured["file_path"] == output_path
metadata = captured["metadata"]
assert metadata[b"cytodataframe:data-producer"]
assert metadata[b"cytodataframe:data-producer-version"]
def test_to_ome_parquet_real_data(
tmp_path: pathlib.Path, cytotable_NF1_data_parquet_shrunken: str
) -> None:
pytest.importorskip(
"ome_arrow", reason="to_ome_parquet real-data test requires ome-arrow"
)
parquet_path = pathlib.Path(cytotable_NF1_data_parquet_shrunken)
image_dir = parquet_path.parent / "Plate_2_images"
mask_dir = parquet_path.parent / "Plate_2_masks"
cdf = CytoDataFrame(
data=cytotable_NF1_data_parquet_shrunken,
data_context_dir=str(image_dir),
data_mask_context_dir=str(mask_dir),
)
output_path = tmp_path / "nf1.ome.parquet"
image_cols = cdf.find_image_columns()
cdf.to_ome_parquet(output_path)
assert output_path.exists()
table = parquet.read_table(output_path)
expected_arrow_cols = []
for col in image_cols:
expected_arrow_cols.extend(
[
f"{col}_OMEArrow_COMP",
f"{col}_OMEArrow_ORIG",
f"{col}_OMEArrow_LABL",
]
)
for column in expected_arrow_cols:
assert column in table.column_names
mask_cols = [f"{col}_OMEArrow_LABL" for col in image_cols]
mask_df = table.select(mask_cols).to_pandas()
assert mask_df.notna().any().any()
def test_to_ome_parquet_layer_flags(
tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
) -> None:
image_dir = tmp_path / "images"
image_dir.mkdir()
image_path = image_dir / "sample.tiff"
imageio.imwrite(image_path, np.zeros((10, 10), dtype=np.uint8))
data = pd.DataFrame(
{
"Image_FileName_DNA": [image_path.name],
"Image_PathName_DNA": [str(image_dir)],
"Cells_AreaShape_BoundingBoxMinimum_X": [0],
"Cells_AreaShape_BoundingBoxMinimum_Y": [0],
"Cells_AreaShape_BoundingBoxMaximum_X": [10],
"Cells_AreaShape_BoundingBoxMaximum_Y": [10],
}
)
cdf = CytoDataFrame(data=data)
class TestOMEArrow:
def __init__(self, data: str): # noqa: ANN204
self.data = data
test_module = types.SimpleNamespace(
OMEArrow=TestOMEArrow,
__version__="test",
__spec__=types.SimpleNamespace(loader=None),
)
monkeypatch.setitem(sys.modules, "ome_arrow", test_module)
captured: dict = {}
def fake_write_table(table, file_path, **kwargs): # noqa: ANN001, ANN202, ANN003
captured["df"] = table.to_pandas()
monkeypatch.setattr("pyarrow.parquet.write_table", fake_write_table, raising=False)
cdf.to_ome_parquet(
tmp_path / "out.parquet",
include_original=False,
include_mask_outline=False,
include_composite=True,
)
columns = captured["df"].columns
assert "Image_FileName_DNA_OMEArrow_COMP" in columns
assert "Image_FileName_DNA_OMEArrow_ORIG" not in columns
assert "Image_FileName_DNA_OMEArrow_LABL" not in columns
def test_ome_arrow_columns_render_html(
tmp_path: pathlib.Path, cytotable_NF1_data_parquet_shrunken: str
) -> None:
pytest.importorskip(
"ome_arrow", reason="OME-Arrow rendering test requires ome-arrow"
)
parquet_path = pathlib.Path(cytotable_NF1_data_parquet_shrunken)
image_dir = parquet_path.parent / "Plate_2_images"
mask_dir = parquet_path.parent / "Plate_2_masks"
raw_cdf = CytoDataFrame(
data=cytotable_NF1_data_parquet_shrunken,
data_context_dir=str(image_dir),
data_mask_context_dir=str(mask_dir),
)
ome_path = tmp_path / "nf1.arrow.parquet"
raw_cdf.to_ome_parquet(ome_path)
arrow_cdf = CytoDataFrame(data=ome_path)
arrow_cols = [col for col in arrow_cdf.columns if col.endswith("_OMEArrow_COMP")]
assert arrow_cols
html_output = arrow_cdf[arrow_cols]._repr_html_(debug=True)
assert "data:image/png;base64" in html_output
def test_prepare_layers_mask_binary(tmp_path: pathlib.Path) -> None:
image_array = np.zeros((6, 6), dtype=np.uint8)
image_path = tmp_path / "cell.tiff"
imageio.imwrite(image_path, image_array)
mask_array = np.zeros((6, 6, 3), dtype=np.uint8)
mask_array[1:4, 1:4] = (0, 255, 0)
mask_path = tmp_path / "cell_mask.png"
imageio.imwrite(mask_path, mask_array)
data = pd.DataFrame(
{
"Image_FileName_DNA": ["cell.tiff"],
"Image_PathName_DNA": [str(tmp_path)],
"Cells_AreaShape_BoundingBoxMinimum_X": [0],
"Cells_AreaShape_BoundingBoxMinimum_Y": [0],
"Cells_AreaShape_BoundingBoxMaximum_X": [6],
"Cells_AreaShape_BoundingBoxMaximum_Y": [6],
}
)
cdf = CytoDataFrame(
data=data,
data_context_dir=str(tmp_path),
data_mask_context_dir=str(tmp_path),
)
layers = cdf._prepare_cropped_image_layers(
data_value="cell.tiff",
bounding_box=(0, 0, 6, 6),
include_mask_outline=True,
include_original=False,
include_composite=False,
)
mask_layer = layers["mask"]
assert mask_layer is not None
assert mask_layer.dtype == np.uint8
assert set(np.unique(mask_layer).tolist()).issubset({0, 255})
def test_prepare_layers_3d_uses_loaded_volume_without_ome_arrow_fallback(
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
volume = np.arange(4 * 5 * 6, dtype=np.uint8).reshape(4, 5, 6)
image_path = tmp_path / "vol3d.tiff"
tifffile.imwrite(image_path, volume)
cdf = CytoDataFrame(
data=pd.DataFrame({"Image_FileName_DNA": [image_path.name]}),
data_context_dir=str(tmp_path),
)
def fail_ome_arrow_path(**_kwargs: object) -> str:
raise AssertionError("OME-Arrow fallback should not be used for 3D TIFF")
monkeypatch.setattr(
"cytodataframe.frame.build_3d_html_from_path",
fail_ome_arrow_path,
)
layers = cdf._prepare_cropped_image_layers(
data_value=image_path.name,
bounding_box=(0, 0, 6, 5),
include_composite=False,
include_original=False,
include_mask_outline=False,
)
html_value = layers.get(CytoDataFrame._HTML_3D_STUB_KEY)
assert isinstance(html_value, str)
assert "data-volume=" in html_value
def test_prepare_layers_3d_includes_label_overlay_from_mask_dir(
tmp_path: pathlib.Path,
) -> None:
volume = np.arange(4 * 5 * 6, dtype=np.uint8).reshape(4, 5, 6)
image_path = tmp_path / "vol3d.tiff"
tifffile.imwrite(image_path, volume)
mask_dir = tmp_path / "masks"
mask_dir.mkdir()
label = np.zeros((4, 5, 6), dtype=np.uint8)
label[1:3, 2:4, 1:5] = 255
tifffile.imwrite(mask_dir / "vol3d_mask.tiff", label)
cdf = CytoDataFrame(
data=pd.DataFrame({"Image_FileName_DNA": [image_path.name]}),
data_context_dir=str(tmp_path),
data_mask_context_dir=str(mask_dir),
)
layers = cdf._prepare_cropped_image_layers(
data_value=image_path.name,
bounding_box=(0, 0, 6, 5),
include_composite=False,
include_original=False,
include_mask_outline=False,
)
html_value = layers.get(CytoDataFrame._HTML_3D_STUB_KEY)
assert isinstance(html_value, str)
assert "data-volume=" in html_value
assert 'data-label-volume="' in html_value
def test_get_3d_label_overlay_from_cell_applies_bbox_crop(
tmp_path: pathlib.Path,
) -> None:
volume = np.arange(4 * 5 * 6, dtype=np.uint8).reshape(4, 5, 6)
image_path = tmp_path / "vol3d.tiff"
tifffile.imwrite(image_path, volume)
mask_dir = tmp_path / "masks"
mask_dir.mkdir()
label = np.zeros((4, 5, 6), dtype=np.uint8)
label[1:3, 1:4, 1:5] = 255
tifffile.imwrite(mask_dir / "vol3d_mask.tiff", label)
data = pd.DataFrame(
{
"Image_FileName_DNA": [image_path.name],
"AreaShape_BoundingBoxMinimum_X": [1],
"AreaShape_BoundingBoxMaximum_X": [5],
"AreaShape_BoundingBoxMinimum_Y": [1],
"AreaShape_BoundingBoxMaximum_Y": [4],
"AreaShape_BoundingBoxMinimum_Z": [1],
"AreaShape_BoundingBoxMaximum_Z": [3],
}
)
cdf = CytoDataFrame(
data=data,
data_context_dir=str(tmp_path),
data_mask_context_dir=str(mask_dir),
)
cropped_volume, _ = cdf._get_3d_volume_from_cell(row=0, column="Image_FileName_DNA")
overlay = cdf._get_3d_label_overlay_from_cell(
row=0,
column="Image_FileName_DNA",
expected_shape=cropped_volume.shape,
)
assert overlay is not None
assert overlay.shape == cropped_volume.shape
assert overlay.dtype == np.uint8
assert overlay.max() == 255
def test_get_3d_bbox_crop_bounds_prefers_cellprofiler_columns() -> None:
cdf = CytoDataFrame(
data=pd.DataFrame(
{
"Other_Minimum_X": [0],
"Other_Maximum_X": [10],
"Other_Minimum_Y": [0],
"Other_Maximum_Y": [10],
"Cells_AreaShape_BoundingBoxMinimum_X": [2],
"Cells_AreaShape_BoundingBoxMaximum_X": [6],
"Cells_AreaShape_BoundingBoxMinimum_Y": [3],
"Cells_AreaShape_BoundingBoxMaximum_Y": [7],
"Cells_AreaShape_BoundingBoxMinimum_Z": [1],
"Cells_AreaShape_BoundingBoxMaximum_Z": [4],
}
)
)
bounds = cdf._get_3d_bbox_crop_bounds(row=0, volume_shape=(8, 8, 8))
assert bounds == (2, 6, 3, 7, 1, 4)
def test_get_3d_bbox_crop_bounds_accepts_custom_column_map() -> None:
cdf = CytoDataFrame(
data=pd.DataFrame(
{
"bbox_x0": [1],
"bbox_x1": [5],
"bbox_y0": [2],
"bbox_y1": [6],
"bbox_z0": [0],
"bbox_z1": [3],
}
),
display_options={
"volume_bbox_column_map": {
"x_min": "bbox_x0",
"x_max": "bbox_x1",
"y_min": "bbox_y0",
"y_max": "bbox_y1",
"z_min": "bbox_z0",
"z_max": "bbox_z1",
}
},
)
bounds = cdf._get_3d_bbox_crop_bounds(row=0, volume_shape=(8, 8, 8))
assert bounds == (1, 5, 2, 6, 0, 3)
def test_find_matching_segmentation_path_filters_by_image_identifier(
tmp_path: pathlib.Path,
) -> None:
mask_dir = tmp_path / "masks"
mask_dir.mkdir()
(mask_dir / "img_a_mask.tiff").write_bytes(b"")
(mask_dir / "img_b_mask.tiff").write_bytes(b"")
matched = CytoDataFrame._find_matching_segmentation_path(
data_value="img_a.tiff",
pattern_map={r".*_mask\.tiff$": r".*"},
file_dir=str(mask_dir),
candidate_path=pathlib.Path("img_a.tiff"),
)
assert matched is not None
assert matched.name == "img_a_mask.tiff"
def test_find_matching_segmentation_path_prefers_candidate_parent_tree(
tmp_path: pathlib.Path,
) -> None:
mask_dir = tmp_path / "masks"
(mask_dir / "plate_a").mkdir(parents=True)
(mask_dir / "plate_b").mkdir(parents=True)
(mask_dir / "plate_a" / "nuclei1_mask.tiff").write_bytes(b"")
(mask_dir / "plate_b" / "nuclei1_mask.tiff").write_bytes(b"")
matched = CytoDataFrame._find_matching_segmentation_path(
data_value="plate_a/nuclei1.tiff",
pattern_map={r".*_mask\.tiff$": r".*"},
file_dir=str(mask_dir),
candidate_path=pathlib.Path("/tmp/plate_a/nuclei1.tiff"),
)
assert matched is not None
assert matched.parent.name == "plate_a"
def test_cytodataframe_input(
tmp_path: pathlib.Path,
basic_outlier_dataframe: pd.DataFrame,
basic_outlier_csv: str,
basic_outlier_csv_gz: str,
basic_outlier_tsv: str,
basic_outlier_parquet: str,
):
# Tests CytoDataFrame with pd.DataFrame input.
sc_df = CytoDataFrame(data=basic_outlier_dataframe)
# test that we ingested the data properly
assert sc_df._custom_attrs["data_source"] == "pandas.DataFrame"
assert sc_df.equals(basic_outlier_dataframe)
# test export
basic_outlier_dataframe.to_parquet(
control_path := f"{tmp_path}/df_input_example.parquet"
)
sc_df.export(test_path := f"{tmp_path}/df_input_example1.parquet")
assert parquet.read_table(control_path).equals(parquet.read_table(test_path))
# Tests CytoDataFrame with pd.Series input.
sc_df = CytoDataFrame(data=basic_outlier_dataframe.loc[0])
# test that we ingested the data properly
assert sc_df._custom_attrs["data_source"] == "pandas.Series"
assert sc_df.equals(pd.DataFrame(basic_outlier_dataframe.loc[0]))
# Tests CytoDataFrame with CSV input.
sc_df = CytoDataFrame(data=basic_outlier_csv)
expected_df = pd.read_csv(basic_outlier_csv)
# test that we ingested the data properly
assert sc_df._custom_attrs["data_source"] == str(basic_outlier_csv)
assert sc_df.equals(expected_df)
# test export
sc_df.export(test_path := f"{tmp_path}/df_input_example.csv", index=False)
pd.testing.assert_frame_equal(expected_df, pd.read_csv(test_path))
# Tests CytoDataFrame with CSV input.
sc_df = CytoDataFrame(data=basic_outlier_csv_gz)
expected_df = pd.read_csv(basic_outlier_csv_gz)
# test that we ingested the data properly
assert sc_df._custom_attrs["data_source"] == str(basic_outlier_csv_gz)
assert sc_df.equals(expected_df)
# test export
sc_df.export(test_path := f"{tmp_path}/df_input_example.csv.gz", index=False)
pd.testing.assert_frame_equal(
expected_df, pd.read_csv(test_path, compression="gzip")
)
# Tests CytoDataFrame with TSV input.
sc_df = CytoDataFrame(data=basic_outlier_tsv)
expected_df = pd.read_csv(basic_outlier_tsv, delimiter="\t")
# test that we ingested the data properly
assert sc_df._custom_attrs["data_source"] == str(basic_outlier_tsv)
assert sc_df.equals(expected_df)
# test export
sc_df.export(test_path := f"{tmp_path}/df_input_example.tsv", index=False)
pd.testing.assert_frame_equal(expected_df, pd.read_csv(test_path, sep="\t"))
# Tests CytoDataFrame with parquet input.
sc_df = CytoDataFrame(data=basic_outlier_parquet)
expected_df = pd.read_parquet(basic_outlier_parquet)
# test that we ingested the data properly
assert sc_df._custom_attrs["data_source"] == str(basic_outlier_parquet)
assert sc_df.equals(expected_df)
# test export
sc_df.export(test_path := f"{tmp_path}/df_input_example2.parquet")
assert parquet.read_table(basic_outlier_parquet).equals(
parquet.read_table(test_path)
)
# test CytoDataFrame with CytoDataFrame input
copy_sc_df = CytoDataFrame(data=sc_df)
pd.testing.assert_frame_equal(copy_sc_df, sc_df)
def test_repr_html_green_pixels(
cytotable_NF1_data_parquet_shrunken: str,
cytotable_nuclear_speckles_data_parquet: str,
cytotable_pediatric_cancer_atlas_parquet: str,
):
"""
Tests how images are rendered through customized repr_html in CytoDataFrame.
"""
# Ensure there's at least one greenish pixel in the image
# when context dirs are set for the NF1 dataset.
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=cytotable_NF1_data_parquet_shrunken,
data_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_images",
data_mask_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_masks",
),
image_cols=["Image_FileName_DAPI", "Image_FileName_GFP", "Image_FileName_RFP"],
color_conditions={"green": 255, "red": None, "blue": None},
), "The NF1 images do not contain green outlines."
# Ensure there's at least one greenish pixel in the image
# when context dirs are NOT set for the NF1 dataset.
nf1_dataset_with_modified_image_paths = pd.read_parquet(
path=cytotable_NF1_data_parquet_shrunken
)
nf1_dataset_with_modified_image_paths.loc[
:, ["Image_PathName_DAPI", "Image_PathName_GFP", "Image_PathName_RFP"]
] = f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_images"
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=nf1_dataset_with_modified_image_paths,
data_mask_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_masks",
),
image_cols=["Image_FileName_DAPI", "Image_FileName_GFP", "Image_FileName_RFP"],
color_conditions={"green": 255, "red": None, "blue": None},
), "The NF1 images do not contain green outlines."
# Ensure there's at least one greenish pixel in the image
# when context dirs are set for the nuclear speckles dataset.
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=cytotable_nuclear_speckles_data_parquet,
data_context_dir=f"{pathlib.Path(cytotable_nuclear_speckles_data_parquet).parent}/images",
data_mask_context_dir=f"{pathlib.Path(cytotable_nuclear_speckles_data_parquet).parent}/masks",
),
image_cols=[
"Image_FileName_A647",
"Image_FileName_DAPI",
"Image_FileName_GOLD",
],
color_conditions={"green": 255, "red": None, "blue": None},
), "The nuclear speckles images do not contain green outlines."
# Ensure there's at least one greenish pixel in the image
# when context dirs are set for the pediatric cancer dataset.
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=cytotable_pediatric_cancer_atlas_parquet,
data_context_dir=f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/orig",
data_outline_context_dir=f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/outlines",
segmentation_file_regex={
r"CellsOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch3.*\.tiff",
r"NucleiOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch5.*\.tiff",
},
),
image_cols=[
"Image_FileName_OrigAGP",
"Image_FileName_OrigDNA",
],
color_conditions={"green": 255, "red": None, "blue": None},
), "The pediatric cancer atlas speckles images do not contain green outlines."
# Ensure there's at least one greenish pixel in the image
# when context dirs are NOT set for the pediatric cancer dataset.
# (tests the regex associations with default image paths)
pediatric_cancer_dataset_with_modified_image_paths = pd.read_parquet(
path=cytotable_pediatric_cancer_atlas_parquet
)
# fmt: off
pediatric_cancer_dataset_with_modified_image_paths = (
pediatric_cancer_dataset_with_modified_image_paths.assign(
Image_PathName_OrigAGP=(
f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/orig"
),
Image_PathName_OrigDNA=(
f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/orig"
),
)
)
# fmt: on
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=pediatric_cancer_dataset_with_modified_image_paths,
data_outline_context_dir=f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/outlines",
segmentation_file_regex={
r"CellsOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch3.*\.tiff",
r"NucleiOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch5.*\.tiff",
},
),
image_cols=[
"Image_FileName_OrigAGP",
"Image_FileName_OrigDNA",
],
color_conditions={"green": 255, "red": None, "blue": None},
), "The pediatric cancer atlas speckles images do not contain green outlines."
def test_repr_html_red_pixels(
cytotable_NF1_data_parquet_shrunken: str,
cytotable_nuclear_speckles_data_parquet: str,
cytotable_pediatric_cancer_atlas_parquet: str,
):
"""
Tests how images are rendered through customized repr_html in CytoDataFrame.
"""
# Ensure there's at least one reddish pixel in the image
# when context dirs are set for the NF1 dataset.
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=cytotable_NF1_data_parquet_shrunken,
data_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_images",
data_mask_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_masks",
),
image_cols=["Image_FileName_DAPI", "Image_FileName_GFP", "Image_FileName_RFP"],
color_conditions={"green": None, "red": 255, "blue": None},
), "The NF1 images do not contain red dots."
# Ensure there are no reddish pixels in the image
# when context dirs are set for the NF1 dataset.
assert not cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=cytotable_NF1_data_parquet_shrunken,
data_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_images",
data_mask_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_masks",
compartment_center_xy=False,
),
image_cols=["Image_FileName_DAPI", "Image_FileName_GFP", "Image_FileName_RFP"],
color_conditions={"green": None, "red": 255, "blue": None},
), "The NF1 images contain red pixels when it shouldn't."
# Ensure there's at least one greenish pixel in the image
# when context dirs are NOT set for the NF1 dataset.
nf1_dataset_with_modified_image_paths = pd.read_parquet(
path=cytotable_NF1_data_parquet_shrunken
)
nf1_dataset_with_modified_image_paths.loc[
:, ["Image_PathName_DAPI", "Image_PathName_GFP", "Image_PathName_RFP"]
] = f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_images"
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=nf1_dataset_with_modified_image_paths,
data_mask_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_masks",
),
image_cols=["Image_FileName_DAPI", "Image_FileName_GFP", "Image_FileName_RFP"],
color_conditions={"green": None, "red": 255, "blue": None},
), "The NF1 images do not contain red dots."
# Ensure there's at least one reddish pixel in the image
# when context dirs are set for the nuclear speckles dataset.
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=cytotable_nuclear_speckles_data_parquet,
data_context_dir=f"{pathlib.Path(cytotable_nuclear_speckles_data_parquet).parent}/images",
data_mask_context_dir=f"{pathlib.Path(cytotable_nuclear_speckles_data_parquet).parent}/masks",
),
image_cols=[
"Image_FileName_A647",
"Image_FileName_DAPI",
"Image_FileName_GOLD",
],
color_conditions={"green": None, "red": 255, "blue": None},
), "The nuclear speckles images do not contain red dots."
# Ensure there's at least one reddish pixel in the image
# when context dirs are set for the pediatric cancer dataset.
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=cytotable_pediatric_cancer_atlas_parquet,
data_context_dir=f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/orig",
data_outline_context_dir=f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/outlines",
segmentation_file_regex={
r"CellsOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch3.*\.tiff",
r"NucleiOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch5.*\.tiff",
},
),
image_cols=[
"Image_FileName_OrigAGP",
"Image_FileName_OrigDNA",
],
color_conditions={"green": None, "red": 255, "blue": None},
), "The pediatric cancer atlas speckles images do not contain red dots."
# Ensure there's at least one reddish pixel in the image
# when context dirs are NOT set for the pediatric cancer dataset.
# (tests the regex associations with default image paths)
pediatric_cancer_dataset_with_modified_image_paths = pd.read_parquet(
path=cytotable_pediatric_cancer_atlas_parquet
)
# fmt: off
pediatric_cancer_dataset_with_modified_image_paths = (
pediatric_cancer_dataset_with_modified_image_paths.assign(
Image_PathName_OrigAGP=(
f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/orig"
),
Image_PathName_OrigDNA=(
f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/orig"
),
)
)
# fmt: on
assert cytodataframe_image_display_contains_pixels(
frame=CytoDataFrame(
data=pediatric_cancer_dataset_with_modified_image_paths,
data_outline_context_dir=f"{pathlib.Path(cytotable_pediatric_cancer_atlas_parquet).parent}/images/outlines",
segmentation_file_regex={
r"CellsOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch3.*\.tiff",
r"NucleiOutlines_BR(\d+)_C(\d{2})_\d+\.tiff": r".*ch5.*\.tiff",
},
),
image_cols=[
"Image_FileName_OrigAGP",
"Image_FileName_OrigDNA",
],
color_conditions={"green": None, "red": 255, "blue": None},
), "The pediatric cancer atlas speckles images do not contain red dots."
def test_return_cytodataframe(cytotable_NF1_data_parquet_shrunken: str):
"""
Tests to ensure we return a CytoDataFrame
from extended Pandas methods.
"""
cdf = CytoDataFrame(data=cytotable_NF1_data_parquet_shrunken)
assert isinstance(cdf.head(), CytoDataFrame)
assert isinstance(cdf.tail(), CytoDataFrame)
assert isinstance(cdf.sort_values(by="Metadata_ImageNumber"), CytoDataFrame)
assert isinstance(cdf.sample(n=5), CytoDataFrame)
assert isinstance(cdf[0:2], CytoDataFrame)
assert isinstance(cdf[1:1], CytoDataFrame)
assert isinstance(cdf[0:5:2], CytoDataFrame)
assert isinstance(cdf.iloc[0:2], CytoDataFrame)
assert isinstance(cdf.iloc[1:1], CytoDataFrame)
assert isinstance(cdf.iloc[0:5:2], CytoDataFrame)
def test_return_cytodataframe_passthroughs_non_dataframe_results() -> None:
"""Ensure helper methods return scalar-like results without wrapping."""
cdf = CytoDataFrame(pd.DataFrame({"a": [1, 2, 3]}))
result = cdf._return_cytodataframe(lambda: 3, "dummy_method")
assert result == 3
def test_iloc_slice_preserves_cytodataframe_html_formatting():
"""Ensure ``iloc`` slices keep the CytoDataFrame notebook HTML renderer."""
cdf = CytoDataFrame(pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}))
bracket_sliced = cdf[0:3:2]
bracket_empty_sliced = cdf[1:1]
sliced = cdf.iloc[0:3:2]
empty_sliced = cdf.iloc[1:1]
assert isinstance(bracket_sliced, CytoDataFrame)
assert isinstance(bracket_empty_sliced, CytoDataFrame)
assert bracket_sliced._custom_attrs["_output"] is cdf._custom_attrs["_output"]
assert (
bracket_sliced._custom_attrs["_widget_state"]
is cdf._custom_attrs["_widget_state"]
)
assert bracket_empty_sliced._custom_attrs["_output"] is cdf._custom_attrs["_output"]
assert (
bracket_empty_sliced._custom_attrs["_widget_state"]
is cdf._custom_attrs["_widget_state"]
)
assert isinstance(sliced, CytoDataFrame)
assert isinstance(empty_sliced, CytoDataFrame)
assert sliced._custom_attrs["_output"] is cdf._custom_attrs["_output"]
assert sliced._custom_attrs["_widget_state"] is cdf._custom_attrs["_widget_state"]
assert empty_sliced._custom_attrs["_output"] is cdf._custom_attrs["_output"]
assert (
empty_sliced._custom_attrs["_widget_state"]
is cdf._custom_attrs["_widget_state"]
)
assert "background:#EBEBEB" in bracket_sliced._repr_html_(debug=True)
assert "background:#EBEBEB" in bracket_empty_sliced._repr_html_(debug=True)
assert "background:#EBEBEB" in sliced._repr_html_(debug=True)
assert "background:#EBEBEB" in empty_sliced._repr_html_(debug=True)
def test_transpose_toggles_transposed_state() -> None:
"""Ensure repeated transposes flip the transposed rendering state back."""
cdf = CytoDataFrame(pd.DataFrame({"a": [1, 2], "b": [3, 4]}))
transposed = cdf.T
double_transposed = transposed.T
assert transposed._custom_attrs["is_transposed"] is True
assert double_transposed._custom_attrs["is_transposed"] is False
def test_cytodataframe_dynamic_width_and_height(
cytotable_NF1_data_parquet_shrunken: str,
):
"""
Tests to ensure we return a CytoDataFrame
from extended Pandas methods.
"""
cdf = CytoDataFrame(
data=cytotable_NF1_data_parquet_shrunken,
data_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_images",
data_mask_context_dir=f"{pathlib.Path(cytotable_NF1_data_parquet_shrunken).parent}/Plate_2_masks",
# set the width to 100px and height to auto for images
display_options={"width": "100px", "height": "auto"},
)
# gather the html of the output for the dataframe
cdf_image_html = cdf[
["Image_FileName_DAPI", "Image_FileName_GFP", "Image_FileName_RFP"]
][1:2]._repr_html_(debug=True)
# test that the html string contains the customized width and height
# constraints on the 3 images which display within the html output.
assert cdf_image_html.count("width:100px") == 3
assert cdf_image_html.count("height:auto") == 3
# transpose and test for the same to ensure the images are
# formatted despite being transposed (that we didn't lose them
# in the process).
cdf_image_html = cdf[
["Image_FileName_DAPI", "Image_FileName_GFP", "Image_FileName_RFP"]
][1:2].T._repr_html_(debug=True)
assert cdf_image_html.count("width:100px") == 3
assert cdf_image_html.count("height:auto") == 3
def test_slider_updates_state(monkeypatch: MonkeyPatch):
"""
Test that the slider for image adjustments updates the internal
widget state and triggers the render method.
"""
# Minimal test dataframe
df = pd.DataFrame({"Image_FileName_DNA": ["example.tif"]})
cdf = CytoDataFrame(df)
# Simulate the change dictionary sent by ipywidgets
change = {"new": 75}
# Track render calls using monkeypatch or a flag
render_called = {}
loading_called = {}
def mock_render_output() -> None:
render_called["called"] = True
def mock_show_loading() -> None:
loading_called["called"] = True
monkeypatch.setattr(cdf, "_render_output", mock_render_output)
monkeypatch.setattr(cdf, "_show_output_loading_indicator", mock_show_loading)
# Call the method manually
cdf._on_slider_change(change)
# Check if internal widget state updated
assert cdf._custom_attrs["_widget_state"]["scale"] == 75
# Check if the render method was triggered
assert render_called.get("called", False)
assert loading_called.get("called", False)
def test_filter_slider_updates_state(monkeypatch: MonkeyPatch):
"""Test that the filter slider updates internal state and triggers render."""
cdf = CytoDataFrame(
pd.DataFrame({"Image_FileName_DNA": ["example.tif"], "AreaShape_Area": [2.0]}),
display_options={"filter_column": "AreaShape_Area"},
)
cdf._custom_attrs["_widget_state"]["filter_column"] = "AreaShape_Area"
render_called = {}
loading_called = {}
def mock_render_output() -> None:
render_called["called"] = True
def mock_show_loading() -> None:
loading_called["called"] = True
monkeypatch.setattr(cdf, "_render_output", mock_render_output)
monkeypatch.setattr(cdf, "_show_output_loading_indicator", mock_show_loading)
cdf._on_filter_slider_change({"new": (1.5, 2.5)})
assert cdf._custom_attrs["_widget_state"]["filter_range"] == (1.5, 2.5)
assert render_called.get("called", False)
assert loading_called.get("called", False)
def test_filter_display_indices_by_widget_range() -> None:
cdf = CytoDataFrame(pd.DataFrame({"FilterScore": [1.0, 2.0, 3.0]}))
cdf._custom_attrs["_widget_state"]["filter_column"] = "FilterScore"
cdf._custom_attrs["_widget_state"]["filter_range"] = (1.5, 2.5)
filtered = cdf._filter_display_indices_by_widget_range(
data=cdf, display_indices=[0, 1, 2]
)
assert filtered == [1]
def test_filter_display_indices_by_widget_range_multiple_columns() -> None:
cdf = CytoDataFrame(
pd.DataFrame(
{
"FilterScoreA": [1.0, 2.0, 3.0, 4.0],
"FilterScoreB": [10.0, 20.0, 30.0, 40.0],
}
)
)
cdf._custom_attrs["_widget_state"]["filter_columns"] = [
"FilterScoreA",
"FilterScoreB",
]
cdf._custom_attrs["_widget_state"]["filter_ranges"] = {
"FilterScoreA": (1.5, 3.5),
"FilterScoreB": (15.0, 35.0),
}
filtered = cdf._filter_display_indices_by_widget_range(
data=cdf, display_indices=[0, 1, 2, 3]
)
assert filtered == [1, 2]