-
Notifications
You must be signed in to change notification settings - Fork 0
/
raytrace.py
1898 lines (1519 loc) · 73.9 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 trace through spherical particle
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 curve C(t) = (xo, yo, zo) + t * (dx, dy, dz)
A paraxial ray has a different representation
(hx, n*ux, hy, n*uy) defined relative to some point and axis.
where (xo, yo, zo) and (dx, dy, dz) define the paraxial axis.
col([hx, n*ux, hy, n*uy, 1]) = [[A, B, 0, 0, K],
[C, D, 0, 0, L],
[0, 0, E, F, M],
[0, 0, G, H, N],
[0, 0, 0, 0, 1]] * col([hx1, n1*ux1, hy2, n2*uy2, 1]
here K, L account for any shift between the definition fo hx, n*ux and the natural center points.
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
"""
import copy
from typing import Optional
import numpy as np
from numpy.typing import NDArray
from matplotlib.figure import Figure
from matplotlib.axes._axes import Axes
import matplotlib.pyplot as plt
import warnings
from raytrace.materials import material, vacuum
# analyze optical systems
def ray_trace_system(rays: NDArray,
surfaces: list,
materials: list[material]):
"""
race rays through a system of diffractive optical elements
:param rays: N x 8 array
:param surfaces: list of surfaces
:param materials: indices of refraction between surfaces. If there are Ns surfaces,
this should have Ns + 1 elements. The first element is the index of refraction before the first
surface of the system, and the last element is the index of refraction after the last surface of the system.
:return rays_out: M x N x 8 array, where we represent the complete raytracing by M positions of each ray
"""
# raise DeprecationWarning("use System() instead")
if len(materials) != len(surfaces) + 1:
raise ValueError("length of materials should be len(surfaces) + 1")
rays = np.array(rays)
for ii in range(len(surfaces)):
rays = surfaces[ii].propagate(rays, materials[ii], materials[ii + 1])
return rays
def compute_paraxial_matrix(surfaces: list,
materials: list[material],
wavelength: float,
initial_distance: float = 0,
final_distance: float = 0):
"""
# todo: instead of indices of refraction use a material and derive index of refraction from material + wavelength
Generate the ray transfer (ABCD) matrix for an optical system
Assume that the optical system starts at the provided initial distance before the first surface
:param surfaces: list of surfaces in the optical system
:param materials:
:param wavelength:
:param initial_distance:
:param final_distance:
:return abcd_mat:
"""
mats = [] # helpful for debugging
indices_of_refraction = [m.n(wavelength) for m in materials]
# propagate initial distance
ray_xfer_mat = get_free_space_abcd(initial_distance, n=indices_of_refraction[0])
mats.append(ray_xfer_mat)
for ii in range(len(surfaces)):
# apply ray transfer matrix for current surface
abcd_temp = surfaces[ii].get_ray_transfer_matrix(indices_of_refraction[ii], indices_of_refraction[ii + 1])
ray_xfer_mat = abcd_temp.dot(ray_xfer_mat)
mats.append(abcd_temp)
# apply ray transfer matrix propagating between surfaces
if ii < (len(surfaces) - 1):
dist = np.linalg.norm(surfaces[ii].paraxial_center - surfaces[ii + 1].paraxial_center)
abcd_prop = get_free_space_abcd(dist, n=indices_of_refraction[ii+1])
ray_xfer_mat = abcd_prop.dot(ray_xfer_mat)
mats.append(abcd_prop)
# propagate final distance
ray_xfer_temp = get_free_space_abcd(final_distance, n=indices_of_refraction[-1])
ray_xfer_mat = ray_xfer_temp.dot(ray_xfer_mat)
mats.append(ray_xfer_temp)
return ray_xfer_mat
def get_reversed_system(surfaces: list,
materials: list[material]):
"""
Create a new optical system where the order of the surfaces is reversed.
:param surfaces:
:param materials:
:return surfaces_rev, n_rev:
"""
# raise DeprecationWarning("use System() instead")
surfaces_rev = [copy.deepcopy(surfaces[-ii]) for ii in range(1, len(surfaces) + 1)]
for ii in range(len(surfaces)):
surfaces_rev[ii].input_axis *= -1
surfaces_rev[ii].output_axis *= -1
n_rev = [materials[-ii] for ii in range(1, len(materials) + 1)]
return surfaces_rev, n_rev
def compute_third_order_seidel(surfaces: list,
materials: list[material],
wavelength: float):
"""
:param surfaces:
:param materials:
:param wavelength:
:return aberrations_3rd:
"""
# first check where the aperture stop is
is_ap_stop = [s.is_aperture_stop for s in surfaces]
if not np.any(is_ap_stop):
raise ValueError("none of the surfaces were labelled as the aperture stop")
if np.sum(is_ap_stop) > 1:
raise ValueError("more than one of the surfaces was labelled as the aperture stop")
istop = int(np.where(is_ap_stop)[0])
# find entrance pupil
surfaces_before_stop = surfaces[:istop + 1]
materials_before_stop = materials[:istop + 2]
surfaces_before_stop, materials_before_stop = get_reversed_system(surfaces_before_stop, materials_before_stop)
# to avoid refracting through the stop again, modify the index of refraction
materials_before_stop[0] = materials_before_stop[1]
s_temp, _ = auto_focus(surfaces_before_stop, materials_before_stop, wavelength, mode="paraxial-focused")
# correct entrance pupil directions
entrance_pupil, _ = get_reversed_system([s_temp[-1]], [1, 1])
entrance_pupil = entrance_pupil[0]
# find exit pupil
# surfaces_after_stop = surfaces[istop:]
# ns_after_stop = materials[istop - 1:]
#
# s_temp, _ = auto_focus(surfaces_after_stop, ns_after_stop, mode="paraxial")
# exit_pupil = s_temp[-1]
# needed quantities
nsurfaces = len(surfaces)
aberrations_3rd = np.zeros((nsurfaces, 5))
s = np.zeros(nsurfaces) # object points per surface
sp = np.zeros(nsurfaces) # image points per surface
h = np.zeros(nsurfaces) # h1 = s1 / (t1 - s1) where t = distance from entrance pupil to surface vertex
H = np.zeros(nsurfaces) # H1 = t1 / no
t = np.zeros(nsurfaces)
tp = np.zeros(nsurfaces)
d = np.zeros(nsurfaces - 1)
# initialize values for first surface
s[0] = surfaces[0].paraxial_center[2]
sp[0] = surfaces[0].solve_img_eqn(s[0], materials[0], materials[1])
t[0] = entrance_pupil.paraxial_center[2] - surfaces[0].paraxial_center[2]
tp[0] = surfaces[0].solve_img_eqn(t[0], materials[0], materials[1])
h[0] = s[0] / (t[0] - s[0])
H[0] = t[0] / materials[0]
# compute subsequent values of image positions and pupil positions
for ii in range(1, len(h)):
# d[ii] is the distance between ii and ii + 1 surfaces
d[ii - 1] = surfaces[ii].paraxial_center[2] - surfaces[ii - 1].paraxial_center[2]
# new object is previous image relative to new surfaces
s[ii] = sp[ii - 1] - d[ii - 1]
sp[ii] = surfaces[ii].solve_img_eqn(s[ii], materials[ii], materials[ii + 1])
# new pupil is previous image relative to new surfaces
t[ii] = tp[ii - 1] - d[ii - 1]
tp[ii] = surfaces[ii].solve_img_eqn(t[ii], materials[ii], materials[ii + 1])
# see Born and Wolf chapter 5.5 eq's (9) and (16)
# h[ii] = h[ii - 1] * s[ii] / sp[ii - 1] # recursion has problem if one is zero...
h[ii] = s[ii] / (t[ii] - s[ii])
# H[ii] = H[ii - 1] * t[ii] / tp[ii - 1]
H[ii] = t[ii] / materials[ii]
# solve for aberrations
for ii in range(nsurfaces):
aberrations_3rd[ii] = surfaces[ii].get_seidel_third_order_fns(
materials[ii], materials[ii + 1],
s[ii], sp[ii], t[ii], tp[ii], h[ii], H[ii])
return aberrations_3rd
# helper methods for finding focus, cardinal points, etc.
def auto_focus(surfaces: list,
materials: list[material],
wavelength: float,
mode: str = "ray-fan"):
"""
Perform auto-focus operation. This function can handle rays which are initially collimated or initially diverging
:param list surfaces: list of surfaces, which should start with the surfaces the rays are incident from
:param materials: list of indices of refraction betweeen surfaces
:param wavelength:
:param mode: "ray-fan", "collimated", "paraxial-focused", or "paraxial-collimated"
:return updated_surfaces, updated_n:
"""
# 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 = ray_trace_system(rays_focus, surfaces, materials)
focus = intersect_rays(rays_focus[-1, 1], rays_focus[-1, 2])[0, 2]
elif mode == "collimated":
rays_focus = get_collimated_rays([0, 0, 0], 1e-9, 3, wavelength)
rays_focus = ray_trace_system(rays_focus, surfaces, materials)
focus = intersect_rays(rays_focus[-1, 1], rays_focus[-1, 2])[0, 2]
elif mode == "paraxial-focused":
ns = [m.n(wavelength) for m in materials]
abcd = compute_paraxial_matrix(surfaces, ns, initial_distance=0, final_distance=0)
# determine what free space propagation matrix we need such that initial ray (0, n*theta) -> (0, n'*theta')
dx = -abcd[0, 1] / abcd[1, 1] * ns[-1]
dy = -abcd[2, 3] / abcd[3, 3] * ns[-1]
if np.abs(dx - dy) >= 1e-12:
warnings.warn("dx and dy focus differs")
focus = surfaces[-1].paraxial_center[2] + 0.5 * (dx + dy) * np.sign(surfaces[-1].input_axis[2])
elif mode == "paraxial-collimated":
ns = [m.n(wavelength) for m in materials]
abcd = compute_paraxial_matrix(surfaces, ns, initial_distance=0, final_distance=0)
# 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] * ns[-1]
dy = -abcd[2, 2] / abcd[3, 2] * ns[-1]
if np.abs(dx - dy) >= 1e-12:
warnings.warn("dx and dy focus differs")
focus = surfaces[-1].paraxial_center[2] + 0.5 * (dx + dy) * np.sign(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}'")
updated_surfaces = surfaces + [flat_surface([0, 0, focus], surfaces[-1].input_axis, surfaces[-1].aperture_rad)]
updated_n = materials + [materials[-1]]
return updated_surfaces, updated_n
def find_paraxial_focus(abcd_mat: NDArray,
n: float = 1):
"""
Find paraxial focus of a paraxial optical system from its ray-tarnsfer matrix
@param abcd_mat:
@param n: index of refraction of final medium
@return dx, abcd_mat_x, efl_x, dy, abcd_mat_y, efl_y:
"""
# 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 * C = 0
dx = -abcd_mat[0, 0] / abcd_mat[1, 0] * n
dy = -abcd_mat[2, 2] / abcd_mat[3, 2] * n
abcd_mat_x = get_free_space_abcd(dx, n).dot(abcd_mat)
abcd_mat_y = get_free_space_abcd(dy, n).dot(abcd_mat)
# 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
# todo: think it is wrong to call this the EFL
# EFL = 1 / C, and this is not affect by right or left-multiplying the ray-transfer matrix by free space propagation
efl_x = -n / abcd_mat_x[1, 0]
efl_y = -n / abcd_mat_y[3, 2]
return dx, abcd_mat_x, efl_x, dy, abcd_mat_y, efl_y
def find_cardinal_points(surfaces: list,
materials: list[material],
wavelength: float):
"""
Compute cardinal points from ray tracing very small angles
# todo: note this fails if BFP is within optical system
:param list surfaces: list of surfaces
:param list materials: list of indices of refraction between surfaces
:param float wavelength: wavelength
:return f1, f2, pp1, pp2, efl1, efl2:
"""
# todo: probably better to write with ABCD matrices...
# find focal point to right of lens
rays = np.array([[0, 0, 0, 0, 0, 1, 0, wavelength],
[1e-9, 0, 0, 0, 0, 1, 0, wavelength]])
rays = ray_trace_system(rays, surfaces, materials)
f2 = intersect_rays(rays[-1, 0], rays[-1, 1])
# find focal point to left of lens
surfaces_rev, n_rev = get_reversed_system(surfaces, materials)
# todo: need to ensure rays past last surface...
rays = np.array([[0, 0, 1e4, 0, 0, -1, 0, wavelength],
[1e-9, 0, 1e4, 0, 0, -1, 0, wavelength]])
rays = ray_trace_system(rays, surfaces_rev, n_rev)
f1 = intersect_rays(rays[-1, 0], rays[-1, 1])
# propagate rays from front focal point to collimated to find first principal plane
rays_fwd = get_ray_fan(f1, 1e-9, 3, wavelength)
rays_fwd = ray_trace_system(rays_fwd, surfaces, materials)
pt1 = intersect_rays(rays_fwd[0, 2], rays_fwd[-1, 2])
pp1 = pt1[0, 2]
# effective focal length
efl1 = pp1 - f1[0, 2]
# propagate rays backward from the back focal point to collimated to find the second principal plane
surfaces_rev, n_rev = get_reversed_system(surfaces, materials)
rays_back = get_ray_fan(f2, 1e-9, 3, wavelength, center_ray=(0, 0, -1))
rays_back = ray_trace_system(rays_back, surfaces_rev, n_rev)
pt2 = intersect_rays(rays_back[0, 2], rays_back[-1, 2])
pp2 = pt2[0, 2]
efl2 = f2[0, 2] - pp2
return f1, f2, pp1, pp2, efl1, efl2
def find_paraxial_collimated_distance(mat1: NDArray,
mat2: NDArray,
n: float) -> (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 mat1: ABCD matrix of first optic
:param mat2: ABCD matrix of second optic
:param n: index of refraction of intervening medium
:return dx, dy:
"""
dx = -(mat1[0, 0] / mat1[1, 0] + mat2[1, 1] / mat2[1, 0]) * n
dy = -(mat1[2, 2] / mat1[3, 2] + mat2[3, 3] / mat2[3, 2]) * n
return dx, dy
# propagation and refraction
def get_free_space_abcd(d: float, n: float = 1.):
"""
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, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, d/n, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]])
return mat
def refract(rays: NDArray,
normals: NDArray,
material1: material,
material2: material):
"""
Refracts rays at surface with given normal by applying Snell's law
:param rays: N x 8 array
:param normals: N x 3 array
:param material1: index of refraction on the side of the interface the rays are travelling from
:param material2: index of refraction on the other side of the interface
:return rays_out: N x 8 array
"""
normals = np.atleast_2d(normals)
rays = np.atleast_2d(rays)
ds = rays[:, 3:6]
wls = np.expand_dims(rays[:, 7], axis=1)
# basis for computation (na, nb, nc)
# na is normal direction, nb orthogonal to normal and ray
na = normals
with np.errstate(invalid="ignore"):
nb = np.cross(ds, normals)
nb = nb / np.expand_dims(np.linalg.norm(nb, axis=1), axis=1)
nb[np.isnan(nb)] = 0
nc = np.cross(na, nb)
nc = nc / np.expand_dims(np.linalg.norm(nc, axis=1), axis=1)
nc[np.isnan(nc)] = 0
# snell's law
# the tangential component (i.e. nc direction) of k*n*ds is preserved across the interface
mag_nc = material1.n(wls) / material2.n(wls) * np.expand_dims(np.sum(nc * ds, axis=1), axis=1)
sign_na = np.expand_dims(np.sign(np.sum(na * ds, axis=1)), axis=1)
# normalize outgoing ray direction. By construction nothing in nb direction
ds_out = mag_nc * nc + sign_na * np.sqrt(1 - mag_nc**2) * na
rays_out = np.concatenate((rays[:, :3], ds_out, rays[:, 6:]), axis=1)
rays_out[np.isnan(ds_out[:, 0]), :3] = np.nan
return rays_out
def reflect(rays: NDArray, normals: NDArray) -> NDArray:
"""
Find new rays after reflecting off a surface defined by a given normal using the law of reflection
:param rays: nrays x 8 array
:param normals: array of size 3, in which case this normal is applied to all rays, or size nrays x 3, in
which case each normal is applied to the corresponding ray
:return rays_out: nrays x 8 array
"""
normals = np.atleast_2d(normals)
rays = np.atleast_2d(rays)
ds = rays[:, 3:6]
# basis for computation (na, nb, nc)
# na is normal direction, nb orthogonal to normal and ray
na = normals
with np.errstate(invalid="ignore"):
nb = np.cross(ds, normals)
nb = nb / np.expand_dims(np.linalg.norm(nb, axis=1), axis=1)
nb[np.isnan(nb)] = 0
nc = np.cross(na, nb)
nc = nc / np.expand_dims(np.linalg.norm(nc, axis=1), axis=1)
nc[np.isnan(nc)] = 0
# law of reflection
# the normal component (i.e. na direction) changes sign
mag_na = -np.expand_dims(np.sum(na * ds, axis=1), axis=1)
mag_nc = np.expand_dims(np.sum(nc * ds, axis=1), axis=1)
ds_out = mag_na * na + mag_nc * nc
rays_out = np.concatenate((rays[:, :3], ds_out, rays[:, 6:]), axis=1)
rays_out[np.isnan(ds_out[:, 0]), :3] = np.nan
return rays_out
# 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)):
"""
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:
"""
# 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 = np.linspace(-theta_max, theta_max, n_thetas)
phis = np.arange(nphis) * 2*np.pi / nphis
rays = np.zeros((n_thetas * nphis, 8))
tts, pps = np.meshgrid(thetas, phis)
tts = tts.ravel()
pps = pps.ravel()
enx = np.cross(np.array([0, 1, 0]), center_ray)
enx = enx / np.linalg.norm(enx)
eny = np.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: NDArray, ray2: NDArray) -> NDArray:
"""
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:
"""
ray1 = np.atleast_2d(ray1)
ray2 = np.atleast_2d(ray2)
if len(ray1) == 1 and len(ray2) > 1:
ray1 = np.tile(ray1, (len(ray2), 1))
if len(ray2) == 1 and len(ray1) > 1:
ray2 = np.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 = np.zeros(len(ray1)) * np.nan
with np.errstate(invalid="ignore"):
use_xz = dx2 * dz1 - dz2 * dx1 != 0
use_xy = np.logical_and(np.logical_not(use_xz),
dx2 * dy1 - dy2 * dx1)
use_yz = np.logical_and.reduce((np.logical_not(use_xz),
np.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 = np.zeros(len(ray1)) * np.nan
with np.errstate(all="ignore"):
use_z = dz1 != 0
use_y = np.logical_and(np.logical_not(use_z), dy1 != 0)
# otherwise dx1 is guaranteed to be != 0 since dr1 is a unit vector
use_x = np.logical_not(np.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 = np.stack((x1, y1, z1), axis=1) + np.expand_dims(t, axis=1) * np.stack((dx1, dy1, dz1), axis=1)
intersect2 = np.stack((x2, y2, z2), axis=1) + np.expand_dims(s, axis=1) * np.stack((dx2, dy2, dz2), axis=1)
with np.errstate(invalid="ignore"):
not_sol = np.max(np.abs(intersect1 - intersect2), axis=1) > 1e-12
intersect1[not_sol] = np.nan
return intersect1
def propagate_ray2plane(rays: NDArray,
normal: NDArray,
center: NDArray,
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
"""
rays = np.atleast_2d(np.array(rays, copy=True))
normal = np.array(normal).squeeze()
if normal.ndim == 1:
normal = np.expand_dims(normal, axis=0)
center = np.array(center).squeeze()
if center.ndim == 1:
center = np.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 = np.ones(rays.shape[0], dtype=int)
prop_direction[ts < 0] = -1
# find intersection points
prop_dist_vect = np.stack((dx, dy, dz), axis=1) * np.expand_dims(ts, axis=1)
pts = np.stack((xo, yo, zo), axis=1) + prop_dist_vect
phase_shift = np.linalg.norm(prop_dist_vect, axis=1) * prop_direction * 2 * np.pi / wls * material.n(wls)
# assemble output rays
rays_out = np.concatenate((pts, np.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, :] = np.nan
return rays_out, ts
def ray_angle_about_axis(rays: NDArray, reference_axis: NDArray) -> (NDArray, NDArray):
"""
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:
"""
rays = np.atleast_2d(rays)
cosines = np.sum(rays[:, 3:6] * np.expand_dims(reference_axis, axis=0), axis=1)
angles = np.arccos(cosines)
na = rays[:, 3:6] - np.expand_dims(cosines, axis=1) * np.expand_dims(reference_axis, axis=0)
na = na / np.expand_dims(np.linalg.norm(na, axis=1), axis=1)
return angles, na
def dist_pt2plane(pts: NDArray,
normal: NDArray,
center: NDArray) -> (NDArray, NDArray):
"""
Calculate minimum distance between points and a plane defined by normal and center
:param pts:
:param normal:
:param center:
:return dists, nearest_pts:
"""
pts = np.atleast_2d(pts)
npts = pts.shape[0]
rays = np.concatenate((pts, np.tile(normal, (npts, 1)), np.zeros((npts, 2))), axis=1)
rays_int, _ = propagate_ray2plane(rays, normal, center, vacuum())
dists = np.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
"""
def __init__(self,
surfaces: list,
materials: list[material],
names: list[str] = None,
surfaces_by_name=None):
"""
:param surfaces: length n
:param materials: length n-1
:param names:
:param surfaces_by_name:
"""
if len(materials) != (len(surfaces) - 1):
raise ValueError()
self.surfaces = surfaces
self.materials = materials
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)
# todo: also need a way to carry names/descriptions of lenses around and show on plot
def reverse(self):
"""
flip direction of the optic we are considering (so typically rays now enter from the right)
:return:
"""
surfaces_rev = [copy.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: float = 0,
axis=(0, 0, 1)):
"""
add another optic after this one
:param other:
:param material:
:param distance:
:param axis:
:return new_system:
"""
# specify distance between surfaces as distances between the paraxial foci
new_surfaces = [copy.deepcopy(s) for s in other.surfaces]
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
s = self.surfaces + new_surfaces
materials = self.materials + [material] + other.materials
names = self.names + other.names
surfaces_by_name = np.concatenate((self.surfaces_by_name,
other.surfaces_by_name + np.max(self.surfaces_by_name) + 1))
return system(s, materials, names=names, surfaces_by_name=surfaces_by_name)
def ray_trace(self,
rays: NDArray,
initial_material: material,
final_material: material) -> NDArray:
"""
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")
rays = np.array(rays)
for ii in range(len(self.surfaces)):
rays = self.surfaces[ii].propagate(rays, materials[ii], materials[ii + 1])
return rays
def compute_paraxial_matrix(self,
wavelength: float,
initial_material: material,
final_material: material):
"""
Generate the ray transfer (ABCD) matrix for an optical system
Assume that the optical system starts at the provided initial distance before the first surface
:param wavelength:
:param initial_material:
:param final_material:
:return abcd_matrix:
"""
# todo: instead of indices of refraction use a material ... and derive index of refraction from material +
# wavelength
mats = [] # helpful for debugging
surfaces = self.surfaces
materials = [initial_material] + self.materials + [final_material]
indices_of_refraction = [m.n(wavelength) for m in materials]
# propagate initial distance
ray_xfer_mat = get_free_space_abcd(0, n=indices_of_refraction[0])
mats.append(ray_xfer_mat)
for ii in range(len(surfaces)):
# apply ray transfer matrix for current surface
abcd_temp = surfaces[ii].get_ray_transfer_matrix(indices_of_refraction[ii], indices_of_refraction[ii + 1])
ray_xfer_mat = abcd_temp.dot(ray_xfer_mat)
mats.append(abcd_temp)
# apply ray transfer matrix propagating between surfaces
if ii < (len(surfaces) - 1):
dist = np.linalg.norm(surfaces[ii].paraxial_center - surfaces[ii + 1].paraxial_center)
abcd_prop = get_free_space_abcd(dist, n=indices_of_refraction[ii + 1])
ray_xfer_mat = abcd_prop.dot(ray_xfer_mat)
mats.append(abcd_prop)
return ray_xfer_mat
def get_cardinal_points(self,
wavelength: float,
initial_material: material,
final_material: material):
"""
:param wavelength:
:param initial_material:
:param final_material:
:return fp1, fp2, pp1, pp2, efl1, efl2::
"""
# todo: add nodal planes
# find focal point to the right of the lens
ray_xfer = self.compute_paraxial_matrix(wavelength, initial_material, final_material)
d2x, _, efl2_x, d2y, _, efl2_y = find_paraxial_focus(ray_xfer, final_material.n(wavelength))
d2 = 0.5 * (d2x + d2y)
efl2 = 0.5 * (efl2_x + efl2_y)
fp2 = self.surfaces[-1].paraxial_center + d2 * self.surfaces[-1].output_axis
# find principal plane to the right
pp2 = fp2 - efl2 * self.surfaces[-1].output_axis
# find focal point to the left of the lens
ray_xfer_inv = self.reverse().compute_paraxial_matrix(wavelength, final_material, initial_material)
d1x, _, efl1_x, d1y, _, efl1_y = find_paraxial_focus(ray_xfer_inv, initial_material.n(wavelength))
d1 = 0.5 * (d1x + d1y)
efl1 = 0.5 * (efl1_x + efl1_y)
fp1 = self.surfaces[0].paraxial_center - d1 * self.surfaces[0].input_axis
# find principal plane to the left of the lens
pp1 = fp1 + efl1 * self.surfaces[0].input_axis
return fp1, fp2, pp1, pp2, efl1, efl2
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)