-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathoptics.py
2036 lines (1690 loc) · 68.4 KB
/
optics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Features for optical imaging of samples.
This module provides classes and functionalities for simulating optical
imaging systems, enabling the generation of realistic camera images of
biological and physical samples. The primary goal is to offer tools for
modeling and computing optical phenomena such as brightfield, fluorescence,
holography, and other imaging modalities.
Key Features
------------
- **Microscope Simulation**
The `Microscope` class acts as a high-level interface for imaging samples
using defined optical systems. It coordinates the interaction between the
sample and the optical system, ensuring seamless simulation of imaging
processes.
- **Optical Systems**
The `Optics` class and its derived classes represent various optical
devices, defining core imaging properties such as resolution, magnification,
numerical aperture (NA), and wavelength. Subclasses like `Brightfield`,
`Fluorescence`, `Holography`, `Darkfield`, and `ISCAT` offer specialized
configurations tailored to different imaging techniques.
- **Sample Illumination and Volume Simulation**
Features like `IlluminationGradient` enable realistic simulation of
non-uniform sample illumination, critical for generating realistic images.
The `_create_volume` function facilitates combining multiple scatterers
into a single unified volume, supporting 3D imaging.
- **Integration with feature pipelines**
Full compatibility with feature pipelines, allows for dynamic and complex
simulations, incorporating physics-based models and real-time adjustments to
sample and imaging properties.
Module Structure
----------------
Classes:
- `Microscope`: Represents a simulated optical microscope that integrates the
sample and optical systems. It provides an interface to simulate imaging by
combining the sample properties with the configured optical system.
- `Optics`: An abstract base class representing a generic optical device.
Subclasses implement specific optical systems by defining imaging properties
and behaviors.
- `Brightfield`: Simulates brightfield microscopy, commonly used for observing
unstained or stained samples under transmitted light. This class serves as the
base for additional imaging techniques.
- `Holography`: Simulates holographic imaging, capturing phase information from
the sample. Suitable for reconstructing 3D images and measuring refractive
index variations.
- `Darkfield`: Simulates darkfield microscopy, which enhances contrast by
imaging scattered light against a dark background. Often used to highlight fine
structures in samples.
- `ISCAT`: Simulates interferometric scattering microscopy (ISCAT), an advanced
technique for detecting small particles or molecules based on scattering and
interference.
- `Fluorescence`: Simulates fluorescence microscopy, modeling emission
processes for fluorescent samples. Includes essential optical system
configurations and fluorophore behavior.
- `IlluminationGradient`: Adds a gradient to the illumination of the sample,
enabling simulations of non-uniform lighting conditions often seen in
real-world experiments.
Utility Functions:
- `_get_position(image, mode, return_z)`
def _get_position(
image: np.ndarray, mode: str = "corner", return_z: bool = False
) -> Tuple[int, int, Optional[int]]
Extracts the position of the upper-left corner of a scatterer in the image.
- `_create_volume(list_of_scatterers:, pad, output_region, refractive_index_medium, **kwargs)`
def _create_volume(
list_of_scatterers: List[np.ndarray],
pad: int,
output_region: Tuple[int, int, int, int],
refractive_index_medium: float,
**kwargs: Dict[str, Any],
) -> np.ndarray
Combines multiple scatterer objects into a single 3D volume for imaging.
- `_pad_volume(volume, limits, padding, output_region, **kwargs)`
def _pad_volume(
volume: np.ndarray,
limits: np.ndarray,
padding: Tuple[int, int, int, int],
output_region: Tuple[int, int, int, int],
**kwargs: Dict[str, Any],
) -> Tuple[np.ndarray, np.ndarray]
Pads a volume with zeros to avoid edge effects during imaging.
Examples
--------
Simulating an image with the `Brightfield` class:
>>> import deeptrack as dt
>>> scatterer = dt.PointParticle()
>>> optics = dt.Brightfield()
>>> image = optics(scatterer)
>>> print(image().shape)
(128, 128, 1)
>>> image.plot(cmap="gray")
Simulating an image with the `Fluorescence` class:
>>> import deeptrack as dt
>>> scatterer = dt.PointParticle()
>>> optics = dt.Fluorescence()
>>> image = optics(scatterer)
>>> print(image().shape)
(128, 128, 1)
>>> image.plot(cmap="gray")
"""
from pint import Quantity
from typing import Any, Dict, List, Tuple, Union
from deeptrack.backend.units import (
ConversionTable,
create_context,
get_active_scale,
get_active_voxel_size,
)
from deeptrack.math import AveragePooling
from deeptrack.features import propagate_data_to_dependencies
import numpy as np
from .features import DummyFeature, Feature, StructuralFeature
from .image import Image, pad_image_to_fft, maybe_cupy
from .types import ArrayLike, PropertyLike
from .backend._config import cupy
from scipy.ndimage import convolve
import warnings
from . import units as u
from .backend import config
from deeptrack import image
class Microscope(StructuralFeature):
"""Simulates imaging of a sample using an optical system.
This class combines a feature-set that defines the sample to be imaged with
a feature-set defining the optical system, enabling the simulation of
optical imaging processes.
Parameters
----------
sample: Feature
A feature-set resolving a list of images describing the sample to be
imaged.
objective: Feature
A feature-set defining the optical device that images the sample.
Attributes
-----------
__distributed__: bool
If True, the feature is distributed across multiple workers.
_sample: Feature
The feature-set defining the sample to be imaged.
_objective: Feature
The feature-set defining the optical system imaging the sample.
Methods
-------
`get(image: Image or None, **kwargs: Dict[str, Any]) -> Image`
Simulates the imaging process using the defined optical system and
returns the resulting image.
Examples
--------
Simulating an image using a brightfield optical system:
>>> import deeptrack as dt
>>> scatterer = dt.PointParticle()
>>> optics = dt.Brightfield()
>>> microscope = dt.Microscope(sample=scatterer, objective=optics)
>>> image = microscope.get(None)
>>> print(image.shape)
(128, 128, 1)
"""
__distributed__ = False
def __init__(
self: 'Microscope',
sample: Feature,
objective: Feature,
**kwargs: Dict[str, Any],
) -> None:
"""Initialize the `Microscope` instance.
Parameters
----------
sample: Feature
A feature-set resolving a list of images describing the sample to be
imaged.
objective: Feature
A feature-set defining the optical device that images the sample.
**kwargs: Dict[str, Any]
Additional parameters passed to the base `StructuralFeature` class.
Attributes
----------
_sample: Feature
The feature-set defining the sample to be imaged.
_objective: Feature
The feature-set defining the optical system imaging the sample.
"""
super().__init__(**kwargs)
self._sample = self.add_feature(sample)
self._objective = self.add_feature(objective)
self._sample.store_properties()
def get(
self: 'Microscope',
image: Union[Image, None],
**kwargs: Dict[str, Any],
) -> Image:
"""Generate an image of the sample using the defined optical system.
This method processes the sample through the optical system to
produce a simulated image.
Parameters
----------
image: Union[Image, None]
The input image to be processed. If None, a new image is created.
**kwargs: Dict[str, Any]
Additional parameters for the imaging process.
Returns
-------
Image: Image
The processed image after applying the optical system.
Examples
--------
Simulating an image with specific parameters:
>>> import deeptrack as dt
>>> scatterer = dt.PointParticle()
>>> optics = dt.Brightfield()
>>> microscope = dt.Microscope(sample=scatterer, objective=optics)
>>> image = microscope.get(None, upscale=(2, 2, 2))
>>> print(image.shape)
(256, 256, 1)
"""
# Grab properties from the objective to pass to the sample
additional_sample_kwargs = self._objective.properties()
# Calculate required output image for the given upscale
# This way of providing the upscale will be deprecated in the future
# in favor of dt.Upscale().
_upscale_given_by_optics = additional_sample_kwargs["upscale"]
if np.array(_upscale_given_by_optics).size == 1:
_upscale_given_by_optics = (_upscale_given_by_optics,) * 3
with u.context(
create_context(
*additional_sample_kwargs["voxel_size"], *_upscale_given_by_optics
)
):
upscale = np.round(get_active_scale())
output_region = additional_sample_kwargs.pop("output_region")
additional_sample_kwargs["output_region"] = [
int(o * upsc)
for o, upsc in zip(
output_region, (upscale[0], upscale[1], upscale[0], upscale[1])
)
]
padding = additional_sample_kwargs.pop("padding")
additional_sample_kwargs["padding"] = [
int(p * upsc)
for p, upsc in zip(
padding, (upscale[0], upscale[1], upscale[0], upscale[1])
)
]
self._objective.output_region.set_value(
additional_sample_kwargs["output_region"]
)
self._objective.padding.set_value(additional_sample_kwargs["padding"])
propagate_data_to_dependencies(
self._sample, **{"return_fft": True, **additional_sample_kwargs}
)
list_of_scatterers = self._sample()
if not isinstance(list_of_scatterers, list):
list_of_scatterers = [list_of_scatterers]
# All scatterers that are defined as volumes.
volume_samples = [
scatterer
for scatterer in list_of_scatterers
if not scatterer.get_property("is_field", default=False)
]
# All scatterers that are defined as fields.
field_samples = [
scatterer
for scatterer in list_of_scatterers
if scatterer.get_property("is_field", default=False)
]
# Merge all volumes into a single volume.
sample_volume, limits = _create_volume(
volume_samples,
**additional_sample_kwargs,
)
sample_volume = Image(sample_volume)
# Merge all properties into the volume.
for scatterer in volume_samples + field_samples:
sample_volume.merge_properties_from(scatterer)
# Let the objective know about the limits of the volume and all the fields.
propagate_data_to_dependencies(
self._objective,
limits=limits,
fields=field_samples,
)
imaged_sample = self._objective.resolve(sample_volume)
# Upscale given by the optics needs to be handled separately.
if _upscale_given_by_optics != (1, 1, 1):
imaged_sample = AveragePooling((*_upscale_given_by_optics[:2], 1))(
imaged_sample
)
# Merge with input
if not image:
if not self._wrap_array_with_image and isinstance(imaged_sample, Image):
return imaged_sample._value
else:
return imaged_sample
if not isinstance(image, list):
image = [image]
for i in range(len(image)):
image[i].merge_properties_from(imaged_sample)
return image
# def _no_wrap_format_input(self, *args, **kwargs) -> list:
# return self._image_wrapped_format_input(*args, **kwargs)
# def _no_wrap_process_and_get(self, *args, **feature_input) -> list:
# return self._image_wrapped_process_and_get(*args, **feature_input)
# def _no_wrap_process_output(self, *args, **feature_input):
# return self._image_wrapped_process_output(*args, **feature_input)
class Optics(Feature):
"""Abstract base optics class.
Provides structure and methods common for most optical devices. Subclasses
implement specific optical systems by defining imaging properties and
behaviors. The `Optics` class is used to define the core imaging properties
of an optical system, such as resolution, magnification, numerical aperture
(NA), and wavelength.
Parameters
----------
NA: float, optional
Numerical aperture (NA) of the limiting aperture, by default 0.7.
wavelength: float, optional
Wavelength of the scattered light in meters, by default 0.66e-6.
magnification: float, optional
Magnification of the optical system, by default 10.
resolution: float or array_like[float], optional
Distance between pixels in the camera (meters). A third value can
define the resolution in the z-direction, by default 1e-6.
refractive_index_medium: float, optional
Refractive index of the medium, by default 1.33.
padding: array_like[int, int, int, int], optional
Padding applied to the sample volume to avoid edge effects,
by default (10, 10, 10, 10).
output_region: array_like[int, int, int, int], optional
Region of the image to output (x, y, width, height). If None, the
entire image is returned, by default (0, 0, 128, 128).
pupil: Feature, optional
Feature-set resolving the pupil function at focus. By default, no pupil
is applied.
illumination: Feature, optional
Feature-set resolving the illumination source. By default, no specific
illumination is applied.
upscale: int, optional
Scaling factor for the resolution of the optical system, by default 1.
**kwargs: Dict[str, Any]
Additional parameters passed to the base `Feature` class.
Attributes
----------
__conversion_table__: ConversionTable
Table used to convert properties of the feature to desired units.
NA: float
Numerical aperture of the optical system.
wavelength: float
Wavelength of the scattered light in meters.
refractive_index_medium: float
Refractive index of the medium.
magnification: float
Magnification of the optical system.
resolution: float or array_like[float]
Pixel spacing in the camera. Optionally includes the z-direction.
padding: array_like[int]
Padding applied to the sample volume to reduce edge effects.
output_region: array_like[int]
Region of the output image to extract (x, y, width, height).
voxel_size: function
Function returning the voxel size of the optical system.
pixel_size: function
Function returning the pixel size of the optical system.
upscale: int
Scaling factor for the resolution of the optical system.
limits: array_like[int, int]
Limits of the volume to be imaged.
fields: list[Feature]
List of fields to be imaged.
Methods
-------
`_process_properties(propertydict: Dict[str, Any]) -> Dict[str, Any]`
Processes and validates the input properties.
`_pupil(shape: array_like[int, int], NA: float, wavelength: float, refractive_index_medium: float, include_aberration: bool, defocus: float, **kwargs: Dict[str, Any]) -> array_like[complex]`
Calculates the pupil function at different focal points.
`_pad_volume(volume: array_like[complex], limits: array_like[int, int], padding: array_like[int], output_region: array_like[int], **kwargs: Dict[str, Any]) -> tuple`
Pads the volume with zeros to avoid edge effects.
`__call__(sample: Feature, **kwargs: Dict[str, Any]) -> Microscope`
Creates a Microscope instance with the given sample and optics.
Examples
--------
Creating an `Optics` instance:
>>> import deeptrack as dt
>>> optics = dt.Optics(NA=0.8, wavelength=0.55e-6, magnification=20)
>>> print(optics.NA())
0.8
"""
__conversion_table__ = ConversionTable(
wavelength=(u.meter, u.meter),
resolution=(u.meter, u.meter),
voxel_size=(u.meter, u.meter),
)
def __init__(
self: 'Optics',
NA: PropertyLike[float] = 0.7,
wavelength: PropertyLike[float] = 0.66e-6,
magnification: PropertyLike[float] = 10,
resolution: PropertyLike[Union[float, ArrayLike[float]]] = 1e-6,
refractive_index_medium: PropertyLike[float] = 1.33,
padding: PropertyLike[ArrayLike[int]] = (10, 10, 10, 10),
output_region: PropertyLike[ArrayLike[int]] = (0, 0, 128, 128),
pupil: Feature = None,
illumination: Feature = None,
upscale: int = 1,
**kwargs: Dict[str, Any],
) -> None:
"""Initialize the `Optics` instance.
Parameters
----------
NA: float, optional
Numerical aperture (NA) of the limiting aperture, by default 0.7.
wavelength: float, optional
Wavelength of the scattered light in meters, by default 0.66e-6.
magnification: float, optional
Magnification of the optical system, by default 10.
resolution: float or array_like[float], optional
Distance between pixels in the camera (meters). A third value can
define the resolution in the z-direction, by default 1e-6.
refractive_index_medium: float, optional
Refractive index of the medium, by default 1.33.
padding: array_like[int, int, int, int], optional
Padding applied to the sample volume to avoid edge effects,
by default (10, 10, 10, 10).
output_region: array_like[int, int, int, int], optional
Region of the image to output (x, y, width, height). If None, the
entire image is returned, by default (0, 0, 128, 128).
pupil: Feature, optional
Feature-set resolving the pupil function at focus. By default, no pupil
is applied.
illumination: Feature, optional
Feature-set resolving the illumination source. By default, no specific
illumination is applied.
upscale: int, optional
Scaling factor for the resolution of the optical system, by default 1.
**kwargs: Dict[str, Any]
Additional parameters passed to the base `Feature` class.
Attributes
----------
NA: float
Numerical aperture of the optical system.
wavelength: float
Wavelength of the scattered light in meters.
refractive_index_medium: float
Refractive index of the medium.
magnification: float
Magnification of the optical system.
resolution: float or array_like[float]
Pixel spacing of the camera in meters. Optionally includes the
z-direction.
padding: array_like[int]
Padding applied to the sample volume to reduce edge effects.
output_region: array_like[int]
Region of the output image to extract (x, y, width, height).
voxel_size: function
Function returning the voxel size of the optical system.
pixel_size: function
Function returning the pixel size of the optical system.
upscale: int
Scaling factor for the resolution of the optical system.
limits: array_like[int, int]
Limits of the volume to be imaged.
fields: list[Feature]
List of fields to be imaged.
Helper Functions
----------------
`get_voxel_size(resolution: float or array_like[float], magnification: float) -> array_like[float]`
Calculate the voxel size.
`get_pixel_size(resolution: float or array_like[float], magnification: float) -> float`
Calculate the pixel size.
"""
def get_voxel_size(
resolution: Union[float, ArrayLike[float]],
magnification: float,
) -> ArrayLike[float]:
""" Calculate the voxel size.
Parameters
----------
resolution: float or array_like[float]
The distance between pixels of the camera in meters. A third
value can define the resolution in the z-direction.
magnification: float
The magnification of the optical system.
Returns
-------
array_like[float]
The voxel size of the optical system.
"""
props = self._normalize(resolution=resolution, magnification=magnification)
return np.ones((3,)) * props["resolution"] / props["magnification"]
def get_pixel_size(
resolution: Union[float, ArrayLike[float]],
magnification: float,
) -> float:
""" Calculate the pixel size.
It differs from the voxel size by only being a single value.
Parameters
----------
resolution: float or array_like[float]
The distance between pixels in the camera. A third value can
define the resolution in the z-direction.
magnification: float
The magnification of the optical system.
Returns
-------
float
The pixel size of the optical system.
"""
props = self._normalize(
resolution=resolution,
magnification=magnification,
)
pixel_size = props["resolution"] / props["magnification"]
if isinstance(pixel_size, Quantity):
return pixel_size.to(u.meter).magnitude
else:
return pixel_size
super().__init__(
NA=NA,
wavelength=wavelength,
refractive_index_medium=refractive_index_medium,
magnification=magnification,
resolution=resolution,
padding=padding,
output_region=output_region,
voxel_size=get_voxel_size,
pixel_size=get_pixel_size,
upscale=upscale,
limits=None,
fields=None,
**kwargs,
)
self.pupil = self.add_feature(pupil) if pupil else DummyFeature()
self.illumination = (
self.add_feature(illumination) if illumination else DummyFeature()
)
def _process_properties(
self: 'Optics',
propertydict: Dict[str, Any],
) -> Dict[str, Any]:
"""Processes and validates the input properties.
Ensures that the provided optical parameters are reasonable.
Parameters
----------
propertydict: Dict[str, Any]
The input properties.
Returns
-------
dict: Dict[str, Any]
The processed properties.
"""
propertydict = super()._process_properties(propertydict)
NA = propertydict["NA"]
wavelength = propertydict["wavelength"]
voxel_size = get_active_voxel_size()
radius = NA / wavelength * np.array(voxel_size)
if np.any(radius[:2] > 0.5):
required_upscale = np.max(np.ceil(radius[:2] * 2))
warnings.warn(
f"""Likely bad optical parameters. NA / wavelength *
resolution / magnification = {radius} should be at most 0.5.
To fix, set magnification to {required_upscale}, and downsample
the resulting image with
dt.AveragePooling(({required_upscale}, {required_upscale}, 1))
"""
)
return propertydict
def _pupil(
self: 'Optics',
shape: ArrayLike[int],
NA: float,
wavelength: float,
refractive_index_medium: float,
include_aberration: bool = True,
defocus: Union[float, ArrayLike[float]] = 0,
**kwargs: Dict[str, Any],
):
"""Calculates the pupil function at different focal points.
Parameters
----------
shape: array_like[int, int]
The shape of the pupil function.
NA: float
The NA of the limiting aperture.
wavelength: float
The wavelength of the scattered light in meters.
refractive_index_medium: float
The refractive index of the medium.
voxel_size: array_like[float (, float, float)]
The distance between pixels in the camera. A third value can be
included to define the resolution in the z-direction.
include_aberration: bool
If True, the aberration is included in the pupil function.
defocus: float or list[float]
The defocus of the system. If a list is given, the pupil is
calculated for each focal point. Defocus is given in meters.
Returns
-------
pupil: array_like[complex]
The pupil function. Shape is (z, y, x).
Examples
--------
Calculating the pupil function:
>>> import deeptrack as dt
>>> optics = dt.Optics()
>>> pupil = optics._pupil(
... shape=(128, 128),
... NA=0.8,
... wavelength=0.55e-6,
... refractive_index_medium=1.33,
... )
>>> print(pupil.shape)
(1, 128, 128)
"""
# Calculates the pupil at each z-position in defocus.
voxel_size = get_active_voxel_size()
shape = np.array(shape)
# Pupil radius
R = NA / wavelength * np.array(voxel_size)[:2]
x_radius = R[0] * shape[0]
y_radius = R[1] * shape[1]
x = (np.linspace(-(shape[0] / 2), shape[0] / 2 - 1, shape[0])) / x_radius + 1e-8
y = (np.linspace(-(shape[1] / 2), shape[1] / 2 - 1, shape[1])) / y_radius + 1e-8
W, H = np.meshgrid(y, x)
W = maybe_cupy(W)
H = maybe_cupy(H)
RHO = (W ** 2 + H ** 2).astype(complex)
pupil_function = Image((RHO < 1) + 0.0j, copy=False)
# Defocus
z_shift = Image(
2
* np.pi
* refractive_index_medium
/ wavelength
* voxel_size[2]
* np.sqrt(1 - (NA / refractive_index_medium) ** 2 * RHO),
copy=False,
)
z_shift._value[z_shift._value.imag != 0] = 0
try:
z_shift = np.nan_to_num(z_shift, False, 0, 0, 0)
except TypeError:
np.nan_to_num(z_shift, z_shift)
defocus = np.reshape(defocus, (-1, 1, 1))
z_shift = defocus * np.expand_dims(z_shift, axis=0)
if include_aberration:
pupil = self.pupil
if isinstance(pupil, Feature):
pupil_function = pupil(pupil_function)
elif isinstance(pupil, np.ndarray):
pupil_function *= pupil
pupil_functions = pupil_function * np.exp(1j * z_shift)
return pupil_functions
def _pad_volume(
self: 'Optics',
volume: ArrayLike[complex],
limits: ArrayLike[int] = None,
padding: ArrayLike[int] = None,
output_region: ArrayLike[int] = None,
**kwargs: Dict[str, Any],
) -> tuple:
"""Pads the volume with zeros to avoid edge effects.
Parameters
----------
volume: array_like[complex]
The volume to pad.
limits: array_like[int, int]
The limits of the volume.
padding: array_like[int]
The padding to apply. Format is (left, right, top, bottom).
output_region: array_like[int, int]
The region of the volume to return. Used to remove regions of the
volume that are far outside the view. If None, the full volume is
returned.
Returns
-------
new_volume: array_like[complex]
The padded volume.
new_limits: array_like[int, int]
The new limits of the volume.
Examples
--------
Padding a volume:
>>> import deeptrack as dt
>>> import numpy as np
>>> volume = np.ones((10, 10, 10), dtype=complex)
>>> limits = np.array([[0, 10], [0, 10], [0, 10]])
>>> optics = dt.Optics()
>>> padded_volume, new_limits = optics._pad_volume(
... volume, limits=limits, padding=[5, 5, 5, 5],
... output_region=[0, 0, 10, 10],
... )
>>> print(padded_volume.shape)
(20, 20, 10)
>>> print(new_limits)
[[-5 15]
[-5 15]
[ 0 10]]
"""
if limits is None:
limits = np.zeros((3, 2))
new_limits = np.array(limits)
output_region = np.array(output_region)
# Replace None entries with current limit
output_region[0] = (
output_region[0] if not output_region[0] is None else new_limits[0, 0]
)
output_region[1] = (
output_region[1] if not output_region[1] is None else new_limits[0, 1]
)
output_region[2] = (
output_region[2] if not output_region[2] is None else new_limits[1, 0]
)
output_region[3] = (
output_region[3] if not output_region[3] is None else new_limits[1, 1]
)
for i in range(2):
new_limits[i, :] = (
np.min([new_limits[i, 0], output_region[i] - padding[i]]),
np.max(
[
new_limits[i, 1],
output_region[i + 2] + padding[i + 2],
]
),
)
new_volume = np.zeros(
np.diff(new_limits, axis=1)[:, 0].astype(np.int32),
dtype=complex,
)
old_region = (limits - new_limits).astype(np.int32)
limits = limits.astype(np.int32)
new_volume[
old_region[0, 0] : old_region[0, 0] + limits[0, 1] - limits[0, 0],
old_region[1, 0] : old_region[1, 0] + limits[1, 1] - limits[1, 0],
old_region[2, 0] : old_region[2, 0] + limits[2, 1] - limits[2, 0],
] = volume
return new_volume, new_limits
def __call__(
self: 'Optics',
sample: Feature,
**kwargs: Dict[str, Any],
) -> Microscope:
"""Creates a Microscope instance with the given sample and optics.
Parameters
----------
sample: Feature
The sample to be imaged.
**kwargs: Dict[str, Any]
Additional parameters for the Microscope.
Returns
-------
Microscope: Microscope
A Microscope instance configured with the sample and optics.
Examples
--------
Creating a Microscope instance:
>>> import deeptrack as dt
>>> scatterer = dt.PointParticle()
>>> optics = dt.Optics()
>>> microscope = optics(scatterer)
>>> print(isinstance(microscope, dt.Microscope))
True
"""
return Microscope(sample, self, **kwargs)
# def _no_wrap_format_input(self, *args, **kwargs) -> list:
# return self._image_wrapped_format_input(*args, **kwargs)
# def _no_wrap_process_and_get(self, *args, **feature_input) -> list:
# return self._image_wrapped_process_and_get(*args, **feature_input)
# def _no_wrap_process_output(self, *args, **feature_input):
# return self._image_wrapped_process_output(*args, **feature_input)
class Fluorescence(Optics):
"""Optical device for fluorescent imaging.
The `Fluorescence` class simulates the imaging process in fluorescence
microscopy by creating a discretized volume where each pixel represents
the intensity of light emitted by fluorophores in the sample. It extends
the `Optics` class to include fluorescence-specific functionalities.
Parameters
----------
NA: float
Numerical aperture of the optical system.
wavelength: float
Emission wavelength of the fluorescent light (in meters).
magnification: float
Magnification of the optical system.
resolution: array_like[float (, float, float)]
Pixel spacing in the camera. Optionally includes the z-direction.
refractive_index_medium: float
Refractive index of the imaging medium.
padding: array_like[int, int, int, int]
Padding applied to the sample volume to reduce edge effects.
output_region: array_like[int, int, int, int], optional
Region of the output image to extract (x, y, width, height). If None,
returns the full image.
pupil: Feature, optional
A feature set defining the pupil function at focus. The input is
the unaberrated pupil.
illumination: Feature, optional
A feature set defining the illumination source.
upscale: int, optional
Scaling factor for the resolution of the optical system.
**kwargs: Dict[str, Any]
Attributes
----------
__gpu_compatible__: bool
Indicates whether the class supports GPU acceleration.
NA: float
Numerical aperture of the optical system.
wavelength: float
Emission wavelength of the fluorescent light (in meters).
magnification: float
Magnification of the optical system.
resolution: array_like[float (, float, float)]
Pixel spacing in the camera. Optionally includes the z-direction.
refractive_index_medium: float
Refractive index of the imaging medium.
padding: array_like[int, int, int, int]
Padding applied to the sample volume to reduce edge effects.
output_region: array_like[int, int, int, int]
Region of the output image to extract (x, y, width, height).
voxel_size: function
Function returning the voxel size of the optical system.
pixel_size: function
Function returning the pixel size of the optical system.
upscale: int
Scaling factor for the resolution of the optical system.
limits: array_like[int, int]
Limits of the volume to be imaged.
fields: list[Feature]
List of fields to be imaged
Methods
-------
`get(illuminated_volume: array_like[complex], limits: array_like[int, int], **kwargs: Dict[str, Any]) -> Image`
Simulates the imaging process using a fluorescence microscope.
Examples
--------