-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathscatterers.py
1383 lines (1100 loc) · 43 KB
/
scatterers.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
"""Classes that implement light-scattering objects.
This module provides implementations of scattering objects
with geometries that are commonly observed in experimental setups
such as ellipsoids, spheres, or point-particles.
These scatterer objects are primarily used in combination with the `Optics`
module to simulate how a (e.g. brightfield) microscope would resolve the
object for a given optical setup (NA, wavelength, Refractive Index etc.).
Key Features
------------
- **Customizable geometries**
The initialization parameters allow the user to choose proportions and
positioning of the scatterer in the image. It is also possible to combine
multiple scatterers and overlay them, e.g. two ellipses orthogonal
to each other would form a plus-shape or combining two spheres
(one small, one large) to simulate a core-shell particle.
- **Defocusing**
As the `z` parameter represents the scatterers position in relation to the
focal point of the microscope, the user can simulate defocusing by setting
this parameter to be non-zero.
- **Mie scatterers**
Implements Mie-theory scatterers that calculates harmonics up to a desired
order with functions and utilities from `deeptrack.backend.mie`. Includes
the case of a spherical Mie scatterer, and a stratified spherical
scatterer which is a sphere with several concentric shells of
uniform refractive index.
Module Structure
----------------
Classes:
- `Scatterer`: Abstract base class for scatterers.
This abstract class stores positional information about the scatterer
and implements a method to convert the position to voxel units,
as well as the a methods to upsample and crop.
- `PointParticle`: Generates point particles with the size of 1 pixel.
Represented as a numpy array of ones.
- `Ellipse`: Generates 2-D elliptical particles.
- `Sphere`: Generates 3-D spheres.
- `Ellipsoid`: Generates 3-D ellipsoids.
- `MieScatterer`: Mie scatterer base class.
- `MieSphere`: Extends `MieScatterer` to the spherical case.
- `MieStratifiedSphere`: Extends `MieScatterer` to the stratified sphere case.
A stratified sphere is a sphere with several concentric shells of uniform
refractive index.
Examples
--------
Create a ellipse scatterer and resolve it through a microscope:
>>> import numpy as np
>>> import deeptrack as dt
>>> optics = dt.Fluorescence(
... NA=0.7,
... wavelength=680e-9,
... resolution=1e-6,
... magnification=10,
... output_region=(0, 0, 64, 64),
... )
>>> scatterer = dt.Ellipse(
... intensity=100,
... position_unit="pixel",
... position=(32, 32),
... radius=(1e-6, 0.5e-6),
... rotation=np.pi / 4,
... upsample=4,
... )
>>> imaged_scatterer = optics(scatterer)
>>> imaged_scatterer.plot(cmap="gray")
Combine multiple scatterers to image a core-shell particle:
>>> import numpy as np
>>> import deeptrack as dt
>>> optics = dt.Fluorescence(
... NA=1.4,
... wavelength=638.0e-9,
... refractive_index_medium=1.33,
... output_region=[0, 0, 64, 64],
... magnification=1,
... resolution=100e-9,
... return_field=False,
... )
>>> inner_sphere = dt.Ellipsoid(
... position=(32, 32),
... z=-500e-9, # Defocus slightly.
... radius=450e-9,
... intensity=100,
... )
>>> outer_sphere = dt.Ellipsoid(
... position=inner_sphere.position,
... z=inner_sphere.z,
... radius=inner_sphere.radius * 2,
... intensity= inner_sphere.intensity * -0.25,
... )
>>> combined_scatterer = inner_sphere >> outer_sphere
>>> imaged_scatterer = optics(combined_scatterer)
>>> imaged_scatterer.plot(cmap="gray")
Create a stratified Mie sphere and resolve it through a microscope:
>>> import numpy as np
>>> import deeptrack as dt
>>> optics = dt.Brightfield(
... NA=0.7,
... wavelength=680e-9,
... resolution=1e-6,
... magnification=5,
... output_region=(0, 0, 64, 64),
... return_field=True,
... upscale=4,
... )
>>> scatterer = dt.MieStratifiedSphere(
... radius=np.array([0.5e-6, 3e-6]),
... refractive_index=[1.45 + 0.1j, 1.52],
... position_unit="pixel",
... position=(128, 128),
... aperature_angle=0.1,
... )
>>> imaged_scatterer = optics(scatterer) # Creates an array of complex numbers.
>>> abs_imaged_scatterer = dt.Abs(imaged_scatterer)
>>> abs_imaged_scatterer.plot()
"""
from __future__ import annotations
from typing import Callable
import warnings
from pint import Quantity
import numpy as np
from deeptrack.holography import get_propagation_matrix
from deeptrack.backend.units import (
ConversionTable,
get_active_scale,
get_active_voxel_size,
)
from deeptrack.backend import mie
from deeptrack.features import Feature, MERGE_STRATEGY_APPEND
from deeptrack.image import pad_image_to_fft, maybe_cupy, Image
from deeptrack.types import ArrayLike
from deeptrack import units as u
class Scatterer(Feature):
"""Base abstract class for scatterers.
A scatterer is defined by a 3-dimensional volume of voxels.
To each voxel corresponds an occupancy factor, i.e., how much
of that voxel does the scatterer occupy. However, this number is not
necessarily limited to the [0, 1] range. It can be any number, and its
interpretation is left to the optical device that images the scatterer.
This abstract class implements the `_process_properties` method to convert
the position to voxel units, as well as the `_process_and_get` method to
upsample the calculation and crop empty slices.
Attributes
----------
position: ArrayLike[float, float (, float)]
The position of the particle, length 2 or 3. Third index is optional,
and represents the position in the direction normal to the
camera plane.
z: float
The position in the direction normal to the
camera plane. Used if `position` is of length 2.
value: float
A default value of the characteristic of the particle. Used by
optics unless a more direct property is set (eg. `refractive_index`
for `Brightfield` and `intensity` for `Fluorescence`).
position_unit: "meter" or "pixel"
The unit of the provided position property.
upsample_axes: tuple of ints
Sets the axes along which the calculation is upsampled (default is
None, which implies all axes are upsampled).
crop_zeros: bool
Whether to remove slices in which all elements are zero.
"""
__list_merge_strategy__ = MERGE_STRATEGY_APPEND
__distributed__ = False
__conversion_table__ = ConversionTable(
position=(u.pixel, u.pixel),
z=(u.zpixel, u.zpixel),
voxel_size=(u.meter, u.meter),
)
def __init__(
self,
position: ArrayLike[float] = (32, 32),
z: float = 0.0,
value: float = 1.0,
position_unit: str = "pixel",
upsample: int = 1,
voxel_size=None,
pixel_size=None,
**kwargs,
) -> None:
# Ignore warning to help with comparison with arrays.
if upsample is not 1: # noqa: F632
warnings.warn(
f"Setting upsample != 1 is deprecated. "
f"Please, instead use dt.Upscale(f, factor={upsample})"
)
self._processed_properties = False
super().__init__(
position=position,
z=z,
value=value,
position_unit=position_unit,
upsample=upsample,
voxel_size=voxel_size,
pixel_size=pixel_size,
_position_sampler=lambda: position,
**kwargs,
)
def _process_properties(
self,
properties: dict
) -> dict:
# Rescales the position property.
properties = super()._process_properties(properties)
self._processed_properties = True
return properties
def _process_and_get(
self,
*args,
voxel_size: ArrayLike[int],
upsample: int,
upsample_axes=None,
crop_empty=True,
**kwargs
) -> list[Image] | list[np.ndarray]:
# Post processes the created object to handle upsampling,
# as well as cropping empty slices.
if not self._processed_properties:
warnings.warn(
"Overridden _process_properties method does not call super. "
+ "This is likely to result in errors if used with "
+ "Optics.upscale != 1."
)
voxel_size = get_active_voxel_size()
# Calls parent _process_and_get.
new_image = super()._process_and_get(
*args,
voxel_size=voxel_size,
upsample=upsample,
**kwargs,
)
new_image = new_image[0]
if new_image.size == 0:
warnings.warn(
"Scatterer created that is smaller than a pixel. "
+ "This may yield inconsistent results."
+ " Consider using upsample on the scatterer,"
+ " or upscale on the optics.",
Warning,
)
# Crops empty slices
if crop_empty:
new_image = new_image[~np.all(new_image == 0, axis=(1, 2))]
new_image = new_image[:, ~np.all(new_image == 0, axis=(0, 2))]
new_image = new_image[:, :, ~np.all(new_image == 0, axis=(0, 1))]
return [Image(new_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
) -> list:
return self._image_wrapped_process_output(*args, **feature_input)
class PointParticle(Scatterer):
"""Generates a point particle
A point particle is approximated by the size of a pixel. For subpixel
positioning, the position is interpolated linearly.
Parameters
----------
position: ArrayLike[float, float (, float)]
The position of the particle, length 2 or 3. Third index is optional,
and represents the position in the direction normal to the
camera plane.
z: float
The position in the direction normal to the
camera plane. Used if `position` is of length 2.
value: float
A default value of the characteristic of the particle. Used by
optics unless a more direct property is set: (eg. `refractive_index`
for `Brightfield` and `intensity` for `Fluorescence`).
"""
def __init__(
self,
**kwargs
) -> None:
super().__init__(upsample=1, upsample_axes=(), **kwargs)
def get(
self,
image: Image | np.ndarray,
**kwarg
) -> ArrayLike[float]:
"""Abstract method to initialize the point scatterer"""
scale = get_active_scale()
return np.ones((1, 1, 1)) * np.prod(scale)
class Ellipse(Scatterer):
"""Generates an elliptical disk scatterer
Parameters
----------
radius: float | ArrayLike[float, (,float)]
Radius of the ellipse in meters. If only one value,
assume circular.
rotation: float
Orientation angle of the ellipse in the camera plane in radians.
position: ArrayLike[float]
The position of the particle. Third index is optional,
and represents the position in the direction normal to the
camera plane.
z: float
The position in the direction normal to the
camera plane. Used if `position` is of length 2.
value: float
A default value of the characteristic of the particle. Used by
optics unless a more direct property is set: (eg. `refractive_index`
for `Brightfield` and `intensity` for `Fluorescence`).
upsample: int
Upsamples the calculations of the pixel occupancy fraction.
transpose: bool
If True, the ellipse is transposed as to align the first axis of the
radius with the first axis of the created volume. This is applied
before rotation.
"""
__conversion_table__ = ConversionTable(
radius=(u.meter, u.meter),
rotation=(u.radian, u.radian),
)
def __init__(
self,
radius: float = 1e-6,
rotation: float = 0,
transpose: bool = False,
**kwargs,
) -> None:
super().__init__(
radius=radius, rotation=rotation, transpose=transpose, **kwargs
)
def _process_properties(
self,
properties: dict
) -> dict:
"""Preprocess the input to the method .get()
Ensures that the radius is an array of length 2. If the radius
is a single value, the particle is made circular
"""
properties = super()._process_properties(properties)
# Ensure radius is of length 2
radius = np.array(properties["radius"])
if radius.ndim == 0:
radius = np.array((properties["radius"], properties["radius"]))
elif radius.size == 1:
radius = np.array((*radius,) * 2)
else:
radius = radius[:2]
properties["radius"] = radius
return properties
def get(
self,
*ignore,
radius: ArrayLike[float] | float,
rotation: float,
voxel_size: float,
transpose: float,
**kwargs
) -> ArrayLike[float]:
"""Abstract method to initialize the ellipse scatterer"""
if not transpose:
radius = radius[::-1]
# rotation = rotation[::-1]
# Create a grid to calculate on.
rad = radius[:2]
ceil = int(np.ceil(np.max(rad) / np.min(voxel_size[:2])))
Y, X = np.meshgrid(
np.arange(-ceil, ceil) * voxel_size[1],
np.arange(-ceil, ceil) * voxel_size[0],
)
# Rotate the grid.
if rotation != 0:
Xt = X * np.cos(-rotation) + Y * np.sin(-rotation)
Yt = -X * np.sin(-rotation) + Y * np.cos(-rotation)
X = Xt
Y = Yt
# Evaluate ellipse.
mask = (
(X * X) / (rad[0] * rad[0]) +
(Y * Y) / (rad[1] * rad[1]) < 1
).astype(float)
mask = np.expand_dims(mask, axis=-1)
return mask
class Sphere(Scatterer):
"""Generates a spherical scatterer
Parameters
----------
radius: float
Radius of the sphere in meters.
position: ArrayLike[float, float (, float)]
The position of the particle, length 2 or 3. Third index is optional,
and represents the position in the direction normal to the
camera plane.
z: float
The position in the direction normal to the
camera plane. Used if `position` is of length 2.
value: float
A default value of the characteristic of the particle. Used by
optics unless a more direct property is set: (eg. `refractive_index`
for `Brightfield` and `intensity` for `Fluorescence`).
upsample: int
Upsamples the calculations of the pixel occupancy fraction.
"""
__conversion_table__ = ConversionTable(
radius=(u.meter, u.meter),
)
def __init__(
self,
radius: float = 1e-6,
**kwargs
) -> None:
super().__init__(radius=radius, **kwargs)
def get(
self,
image: Image | np.ndarray,
radius: float,
voxel_size: float,
**kwargs
) -> ArrayLike[float]:
"""Abstract method to initialize the sphere scatterer"""
# Create a grid to calculate on.
rad = radius * np.ones(3) / voxel_size
rad_ceil = np.ceil(rad)
x = np.arange(-rad_ceil[0], rad_ceil[0])
y = np.arange(-rad_ceil[1], rad_ceil[1])
z = np.arange(-rad_ceil[2], rad_ceil[2])
X, Y, Z = np.meshgrid(
(y / rad[1]) ** 2,
(x / rad[0]) ** 2,
(z / rad[2]) ** 2
)
mask = (X + Y + Z <= 1).astype(float)
return mask
class Ellipsoid(Scatterer):
"""Generates an ellipsoidal scatterer
Parameters
----------
radius: float | ArrayLike[float (, float, float)]
Radius of the ellipsoid in meters. If only one value,
assume spherical.
rotation: float
Rotation of the ellipsoid in about the x, y and z axis.
position: ArrayLike[float, float (, float)]
The position of the particle. Third index is optional,
and represents the position in the direction normal to the
camera plane.
z: float
The position in the direction normal to the
camera plane. Used if `position` is of length 2.
value: float
A default value of the characteristic of the particle. Used by
optics unless a more direct property is set: (eg. `refractive_index`
for `Brightfield` and `intensity` for `Fluorescence`).
upsample: int
Upsamples the calculations of the pixel occupancy fraction.
transpose: bool
If True, the ellipse is transposed as to align the first axis
of the radius with the first axis of the created volume.
This is applied before rotation.
"""
__conversion_table__ = ConversionTable(
radius=(u.meter, u.meter),
rotation=(u.radian, u.radian),
)
def __init__(
self,
radius: float = 1e-6,
rotation: float = 0,
transpose: float = False,
**kwargs,
) -> None:
super().__init__(
radius=radius, rotation=rotation, transpose=transpose, **kwargs
)
def _process_properties(
self,
propertydict: dict
) -> dict:
"""Preprocess the input to the method .get()
Ensures that the radius and the rotation properties both are arrays of
length 3.
If the radius is a single value, the particle is made a sphere
If the radius are two values, the smallest value is appended as the
third value
The rotation vector is padded with zeros until it is of length 3
"""
propertydict = super()._process_properties(propertydict)
# Ensure radius has three values.
radius = np.array(propertydict["radius"])
if radius.ndim == 0:
radius = np.array([radius])
if radius.size == 1:
# If only one value, assume sphere.
radius = (*radius,) * 3
elif radius.size == 2:
# If two values, duplicate the minor axis.
radius = (*radius, np.min(radius[-1]))
elif radius.size == 3:
# If three values, convert to tuple for consistency.
radius = (*radius,)
propertydict["radius"] = radius
# Ensure rotation has three values.
rotation = np.array(propertydict["rotation"])
if rotation.ndim == 0:
rotation = np.array([rotation])
if rotation.size == 1:
# If only one value, pad with two zeros.
rotation = (*rotation, 0, 0)
elif rotation.size == 2:
# If two values, pad with one zero.
rotation = (*rotation, 0)
elif rotation.size == 3:
# If three values, convert to tuple for consistency.
rotation = (*rotation,)
propertydict["rotation"] = rotation
return propertydict
def get(
self,
image: Image | np.ndarray,
radius: float,
rotation: ArrayLike[float] | float,
voxel_size: float,
transpose: bool,
**kwargs
) -> ArrayLike[float]:
"""Abstract method to initialize the ellipsoid scatterer"""
if not transpose:
# Swap the first and second value of the radius vector.
radius = (radius[1], radius[0], radius[2])
# radius_in_pixels = np.array(radius) / np.array(voxel_size)
# max_rad = np.max(radius_in_pixels)
rad_ceil = np.ceil(np.max(radius) / np.min(voxel_size))
# Create grid to calculate on.
x = np.arange(-rad_ceil, rad_ceil) * voxel_size[0]
y = np.arange(-rad_ceil, rad_ceil) * voxel_size[1]
z = np.arange(-rad_ceil, rad_ceil) * voxel_size[2]
Y, X, Z = np.meshgrid(y, x, z)
# Rotate the grid.
cos = np.cos(rotation)
sin = np.sin(rotation)
XR = (
(cos[0] * cos[1] * X)
+ (cos[0] * sin[1] * sin[2] - sin[0] * cos[2]) * Y
+ (cos[0] * sin[1] * cos[2] + sin[0] * sin[2]) * Z
)
YR = (
(sin[0] * cos[1] * X)
+ (sin[0] * sin[1] * sin[2] + cos[0] * cos[2]) * Y
+ (sin[0] * sin[1] * cos[2] - cos[0] * sin[2]) * Z
)
ZR = (-sin[1] * X) + cos[1] * sin[2] * Y + cos[1] * cos[2] * Z
mask = (
(XR / radius[0]) ** 2 +
(YR / radius[1]) ** 2 +
(ZR / radius[2]) ** 2 < 1
).astype(float)
return mask
class MieScatterer(Scatterer):
"""Base implementation of a Mie particle.
New Mie-theory scatterers can be implemented by extending this class, and
passing a function that calculates the coefficients of the harmonics up to
order `L`. To be precise, the feature expects a wrapper function that takes
the current values of the properties, as well as a inner function that
takes an integer as the only parameter, and calculates the coefficients up
to that integer. The return format is expected to be a tuple with two
values, corresponding to `an` and `bn`.
See `deeptrack.backend.mie.coefficients` for an example.
Attributes
----------
coefficients: Callable[int] -> tuple[ndarray, ndarray]
Function that returns the harmonics coefficients.
offset_z: "auto" | float
Distance from the particle in the z direction the field is evaluated.
If "auto", this is calculated from the pixel size and
`collection_angle`.
collection_angle: "auto" | float
The maximum collection angle in radians. If "auto", this
is calculated from the objective NA (which is true if the objective is
the limiting aperature).
input_polarization: float | Quantity
Defines the polarization angle of the input. For simulating circularly
polarized light we recommend a coherent sum of two simulated fields.
For unpolarized light we recommend a incoherent sum of two simulated
fields. If defined as "circular", the coefficients are set to 1/2.
output_polarization: float | Quantity | None
If None, the output light is not polarized. Otherwise defines the
angle of the polarization filter after the sample. For off-axis, keep
the same as input_polarization. If defined as "circular", the
coefficients are multiplied by 1. I.e. no change.
L: int | str
The number of terms used to evaluate the mie theory. If `"auto"`,
it determines the number of terms automatically.
position: ArrayLike[float, float (, float)]
The position of the particle, length 2 or 3. Third index is optional,
and represents the position in the direction normal to the
camera plane.
z: float
The position in the direction normal to the
camera plane. Used if `position` is of length 2.
return_fft: bool
If True, the feature returns the fft of the field, rather than the
field itself.
coherence_length: float
The temporal coherence length of a partially coherent light given in
meters. If None, the illumination is assumed to be coherent.
amp_factor: float
A factor that scales the amplification of the field.
This is useful for scaling the field to the correct intensity.
Default is 1.
phase_shift_correction: bool
If True, the feature applies a phase shift correction to the output
field. This is necessary for ISCAT simulations.
The correction depends on the k-vector and z according to the formula:
arr*=np.exp(1j * k * z + 1j * np.pi / 2)
"""
__gpu_compatible__ = True
__conversion_table__ = ConversionTable(
radius=(u.meter, u.meter),
polarization_angle=(u.radian, u.radian),
collection_angle=(u.radian, u.radian),
wavelength=(u.meter, u.meter),
offset_z=(u.meter, u.meter),
coherence_length=(u.meter, u.pixel),
)
def __init__(
self,
coefficients,
input_polarization: int=0,
output_polarization: int=0,
offset_z: str="auto",
collection_angle: str = "auto",
L: str = "auto",
refractive_index_medium: float=None,
wavelength: float=None,
NA: float=None,
padding=(0,) * 4,
output_region=None,
polarization_angle: float=None,
working_distance: float=1000000, # Value to avoid numerical issues.
position_objective: tuple[float, float]=(0, 0),
return_fft: bool=False,
coherence_length: float=None,
illumination_angle: float=0,
amp_factor: float=1,
phase_shift_correction: bool=False,
**kwargs,
) -> None:
if polarization_angle is not None:
warnings.warn(
"polarization_angle is deprecated. "
"Please use input_polarization instead"
)
input_polarization = polarization_angle
kwargs.pop("is_field", None)
kwargs.pop("crop_empty", None)
super().__init__(
is_field=True,
crop_empty=False,
L=L,
offset_z=offset_z,
input_polarization=input_polarization,
output_polarization=output_polarization,
collection_angle=collection_angle,
coefficients=coefficients,
refractive_index_medium=refractive_index_medium,
wavelength=wavelength,
NA=NA,
padding=padding,
output_region=output_region,
polarization_angle=polarization_angle,
working_distance=working_distance,
position_objective=position_objective,
return_fft=return_fft,
coherence_length=coherence_length,
illumination_angle=illumination_angle,
amp_factor=amp_factor,
phase_shift_correction=phase_shift_correction,
**kwargs,
)
def _process_properties(
self,
properties: dict
) -> dict:
properties = super()._process_properties(properties)
if properties["L"] == "auto":
try:
v = (
2 * np.pi *
np.max(properties["radius"]) / properties["wavelength"]
)
properties["L"] = int(np.floor((v + 4 * (v ** (1 / 3)) + 1)))
except (ValueError, TypeError):
pass
if properties["collection_angle"] == "auto":
properties["collection_angle"] = np.arcsin(
properties["NA"] / properties["refractive_index_medium"]
)
if properties["offset_z"] == "auto":
size = (
np.array(properties["output_region"][2:])
- properties["output_region"][:2]
)
xSize, ySize = size
arr = pad_image_to_fft(np.zeros((xSize, ySize))).astype(complex)
min_edge_size = np.min(arr.shape)
properties["offset_z"] = (
min_edge_size
* 0.45
* min(properties["voxel_size"][:2])
/ np.tan(properties["collection_angle"])
)
return properties
def get_xy_size(
self,
output_region: ArrayLike[int],
padding: ArrayLike[int]
) -> ArrayLike[int]:
"""Computes the x and y dimensions of the output region with padding.
Parameters
----------
output_region: ArrayLike[int]
The coordinates defining the output region.
padding: ArrayLike[int]
The padding applied in each direction.
Returns
-------
ArrayLike[int]
The total size in x and y directions.
"""
return (
output_region[2] - output_region[0] + padding[0] + padding[2],
output_region[3] - output_region[1] + padding[1] + padding[3],
)
def get_XY(
self,
shape: ArrayLike[float],
voxel_size: ArrayLike[float]
) -> ArrayLike[int] :
"""Generates meshgrid for X and Y given the shape and voxel size.
Parameters
----------
shape: ArrayLike[float]
The dimensions of the output region.
voxel_size: ArrayLike[float]
The size of each voxel in meters.
Returns
-------
ArrayLike[int]
The meshgrid of X and Y coordinates.
"""
x = np.arange(shape[0]) - shape[0] / 2
y = np.arange(shape[1]) - shape[1] / 2
return np.meshgrid(x * voxel_size[0], y * voxel_size[1], indexing="ij")
def get_detector_mask(
self,
X: float,
Y: float,
radius: float
) -> ArrayLike[bool]:
"""Creates a mask based on a circular aperture.
Parameters
----------
X: float
X-coordinates of the field.
Y: float
Y-coordinates of the field.
radius: float
The radius of the detector aperture.
Returns
-------
ArrayLike[bool]
A boolean mask.
"""
return np.sqrt(X ** 2 + Y ** 2) < radius
def get_plane_in_polar_coords(
self,
shape: int,
voxel_size: ArrayLike[float],
plane_position: float,
illumination_angle: float
) -> tuple[float, float, float, float]:
"""Computes the coordinates of the plane in polar form."""
X, Y = self.get_XY(shape, voxel_size)
X = maybe_cupy(X)
Y = maybe_cupy(Y)
# The X, Y coordinates of the pupil relative to the particle.
X = X + plane_position[0]
Y = Y + plane_position[1]
Z = plane_position[2] # Might be +z or -z.
R2_squared = X ** 2 + Y ** 2
R3 = np.sqrt(R2_squared + Z ** 2) # Might be +z instead of -z.
# Fet the angles.