-
Notifications
You must be signed in to change notification settings - Fork 22
/
optics.py
2059 lines (1724 loc) · 74 KB
/
optics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from .basics import *
from .shapes import *
from scipy.interpolate import LSQBivariateSpline
import matplotlib.pyplot as plt
import copy
import pathlib
def tex(img_2d, size_2d, x, y, bmode=BoundaryMode.replicate): # texture indexing function
if bmode is BoundaryMode.zero:
raise NotImplementedError()
elif bmode is BoundaryMode.replicate:
x = torch.clamp(x, min=0, max=size_2d[0]-1)
y = torch.clamp(y, min=0, max=size_2d[1]-1)
elif bmode is BoundaryMode.symmetric:
raise NotImplementedError()
elif bmode is BoundaryMode.periodic:
raise NotImplementedError()
img = img_2d[x.flatten(), y.flatten()]
return img.reshape(x.shape)
def tex4(img_2d, size_2d, x0, y0, bmode=BoundaryMode.replicate): # texture indexing four pixels
_tex = lambda x, y : tex(img_2d, size_2d, x, y, bmode)
s00 = _tex( x0, y0)
s01 = _tex( x0, 1+y0)
s10 = _tex(1+x0, y0)
s11 = _tex(1+x0, 1+y0)
return s00, s01, s10, s11
class Lensgroup(Endpoint):
"""
The origin of the Lensgroup, which is a collection of multiple optical surfaces, is located at "origin".
The Lensgroup can rotate freely around the x/y axes, and the rotation angles are defined as "theta_x", "theta_y", and "theta_z" (in degrees).
In the Lensgroup's coordinate system, which is the object frame coordinate system, surfaces are arranged starting from "z = 0".
There is a small 3D origin shift, called "shift", between the center of the surface (0,0,0) and the mount's origin.
The sum of the shift and the origin is equal to the Lensgroup's origin.
There are two configurations for ray tracing: forward and backward.
- In the forward mode, rays begin at the surface with "d = 0" and propagate along the +z axis, e.g. from scene to image plane.
- In the backward mode, rays begin at the surface with "d = d_max" and propagate along the -z axis, e.g. from image plane to scene.
"""
def __init__(self, origin=np.zeros(3), shift=np.zeros(3), theta_x=0., theta_y=0., theta_z=0., device=torch.device('cpu')):
self.origin = torch.Tensor(origin).to(device)
self.shift = torch.Tensor(shift).to(device)
self.theta_x = torch.Tensor(np.asarray(theta_x)).to(device)
self.theta_y = torch.Tensor(np.asarray(theta_y)).to(device)
self.theta_z = torch.Tensor(np.asarray(theta_z)).to(device)
self.device = device
# Sequentials properties
self.surfaces = []
self.materials = []
# Sensor properties
self.pixel_size = 6.45 # [um]
self.film_size = [640, 480] # [pixel]
Endpoint.__init__(self, self._compute_transformation(), device)
# TODO: in case you would like to render something in Mitsuba2 ...
self.mts_prepared = False
def load_file(self, filename: pathlib.Path):
self.surfaces, self.materials, self.r_last, d_last = self.read_lensfile(str(filename))
self.d_sensor = d_last + self.surfaces[-1].d
self._sync()
def load(self, surfaces: list, materials: list):
self.surfaces = surfaces
self.materials = materials
self._sync()
def _sync(self):
for i in range(len(self.surfaces)):
self.surfaces[i].to(self.device)
self.aperture_ind = self._find_aperture()
def update(self, _x=0.0, _y=0.0):
self.to_world = self._compute_transformation(_x, _y)
self.to_object = self.to_world.inverse()
def _compute_transformation(self, _x=0.0, _y=0.0, _z=0.0):
# we compute to_world transformation given the input positional parameters (angles)
R = ( rodrigues_rotation_matrix(torch.Tensor([1, 0, 0]).to(self.device), torch.deg2rad(self.theta_x+_x)) @
rodrigues_rotation_matrix(torch.Tensor([0, 1, 0]).to(self.device), torch.deg2rad(self.theta_y+_y)) @
rodrigues_rotation_matrix(torch.Tensor([0, 0, 1]).to(self.device), torch.deg2rad(self.theta_z+_z)) )
t = self.origin + R @ self.shift
return Transformation(R, t)
def _find_aperture(self):
for i in range(len(self.surfaces)-1):
if self.materials[i].A < 1.0003 and self.materials[i+1].A < 1.0003: # both are AIR
return i
@staticmethod
def read_lensfile(filename):
surfaces = []
materials = []
ds = [] # no use for now
with open(filename) as file:
line_no = 0
d_total = 0.
for line in file:
if line_no < 2: # first two lines are comments; ignore them
line_no += 1
else:
ls = line.split()
surface_type, d, r = ls[0], float(ls[1]), float(ls[3])/2
roc = float(ls[2])
if roc != 0: roc = 1/roc
materials.append(Material(ls[4]))
d_total += d
ds.append(d)
if surface_type == 'O': # object
d_total = 0.
ds.pop()
elif surface_type == 'X': # XY-polynomial
del roc
ai = []
for ac in range(5, len(ls)):
if ac == 5:
b = float(ls[5])
else:
ai.append(float(ls[ac]))
surfaces.append(XYPolynomial(r, d_total, J=3, ai=ai, b=b))
elif surface_type == 'B': # B-spline
del roc
ai = []
for ac in range(5, len(ls)):
if ac == 5:
nx = int(ls[5])
elif ac == 6:
ny = int(ls[6])
else:
ai.append(float(ls[ac]))
tx = ai[:nx+8]
ai = ai[nx+8:]
ty = ai[:ny+8]
ai = ai[ny+8:]
c = ai
surfaces.append(BSpline(r, d, size=[nx, ny], tx=tx, ty=ty, c=c))
elif surface_type == 'M': # mixed-type of X and B
raise NotImplementedError()
elif surface_type == 'S': # aspheric surface
if len(ls) <= 5:
surfaces.append(Aspheric(r, d_total, roc))
else:
ai = []
for ac in range(5, len(ls)):
if ac == 5:
conic = float(ls[5])
else:
ai.append(float(ls[ac]))
surfaces.append(Aspheric(r, d_total, roc, conic, ai))
elif surface_type == 'A': # aperture
surfaces.append(Aspheric(r, d_total, roc))
elif surface_type == 'I': # sensor
d_total -= d
ds.pop()
materials.pop()
r_last = r
d_last = d
return surfaces, materials, r_last, d_last
def reverse(self):
# reverse surfaces
d_total = self.surfaces[-1].d
for i in range(len(self.surfaces)):
self.surfaces[i].d = d_total - self.surfaces[i].d
self.surfaces[i].reverse()
self.surfaces.reverse()
# reverse materials
self.materials.reverse()
# ------------------------------------------------------------------------------------
# Analysis
# ------------------------------------------------------------------------------------
def rms(self, ps, units=1, option='centroid', squared=False):
ps = ps[...,:2] * units
if option == 'centroid':
ps_mean = torch.mean(ps, axis=0)
ps = ps - ps_mean[None,...] # we now use normalized ps
if squared:
return torch.mean(torch.sum(ps**2, axis=-1)), ps/units
else:
return torch.sqrt(torch.mean(torch.sum(ps**2, axis=-1))), ps/units
def spot_diagram(self, ps, show=True, xlims=None, ylims=None, color='b.', savepath=None):
"""
Plot spot diagram.
"""
units = 1
spot_rms = float(self.rms(ps, units)[0])
ps = ps.cpu().detach().numpy()[...,:2]
ps_mean = np.mean(ps, axis=0) # centroid
ps = ps - ps_mean[None,...] # we now use normalized ps
fig = plt.figure()
ax = plt.axes()
ax.plot(ps[...,1], ps[...,0], color)
plt.gca().set_aspect('equal', adjustable='box')
if xlims is not None:
plt.xlim(*xlims)
if ylims is not None:
plt.ylim(*ylims)
ax.set_aspect(1./ax.get_data_ratio())
units_str = '[mm]'
plt.xlabel('x ' + units_str)
plt.ylabel('y ' + units_str)
plt.xticks(np.linspace(xlims[0], xlims[1], 11))
plt.yticks(np.linspace(ylims[0], ylims[1], 11))
# plt.grid(True)
if savepath is not None:
fig.savefig(savepath, bbox_inches='tight')
if show: plt.show()
else: plt.close()
return spot_rms
def split(self, combine_flags=None):
"""
Split a lensgroup into several smaller lensgroups.
"""
def create_lens(indices):
d = float(self.surfaces[indices[0]].d.cpu().detach().numpy())
lens = Lensgroup(
origin=np.array([0.0,0.0,d]), #_compute_transformation
shift=np.zeros(3),
theta_x=0.0,
theta_y=0.0,
theta_z=0.0,
device=self.device
)
lens.load( # here we make a deep copy to make a copy for every surface & material
copy.deepcopy([self.surfaces[j] for j in indices]),
copy.deepcopy([self.materials[j] for j in indices + [indices[-1]+1]])
)
# de-center the surfaces
for i in range(len(lens.surfaces)):
lens.surfaces[i].d = lens.surfaces[i].d - d
return lens
lenses = []
indices = []
k = 0
for i in range(len(self.surfaces)):
if self.materials[i].A < 1.0003: # AIR
if i > 0: # ends of a lensgroup
if combine_flags is not None:
k += 1
if combine_flags[k]: # skip this one
indices.append(i)
continue
else:
lenses.append(create_lens(indices))
indices = []
else:
lenses.append(create_lens(indices))
indices = []
indices.append(i)
else:
indices.append(i)
# end of a lensgroup
lenses.append(create_lens(indices))
return lenses
# ------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------
# IO and visualizations
# ------------------------------------------------------------------------------------
def draw_points(self, ax, options, seq=range(3)):
for surface in self.surfaces:
points_world = self._generate_points(surface)
ax.plot(points_world[seq[0]], points_world[seq[1]], points_world[seq[2]], options)
def get_lines_from_plot_setup2D(self, with_sensor=True):
lines = []
# to world coordinate
def plot(lines: list, surface_id, z, x):
p = self.to_world.transform_point(
torch.stack(
(x, torch.zeros_like(x, device=self.device), z), axis=-1
)
).cpu().detach().numpy()
lines.append({'z': p[...,2], 'x': p[...,0], 'id': surface_id})
def draw_aperture(lines: list, surface, surface_id):
N = 3
d = surface.d.cpu()
R = surface.r
APERTURE_WEDGE_LENGTH = 0.05 * R # [mm]
APERTURE_WEDGE_HEIGHT = 0.15 * R # [mm]
# wedge length
z = torch.linspace(d - APERTURE_WEDGE_LENGTH, d + APERTURE_WEDGE_LENGTH, N, device=self.device)
x = -R * torch.ones(N, device=self.device)
plot(lines, surface_id, z, x)
x = R * torch.ones(N, device=self.device)
plot(lines, surface_id, z, x)
# wedge height
z = d * torch.ones(N, device=self.device)
x = torch.linspace(R, R+APERTURE_WEDGE_HEIGHT, N, device=self.device)
plot(lines, surface_id, z, x)
x = torch.linspace(-R-APERTURE_WEDGE_HEIGHT, -R, N, device=self.device)
plot(lines, surface_id, z, x)
if len(self.surfaces) == 1: # if there is only one surface, then it has to be the aperture
draw_aperture(lines, self.surfaces[0], 0)
else:
# draw sensor plane
if with_sensor == True:
try:
tmpr, tmpdd = self.r_last, self.d_sensor
except AttributeError:
with_sensor = False
if with_sensor:
self.surfaces.append(Aspheric(self.r_last, self.d_sensor, 0.0))
# draw surface
for i, s in enumerate(self.surfaces):
# find aperture
if i < len(self.surfaces)-1:
if self.materials[i].A < 1.0003 and self.materials[i+1].A < 1.0003: # both are AIR
draw_aperture(lines, s, i)
continue
r = torch.linspace(-s.r, s.r, s.APERTURE_SAMPLING, device=self.device) # aperture sampling
z = s.surface_with_offset(r, torch.zeros(len(r), device=self.device))
plot(lines, i, z, r)
# draw boundary
s_prev = []
for i, s in enumerate(self.surfaces):
if self.materials[i].A < 1.0003: # AIR
s_prev = s
else:
r_prev = s_prev.r
r = s.r
sag_prev = s_prev.surface_with_offset(r_prev, 0.0)
sag = s.surface_with_offset(r, 0.0)
z = torch.stack((sag_prev, sag))
x = torch.Tensor(np.array([r_prev, r])).to(self.device)
plot(lines, i, z, x)
plot(lines, i, z,-x)
s_prev = s
# remove sensor plane
if with_sensor:
self.surfaces.pop()
return lines
def plot_setup2D(self, ax=None, fig=None, show=True, color='k', with_sensor=True):
"""
Plot elements in 2D.
"""
if ax is None and fig is None:
fig, ax = plt.subplots(figsize=(8,6))
else:
show=False
# to world coordinate
def plot(ax, z, x, color):
p = self.to_world.transform_point(
torch.stack(
(x, torch.zeros_like(x, device=self.device), z), axis=-1
)
).cpu().detach().numpy()
ax.plot(p[...,2], p[...,0], color)
def draw_aperture(ax, surface, color):
N = 3
d = surface.d.cpu()
R = surface.r
APERTURE_WEDGE_LENGTH = 0.05 * R # [mm]
APERTURE_WEDGE_HEIGHT = 0.15 * R # [mm]
# wedge length
z = torch.linspace(d - APERTURE_WEDGE_LENGTH, d + APERTURE_WEDGE_LENGTH, N, device=self.device)
x = -R * torch.ones(N, device=self.device)
plot(ax, z, x, color)
x = R * torch.ones(N, device=self.device)
plot(ax, z, x, color)
# wedge height
z = d * torch.ones(N, device=self.device)
x = torch.linspace(R, R+APERTURE_WEDGE_HEIGHT, N, device=self.device)
plot(ax, z, x, color)
x = torch.linspace(-R-APERTURE_WEDGE_HEIGHT, -R, N, device=self.device)
plot(ax, z, x, color)
if len(self.surfaces) == 1: # if there is only one surface, then it has to be the aperture
draw_aperture(ax, self.surfaces[0], color)
else:
# draw sensor plane
if with_sensor:
try:
self.surfaces.append(Aspheric(self.r_last, self.d_sensor, 0.0))
except AttributeError:
with_sensor = False
# draw surface
for i, s in enumerate(self.surfaces):
# find aperture
if i < len(self.surfaces)-1:
if self.materials[i].A < 1.0003 and self.materials[i+1].A < 1.0003: # both are AIR
draw_aperture(ax, s, color)
continue
r = torch.linspace(-s.r, s.r, s.APERTURE_SAMPLING, device=self.device) # aperture sampling
z = s.surface_with_offset(r, torch.zeros(len(r), device=self.device))
plot(ax, z, r, color)
# draw boundary
s_prev = []
for i, s in enumerate(self.surfaces):
if self.materials[i].A < 1.0003: # AIR
s_prev = s
else:
r_prev = s_prev.r
r = s.r
sag_prev = s_prev.surface_with_offset(r_prev, 0.0)
sag = s.surface_with_offset(r, 0.0)
z = torch.stack((sag_prev, sag))
x = torch.Tensor(np.array([r_prev, r])).to(self.device)
plot(ax, z, x, color)
plot(ax, z,-x, color)
s_prev = s
# remove sensor plane
if with_sensor:
self.surfaces.pop()
plt.gca().set_aspect('equal', adjustable='box')
plt.xlabel('z [mm]')
plt.ylabel('r [mm]')
plt.title("Layout 2D")
if show: plt.show()
return ax, fig
# TODO: modify the tracing part to include oss
def plot_raytraces(self, oss, ax=None, fig=None, color='b-', show=True, p=None, valid_p=None):
"""
Plot all ray traces (oss).
"""
if ax is None and fig is None:
ax, fig = self.plot_setup2D(show=False)
else:
show=False
for i, os in enumerate(oss):
o = torch.Tensor(np.array(os)).to(self.device)
x = o[...,0]
z = o[...,2]
# to world coordinate
o = self.to_world.transform_point(
torch.stack(
(x, torch.zeros_like(x, device=self.device), z), axis=-1
)
)
o = o.cpu().detach().numpy()
z = o[...,2].flatten()
x = o[...,0].flatten()
if p is not None and valid_p is not None:
if valid_p[i]:
x = np.append(x, p[i,0])
z = np.append(z, p[i,2])
ax.plot(z, x, color, linewidth=1.0)
if show: plt.show()
else: plt.close()
return ax, fig
def plot_setup2D_with_trace(self, views, wavelength, M=2, R=None, entrance_pupil=True):
if R is None:
R = self.surfaces[0].r
colors_list = 'bgrymck'
ax, fig = self.plot_setup2D(show=False)
for i, view in enumerate(views):
ray = self.sample_ray_2D(R, wavelength, view=view, M=M, entrance_pupil=entrance_pupil)
ps, oss = self.trace_to_sensor_r(ray)
ax, fig = self.plot_raytraces(oss, ax=ax, fig=fig, color=colors_list[i])
# fig.show()
return ax, fig
# ------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------
# Utilities
# ------------------------------------------------------------------------------------
def calc_entrance_pupil(self, view=0.0, R=None):
angle = np.radians(np.asarray(view))
# maximum radius input
if R is None:
with torch.no_grad():
sag = self.surfaces[0].surface(self.surfaces[0].r, 0.0)
R = np.tan(angle) * sag + self.surfaces[0].r # [mm]
R = R.item()
APERTURE_SAMPLING = 101
x, y = torch.meshgrid(
torch.linspace(-R, R, APERTURE_SAMPLING, device=self.device),
torch.linspace(-R, R, APERTURE_SAMPLING, device=self.device),
indexing='ij'
)
# generate rays and find valid map
ones = torch.ones_like(x)
zeros = torch.zeros_like(x)
o = torch.stack((x,y,zeros), axis=2)
d = torch.stack((
np.sin(angle)*ones,
zeros,
np.cos(angle)*ones), axis=-1
)
ray = Ray(o, d, torch.Tensor([580.0]).to(self.device), device=self.device)
valid_map = self.trace_valid(ray)
# find bounding box
xs, ys = x[valid_map], y[valid_map]
return valid_map, xs, ys
def sample_ray(self, wavelength, view=0.0, M=15, R=None, shift_x=0., shift_y=0., sampling='grid', entrance_pupil=False):
angle = np.radians(np.asarray(view))
# maximum radius input
if R is None:
with torch.no_grad():
sag = self.surfaces[0].surface(self.surfaces[0].r, 0.0)
R = np.tan(angle) * sag + self.surfaces[0].r # [mm]
R = R.item()
if entrance_pupil:
xs, ys = self.calc_entrance_pupil(view, R)[1:]
if sampling == 'grid':
x, y = torch.meshgrid(
torch.linspace(xs.min(), xs.max(), M, device=self.device),
torch.linspace(ys.min(), ys.max(), M, device=self.device),
indexing='ij'
)
elif sampling == 'radial':
R = np.minimum(xs.max() - xs.min(), ys.max() - ys.min())
r = torch.linspace(0, R, M, device=self.device)
theta = torch.linspace(0, 2*np.pi, M+1, device=self.device)[0:M]
x = xs.mean() + r[None,...] * torch.cos(theta[...,None])
y = ys.mean() + r[None,...] * torch.sin(theta[...,None])
else:
if sampling == 'grid':
x, y = torch.meshgrid(
torch.linspace(-R, R, M, device=self.device),
torch.linspace(-R, R, M, device=self.device),
indexing='ij'
)
elif sampling == 'radial':
r = torch.linspace(0, R, M, device=self.device)
theta = torch.linspace(0, 2*np.pi, M+1, device=self.device)[0:M]
x = r[None,...] * torch.cos(theta[...,None])
y = r[None,...] * torch.sin(theta[...,None])
p = 2*R / M
x = x + p * shift_x
y = y + p * shift_y
o = torch.stack((x,y,torch.zeros_like(x, device=self.device)), axis=2)
d = torch.stack((
np.sin(angle)*torch.ones_like(x),
torch.zeros_like(x),
np.cos(angle)*torch.ones_like(x)), axis=-1
)
return Ray(o, d, wavelength, device=self.device)
# TODO: merge `sample_ray_fullfield` with `sample_ray`
def sample_ray_fullfield(self, wavelength, view_xy=[0.0,0.0], M=15, R=None, shift_xy=[0.,0.], sampling='grid'):
angle_xy = torch.Tensor(np.radians(np.asarray(view_xy))).to(self.device)
if sampling == 'grid':
x, y = torch.meshgrid(
torch.linspace(-R, R, M, device=self.device),
torch.linspace(-R, R, M, device=self.device),
indexing='ij'
)
elif sampling == 'radial':
r = torch.linspace(0, R, M, device=self.device)
theta = torch.linspace(0, 2*np.pi, M+1, device=self.device)[0:M]
x = r[None,...] * torch.cos(theta[...,None])
y = r[None,...] * torch.sin(theta[...,None])
p = 2*R / M
x = x + p * shift_xy[0]
y = y + p * shift_xy[1]
o = torch.stack((x,y,torch.zeros_like(x, device=self.device)), axis=2)
d = torch.stack((
torch.sin(angle_xy[0])*torch.ones_like(x),
torch.sin(angle_xy[1])*torch.ones_like(x),
torch.cos(angle_xy[0])*torch.cos(angle_xy[1])*torch.ones_like(x)), axis=-1
)
return Ray(o, d, wavelength, device=self.device)
def sample_ray_2D(self, R, wavelength, view=0.0, M=15, shift_x=0., entrance_pupil=False):
if entrance_pupil:
# x_up, x_down, x_center = self.find_ray_2D(view=view)
xs = self.calc_entrance_pupil(view=view)[1]
x_up = xs.min()
x_down = xs.max()
x_center = xs.mean()
x = torch.hstack((
torch.linspace(x_down, x_center, M+1, device=self.device)[:M],
torch.linspace(x_center, x_up, M+1, device=self.device),
))
else:
x = torch.linspace(-R, R, M, device=self.device)
p = 2*R / M
x = x + p * shift_x
ones = torch.ones_like(x)
zeros = torch.zeros_like(x)
o = torch.stack((x,zeros,zeros), axis=1)
angle = torch.Tensor(np.asarray(np.radians(view))).to(self.device)
d = torch.stack((
torch.sin(angle)*ones,
zeros,
torch.cos(angle)*ones), axis=-1
)
return Ray(o, d, wavelength, device=self.device)
def find_ray_2D(self, view=0.0, y=0.0):
"""
This function finds chief and marginal rays at a specific view.
"""
wavelength = torch.Tensor([589.3]).to(self.device)
R_aperture = self.surfaces[self.aperture_ind].r
angle = np.radians(view)
d = torch.Tensor(np.stack((
np.sin(angle),
y,
np.cos(angle)), axis=-1
)).to(self.device)
def find_x(alpha=1.0): # TODO: does not work for wide-angle lenses!
x = - np.tan(angle) * self.surfaces[self.aperture_ind].d.cpu().detach().numpy()
is_converge = False
for k in range(30):
o = torch.Tensor([x, y, 0.0])
ray = Ray(o, d, wavelength, device=self.device)
ray_final, valid = self.trace(ray, stop_ind=self.aperture_ind)[:2]
x_aperture = ray_final.o[0].cpu().detach().numpy()
diff = 0.0 - x_aperture
if np.abs(diff) < 0.001:
print('`find_x` converges!')
is_converge = True
break
if valid:
x_last = x
if diff > 0.0:
x += alpha * diff
else:
x -= alpha * diff
else:
x = (x + x_last)/2
return x, is_converge
def find_bx(x_center, R_aperture, alpha=1.0):
x = x_center
x_last = 0.0 # temp
for k in range(100):
o = torch.Tensor([x, y, 0.0])
ray = Ray(o, d, wavelength, device=self.device)
ray_final, valid = self.trace(ray, stop_ind=self.aperture_ind)[:2]
x_aperture = ray_final.o[0].cpu().detach().numpy()
diff = R_aperture - x_aperture
if np.abs(diff) < 0.01:
print('`find_x` converges!')
break
if valid:
x_last = x
if diff > 0.0:
x += alpha * diff
else:
x -= alpha * diff
else:
x = (x + x_last)/2
return x_last
x_center, is_converge = find_x(alpha=-np.sign(view)*1.0)
if not is_converge:
x_center, is_converge = find_x(alpha=np.sign(view)*1.0)
x_up = find_bx(x_center, R_aperture, alpha=1)
x_down = find_bx(x_center, -R_aperture, alpha=-1)
return x_up, x_down, x_center
# ------------------------------------------------------------------------------------
def render(self, ray, irr=1.0):
"""
Forward rendering.
"""
# TODO: remind users to prepare filmsize and pixelsize before using this function.
# trace rays
ray_final, valid = self.trace(ray)
# intersecting sensor plane
t = (self.d_sensor - ray_final.o[...,2]) / ray_final.d[...,2]
p = ray_final(t)
R_sensor = [self.film_size[i] * self.pixel_size/2 for i in range(2)]
valid = valid & (
(-R_sensor[0] <= p[...,0]) & (p[...,0] <= R_sensor[0]) &
(-R_sensor[1] <= p[...,1]) & (p[...,1] <= R_sensor[1])
)
# intensity
J = irr
p = p[valid]
# compute shift and find nearest pixel index
u = (p[...,0] + R_sensor[0]) / self.pixel_size
v = (p[...,1] + R_sensor[1]) / self.pixel_size
index_l = torch.stack(
(torch.clamp(torch.floor(u).long(), min=0, max=self.film_size[0]-1),
torch.clamp(torch.floor(v).long(), min=0, max=self.film_size[1]-1)),
axis=-1
)
index_r = torch.stack(
(torch.clamp(index_l[...,0] + 1, min=0, max=self.film_size[0]-1),
torch.clamp(index_l[...,1] + 1, min=0, max=self.film_size[1]-1)),
axis=-1
)
w_r = torch.clamp(torch.stack((u,v), axis=-1) - index_l, min=0, max=1)
w_l = 1.0 - w_r
del u, v
# compute image
I = torch.zeros(*self.film_size, device=self.device)
I = torch.index_put(I, (index_l[...,0],index_l[...,1]), w_l[...,0]*w_l[...,1]*J, accumulate=True)
I = torch.index_put(I, (index_r[...,0],index_l[...,1]), w_r[...,0]*w_l[...,1]*J, accumulate=True)
I = torch.index_put(I, (index_l[...,0],index_r[...,1]), w_l[...,0]*w_r[...,1]*J, accumulate=True)
I = torch.index_put(I, (index_r[...,0],index_r[...,1]), w_r[...,0]*w_r[...,1]*J, accumulate=True)
return I
def trace_valid(self, ray):
"""
Trace rays to see if they intersect the sensor plane or not.
"""
valid = self.trace(ray)[1]
return valid
def trace_to_sensor(self, ray, ignore_invalid=False):
"""
Trace rays towards intersecting onto the sensor plane.
"""
# trace rays
ray_final, valid = self.trace(ray)
# intersecting sensor plane
t = (self.d_sensor - ray_final.o[...,2]) / ray_final.d[...,2]
p = ray_final(t)
if ignore_invalid:
p = p[valid]
else:
if len(p.shape) < 2:
return p
p = torch.reshape(p, (np.prod(p.shape[:-1]), 3))
return p
def trace_to_sensor_r(self, ray, ignore_invalid=False):
"""
Trace rays towards intersecting onto the sensor plane, with records.
"""
# trace rays
ray_final, valid, oss = self.trace_r(ray)
# intersecting sensor plane
t = (self.d_sensor - ray_final.o[...,2]) / ray_final.d[...,2]
p = ray_final(t)
if ignore_invalid:
p = p[valid]
else:
p = torch.reshape(p, (np.prod(p.shape[:-1]), 3))
for v, os, pp in zip(valid, oss, p):
if v:
os.append(pp.cpu().detach().numpy())
return p, oss
def trace(self, ray, stop_ind=None):
# update transformation when doing pose estimation
if (
self.origin.requires_grad
or
self.shift.requires_grad
or
self.theta_x.requires_grad
or
self.theta_y.requires_grad
or
self.theta_z.requires_grad
):
self.update()
# in local
ray_in = self.to_object.transform_ray(ray)
valid, ray_out = self._trace(ray_in, stop_ind=stop_ind, record=False)
# in world
ray_final = self.to_world.transform_ray(ray_out)
return ray_final, valid
def trace_r(self, ray, stop_ind=None):
# update transformation when doing pose estimation
if (
self.origin.requires_grad
or
self.shift.requires_grad
or
self.theta_x.requires_grad
or
self.theta_y.requires_grad
or
self.theta_z.requires_grad
):
self.update()
# in local
ray_in = self.to_object.transform_ray(ray)
valid, ray_out, oss = self._trace(ray_in, stop_ind=stop_ind, record=True)
# in world
ray_final = self.to_world.transform_ray(ray_out)
for os in oss:
for o in os:
os = self.to_world.transform_point(torch.Tensor(np.asarray(os)).to(self.device)).cpu().detach().numpy()
return ray_final, valid, oss
# ------------------------------------------------------------------------------------
# Rendering
# ------------------------------------------------------------------------------------
def prepare_mts(self, pixel_size, film_size, R=np.eye(3), t=np.zeros(3)):
# TODO: this is actually prepare_backward tracing ...
"""
Revert surfaces for Mitsuba2 rendering.
"""
if self.mts_prepared:
print('MTS already prepared for this lensgroup.')
return
# sensor parameters
self.pixel_size = pixel_size # [mm]
self.film_size = film_size # [pixel]
# rendering parameters
self.mts_Rt = Transformation(R, t) # transformation of the lensgroup
self.mts_Rt.to(self.device)
# for visualization
self.r_last = self.pixel_size * max(self.film_size) / 2
# TODO: could be further optimized:
# treat the lenspart as a camera; append one more surface to it
self.surfaces.append(Aspheric(self.r_last, self.d_sensor, 0.0))
# reverse surfaces
d_total = self.surfaces[-1].d
for i in range(len(self.surfaces)):
self.surfaces[i].d = d_total - self.surfaces[i].d
self.surfaces[i].reverse()
self.surfaces.reverse()
self.surfaces.pop(0) # remove sensor plane
# reverse materials
self.materials.reverse()
# aperture plane (TODO: could be optimized further to trace pupil positions)
self.aperture_radius = self.surfaces[0].r
self.aperture_distance = self.surfaces[0].d
self.mts_prepared = True
self.d_sensor = 0
def _generate_sensor_samples(self):
sX, sY = np.meshgrid(
np.linspace(0, 1, self.film_size[0]),
np.linspace(0, 1, self.film_size[1])
)
return np.stack((sX.flatten(), sY.flatten()), axis=1)
def _generate_aperture_samples(self):
Dx = np.random.rand(*self.film_size)
Dy = np.random.rand(*self.film_size)
[px, py] = Sampler().concentric_sample_disk(Dx, Dy)
return np.stack((px.flatten(), py.flatten()), axis=1)
def sample_ray_sensor_pinhole(self, wavelength, focal_length):
"""
Sample ray on the sensor plane, assuming a pinhole camera model, given a focal length.
"""
if not self.mts_prepared:
raise Exception('MTS unprepared; please call `prepare_mts()` first!')
N = np.prod(self.film_size)
# sensor and aperture plane samplings
sample2 = self._generate_sensor_samples()
# wavelength [nm]
wavelength = torch.Tensor(wavelength * np.ones(N))
# normalized to [-0,5, 0.5]
sample2 = sample2 - 0.5
# sample sensor and aperture planes
p_sensor = sample2 * np.array([
self.pixel_size * self.film_size[0], self.pixel_size * self.film_size[1]
])[None,:]
# aperture samples (last surface plane)
p_aperture = 0
d_xy = p_aperture - p_sensor
# construct ray
o = torch.Tensor(np.hstack((p_sensor, np.zeros((N,1)))).reshape((N,3)))
d = torch.Tensor(np.hstack((d_xy, focal_length * np.ones((N,1)))).reshape((N,3)))
d = normalize(d)
ray = Ray(o, d, wavelength, device=self.device)
valid = torch.ones(ray.o[..., 2].shape, device=self.device).bool()
return valid, ray
def sample_ray_sensor(self, wavelength, offset=np.zeros(2)):
"""
Sample rays on the sensor plane.
"""
if not self.mts_prepared:
raise Exception('MTS unprepared; please call `prepare_mts()` first!')
N = np.prod(self.film_size)
# sensor and aperture plane samplings
sample2 = self._generate_sensor_samples()
sample3 = self._generate_aperture_samples()
# wavelength [nm]
wav = wavelength * np.ones(N)
# sample ray
valid, ray = self._sample_ray_render(N, wav, sample2, sample3, offset)
ray_new = self.mts_Rt.transform_ray(ray)
return valid, ray_new
def _sample_ray_render(self, N, wav, sample2, sample3, offset):
"""
`offset`: sensor position offsets [mm].
"""
# sample2 \in [ 0, 1]^2
# sample3 \in [-1, 1]^2
if not self.mts_prepared:
raise Exception('MTS unprepared; please call `prepare_mts()` first!')
# normalized to [-0,5, 0.5]
sample2 = sample2 - 0.5
# sample sensor and aperture planes
p_sensor = sample2 * np.array([
self.pixel_size * self.film_size[0], self.pixel_size * self.film_size[1]
])[None,:]
# perturb sensor position by half pixel size
p_sensor = p_sensor + (np.random.rand(*p_sensor.shape) - 0.5) * self.pixel_size
# offset sensor positions
p_sensor = p_sensor + offset
# aperture samples (last surface plane)
p_aperture = sample3 * self.aperture_radius
d_xy = p_aperture - p_sensor