-
Notifications
You must be signed in to change notification settings - Fork 0
/
raytrace.py
1821 lines (1494 loc) · 74.2 KB
/
raytrace.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
"""
ray represented by eight parameters
(xo, yo, zo, dx, dy, dz, phase, wavelength) where (xo, yo, zo) is a point the ray passes through,
and (dx, dy, dz) is a unit vector specifying its direction. The ray travels along the line
C(t) = (xo, yo, zo) + t * (dx, dy, dz)
A paraxial ray has a different representation, in terms of height and angle,
(hx, n*ux, hy, n*uy). Heights and angles are defined relative to some point and axis,
(xo, yo, zo) and (dx, dy, dz).
We adopt a default coordinate system where z points to the right, along the optical axis. x points upwards,
and y points out of the plane, ensuring the coordinate System is right-handed
"""
from typing import Optional, Union
from collections.abc import Sequence
from numpy.typing import NDArray
from copy import deepcopy
import numpy as np
from matplotlib.figure import Figure
from matplotlib.axes._axes import Axes
import matplotlib.pyplot as plt
from raytrace.materials import Material, Vacuum
try:
import cupy as cp
array = Union[NDArray, cp.ndarray]
except ImportError:
cp = None
array = NDArray
def get_free_space_abcd(d: float, n: float = 1.) -> NDArray:
"""
Compute the ray-transfer (ABCD) matrix for free space beam propagation
:param d: distance beam propagated
:param n: index of refraction
:return mat:
"""
mat = np.array([[1, d/n], [0, 1]])
return mat
# tools for creating ray fans, manipulating rays, etc.
def get_ray_fan(pt: NDArray,
theta_max: float,
n_thetas: int,
wavelengths: float,
nphis: int = 1,
center_ray=(0, 0, 1)) -> array:
"""
Get fan of rays emanating from pt
:param pt: [cx, cy, cz]
:param theta_max: maximum angle in radians
:param n_thetas: number of rays at different angles on axis
:param wavelengths:
:param nphis: number of points of rotation about the optical axis. If nphis = 1, all rays will be in the plane
:param center_ray:
"""
xp = cp if cp is not None and isinstance(pt, cp.ndarray) else np
# consider the central ray in direction no. Construct an orthonormal basis from enx = y x no, eny = no x enx
# then construct rays v(theta, phi), where theta is the angle between v and no and phi is the angle rotated about no
# v(theta, phi) = cos(theta) * no + cos(phi) * sin(theta) * enx + sin(phi) * sin(theta) * eny
center_ray = np.array(center_ray)
if np.linalg.norm(center_ray) != 1:
raise ValueError("center_ray must be a unit vector")
thetas = xp.linspace(-theta_max, theta_max, n_thetas)
phis = xp.arange(nphis) * 2*np.pi / nphis
rays = xp.zeros((n_thetas * nphis, 8))
tts, pps = xp.meshgrid(thetas, phis)
tts = tts.ravel()
pps = pps.ravel()
enx = xp.cross(np.array([0, 1, 0]), center_ray)
enx = enx / xp.linalg.norm(enx)
eny = xp.cross(center_ray, enx)
pt = np.array(pt).squeeze()
rays[:, 0] = pt[0]
rays[:, 1] = pt[1]
rays[:, 2] = pt[2]
rays[:, 3] = center_ray[0] * np.cos(tts) + enx[0] * np.cos(pps) * np.sin(tts) + eny[0] * np.sin(pps) * np.sin(tts)
rays[:, 4] = center_ray[1] * np.cos(tts) + enx[1] * np.cos(pps) * np.sin(tts) + eny[1] * np.sin(pps) * np.sin(tts)
rays[:, 5] = center_ray[2] * np.cos(tts) + enx[2] * np.cos(pps) * np.sin(tts) + eny[2] * np.sin(pps) * np.sin(tts)
rays[:, 6] = 0
rays[:, 7] = wavelengths
return rays
def get_collimated_rays(pt: NDArray,
displacement_max,
n_disps: int,
wavelengths: float,
nphis: int = 1,
phi_start: float = 0.,
normal=(0, 0, 1)) -> NDArray:
"""
Get a fan of collimated arrays along a certain direction. The rays will be generated in a plane
with normal along this direction, which will generally not be perpendicular to the optical axis.
Note that this approach avoids the need to know what the index of refraction of the medium is
:param pt: point in the origin plane
:param displacement_max: maximum radial displacement
:param n_disps: number of displacements
:param wavelengths: either floating point or an array the same size as n_disps * nphis
:param nphis: number of rays in azimuthal direction
:param phi_start: angle about normal to start at
:param normal: normal of plane
:return rays:
"""
if np.abs(np.linalg.norm(normal) - 1) > 1e-12:
raise ValueError("normal must be a normalized vector")
# build all angles and offsets and put in 1d arrays
phis = np.arange(nphis) * 2*np.pi / nphis + phi_start
offs = np.linspace(-displacement_max, displacement_max, n_disps)
pps, oos = np.meshgrid(phis, offs)
pps = pps.ravel()
oos = oos.ravel()
pt = np.array(pt).squeeze()
normal = np.array(normal).squeeze()
# build orthogonal unit vectors versus the normal
# n1 -> ex if normal = [0, 0, 1]
n1 = np.cross(np.array([0, 1, 0]), normal)
# except in the case normal is already [0, 1, 0]
if np.linalg.norm(n1) == 0:
n1 = np.cross(normal, np.array([1, 0, 0]))
n1 = n1 / np.linalg.norm(n1)
# n2 -> ey if normal = [0, 0, 1]
n2 = np.cross(normal, n1)
n2 = n2 / np.linalg.norm(n2)
# construct rays
rays = np.zeros((n_disps * nphis, 8))
# position = d * (n1 * cos(theta) + n2 * sin(theta))
rays[:, 0:3] = np.expand_dims(pt, axis=0) + \
np.expand_dims(n1, axis=0) * np.expand_dims(oos * np.cos(pps), axis=1) + \
np.expand_dims(n2, axis=0) * np.expand_dims(oos * np.sin(pps), axis=1)
# rays are parallel
rays[:, 3] = normal[0]
rays[:, 4] = normal[1]
rays[:, 5] = normal[2]
# assume phase is the same on plane perpendicular to the normal
rays[:, 6] = 0
# wavelength
rays[:, 7] = wavelengths
return rays
def intersect_rays(ray1: array, ray2: array) -> array:
"""
Find intersection point between two rays, assuming free space propagation. If either s or t is negative
then these rays previously intersected
:param ray1:
:param ray2:
:return intersection_pt:
"""
xp = cp if cp is not None and isinstance(ray1, cp.ndarray) else np
ray1 = xp.atleast_2d(ray1)
ray2 = xp.atleast_2d(ray2)
if len(ray1) == 1 and len(ray2) > 1:
ray1 = xp.tile(ray1, (len(ray2), 1))
if len(ray2) == 1 and len(ray1) > 1:
ray2 = xp.tile(ray2, (len(ray1), 1))
if len(ray1) != len(ray2):
raise ValueError("ray1 and ray2 must be the same length")
# ray1 = (x1, y1, z1) + t * (dx1, dy1, dz1)
# ray2 = (x2, y2, z2) + s * (dx2, dy2, dz2)
x1 = ray1[:, 0]
y1 = ray1[:, 1]
z1 = ray1[:, 2]
dx1 = ray1[:, 3]
dy1 = ray1[:, 4]
dz1 = ray1[:, 5]
x2 = ray2[:, 0]
y2 = ray2[:, 1]
z2 = ray2[:, 2]
dx2 = ray2[:, 3]
dy2 = ray2[:, 4]
dz2 = ray2[:, 5]
# intersection problem is overdetermined, so this is solution if there is one
# determine distance along ray1
s = xp.zeros(len(ray1)) * np.nan
with np.errstate(invalid="ignore"):
use_xz = dx2 * dz1 - dz2 * dx1 != 0
use_xy = xp.logical_and(xp.logical_not(use_xz),
dx2 * dy1 - dy2 * dx1)
use_yz = xp.logical_and.reduce((xp.logical_not(use_xz),
xp.logical_not(use_xy),
dz2 * dy1 - dy2 * dz1))
s[use_xz] = (((z2 - z1) * dx1 - (x2 - x1) * dz1) / (dx2 * dz1 - dz2 * dx1))[use_xz]
s[use_xy] = (((y2 - y1) * dx1 - (x2 - x1) * dy1) / (dx2 * dy1 - dy2 * dx1))[use_xy]
s[use_yz] = (((y2 - y1) * dz1 - (z2 - z1) * dy1) / (dz2 * dy1 - dy2 * dz1))[use_yz]
# otherwise, d1 \cross d2 = 0, so rays are parallel and leave as NaN
# determine distance along ray2, but avoid undefined expressions
t = xp.zeros(len(ray1)) * np.nan
with np.errstate(all="ignore"):
use_z = dz1 != 0
use_y = xp.logical_and(xp.logical_not(use_z), dy1 != 0)
# otherwise dx1 is guaranteed to be != 0 since dr1 is a unit vector
use_x = xp.logical_not(xp.logical_or(use_z, use_y))
t[use_z] = ((z2 + s * dz2 - z1) / dz1)[use_z]
t[use_y] = ((y2 + s * dy2 - y1) / dy1)[use_y]
t[use_x] = ((x2 + s * dx2 - x1) / dx1)[use_x]
# but to verify the solution, must check intersection points are actually equal
intersect1 = xp.stack((x1, y1, z1), axis=1) + xp.expand_dims(t, axis=1) * xp.stack((dx1, dy1, dz1), axis=1)
intersect2 = xp.stack((x2, y2, z2), axis=1) + xp.expand_dims(s, axis=1) * xp.stack((dx2, dy2, dz2), axis=1)
with np.errstate(invalid="ignore"):
not_sol = xp.max(xp.abs(intersect1 - intersect2), axis=1) > 1e-12
intersect1[not_sol] = np.nan
return intersect1
def propagate_ray2plane(rays: array,
normal: array,
center: array,
material: Material,
exclude_backward_propagation: bool = False) -> (NDArray, NDArray):
"""
Find intersection between rays and a plane. Plane is defined by a normal vector and a point on the
plane
:param rays: N x 8 array
:param normal: normal of the plane. Should be broadcastable to the shape N x 3
:param center: point on the plane. Should be broadcastable to the shape N x 3
:param material: Material through which rays are propagating
:param exclude_backward_propagation:
:return rays_out, ts: where rays_out is an N x 8 array and ts is a length N array giving the propagation distance
"""
xp = cp if cp is not None and isinstance(rays, cp.ndarray) else np
normal = xp.asarray(normal)
center = xp.asarray(center)
rays = xp.atleast_2d(xp.array(rays, copy=True))
normal = xp.array(normal).squeeze()
if normal.ndim == 1:
normal = xp.expand_dims(normal, axis=0)
center = xp.array(center).squeeze()
if center.ndim == 1:
center = xp.expand_dims(center, axis=0)
xo = rays[:, 0]
yo = rays[:, 1]
zo = rays[:, 2]
dx = rays[:, 3]
dy = rays[:, 4]
dz = rays[:, 5]
phase_o = rays[:, 6]
wls = rays[:, 7]
xc = center[:, 0]
yc = center[:, 1]
zc = center[:, 2]
nx = normal[:, 0]
ny = normal[:, 1]
nz = normal[:, 2]
# parameterize distance along ray by t
ts = - ((xo - xc) * nx + (yo - yc) * ny + (zo - zc) * nz) / (dx * nx + dy * ny + dz * nz)
# determine if this is a forward or backward propagation for the ray
with np.errstate(invalid="ignore"):
prop_direction = xp.ones(rays.shape[0], dtype=int)
prop_direction[ts < 0] = -1
# find intersection points
prop_dist_vect = xp.stack((dx, dy, dz), axis=1) * xp.expand_dims(ts, axis=1)
pts = xp.stack((xo, yo, zo), axis=1) + prop_dist_vect
phase_shift = xp.linalg.norm(prop_dist_vect, axis=1) * prop_direction * 2 * np.pi / wls * material.n(wls)
# assemble output rays
rays_out = xp.concatenate((pts, xp.stack((dx, dy, dz, phase_o + phase_shift, wls), axis=1)), axis=1)
# replace back propagating rays with Nans if desired
if exclude_backward_propagation:
rays_out[prop_direction == -1, :] = xp.nan
return rays_out, ts
def ray_angle_about_axis(rays: array, reference_axis: array) -> (array, array):
"""
Given a set of rays, compute their angles relative to a given axis, and compute the orthogonal direction to the
axis which the ray travels in
:param rays:
:param reference_axis:
:return angles, na:
"""
xp = cp if cp is not None and isinstance(rays, cp.ndarray) else np
rays = xp.atleast_2d(rays)
reference_axis = xp.asarray(reference_axis)
cosines = xp.sum(rays[:, 3:6] * xp.expand_dims(reference_axis, axis=0), axis=1)
angles = xp.arccos(cosines)
na = rays[:, 3:6] - xp.expand_dims(cosines, axis=1) * xp.expand_dims(reference_axis, axis=0)
na = na / xp.expand_dims(np.linalg.norm(na, axis=1), axis=1)
return angles, na
def dist_pt2plane(pts: array,
normal: array,
center: array) -> (array, array):
"""
Calculate minimum distance between points and a plane defined by normal and center
:param pts:
:param normal:
:param center:
:return dists, nearest_pts:
"""
xp = cp if cp is not None and isinstance(pts, cp.ndarray) else np
pts = xp.atleast_2d(pts)
npts = pts.shape[0]
rays = xp.concatenate((pts, xp.tile(normal, (npts, 1)), xp.zeros((npts, 2))), axis=1)
rays_int, _ = propagate_ray2plane(rays, normal, center, Vacuum())
dists = xp.linalg.norm(rays_int[:, :3] - pts, axis=1)
nearest_pts = rays_int[:, :3]
return dists, nearest_pts
# ################################################
# collections of optical elements
# ################################################
class System:
"""
Collection of optical surfaces
"""
# todo: think life will be easier if keep materials at start and end too
def __init__(self,
surfaces: list,
materials: list[Material],
names: list[str] = None,
surfaces_by_name=None,
aperture_stop: Optional[int] = None):
"""
:param surfaces: length n
:param materials: length n-1
:param names:
:param surfaces_by_name:
"""
if len(materials) > 1:
if len(materials) != (len(surfaces) - 1):
raise ValueError(f"len(materials) = {len(materials):d} != len(surfaces) - 1 = {len(surfaces) - 1:d}")
self.surfaces = surfaces
self.materials = materials
self.aperture_stop = aperture_stop
if names is None:
self.names = [""]
else:
if not isinstance(names, list):
names = [names]
self.names = names
# should be able to get name of surfaces ii from self.names[self.surfaces_by_name[ii]]
if surfaces_by_name is None:
self.surfaces_by_name = np.zeros(len(surfaces), dtype=int)
else:
if len(surfaces_by_name) != len(surfaces):
raise ValueError("len(surfaces_by_name) must equal len(surfaces)")
self.surfaces_by_name = np.array(surfaces_by_name).astype(int)
def reverse(self):
"""
flip direction of the optic we are considering (so typically rays now enter from the right)
:return:
"""
surfaces_rev = [deepcopy(self.surfaces[-ii]) for ii in range(1, len(self.surfaces) + 1)]
for ii in range(len(self.surfaces)):
surfaces_rev[ii].input_axis *= -1
surfaces_rev[ii].output_axis *= -1
materials_rev = [self.materials[-ii] for ii in range(1, len(self.materials) + 1)]
return System(surfaces_rev, materials_rev)
def concatenate(self,
other,
material: Material,
distance: Optional[float] = None,
axis: Sequence[float, float, float] = (0., 0., 1.)):
"""
add another optical Surface to the end of this System
:param other: the optical elements to add. Should be a System or a Surface
:param material: the Material between the end of this System and the start of the next
:param distance: the distance between the last surface of the current system and the first surface of the
next system, determined by the paraxial center. If None, then place the next system at the
coordinates of the surface
:param axis:
:return new_system:
"""
# todo: want to make it possible to add surface at intermediate location
# todo: how to make type hints work?
# specify distance between surfaces as distances between the paraxial foci
if isinstance(other, System):
new_surfaces = [deepcopy(s) for s in other.surfaces]
new_materials = other.materials
other_stop = other.aperture_stop
new_surfaces_by_name = other.surfaces_by_name
new_names = other.names
elif isinstance(other, Surface):
new_surfaces = [deepcopy(other)]
new_materials = []
other_stop = None
new_surfaces_by_name = np.array([0])
new_names = [""]
else:
raise TypeError(f"other should be of type System or Surface, but was {type(other)}")
if distance is not None:
for ii, s in enumerate(new_surfaces):
# C_i(new) = C_{i-1}(new) + [C_i(old) - C_{i-1}(old)]
if ii == 0:
shift = self.surfaces[-1].paraxial_center + distance * np.array(axis) - s.paraxial_center
else:
shift = new_surfaces[ii - 1].paraxial_center - other.surfaces[ii - 1].paraxial_center
s.center += shift
s.paraxial_center += shift
surfaces_by_name = np.concatenate((self.surfaces_by_name,
new_surfaces_by_name + np.max(self.surfaces_by_name) + 1))
if self.aperture_stop is None:
if other_stop is None:
aperture_stop = self.aperture_stop
else:
aperture_stop = other_stop + len(self.surfaces)
else:
aperture_stop = self.aperture_stop
return System(self.surfaces + new_surfaces,
self.materials + [material] + new_materials,
names=self.names + new_names,
surfaces_by_name=surfaces_by_name,
aperture_stop=aperture_stop)
def set_aperture_stop(self,
surface_index: int):
self.aperture_stop = surface_index
def seidel_third_order(self,
wavelength: float,
initial_material: Material,
final_material: Material,
print_results: bool = False,
object_distance: float = 0.,
object_height: float = 0.,
object_angle: float = 0.,
):
"""
Calculate Seidel aberration coefficients
We assume the initial object is at the first surface (if this is not true, add a surface)
:param wavelength:
:param initial_material:
:param final_material:
:param print_results:
:param object_distance: distance of object before first surface. Positive if before surface
:param object_height: field-of-view, used to calculate chief ray. Object height is used if object_distance
is not infinite
:param object_angle: field of view angle. object_angle is only used if object_distance = np.inf
:return:
"""
if self.aperture_stop is None:
raise ValueError("aperture_stop was None, but aperture_stop must be provided to "
"compute Seidel aberrations")
materials = [initial_material] + self.materials + [final_material]
ns = np.array([m.n(wavelength) for m in materials])
# get ray transfer matrices for each surface
rt_mats = self.get_ray_transfer_matrix(wavelength, initial_material, final_material)
rt_stop = rt_mats[self.aperture_stop]
# compute marginal and chiefs rays at first surface
if np.isinf(object_distance):
h_chief_first = 0.
u_chief_first = object_angle
h_first = self.surfaces[self.aperture_stop].aperture_rad / rt_stop[0, 0]
u_first = 0.
else:
rt_obj2stop = rt_stop.dot(get_free_space_abcd(object_distance, ns[0]))
# B * n_start * u_start = h_stop
h_start = 0.
u_start = self.surfaces[self.aperture_stop].aperture_rad / rt_obj2stop[0, 1] / ns[0]
h_first = rt_obj2stop[0, 0] * h_start + rt_obj2stop[0, 1] * ns[0] * u_start
u_first = rt_obj2stop[1, 0] * h_start + rt_obj2stop[1, 1] * ns[0] * u_start
h_chief_start = object_height
u_chief_start = -rt_obj2stop[0, 0] / rt_obj2stop[0, 1] / ns[0] * h_chief_start # A*h + B*n*u = h_chief = 0
h_chief_first = rt_obj2stop[0, 0] * h_chief_start + rt_obj2stop[0, 1] * ns[0] * u_chief_start
u_chief_first = rt_obj2stop[1, 0] * h_chief_start + rt_obj2stop[1, 1] * ns[0] * u_chief_start
# trace marginal and chief rays
# nsurfaces x 2 x 2 array
# rays[:, :, 0] are marginal ray data (h, n*u); rays[:, :, 1] are chief ray data
rays_start = np.array([[h_first, h_chief_first],
[ns[0] * u_first, ns[0] * u_chief_first]])
rays = rt_mats.dot(rays_start)
# values needed to calculate aberrations
cs = np.array([1 / s.radius if isinstance(s, SphericalSurface) else 0 for s in self.surfaces])
refraction_inv = ns[:-1] * rays[:-1, 0, 0] * cs + rays[:-1, 1, 0]
refraction_inv_chief = ns[:-1] * rays[:-1, 0, 1] * cs + rays[:-1, 1, 1]
delta_un = rays[1:, 1, 0] / ns[1:] / ns[1:] - rays[:-1, 1, 0] / ns[:-1] / ns[:-1]
lagrange_inv = ns[:-1] * (rays[:-1, 0, 1] * rays[:-1, 1, 0] / ns[:-1] -
rays[:-1, 0, 0] * rays[:-1, 1, 1] / ns[:-1])
# compute aberrations following "Fundamentals of Optical Design" by Michael J. Kidger,
# chapter 6, eqs 6.27-6.30 and 6.37
# spherical, coma, astigmatism, field curvature, distortion
aberrations = np.zeros((len(self.surfaces), 5)) * np.nan
aberrations[:, 0] = -refraction_inv**2 * rays[:-1, 0, 0] * delta_un
aberrations[:, 1] = -refraction_inv * refraction_inv_chief * rays[:-1, 0, 0] * delta_un
aberrations[:, 2] = -refraction_inv_chief ** 2 * rays[:-1, 0, 0] * delta_un
aberrations[:, 3] = -lagrange_inv ** 2 * cs * (1 / ns[1:] - 1 / ns[:-1])
# aberrations[:, 4] = refraction_inv_chief / refraction_inv * (aberrations[:, 2] + aberrations[:, 3])
aberrations[:, 4] = (-refraction_inv_chief ** 3 * rays[:-1, 0, 0] * (1 / ns[1:]**2 - 1 / ns[:-1]**2) +
rays[:-1, 0, 1] * refraction_inv_chief * cs *
(2 * rays[:-1, 0, 0] * refraction_inv_chief - rays[:-1, 0, 1] * refraction_inv) *
(1 / ns[1:] - 1 / ns[:-1])
)
if print_results:
print("surface,"
" h,"
" u,"
" hbar,"
" ubar,"
" delta(u/n)"
" A,"
" Abar,"
" Lag. inv."
)
for ii in range(len(self.surfaces)):
print(f"{ii:02d}: "
f"{rays[ii, 0, 0]:10.6g}, "
f"{rays[ii, 1, 0] / ns[ii]:10.6g}, "
f"{rays[ii, 0, 1]:10.6g}, "
f"{rays[ii, 1, 1] / ns[ii]:10.6g}, "
f"{delta_un[ii]:10.6g}, "
f"{refraction_inv[ii]:10.6g}, "
f"{refraction_inv_chief[ii]:10.6g}, "
f"{lagrange_inv[ii]:10.6g}"
)
print("surfaces,"
" spherical,"
" coma,"
" astig.,"
" field curv.,"
" distortion")
for ii in range(len(self.surfaces)):
print(f"{ii:02d}: "
f"{aberrations[ii, 0]:10.6g}, "
f"{aberrations[ii, 1]:10.6g}, "
f"{aberrations[ii, 2]:10.6g}, "
f"{aberrations[ii, 3]:10.6g}, "
f"{aberrations[ii, 4]:10.6g}")
print(f"sum: "
f"{np.sum(aberrations[:, 0], axis=0):10.6g}, "
f"{np.sum(aberrations[:, 1], axis=0):10.6g}, "
f"{np.sum(aberrations[:, 2], axis=0):10.6g}, "
f"{np.sum(aberrations[:, 3], axis=0):10.6g}, "
f"{np.sum(aberrations[:, 4], axis=0):10.6g}")
return aberrations
def find_paraxial_collimated_distance(self,
other,
wavelength: float,
initial_material: Material,
intermediate_material: Material,
final_material: Material,
axis=None) -> (float, float):
"""
Given two sets of surfaces (e.g. two lenses) determine the distance which should be inserted between them
to give a System which converts collimated rays to collimated rays
:param other:
:param wavelength:
:param initial_material:
:param intermediate_material:
:param final_material:
:param axis:
:return dx, dy:
"""
mat1 = self.get_ray_transfer_matrix(wavelength, initial_material, intermediate_material)[-1]
mat2 = other.get_ray_transfer_matrix(wavelength, intermediate_material, final_material)[-1]
# todo: implement axis
d = -(mat1[0, 0] / mat1[1, 0] + mat2[1, 1] / mat2[1, 0]) * intermediate_material.n(wavelength)
return d
def ray_trace(self,
rays: array,
initial_material: Material,
final_material: Material) -> array:
"""
ray trace through optical System
:param rays:
:param initial_material:
:param final_material:
:return rays:
"""
materials = [initial_material] + self.materials + [final_material]
if len(materials) != len(self.surfaces) + 1:
raise ValueError("length of materials should be len(surfaces) + 1")
for ii in range(len(self.surfaces)):
rays = self.surfaces[ii].propagate(rays, materials[ii], materials[ii + 1])
return rays
def gaussian_paraxial(self,
q_in: complex,
wavelength: float,
initial_material: Material,
final_material: Material,
print_results: bool = False):
"""
:param q_in:
:param wavelength:
:param initial_material:
:param final_material:
:param print_results:
:return:
"""
ns = np.zeros(len(self.surfaces) + 1)
qs = np.zeros(len(self.surfaces) + 1, dtype=complex)
qs[0] = q_in
for ii, s in enumerate(self.surfaces):
if ii == 0:
n1 = initial_material.n(wavelength)
else:
n1 = self.materials[ii - 1].n(wavelength)
if ii < len(self.surfaces) - 1:
n2 = self.materials[ii].n(wavelength)
d = np.linalg.norm(self.surfaces[ii + 1].paraxial_center - s.paraxial_center)
else:
n2 = final_material.n(wavelength)
d = 0.
abcd = get_free_space_abcd(d, n2).dot(s.get_ray_transfer_matrix(n1, n2))
qs[ii + 1] = (qs[ii] * abcd[0, 0] + abcd[0, 1]) / (qs[ii] * abcd[1, 0] + abcd[1, 1])
ns[ii] = n1
ns[ii + 1] = n2
if print_results:
import mcsim.analysis.gauss_beam as gb
r, w_sqr, wo_sqr, z, zr = gb.q2beam_params(qs, wavelength, ns)
print("surfaces \t R,"
" w,"
" wo,"
" z,"
" zr")
for ii in range(len(self.surfaces) + 1):
print(f"{ii:02d}: "
f"{r[ii]:10.6g}, "
f"{np.sqrt(w_sqr[ii]):10.6g}, "
f"{np.sqrt(wo_sqr[ii]):10.6g}, "
f"{z[ii]:10.6g}, "
f"{zr[ii]:10.6g}")
return qs
def get_ray_transfer_matrix(self,
wavelength: float,
initial_material: Material,
final_material: Material,
axis=None):
"""
Generate the ray transfer (ABCD) matrices throughout an optical system.
If the optical system as n surfaces, then this returns an array of size n+1 x 2 x 2,
where the first n matrices transfer a ray to just before each surface, and the last matrix
transfers a ray to just after the last surface
:param wavelength:
:param initial_material:
:param final_material:
:param axis: axis which should be a direction orthogonal to the main beam direction. Only relevant for
non-symmetric optics
:return abcd_matrix:
"""
materials = [initial_material] + self.materials + [final_material]
ns = np.array([m.n(wavelength) for m in materials])
rt_mats = np.zeros((len(self.surfaces) + 1, 2, 2))
for ii in range(len(self.surfaces) + 1):
if ii == 0:
rt_mats[ii] = get_free_space_abcd(0, ns[0])
elif ii == len(self.surfaces):
rt_next = self.surfaces[-1].get_ray_transfer_matrix(ns[-2], ns[-1])
rt_mats[ii] = rt_next.dot(rt_mats[ii - 1])
else:
d = np.linalg.norm(self.surfaces[ii].paraxial_center - self.surfaces[ii - 1].paraxial_center)
rt_surf = self.surfaces[ii - 1].get_ray_transfer_matrix(ns[ii - 1], ns[ii])
rt_next = get_free_space_abcd(d, ns[ii]).dot(rt_surf)
rt_mats[ii] = rt_next.dot(rt_mats[ii - 1])
return rt_mats
def get_cardinal_points(self,
wavelength: float,
initial_material: Material,
final_material: Material,
axis=None):
"""
Get cardinal points of the system. These are the focal points, principal points, and nodal points.
This function also returns the effective focal length
:param wavelength:
:param initial_material:
:param final_material:
:param axis: for non-radially symmetric objects, which axis
:return fp1, fp2, pp1, pp2, np1, np2, efl1, efl2:
"""
abcd_mat = self.get_ray_transfer_matrix(wavelength, initial_material, final_material)[-1]
abcd_inv = self.reverse().get_ray_transfer_matrix(wavelength, final_material, initial_material)[-1]
n_obj = initial_material.n(wavelength)
n_img = final_material.n(wavelength)
# ###############################################
# find focal point to the right of the lens
# ###############################################
# if I left multiply my ray transfer matrix by free space matrix, then combined matrix has lens/focal form
# for certain distance of propagation dx. Find this by setting A + d/n_img * C = 0
d2 = -abcd_mat[0, 0] / abcd_mat[1, 0] * n_img
# can also find the principal plane with the following construction
# take income ray at (h1, n1*theta1 = 0). Consider the ray-transfer matrix which combines the optic and the
# distance travelled dx to the focus
# then extend the corresponding ray at (h2=0, n2*theta2) backwards until it reaches height h
# can check this happens at position P2 = f2 + h1/theta2 (where theta2<0 here)
# by construction the ray-transfer matrix above has A=0,
# but in any case we have the relationship C*h1 = n2*theta2
# or P2 = f2 + n2/C -> EFL2 = f2 - P2 = -n2/C
# EFL = 1 / C, and this is not affect by multiplying the ray-transfer matrix by free-space propagation
efl2 = -n_img / abcd_mat[1, 0]
fp2 = self.surfaces[-1].paraxial_center + d2 * self.surfaces[-1].output_axis
# find principal plane image space
pp2 = fp2 - efl2 * self.surfaces[-1].output_axis
# find nodal point in image space
d2_nodal = (n_img - n_obj * abcd_inv[1, 1]) / abcd_inv[1, 0]
np2 = self.surfaces[-1].paraxial_center + d2_nodal * self.surfaces[-1].output_axis
# find focal point in object space
d1 = -abcd_inv[0, 0] / abcd_inv[1, 0] * n_obj
efl1 = -n_obj / abcd_inv[1, 0]
fp1 = self.surfaces[0].paraxial_center - d1 * self.surfaces[0].input_axis
# find principal plane in object space
pp1 = fp1 + efl1 * self.surfaces[0].input_axis
# find nodal point in object space
d1_nodal = (n_obj - n_img * abcd_mat[1, 1]) / abcd_mat[1, 0]
np1 = self.surfaces[0].paraxial_center - d1_nodal * self.surfaces[0].output_axis
return fp1, fp2, pp1, pp2, np1, np2, efl1, efl2
def auto_focus(self,
wavelength: float,
initial_material: Material,
final_material: Material,
mode: str = "ray-fan"):
"""
Perform an autofocus operation. This function can handle rays which are
initially collimated or initially diverging
:param wavelength:
:param initial_material:
:param final_material:
:param mode: "ray-fan", "collimated", "paraxial-focused", or "paraxial-collimated"
:return f:
"""
# todo: handle case where optical System extends past focus
if mode == "ray-fan":
# todo: maybe take sequence of rays with smaller and smaller angles...
rays_focus = get_ray_fan([0, 0, 0], 1e-9, 3, wavelength)
rays_focus = self.ray_trace(rays_focus, initial_material, final_material)
focus = intersect_rays(rays_focus[-1, 1], rays_focus[-1, 2])[0]
elif mode == "collimated":
rays_focus = get_collimated_rays([0, 0, 0], 1e-9, 3, wavelength)
rays_focus = self.ray_trace(rays_focus, initial_material, final_material)
focus = intersect_rays(rays_focus[-1, 1], rays_focus[-1, 2])[0]
elif mode == "paraxial-focused":
f1, focus, _, _, _, _, _, _ = self.get_cardinal_points(wavelength, initial_material, final_material)
elif mode == "paraxial-collimated":
abcd = self.get_ray_transfer_matrix(wavelength,
initial_material,
final_material)[-1]
# determine what free space propagation matrix we need such that initial ray (h, n*theta) -> (0, n'*theta')
dx = -abcd[0, 0] / abcd[1, 0] * self.materials[-1].n(wavelength)
focus = (self.surfaces[-1].paraxial_center[2] + dx * np.sign(self.surfaces[-1].input_axis[2]))
else:
raise ValueError(f"mode must be 'ray-fan', or 'collimated' 'paraxial-focused',"
f" or paraxial-collimated' but was '{mode:s}'")
return focus
def plot(self,
ray_array: Optional[NDArray] = None,
phi: float = 0,
colors: Optional[list] = None,
label: str = None,
ax: Optional[Axes] = None,
show_names: bool = True,
fontsize: float = 16,
**kwargs) -> (Figure, Axes):
"""
Plot rays and optical surfaces
:param ray_array: nsurfaces X nrays x 8
:param phi: angle describing the azimuthal plane to plot. phi = 0 gives the meridional/tangential plane while
phi = pi/2 gives the sagittal plane. # todo: not implemented for drawing the Surface projections
:param colors: list of colors to plot rays
:param label:
:param ax: axis to plot results on. If None, a new figure will be generated
:param show_names:
:param fontsize:
:param kwargs: passed through to figure, if it does not already exist
:return fig_handle, axis:
"""
# get axis to plot on
if ax is None:
figh = plt.figure(**kwargs)
ax = plt.subplot(1, 1, 1)
else:
figh = ax.get_figure()
# plot rays
if ray_array is not None:
# ray height in the desired azimuthal plane
h_data = ray_array[:, :, 0] * np.cos(phi) + ray_array[:, :, 1] * np.sin(phi)
if label is None:
label = ""
if colors is None:
ax.plot(ray_array[:, :, 2], h_data, label=label)
else:
# ensure color argument is ok
if len(colors) == 1 and not isinstance(colors, list):
colors = [colors] * ray_array.shape[1]
if len(colors) != ray_array.shape[1]:
raise ValueError("len(colors) must equal ray_array.shape[1]")
# plot each ray a different color
for ii in range(ray_array.shape[1]):
if ii == 0:
ax.plot(ray_array[:, ii, 2], h_data[:, ii], color=colors[ii], label=label)
else:
ax.plot(ray_array[:, ii, 2], h_data[:, ii], color=colors[ii])
ax.set_xlabel("z-position (mm)", fontsize=fontsize)
ax.set_ylabel("height (mm)", fontsize=fontsize)
ax.tick_params(axis='x', labelsize=fontsize)
ax.tick_params(axis='y', labelsize=fontsize)
# plot surfaces
if self.surfaces is not None:
for ii, s in enumerate(self.surfaces):
s.draw(ax)
if show_names:
if ii == 0 or self.surfaces_by_name[ii] != self.surfaces_by_name[ii - 1]:
ax.text(s.paraxial_center[2], # x
s.paraxial_center[0] + 1.1 * s.aperture_rad, # y
self.names[self.surfaces_by_name[ii]], # s
horizontalalignment="center",
fontsize=fontsize
)
return figh, ax
class Doublet(System):
def __init__(self,
material_crown: Optional[Material] = None,
material_flint: Optional[Material] = None,
radius_crown: Optional[float] = None,
radius_flint: Optional[float] = None,
radius_interface: Optional[float] = None,
thickness_crown: Optional[float] = None,
thickness_flint: Optional[float] = None,
aperture_radius: float = 25.4,
input_collimated: bool = True,
names: str = ""):
"""
Provide the radii of curvature assuming the lens is oriented with the crown side
to the left (i.e. the proper orientation to focus a collimated beam oriented from the left)
Positive curvature indicates a Surface appears convex when looking from the left. Most
commonly the crown Surface will have a positive radius of curvatures while
the intermediate Surface and flint Surface will have negative radii of curvature
To create a lens oriented the other way, set input_collimated=True (but define the curvatures and
other parameters as described above)
:param material_crown:
:param material_flint:
:param radius_crown:
:param radius_flint:
:param radius_interface:
:param thickness_crown:
:param thickness_flint:
:param aperture_radius:
:param input_collimated: if True, the input goes into the crown Surface.
:param names:
"""
if input_collimated:
m1 = material_crown
m2 = material_flint
if not np.isinf(radius_crown):
s1 = SphericalSurface.get_on_axis(radius_crown, 0, aperture_radius)
else:
s1 = FlatSurface([0, 0, 0], [0, 0, 1], aperture_rad=aperture_radius)
if not np.isinf(radius_interface):
s2 = SphericalSurface.get_on_axis(radius_interface, thickness_crown, aperture_radius)
else:
s2 = FlatSurface([0, 0, thickness_crown], [0, 0, 1], aperture_rad=aperture_radius)
if not np.isinf(radius_flint):
s3 = SphericalSurface.get_on_axis(radius_flint, thickness_crown + thickness_flint, aperture_radius)
else:
s3 = FlatSurface([0, 0, thickness_crown + thickness_flint], [0, 0, 1], aperture_rad=aperture_radius)
else:
m1 = material_flint
m2 = material_crown
if not np.isinf(radius_flint):
s1 = SphericalSurface.get_on_axis(-radius_flint,
0,
aperture_radius)
else:
s1 = FlatSurface([0, 0, 0],
[0, 0, 1],
aperture_rad=aperture_radius)
if not np.isinf(radius_interface):
s2 = SphericalSurface.get_on_axis(-radius_interface,
thickness_flint,