-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathproject.py
More file actions
1744 lines (1397 loc) · 70.9 KB
/
project.py
File metadata and controls
1744 lines (1397 loc) · 70.9 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
"""
project
=======
At the core of scPortrait is the concept of a `Project`. A `Project` is a Python class that orchestrates all scPortrait processing steps, serving as the central element for all operations.
Each `Project` corresponds to a directory on the file system, which houses the input data for a specific scPortrait run along with the generated outputs.
The choice of the appropriate `Project` class depends on the structure of the data to be processed.
For more details, refer to :ref:`here <projects>`.
"""
from __future__ import annotations
import os
import re
import shutil
import tempfile
import warnings
from pathlib import PosixPath
from typing import TYPE_CHECKING, Literal
import dask.array as da
import dask.array as darray
import matplotlib.pyplot as plt
import numpy as np
import psutil
import zarr
from alphabase.io import tempmmap
from spatialdata import SpatialData
from tifffile import imread
from scportrait.io import daskmmap
from scportrait.pipeline._base import Logable
from scportrait.pipeline._utils.helper import _check_for_spatialdata_plot, read_config, write_config
from scportrait.pipeline._utils.sdata_io import sdata_filehandler
from scportrait.pipeline._utils.spatialdata_helper import (
get_chunk_size,
rechunk_image,
)
from scportrait.tools.sdata.write._helper import _get_image, _get_shape, _normalize_anndata_strings
if TYPE_CHECKING:
from collections.abc import Callable
from anndata import AnnData
from matplotlib.pyplot import Figure
from scportrait.io import read_h5sc
from scportrait.pipeline._utils.constants import (
DEFAULT_CELL_ID_NAME,
DEFAULT_CENTERS_NAME,
DEFAULT_CHUNK_SIZE_2D,
DEFAULT_CHUNK_SIZE_3D,
DEFAULT_CONFIG_NAME,
DEFAULT_DATA_DIR,
DEFAULT_EXTRACTION_DIR_NAME,
DEFAULT_EXTRACTION_FILE,
DEFAULT_FEATURIZATION_DIR_NAME,
DEFAULT_IMAGE_DTYPE,
DEFAULT_INPUT_IMAGE_NAME,
DEFAULT_PREFIX_FILTERED_SEG,
DEFAULT_PREFIX_MAIN_SEG,
DEFAULT_PREFIX_SELECTED_SEG,
DEFAULT_SDATA_FILE,
DEFAULT_SEG_NAME_0,
DEFAULT_SEG_NAME_1,
DEFAULT_SEGMENTATION_DIR_NAME,
DEFAULT_SEGMENTATION_DTYPE,
DEFAULT_SELECTION_DIR_NAME,
DEFAULT_SINGLE_CELL_IMAGE_DTYPE,
ChunkSize2D,
ChunkSize3D,
)
from scportrait.processing.images._image_processing import percentile_normalization
class Project(Logable):
"""Base implementation for a scPortrait ``project``.
This class is designed to handle single-timepoint, single-location data, like e.g. whole-slide images.
Segmentation Methods should be based on :func:`Segmentation <scportrait.pipeline.segmentation.Segmentation>` or :func:`ShardedSegmentation <scportrait.pipeline.segmentation.ShardedSegmentation>`.
Extraction Methods should be based on :func:`HDF5CellExtraction <scportrait.pipeline.extraction.HDF5CellExtraction>`.
Attributes:
config (dict): Dictionary containing the config file.
nuc_seg_name (str): Name of the nucleus segmentation object.
cyto_seg_name (str): Name of the cytosol segmentation object.
sdata_path (str): Path to the spatialdata object.
filehander (sdata_filehandler): Filehandler for the spatialdata object which manages all calls or updates to the spatialdata object.
"""
# define cleanup behaviour
CLEAN_LOG: bool = True
# import all default values from constants
DEFAULT_CONFIG_NAME = DEFAULT_CONFIG_NAME
DEFAULT_INPUT_IMAGE_NAME = DEFAULT_INPUT_IMAGE_NAME
DEFAULT_SDATA_FILE = DEFAULT_SDATA_FILE
DEFAULT_PREFIX_MAIN_SEG = DEFAULT_PREFIX_MAIN_SEG
DEFAULT_PREFIX_FILTERED_SEG = DEFAULT_PREFIX_FILTERED_SEG
DEFAULT_PREFIX_SELECTED_SEG = DEFAULT_PREFIX_SELECTED_SEG
DEFAULT_SEG_NAME_0: str = DEFAULT_SEG_NAME_0
DEFAULT_SEG_NAME_1: str = DEFAULT_SEG_NAME_1
DEFAULT_CENTERS_NAME: str = DEFAULT_CENTERS_NAME
DEFAULT_CHUNK_SIZE_3D: ChunkSize3D = DEFAULT_CHUNK_SIZE_3D
DEFAULT_CHUNK_SIZE_2D: ChunkSize2D = DEFAULT_CHUNK_SIZE_2D
DEFAULT_SEGMENTATION_DIR_NAME = DEFAULT_SEGMENTATION_DIR_NAME
DEFAULT_EXTRACTION_DIR_NAME = DEFAULT_EXTRACTION_DIR_NAME
DEFAULT_DATA_DIR = DEFAULT_DATA_DIR
DEFAULT_EXTRACTION_FILE = DEFAULT_EXTRACTION_FILE
DEFAULT_FEATURIZATION_DIR_NAME = DEFAULT_FEATURIZATION_DIR_NAME
DEFAULT_SELECTION_DIR_NAME = DEFAULT_SELECTION_DIR_NAME
DEFAULT_IMAGE_DTYPE = DEFAULT_IMAGE_DTYPE
DEFAULT_SEGMENTATION_DTYPE = DEFAULT_SEGMENTATION_DTYPE
DEFAULT_SINGLE_CELL_IMAGE_DTYPE = DEFAULT_SINGLE_CELL_IMAGE_DTYPE
DEFAULT_CELL_ID_NAME = DEFAULT_CELL_ID_NAME
_h5sc_handle = None
_h5sc_adata = None
PALETTE = [
"blue",
"green",
"red",
"yellow",
"purple",
"orange",
"pink",
"cyan",
"magenta",
"lime",
"teal",
"lavender",
"brown",
"beige",
"maroon",
"mint",
"olive",
"apricot",
"navy",
"grey",
"white",
"black",
]
def __init__(
self,
project_location: str,
config_path: str = None,
segmentation_f=None,
extraction_f=None,
featurization_f=None,
selection_f=None,
overwrite: bool = False,
debug: bool = False,
):
"""
Args:
project_location (str): Path to the project directory.
config_path (str): Path to the config file.
segmentation_f (optional): Segmentation method to be used for the project.
extraction_f (optional): Extraction method to be used for the project.
featurization_f (optional): Featurization method to be used for the project.
selection_f (optional): Selection method to be used for the project.
overwrite (optional): If set to ``True``, will overwrite existing files in the project directory. Default is ``False``.
debug (optional): If set to ``True``, will print additional debug messages/plots. Default is ``False``.
"""
super().__init__(directory=project_location, debug=debug)
self.project_location = project_location
self.overwrite = overwrite
self.config: None | dict = None
if config_path is None or isinstance(config_path, str | PosixPath):
self._get_config_file(config_path)
elif isinstance(config_path, dict):
self._load_config_from_dict(config_path)
self.nuc_seg_name = f"{self.DEFAULT_PREFIX_MAIN_SEG}_{self.DEFAULT_SEG_NAME_0}"
self.cyto_seg_name = f"{self.DEFAULT_PREFIX_MAIN_SEG}_{self.DEFAULT_SEG_NAME_1}"
self.segmentation_f = segmentation_f
self.extraction_f = extraction_f
self.featurization_f = featurization_f
self.selection_f = selection_f
# intialize containers to support interactive viewing of the spatialdata object
self.interactive_sdata = None
self.interactive = None
if self.CLEAN_LOG:
self._clean_log_file()
# check if project directory exists, if it does not create
if not os.path.isdir(self.project_location):
os.makedirs(self.project_location)
else:
warnings.warn("There is already a directory in the location path", stacklevel=2)
# === setup sdata reader/writer ===
self.filehandler = sdata_filehandler(
directory=self.directory,
sdata_path=self.sdata_path,
input_image_name=self.DEFAULT_INPUT_IMAGE_NAME,
nuc_seg_name=self.nuc_seg_name,
cyto_seg_name=self.cyto_seg_name,
centers_name=self.DEFAULT_CENTERS_NAME,
default_cell_id_name=self.DEFAULT_CELL_ID_NAME,
debug=self.debug,
)
self.filehandler._check_sdata_status() # update sdata object and status
# === setup segmentation ===
self._setup_segmentation_f(segmentation_f)
# === setup extraction ===
self._setup_extraction_f(extraction_f)
# === setup featurization ===
self._setup_featurization_f(featurization_f)
# ==== setup selection ===
self._setup_selection(selection_f)
def __exit__(self):
self._clear_temp_dir()
def __del__(self):
self._clear_temp_dir()
def __getstate__(self):
state = self.__dict__.copy()
state["_h5sc_handle"] = None # ensure closed before pickling
return state
def __setstate__(self, state):
self.__dict__.update(state)
self._h5sc_handle = None # will be reopened lazily
@property
def sdata_path(self) -> str:
return self._get_sdata_path()
@property
def sdata(self) -> SpatialData:
"""Shape of data matrix (:attr:`n_obs`, :attr:`n_vars`)."""
return self.filehandler.get_sdata()
@property
def h5sc(self) -> AnnData:
# Always safely close previous handle if it exists
if hasattr(self, "_h5sc_handle") and self._h5sc_handle is not None:
try:
self._h5sc_handle.close()
except (ValueError, RuntimeError):
# handle was already closed or in invalid state
pass
self._h5sc_handle = None
# Load a fresh AnnData
adata = read_h5sc(self.extraction_f.output_path or self.extraction_f.extraction_file)
# Track only the handle, not the adata
self._h5sc_handle = adata.uns["_h5sc_file_handle"]
return adata
##### Setup Functions #####
def _load_config_from_file(self, file_path):
"""
Loads config from file and writes it to self.config
Args:
file_path (str): Path to the config.yml file that should be loaded.
"""
self.log(f"Loading config from {file_path}")
if not os.path.isfile(file_path):
raise ValueError(f"Your config path {file_path} is invalid.")
self.config = read_config(file_path)
def _load_config_from_dict(self, config_dict):
self.config = config_dict
write_config(self.config, os.path.join(self.project_location, self.DEFAULT_CONFIG_NAME))
def _get_config_file(self, config_path: str | None = None) -> None:
"""Load the config file for the project. If no config file is passed the default config file in the project directory is loaded.
Args:
config_path (str, optional): Path to the config file. Default is ``None``.
Returns:
None: the config dictionary project.config is updated.
"""
# load config file
self.config_path = os.path.join(self.project_location, self.DEFAULT_CONFIG_NAME)
if config_path is None:
# Check if there is already a config file in the dataset folder in case no config file has been specified
if os.path.isfile(self.config_path):
self._load_config_from_file(self.config_path)
else:
raise ValueError("No config passed and no config found in project directory.")
else:
if not os.path.isfile(config_path):
raise ValueError(f"Your config path {config_path} is invalid. Please specify a valid config path.")
else:
print("Updating project config file.")
if os.path.isfile(self.config_path):
os.remove(self.config_path)
# ensure that the project location exists
if not os.path.isdir(self.project_location):
os.makedirs(self.project_location)
# The blueprint config file is copied to the dataset folder and renamed to the default name
shutil.copy(config_path, self.config_path)
self._load_config_from_file(self.config_path)
def _setup_segmentation_f(self, segmentation_f):
"""Configure the segmentation method for the project.
Args:
segmentation_f (Callable): Segmentation method to be used for the project.
Returns:
None: the segmentation method is updated in the project object.
"""
if segmentation_f is not None:
if segmentation_f.__name__ not in self.config:
raise ValueError(f"Config for {segmentation_f.__name__} is missing from the config file.")
seg_directory = os.path.join(self.project_location, self.DEFAULT_SEGMENTATION_DIR_NAME)
self.seg_directory = seg_directory
self.segmentation_f = segmentation_f(
self.config[segmentation_f.__name__],
self.seg_directory,
nuc_seg_name=self.nuc_seg_name,
cyto_seg_name=self.cyto_seg_name,
_tmp_image_path=None,
project_location=self.project_location,
debug=self.debug,
overwrite=self.overwrite,
project=None,
filehandler=self.filehandler,
from_project=True,
)
def _update_segmentation_f(self, segmentation_f):
self._setup_segmentation_f(segmentation_f)
def _setup_extraction_f(self, extraction_f):
"""Configure the extraction method for the project.
Args:
extraction_f (Callable): Extraction method to be used for the project.
Returns:
None: the extraction method is updated in the project object.
"""
if extraction_f is not None:
extraction_directory = os.path.join(self.project_location, self.DEFAULT_EXTRACTION_DIR_NAME)
self.extraction_directory = extraction_directory
if extraction_f.__name__ not in self.config:
raise ValueError(f"Config for {extraction_f.__name__} is missing from the config file")
self.extraction_f = extraction_f(
self.config[extraction_f.__name__],
self.extraction_directory,
project_location=self.project_location,
debug=self.debug,
overwrite=self.overwrite,
project=self,
filehandler=self.filehandler,
from_project=True,
)
def _update_extraction_f(self, extraction_f):
self._setup_extraction_f(extraction_f)
def _setup_featurization_f(self, featurization_f):
"""Configure the featurization method for the project.
Args:
featurization_f (Callable): Featurization method to be used for the project.
Returns:
None: the featurization method is updated in the project object.
"""
if featurization_f is not None:
if featurization_f.__name__ not in self.config:
raise ValueError(f"Config for {featurization_f.__name__} is missing from the config file")
featurization_directory = os.path.join(self.project_location, self.DEFAULT_FEATURIZATION_DIR_NAME)
self.featurization_directory = featurization_directory
self.featurization_f = featurization_f(
self.config[featurization_f.__name__],
self.featurization_directory,
project_location=self.project_location,
debug=self.debug,
overwrite=False, # this needs to be set to false as the featurization step should not remove previously created features
project=self,
filehandler=self.filehandler,
from_project=True,
)
def update_featurization_f(self, featurization_f):
"""Update the featurization method chosen for the project without reinitializing the entire project.
Args:
featurization_f : The featurization method that should be used for the project.
Returns:
None : the featurization method is updated in the project object.
Examples:
Update the featurization method for a project::
from scportrait.pipeline.featurization import CellFeaturizer
project.update_featurization_f(CellFeaturizer)
"""
self.log(f"Replacing current featurization method {self.featurization_f.__class__} with {featurization_f}")
self._setup_featurization_f(featurization_f)
def _setup_selection(self, selection_f):
"""Configure the selection method for the project.
Args:
selection_f (Callable): Selection method to be used for the project.
Returns:
None: the selection method is updated in the project object.
"""
if self.selection_f is not None:
if selection_f.__name__ not in self.config:
raise ValueError(f"Config for {selection_f.__name__} is missing from the config file")
selection_directory = os.path.join(self.project_location, self.DEFAULT_SELECTION_DIR_NAME)
self.selection_directory = selection_directory
self.selection_f = selection_f(
self.config[selection_f.__name__],
self.selection_directory,
project_location=self.project_location,
debug=self.debug,
overwrite=self.overwrite,
project=self,
filehandler=self.filehandler,
from_project=True,
)
def _update_selection_f(self, selection_f):
self._setup_selection(selection_f)
##### General small helper functions ####
def _check_memory(self, item):
"""
Check the memory usage of the given if it were completely loaded into memory using .compute().
"""
array_size = item.nbytes
available_memory = psutil.virtual_memory().available
return array_size < available_memory
def _check_chunk_size(self, elem, chunk_size):
"""
Check if the chunk size of the element is the default chunk size. If not rechunk the element to the default chunk size.
"""
# get chunk size of element
chunk_size = get_chunk_size(elem)
if isinstance(chunk_size, list):
# check if all chunk sizes are the same otherwise rechunking needs to occur anyways
if not all(x == chunk_size[0] for x in chunk_size):
elem = rechunk_image(elem, chunk_size=chunk_size)
else:
# ensure that the chunk size is the default chunk size
if chunk_size != chunk_size:
elem = rechunk_image(elem, chunk_size=chunk_size)
else:
# ensure that the chunk size is the default chunk size
if chunk_size != chunk_size:
elem = rechunk_image(elem, chunk_size=chunk_size)
def _check_image_dtype(self, image: np.ndarray) -> None:
"""Check if the image dtype is the default image dtype.
Args:
image (np.ndarray): Image to be checked.
Returns:
None: If the image dtype is the default image dtype, no action is taken.
Raises:
Warning: If the image dtype is not the default image dtype.
"""
if not image.dtype == self.DEFAULT_IMAGE_DTYPE:
warnings.warn(
f"Image dtype is not {self.DEFAULT_IMAGE_DTYPE} but insteadt {image.dtype}. The workflow expects images to be of dtype {self.DEFAULT_IMAGE_DTYPE}. Proceeding with the incorrect dtype can lead to unexpected results.",
stacklevel=2,
)
self.log(
f"Image dtype is not {self.DEFAULT_IMAGE_DTYPE} but insteadt {image.dtype}. The workflow expects images to be of dtype {self.DEFAULT_IMAGE_DTYPE}. Proceeding with the incorrect dtype can lead to unexpected results."
)
def _create_temp_dir(self, path) -> None:
"""
Create a temporary directory in the specified directory with the name of the class.
Args:
path (str): Path to the directory where the temporary directory should be created.
Returns:
None: The temporary directory is created in the specified directory. The path to the temporary directory is stored in the project object as self._tmp_dir_path.
"""
path = os.path.join(path, f"{self.__class__.__name__}_")
self._tmp_dir = tempfile.TemporaryDirectory(prefix=path)
self._tmp_dir_path = self._tmp_dir.name
"""str: Path to the temporary directory."""
self.log(f"Initialized temporary directory at {self._tmp_dir_path} for {self.__class__.__name__}")
def _clear_temp_dir(self):
"""Clear the temporary directory."""
if "_tmp_dir" in self.__dict__.keys():
shutil.rmtree(self._tmp_dir_path, ignore_errors=True)
self.log(f"Cleaned up temporary directory at {self._tmp_dir}")
del self._tmp_dir, self._tmp_dir_path
else:
self.log("Temporary directory not found, skipping cleanup")
##### Functions for handling sdata object #####
def _cleanup_sdata_object(self):
"""
Check if the output location exists and if it does cleanup if allowed, otherwise raise an error.
"""
if os.path.exists(self.sdata_path):
if self.overwrite:
if not self.filehandler._check_empty_sdata():
self.log(f"Output location {self.sdata_path} already exists. Overwriting.")
shutil.rmtree(self.sdata_path, ignore_errors=True)
else:
# check to see if the sdata object is empty
if not self.filehandler._check_empty_sdata():
raise ValueError(
f"Output location {self.sdata_path} already exists. Set overwrite=True to overwrite."
)
self.filehandler._check_sdata_status()
def _get_sdata_path(self):
"""
Get the path to the spatialdata object.
"""
return os.path.join(self.project_location, self.DEFAULT_SDATA_FILE)
def print_project_status(self):
"""Print the current project status."""
self.get_project_status(print_status=True)
def get_project_status(self, print_status=False):
self.filehandler._check_sdata_status()
self.input_image_status = self.filehandler.input_image_status
self.nuc_seg_status = self.filehandler.nuc_seg_status
self.cyto_seg_status = self.filehandler.cyto_seg_status
self.nuc_centers_status = self.filehandler.nuc_centers_status
self.cyto_centers_status = self.filehandler.cyto_centers_status
extraction_file = os.path.join(
self.project_location, self.DEFAULT_EXTRACTION_DIR_NAME, self.DEFAULT_DATA_DIR, self.DEFAULT_EXTRACTION_FILE
)
self.extraction_status = True if os.path.isfile(extraction_file) else False
if self.input_image_status:
if self.DEFAULT_INPUT_IMAGE_NAME in self.sdata:
self.input_image = _get_image(self.sdata[self.DEFAULT_INPUT_IMAGE_NAME])
else:
self.input_image = None
if print_status:
self.log("Current Project Status:")
self.log("--------------------------------")
self.log(f"Input Image in sdata: {self.input_image_status}")
self.log(f"Nucleus Segmentation in sdata: {self.nuc_seg_status}")
self.log(f"Cytosol Segmentation in sdata: {self.cyto_seg_status}")
self.log(f"Nucleus Centers in sdata: {self.nuc_centers_status}")
self.log(f"Cytosol Centers in sdata: {self.cyto_centers_status}")
self.log(f"Extracted single-cell images saved to file: {self.extraction_status}")
self.log("--------------------------------")
return None
def view_sdata(self):
"""Start an interactive napari viewer to look at the sdata object associated with the project.
Note:
This only works in sessions with a visual interface.
"""
# open interactive viewer in napari
try:
from napari_spatialdata import Interactive
except ImportError:
raise ImportError(
"napari-spatialdata must be installed to use the interactive viewer. Please install with `pip install scportrait[plotting]`."
) from None
self.interactive_sdata = self.filehandler.get_sdata()
self.interactive = Interactive(self.interactive_sdata)
self.interactive.run()
def _save_interactive_sdata(self):
assert self.interactive_sdata is not None, "No interactive sdata object found."
in_memory_only, _ = self.interactive_sdata._symmetric_difference_with_zarr_store()
print(f"Writing the following manually added files to the sdata object: {in_memory_only}")
dict_lookup = {}
for elem in in_memory_only:
key, name = elem.split("/")
if key not in dict_lookup:
dict_lookup[key] = []
dict_lookup[key].append(name)
for _, name in dict_lookup.items():
self.interactive_sdata.write_element(name) # replace with correct function once pulled in from sdata
def close_interactive_viewer(self):
if self.interactive is not None:
self._save_interactive_sdata()
self.interactive._viewer.close()
# reset to none values to track next call of view_sdata
self.interactive_sdata = None
self.interactive = None
def _check_for_interactive_session(self):
if self.interactive is not None:
warnings.warn(
"Interactive viewer is still open. Will automatically close before proceeding with processing.",
stacklevel=2,
)
self.close_interactive_viewer()
#### Functions to visualize results ####
def plot_input_image(
self,
image_name="input_image",
max_width: int = 1000,
select_region: tuple[int, int] | None = None,
channels: list[int] | list[str] | None = None,
normalize: bool = False,
normalization_percentile: tuple[float, float] = (0.01, 0.99),
title_fontsize: int = 20,
figsize_single_tile: tuple[float, float] = (8, 8),
return_fig: bool = False,
) -> Figure | None:
"""Plot the input image associated with the project. If the image is large it will automatically plot a subset in the center
Args:
image_name: Name of the element containing the input image in the spatialdata object.
max_width: Maximum size of the image to be plotted in pixels.
select_region: Tuple containing the x and y coordinates of the center of the region to be plotted. If not set it will use the center of the image.
channels: List of channel names or indices to be plotted. If not set, the first 4 channels will be plotted.
normalize: If set to ``True``, the image will be normalized to the specified percentile values.
normalization_percentile: Tuple containing the lower and upper percentile values to be used for normalization.
title_fontsize: Fontsize of the title of the plot.
figsize_single_tile: size to be used during figure creation for a single axes in the resulting plot.
return_fig: If set to ``True``, the function returns the figure object instead of displaying it.
Returns:
A matplotlib figure object if return_fig is set to ``True``.
Examples:
Plot the input image of a project::
project.plot_input_image()
"""
# check if spatialdata_plot is installed
_check_for_spatialdata_plot()
from scportrait.plotting import plot_image
from scportrait.tools.sdata.processing import get_bounding_box_sdata
_sdata = self.sdata
# get relevant information from spatialdata object
c, x, y = _sdata[image_name].scale0.image.shape
channel_names = list(_sdata[image_name].scale0.c.values)
if max_width is not None:
# get center coordinates
if select_region is None:
center_x = x // 2
center_y = y // 2
else:
center_x, center_y = select_region
# subset spatialdata object if its too large
if x > max_width or y > max_width:
_sdata = get_bounding_box_sdata(_sdata, max_width, center_x, center_y)
if normalize:
lower_percentile, upper_percentile = normalization_percentile
# get percentile values to normalize viewing to
for channel in channel_names:
idx = list(_sdata[image_name].scale0.c.values).index(channel)
for scale in _sdata[image_name]:
im = _sdata[image_name].get(scale).image[idx].compute()
_sdata[image_name].get(scale).image[idx] = (
percentile_normalization(im, lower_percentile, upper_percentile) * np.iinfo(np.uint16).max
).astype(np.uint16)
if channels is not None:
if isinstance(channels[0], int):
assert all(x in range(c) for x in channels), (
"The specified channel indices are not found in the spatialdata object."
)
valid_channels = [i for i in channels if isinstance(i, int)]
channel_names = [channel_names[i] for i in valid_channels]
if isinstance(channels[0], str):
assert all(x in channel_names for x in channels), (
"The specified channel names are not found in the spatialdata object."
)
channel_names = channels
c = len(channels)
palette = self.PALETTE[:c]
else:
palette = self.PALETTE[:c]
fig_size_x, fig_size_y = figsize_single_tile
fig, axs = plt.subplots(1, len(channel_names) + 1, figsize=(fig_size_x * (len(channel_names) + 1), fig_size_y))
plot_image(
_sdata,
image_name=image_name,
channel_names=channel_names,
palette=palette,
ax=axs[0],
title="overlayed",
title_fontsize=title_fontsize,
return_fig=False,
show_fig=False,
)
for i, channel in enumerate(channel_names):
plot_image(
_sdata,
image_name=image_name,
channel_names=[channel],
palette=[palette[i]],
ax=axs[i + 1],
title=channel,
title_fontsize=title_fontsize,
return_fig=False,
show_fig=False,
)
fig.tight_layout()
if return_fig:
return fig
else:
plt.show()
return None
def plot_he_image(
self,
image_name: str = "he_image",
max_width: int | None = None,
select_region: tuple[int, int] | None = None,
title_fontsize: int = 20,
return_fig: bool = False,
) -> None | Figure:
"""Plot the hematoxylin and eosin (HE) channel of the input image.
Args:
image_name: Name of the element containing the H&E image in the spatialdata object.
max_width: Maximum width of the image to be plotted in pixels.
select_region: Tuple containing the x and y coordinates of the region to be plotted. If not set it will use the center of the image.
title_fontsize: Fontsize of the title of the plot.
return_fig: If set to ``True``, the function returns the figure object instead of displaying it.
Returns:
A matplotlib figure object if return_fig is set to ``True``.
Examples:
Plot the HE channel of a project::
project.plot_he()
"""
_check_for_spatialdata_plot()
# import optional dependencies required for this method
import spatialdata_plot # this does not have an explicit call put allows for sdata.pl calls
_sdata = self.sdata
# remove points object as this makes it
points_keys = list(_sdata.points.keys())
if len(points_keys) > 0:
for x in points_keys:
del _sdata.points[x]
channel_names = list(_sdata[image_name].scale0.c.values)
assert channel_names == ["r", "g", "b"], "The image is not an RGB image."
# subset spatialdata object if its too large
if max_width is not None:
c, x, y = _sdata[image_name].scale0.image.shape
width = max_width // 2
if select_region is None:
center_x = x // 2
center_y = y // 2
else:
center_x, center_y = select_region
if x > max_width or y > max_width:
_sdata = _sdata.query.bounding_box(
axes=["x", "y"],
min_coordinate=[center_x - width, center_y - width],
max_coordinate=[center_x + width, center_y + width],
target_coordinate_system="global",
)
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
_sdata.pl.render_images(image_name).pl.show(ax=ax)
ax.axis("off")
ax.set_title("H&E Image", fontsize=title_fontsize)
fig.tight_layout()
if return_fig:
return fig
plt.show()
return None
def plot_segmentation_masks(
self,
max_width: int = 1500,
select_region: tuple[int, int] | None = None,
image_name: str = "input_image",
mask_names: list[str] | None = None,
normalize: bool = False,
normalization_percentile: tuple[float, float] = (0.01, 0.99),
title_fontsize: int = 20,
line_width: int = 1,
return_fig: bool = False,
) -> None | Figure:
"""Plot the generated segmentation masks. If the image is large it will automatically plot a subset cropped to the center of the spatialdata object.
Uses the function `scportrait.plotting.sdata.plot_segmentation_mask` to plot the found segmentation masks in an scPortrait project.
Please refer to the documentation of this function for further customization.
Args:
return_fig: If set to ``True``, the function returns the figure object instead of displaying it.
max_width: Maximum width of the image to be plotted in pixels.
select_region: Tuple containing the x and y coordinates of the region to be plotted. If not set it will use the center of the image.
image_name: Name of the element containing the input image in the spatialdata object.
mask_names: List of mask names to be plotted. If not set, all available masks will be plotted.
normalize: If set to ``True``, the image will be normalized to the specified percentile values.
normalization_percentile: Tuple containing the lower and upper percentile values to be used for normalization.
title_fontsize: Fontsize of the title of the plot.
line_width: Width of the lines in the plot.
return_fig: If set to ``True``, the function returns the figure object instead of displaying it.
Returns:
A matplotlib figure object if return_fig is set to ``True``.
Examples:
Plot the segmentation masks of a project::
project.plot_segmentation_masks()
"""
_check_for_spatialdata_plot()
# import relevant functions for this method
from scportrait.plotting.sdata import plot_segmentation_mask
from scportrait.tools.sdata.processing import get_bounding_box_sdata
_sdata = self.sdata
# get relevant information from spatialdata object
_, x, y = _sdata[image_name].scale0.image.shape
channel_names = list(_sdata[image_name].scale0.c.values)
if max_width is not None:
# get center coordinates
if select_region is None:
center_x = x // 2
center_y = y // 2
else:
center_x, center_y = select_region
# subset spatialdata object if its too large
if x > max_width or y > max_width:
_sdata = get_bounding_box_sdata(_sdata, max_width, center_x, center_y)
if normalize:
lower_percentile, upper_percentile = normalization_percentile
# get percentile values to normalize viewing to
for channel in channel_names:
idx = list(_sdata[image_name].scale0.c.values).index(channel)
for scale in _sdata[image_name]:
im = _sdata[image_name].get(scale).image[idx].compute()
_sdata[image_name].get(scale).image[idx] = (
percentile_normalization(im, lower_percentile, upper_percentile) * np.iinfo(np.uint16).max
).astype(np.uint16)
# get relevant segmentation masks
if mask_names is None:
masks = []
if self.filehandler.nuc_seg_status:
masks.append("seg_all_nucleus")
if self.filehandler.cyto_seg_status:
masks.append("seg_all_cytosol")
if len(masks) == 0:
raise ValueError("No segmentation masks found in the sdata object.")
else:
for mask in mask_names:
if mask not in _sdata:
raise ValueError(f"Mask {mask} not found in the spatialdata object.")
masks = mask_names
# create plot
fig, axs = plt.subplots(1, len(masks) + 1, figsize=(8 * (len(masks) + 1), 8))
plot_segmentation_mask(
_sdata,
masks,
ax=axs[0],
title="overlayed",
title_fontsize=title_fontsize,
line_width=line_width,
show_fig=False,
)
for mask in masks:
idx = masks.index(mask)
if "nucleus" in mask:
channel = [0]
name = "Nucleus Mask"
elif "cytosol" in mask:
channel = [1]
name = "Cytosol Mask"
else:
channel = list(range(len(channel_names)))
name = mask
plot_segmentation_mask(
_sdata,
[mask],
selected_channels=channel,
ax=axs[idx + 1],
title=name,
title_fontsize=title_fontsize,
line_width=line_width,
show_fig=False,
)
fig.tight_layout()
if return_fig:
return fig
else:
plt.show()
return None
def plot_single_cell_images(
self,
n_cells: int | None = None,