-
Notifications
You must be signed in to change notification settings - Fork 51
/
aics_image.py
726 lines (598 loc) · 23.8 KB
/
aics_image.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import warnings
from typing import Any, Dict, List, Optional, Tuple, Type
import dask.array as da
import numpy as np
from . import transforms, types
from .constants import Dimensions
from .exceptions import InvalidDimensionOrderingError, UnsupportedFileFormatError
from .readers import (
ArrayLikeReader,
CziReader,
DefaultReader,
LifReader,
OmeTiffReader,
TiffReader,
)
from .readers.reader import Reader
###############################################################################
log = logging.getLogger(__name__)
###############################################################################
# The order of the readers in this list is important.
# Example:
# if TiffReader was placed before OmeTiffReader,
# we would never hit the OmeTiffReader
SUPPORTED_READERS = [
ArrayLikeReader,
CziReader,
LifReader,
OmeTiffReader,
TiffReader,
DefaultReader,
]
###############################################################################
class AICSImage:
def __init__(
self,
data: types.ImageLike,
known_dims: Optional[str] = None,
dask_kwargs: Dict[str, Any] = {},
**kwargs,
):
"""
AICSImage takes microscopy image data types (files) of varying dimensions
("ZYX", "TCZYX", "CYX") and puts them into a consistent 6D "STCZYX" ordered
dask array. The data, metadata are lazy loaded and can be accessed as needed.
Note the dims are assumed to match "STCZYX" from right to left meaning if
dimensional data is provided then the dimensions are assigned to be "CZYX", 2
dimensional would be "YX". This guessed assignment is only for file types
without dimension metadata (i.e. not .ome.tiff or .czi).
Parameters
----------
data: types.ImageLike
String with path to file, numpy.ndarray, or dask.array.Array with up to six
dimensions.
known_dims: Optional[str]
Optional string with the known dimension order. If None, the reader will
attempt to parse dim order.
dask_kwargs: Dict[str, Any] = {}
A dictionary of arguments to pass to a dask cluster and or client.
kwargs: Dict[str, Any]
Extra keyword arguments that can be passed down to either the reader
subclass or, if using the context manager, the LocalCluster initialization.
Examples
--------
Initialize an image and read the slices specified as a numpy array.
>>> img = AICSImage("my_file.tiff")
... zstack_t8 = img.get_image_data("ZYX", S=0, T=8, C=0)
Initialize an image, construct a delayed dask array for certain slices, then
read the data.
>>> img = AICSImage("my_file.czi")
... zstack_t8 = img.get_image_dask_data("ZYX", S=0, T=8, C=0)
... zstack_t8_data = zstack_t8.compute()
Initialize an image with a dask or numpy array.
>>> data = np.random.rand(100, 100)
... img = AICSImage(data)
Initialize an image and pass arguments to the reader using kwargs.
>>> img = AICSImage("my_file.czi", chunk_by_dims=["T", "Y", "X"])
Create a local dask cluster for the duration of the context manager.
>>> with AICSImage("filename.ome.tiff") as img:
... data = img.get_image_data("ZYX", S=0, T=0, C=0)
Create a local dask cluster with arguments for the duration of the context
manager.
>>> with AICSImage("filename.ome.tiff", dask_kwargs={"nworkers": 4}) as img:
... data = img.get_image_data("ZYX", S=0, T=0, C=0)
Connect to a specific dask cluster for the duration of the context manager.
>>> with AICSImage(
... "filename.ome.tiff",
... dask_kwargs={"address": "tcp://localhost:1234"},
... ) as img:
... data = img.get_image_data("ZYX", S=0, T=0, C=0)
Notes
-----
When using the AICSImage context manager, the processing machine or container
must have networking capabilities enabled to function properly.
Constructor for AICSImage class intended for providing a unified interface for
dealing with microscopy images. To extend support to a new reader simply add a
new reader child class of Reader ([readers/reader.py]) and add the class to
SUPPORTED_READERS variable.
"""
# Check known dims
if known_dims is not None:
if not all([d in Dimensions.DefaultOrder for d in known_dims]):
raise InvalidDimensionOrderingError(
f"The provided dimension string to the 'known_dims' argument "
f"includes dimensions that AICSImage does not support. "
f"Received: '{known_dims}'. "
f"Supported dimensions: {Dimensions.DefaultOrderList}."
)
# Hold onto known dims until data is requested
self._known_dims = known_dims
# Dims should nearly always be default dim order unless explictly overridden
self.dims = Dimensions.DefaultOrder
# Determine reader class and create dask delayed array
reader_class = self.determine_reader(data=data)
self._reader = reader_class(data, **kwargs)
# Lazy load data from reader and reformat to standard dimensions
self._dask_data = None
self._data = None
# Store dask client and cluster setup
self._dask_kwargs = dask_kwargs
self._client = None
self._cluster = None
@staticmethod
def determine_reader(data: types.ImageLike) -> Type[Reader]:
"""
Cheaply check to see if a given file is a recognized type and return the
appropriate reader for the file.
"""
# Iterate through the ordered supported readers to find the right one
for reader_class in SUPPORTED_READERS:
if reader_class.is_this_type(data):
return reader_class
raise UnsupportedFileFormatError(data)
@property
def dask_data(self) -> da.core.Array:
"""
Returns a dask array with dimension ordering "STCZYX".
"""
# Construct dask array if never before constructed
if self._dask_data is None:
reader_data = self.reader.dask_data
# Read and reshape and handle delayed known dims reshape
self._dask_data = transforms.reshape_data(
data=reader_data,
given_dims=self._known_dims or self.reader.dims,
return_dims=self.dims,
)
return self._dask_data
@property
def data(self) -> np.ndarray:
"""
Return the entire image as a numpy array with dimension ordering "STCZYX".
"""
if self._data is None:
self._data = transforms.reshape_data(
data=self.reader.data,
given_dims=self._known_dims or self.reader.dims,
return_dims=self.dims,
)
return self._data
def size(self, dims: str = Dimensions.DefaultOrder) -> Tuple[int]:
"""
Parameters
----------
dims: str
A string containing a list of dimensions being requested. The default is to
return the six standard dims.
Returns
-------
size: Tuple[int]
A tuple with the requested dimensions filled in.
"""
# Ensure dims is an uppercase string
dims = dims.upper()
# Check that dims requested are all a part of the available dims in the package
if not (all(d in Dimensions.DefaultOrder for d in dims)):
raise InvalidDimensionOrderingError(f"Invalid dimensions requested: {dims}")
# Check that the dims requested are in the image dims
if not (all(d in self.dims for d in dims)):
raise InvalidDimensionOrderingError(f"Invalid dimensions requested: {dims}")
# Return the shape of the data for the dimensions requested
return tuple([self.dask_data.shape[self.dims.index(dim)] for dim in dims])
@property
def shape(self) -> Tuple[int]:
"""
Returns
-------
shape: Tuple[int]
A tuple with the size of all dimensions.
"""
return self.size()
@property
def size_x(self) -> int:
"""
Returns
-------
size: int
The size of the Spatial X dimension.
"""
return self.size(Dimensions.SpatialX)[0]
@property
def size_y(self) -> int:
"""
Returns
-------
size: int
The size of the Spatial Y dimension.
"""
return self.size(Dimensions.SpatialY)[0]
@property
def size_z(self) -> int:
"""
Returns
-------
size: int
The size of the Spatial Z dimension.
"""
return self.size(Dimensions.SpatialZ)[0]
@property
def size_c(self) -> int:
"""
Returns
-------
size: int
The size of the Channel dimension.
"""
return self.size(Dimensions.Channel)[0]
@property
def size_t(self) -> int:
"""
Returns
-------
size: int
The size of the Time dimension.
"""
return self.size(Dimensions.Time)[0]
@property
def size_s(self) -> int:
"""
Returns
-------
size: int
The size of the Scene dimension.
"""
return self.size(Dimensions.Scene)[0]
@property
def metadata(self) -> Any:
"""
Returns
-------
metadata: Any
The Metadata from the Czi, or Ome.Tiff file, or other base class type with
metadata. For pure image files an empty string or None is returned.
"""
# The reader can implement read optimization or not.
return self.reader.metadata
def get_ome_metadata(self):
"""
Get the OME transformed metadata by applying the XSLT to the native
metadata format.
Returns
-------
lxml.etree.Element
The metadata converted into OME format using the XSLT sheets.
"""
return self.reader.get_ome_metadata()
@property
def reader(self) -> Reader:
"""
This property returns the class created to read the image file type.
The intent is that if the AICSImage class doesn't provide a raw enough
interface then the base class can be used directly.
Returns
-------
reader: Reader
A child of Reader; CziReader OmeTiffReader, TiffReader, DefaultReader, etc.
"""
return self._reader
def get_image_dask_data(
self, out_orientation: Optional[str] = None, **kwargs
) -> da.core.Array:
"""
Get specific dimension image data out of an image as a dask array.
Parameters
----------
out_orientation: Optional[str]
A string containing the dimension ordering desired for the returned ndarray.
Default: The current image dimensions. i.e. `self.dims`
kwargs:
* C=1: specifies Channel 1
* T=3: specifies the fourth index in T
* D=n: D is Dimension letter and n is the index desired. D should not be
present in the out_orientation.
* D=[a, b, c]: D is Dimension letter and a, b, c is the list of indicies
desired. D should be present in the out_orientation.
* D=(a, b, c): D is Dimension letter and a, b, c is the tuple of indicies
desired. D should be present in the out_orientation.
* D=range(...): D is Dimension letter and range is the standard Python
range function. D should be present in the out_orientation.
* D=slice(...): D is Dimension letter and slice is the standard Python
slice function. D should be present in the out_orientation.
Returns
-------
data: dask array
The read data with the dimension ordering that was specified with
out_orientation.
Examples
--------
Specific index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... c1 = img.get_image_dask_data("ZYX", C=1)
List of index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... first_and_second = img.get_image_dask_data("CZYX", C=[0, 1])
Tuple of index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... first_and_last = img.get_image_dask_data("CZYX", C=(0, -1))
Range of index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... first_three = img.get_image_dask_data("CZYX", C=range(3))
Slice selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... every_other = img.get_image_dask_data("CZYX", C=slice(0, -1, 2))
Notes
-----
* If a requested dimension is not present in the data the dimension is
added with a depth of 1.
See `aicsimageio.transforms.reshape_data` for more details.
"""
# If no out orientation, simply return current data as dask array
if out_orientation is None:
return self.dask_data
# Transform and return
return transforms.reshape_data(
data=self.dask_data,
given_dims=self.dims,
return_dims=out_orientation,
**kwargs,
)
def get_image_data(
self, out_orientation: Optional[str] = None, **kwargs
) -> np.ndarray:
"""
Get specific dimension image data out of an image as a numpy array.
Parameters
----------
out_orientation: Optional[str]
A string containing the dimension ordering desired for the returned ndarray.
Default: The current image dimensions. i.e. `self.dims`
kwargs:
* C=1: specifies Channel 1
* T=3: specifies the fourth index in T
* D=n: D is Dimension letter and n is the index desired. D should not be
present in the out_orientation.
* D=[a, b, c]: D is Dimension letter and a, b, c is the list of indicies
desired. D should be present in the out_orientation.
* D=(a, b, c): D is Dimension letter and a, b, c is the tuple of indicies
desired. D should be present in the out_orientation.
* D=range(...): D is Dimension letter and range is the standard Python
range function. D should be present in the out_orientation.
* D=slice(...): D is Dimension letter and slice is the standard Python
slice function. D should be present in the out_orientation.
Examples
--------
Specific index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... c1 = img.get_image_data("ZYX", C=1)
List of index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... first_and_second = img.get_image_data("CZYX", C=[0, 1])
Tuple of index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... first_and_last = img.get_image_data("CZYX", C=(0, -1))
Range of index selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... first_three = img.get_image_data("CZYX", C=range(3))
Slice selection
>>> img = AICSImage("s_1_t_1_c_10_z_20.ome.tiff")
... every_other = img.get_image_data("CZYX", C=slice(0, -1, 2))
Returns
-------
data: np.ndarray
The read data with the dimension ordering that was specified with
out_orientation.
Notes
-----
* If a requested dimension is not present in the data the dimension is
added with a depth of 1.
See `aicsimageio.transforms.reshape_data` for more details.
"""
return self.get_image_dask_data(
out_orientation=out_orientation, **kwargs
).compute()
def view_napari(self, rgb: bool = False, **kwargs):
"""
If installed, load the image in a napari viewer.
Parameters
----------
rgb: bool
Is the image RGB / RGBA
Default: False (is not RGB)
**kwargs
Extra arguments passed down to the viewer
"""
try:
import napari
# Construct getitem operations tuple to select down the data
# in the filled dimensions
ops = []
selected_dims = []
for dim in self.dims:
if self.size(dim)[0] == 1:
ops.append(0)
else:
ops.append(slice(None, None, None))
selected_dims.append(dim)
# Actually select the down
data = self.dask_data[tuple(ops)]
# Convert selected_dims to string
dims = "".join(selected_dims)
# Create name for window
if isinstance(self.reader, ArrayLikeReader):
title = f"napari: {self.dask_data.shape}"
else:
title = f"napari: {self.reader._file.name}"
# Handle RGB entirely differently
if rgb:
# Swap channel to last dimension
new_dims = f"{dims.replace(Dimensions.Channel, '')}{Dimensions.Channel}"
data = transforms.transpose_to_dims(
data=data, given_dims=dims, return_dims=new_dims
)
# Run napari
with napari.gui_qt():
napari.view_image(
data,
is_pyramid=False,
ndisplay=3 if Dimensions.SpatialZ in dims else 2,
title=title,
axis_labels=dims.replace(Dimensions.Channel, ""),
rgb=rgb,
**kwargs,
)
# Handle all other images besides RGB not requested
else:
# Channel axis
c_axis = (
dims.index(Dimensions.Channel)
if Dimensions.Channel in dims
else None
)
# Set visible based on number of channels
if c_axis is not None:
if data.shape[c_axis] > 3:
visible = False
else:
visible = True
else:
visible = True
# Drop channel from dims string
dims = (
dims.replace(Dimensions.Channel, "")
if Dimensions.Channel in dims
else dims
)
# Run napari
with napari.gui_qt():
napari.view_image(
data,
is_pyramid=False,
ndisplay=3 if Dimensions.SpatialZ in dims else 2,
channel_axis=c_axis,
axis_labels=dims,
title=title,
visible=visible,
**kwargs,
)
except ModuleNotFoundError:
raise ModuleNotFoundError(
f"'napari' has not been installed. To use this function install napari "
f"with either: pip install napari' or "
f"'pip install aicsimageio[interactive]'"
)
def get_channel_names(self, scene: int = 0) -> List[str]:
"""
Attempts to use the image's metadata to get the image's channel names.
Parameters
----------
scene: int
The index of the scene for which to return channel names.
Returns
-------
channels_names: List[str]
List of strings representing the channel names.
"""
# Get channel names from reader
channel_names = self.reader.get_channel_names(scene)
# Unlike the readers, AICSImage objects always have a channel dimension
# In the case the base reader returns None, return a list of "0"
if channel_names is None:
return [str(i) for i in range(self.size_c)]
# Return the read channel names
return channel_names
def get_physical_pixel_size(self, scene: int = 0) -> Tuple[float]:
"""
Attempts to retrieve physical pixel size for the specified scene.
If none available, returns `1.0` for each spatial dimension.
Parameters
----------
scene: int
The index of the scene for which to return physical pixel sizes.
Returns
-------
sizes: Tuple[float]
Tuple of floats representing the pixel sizes for X, Y, Z, in that order.
"""
return self.reader.get_physical_pixel_size(scene)
def __repr__(self) -> str:
return f"<AICSImage [{type(self.reader).__name__}]>"
@property
def cluster(self) -> Optional["distributed.LocalCluster"]:
"""
If this object created a local Dask cluster, return it.
"""
return self._cluster
@property
def client(self) -> Optional["distributed.Client"]:
"""
If connected to a Dask cluster, return the connected Client.
"""
return self._client
def close(self):
"""
Close the connection to the Dask distributed Client.
If this object created a LocalCluster, close it down as well.
"""
from . import dask_utils
self._cluster, self._client = dask_utils.shutdown_cluster_and_client(
self.cluster, self.client
)
def __enter__(self):
"""
If provided an address, create a Dask Client connection.
If not provided an address, create a LocalCluster and Client connection.
If not provided an address, other Dask kwargs are accepted and passed down to
the LocalCluster object.
"""
# Warn of future changes to API
warnings.warn(
"In aicsimageio>=4.*, the AICSImage context manager will no longer "
f"construct and manage a distributed local dask cluster for you. If this "
f"functionality is desired for your work, please switch to explictly "
f"calling the `aicsimageio.dask_utils.cluster_and_client` context manager.",
FutureWarning,
)
from . import dask_utils
self._cluster, self._client = dask_utils.spawn_cluster_and_client(
**self._dask_kwargs
)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
Always close the Dask Client connection.
If connected to *strictly* a LocalCluster, close it down as well.
"""
self.close()
def imread_dask(data: types.ImageLike, **kwargs) -> da.core.Array:
"""
Read image as a dask array.
Parameters
----------
data: types.ImageLike
A filepath, in memory numpy array, or preconfigured dask array.
kwargs: Dict[str, Any]
Any extra arguments to passed down to AICSImage and subsequent readers.
Returns
-------
data: da.core.Array
The image read and configured as a dask array.
"""
return AICSImage(data, **kwargs).dask_data
def imread(data: types.ImageLike, **kwargs) -> np.ndarray:
"""
Read image as a numpy ndarray.
Parameters
----------
data: types.ImageLike
A filepath, in memory numpy array, or preconfigured dask array.
kwargs: Dict[str, Any]
Any extra arguments to passed down to AICSImage and subsequent readers.
Returns
-------
data: np.ndarray
The image read and configured as a numpy ndarray.
"""
return AICSImage(data, **kwargs).data