-
Notifications
You must be signed in to change notification settings - Fork 0
/
ray_tracing_utils.py
1544 lines (1338 loc) · 66.9 KB
/
ray_tracing_utils.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
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.patches as mpatches
from matplotlib.ticker import FormatStrFormatter
from mpl_toolkits.mplot3d import Axes3D
from math import ceil
import json
from os.path import join, exists
from os import mkdir,listdir
from tqdm import tqdm
from collections import deque #to implement stack
# import scripts
import ray_tracing_constants as rtc
from option import args
from hierarchical_ray import Forest
class BoundaryPoints:
def __init__(self,HD, solar_altitude,solar_azimuth,step):
"""
HD (HexagonalDomain class)
solar_altitude (float): in degrees, angle between horizontal surface to location of "sun"
solar_azimuth (float): in degrees, angle between location of sun and +ve i direction
step (float): subdivisions to divide the slanted_length/horizontal_length
# n (int): order of HD
# n_max (float): max height of wave facet
# zenith (float): angle (rad) bounded by ray and vertical
# d (float): projected length of ray on the horizontal
# s (np.array): point on the vector
# l (float): scaling factor of vector
# r_1 is pointing towards +ve i and +ve j direction
# r_2 is pointing towards -ve i and +ve j direction
# i_vector is point towards +ve i
"""
self.n = HD.n
self.n_max = HD.n_max
self.solar_altitude = solar_altitude/180*np.pi #in rad
self.solar_azimuth = solar_azimuth/180*np.pi #in rad
self.solar_zenith = np.pi/2 - self.solar_altitude #in rad
self.d = np.tan(self.solar_zenith)*self.n_max
self.delta = rtc.delta
self.eps = rtc.eps
self.gamma = rtc.gamma
self.corner_points = HD.corner_points
# get points along the vector
self.r1_vector = lambda s,l: s + l*rtc.r_1
self.r2_vector = lambda s,l: s + l*rtc.r_2
self.i_vector = lambda s,l: s+ l*np.array([1,0,0])
self.step = step
self.slanted_length = self.n*self.gamma
self.horizontal_length = self.n*self.delta
self.slanted_division = np.arange(0,self.slanted_length,self.step)
self.horizontal_division = np.arange(0,self.horizontal_length,self.step)
self.xi_prime = self.get_xi_prime()
def get_boundary_points(self):
"""
returns points_dict (dict): where keys (int) corresponds to the index of corner points of HD, from x0 to x3 in a cw direction,
and values (list of np.arrays) correspond the the coordinate points generated along the r1,r,r2 vectors (on all surface boundaries of the HD)
Do refer to the labelling of the corner points on the HD
"""
# random_index = random.randint(0,len(self.slanted_division)-1) #index to find the length along the vector
# x0_x2 = self.r1_vector(self.corner_points[1],self.slanted_division[random_index])
# x2_x4 = self.i_vector(self.corner_points[2],self.horizontal_division[random_index])
# x4_x6 = self.r2_vector(self.corner_points[4],-self.slanted_division[random_index])
# x6_x5 = self.r1_vector(self.corner_points[6],-self.slanted_division[random_index])
# x5_x3 = self.i_vector(self.corner_points[5],-self.horizontal_division[random_index])
# x3_x0 = self.r2_vector(self.corner_points[3],self.slanted_division[random_index])
points_dict = {i:[] for i in range(1,7)} #which corresponds to the corner points of HD, from x0 to x3 in a cw direction
for i,v in enumerate([self.r1_vector, self.i_vector, self.r2_vector]):
coord_start_index = i+1
coord_start_index_rev = 7 - coord_start_index
for s_l in range(len(self.slanted_division)): #iterate across all the subdivisions along the length
if i%2 == 0: #if either the r1 or r2 vector
points_dict[coord_start_index].append(v(self.corner_points[coord_start_index],self.slanted_division[s_l]))
points_dict[coord_start_index_rev].append(v(self.corner_points[coord_start_index_rev],-self.slanted_division[s_l]))
for h_l in range(len(self.horizontal_division)): #iterate across all the subdivisions along the length
if i%2 != 0: #if it's the i_vector
points_dict[coord_start_index].append(v(self.corner_points[coord_start_index],self.horizontal_division[h_l]))
points_dict[coord_start_index_rev].append(v(self.corner_points[coord_start_index_rev],-self.horizontal_division[h_l]))
return points_dict
def get_points_within_HD(self):
"""
step (float): distance between adjacent points
returns points within the HD with height at n_max (highest wave facet) to ensure that they intersect the wave facet
"""
ref_point = np.array([-self.n*self.delta,0,0]) #x0 point
x_dist = lambda x1,x2: abs(x1[0]-x2[0]) # horizontal x distance between two points, x1, x2 represents the np.arrays of coord
base_of_parallelogram = lambda d: self.n*self.gamma + 2*self.gamma/self.delta*d #where d represents the horizontal x distance
# if distance is zero it is just the length x0 to x3
BP = self.get_boundary_points()
points_list = []
for s in BP[1]:
d = x_dist(s,ref_point)
L = base_of_parallelogram(d)
for l in np.arange(0,L,step=self.step):
p = self.r2_vector(s,-l)
points_list.append(np.array([p[0],p[1],self.n_max]))
points_list.append(np.array([-p[0],-p[1],self.n_max]))
return points_list
def get_xi_prime(self):
"""
returns unit xi_prime, directed downwards, towards azimuth
"""
# location of sun
theta_s = self.solar_zenith
phi_s = self.solar_azimuth
# direction of where ray is travelling
theta = np.pi - theta_s
phi = (phi_s + np.pi)%(2*np.pi) #modulo 360
self.ray_zenith = theta
self.ray_azimuth = phi
xi_prime = np.array([np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi),np.cos(theta)])
# xi_prime = np.array([self.d*np.cos(self.azimuth),self.d*np.sin(self.azimuth),-self.n_max]) # target where the ray hits the horizontal surface i.e. distance from p_h to target
t = xi_prime/np.linalg.norm(xi_prime) # ray is directed
# lambda_t = lambda t,p: t + np.array([p[0],p[1],0])
# points_within_HD = self.get_points_within_HD()
# unit_xi_prime = [(lambda_t(t,p)-p) for p in points_within_HD]
return t
class TIP:
"""
stores the attributes of TIPs
k (int): k family to identify if TIP lies on the r_0, r_1 or r_2 line
s (float): scalar distance from p_h along xi_h
index (int): the order (in ascending order) of TIPs
coord (np.array): location of TIPs w.r.t origin
"""
def __init__(self,k,index,s,p_h,xi_h):
self.delta = rtc.delta
self.eps = rtc.eps
self.r_1_hat = rtc.r_1_hat
self.r_2_hat = rtc.r_2_hat
self.gamma = rtc.gamma
self.i = rtc.i#np.array([1,0,0])
self.j = rtc.j#np.array([0,1,0])
self.k = rtc.k#np.array([0,0,1])
self.k = k
self.index = index
self.s = s
self.p_h = p_h
self.xi_h = xi_h
self.coord = self.p_h + self.s*self.xi_h
if self.k == 1:
d_k = np.dot(self.coord,self.r_1_hat)/np.dot(self.j,self.r_1_hat)
elif self.k == 2:
d_k = np.dot(self.coord,self.r_2_hat)/np.dot(self.j,self.r_2_hat)
else:
d_k = np.dot(self.coord, self.j)
self.d_k = d_k
class WaveFacet:
"""
obtains the attributes of wave facet
nodes (tuple of np.array): triple tuple of array of nodes that define the triad vertices
norm (np.array): (3,) array of unit vector of the normal of the wave triad facets
"""
def __init__(self,nodes):
self.nodes = nodes
self.norm = self.get_norm()
self.tilt = self.get_tilt()
def get_norm(self):
n1 = np.cross((self.nodes[2] - self.nodes[0]),(self.nodes[1] - self.nodes[0]))
n1 = n1/np.linalg.norm(n1)
if np.dot(n1,np.array([0,0,1])) < 0:
sign = -1
else:
sign = 1
n1 = sign*n1
return n1
def get_tilt(self):
"""
get average tilt of the wave facet's unit normal n from the vertical k (aka beta)
"""
return np.arccos(np.dot(self.norm,np.array([0,0,1])))
class DaughterRay:
"""
theta_r (float): angle of incidence = reflectance (in rad)
theta_t (float): angle of refraction (in rad)
xi_r (np.array): vector of reflectance
xi_t (np.array): vector of transmittance
WF (WaveFacet class): wave facet where incident ray intercepts with WaveFacet
returns the attributes of a daughter ray
"""
def __init__(self,p_prime,xi_prime,theta_r,theta_t,xi_r,xi_t,WF):
self.p_prime = p_prime
self.xi_prime = xi_prime
self.theta_r = theta_r
self.theta_t = theta_t
self.xi_r = xi_r
self.xi_t = xi_t
self.fresnel_reflectance = self.get_fresnel_reflectance()
self.fresnel_transmittance = 1- self.fresnel_reflectance
self.WF = WF
def get_fresnel_reflectance(self):
"""
DR (DaughterRay class)
"""
if (isinstance(self.theta_t,float)) and (isinstance(self.xi_t,np.ndarray)): #(self.theta_t is not None) and (self.xi_t is not None):
reflectance_theta_prime = 0.5*((np.sin(self.theta_r - self.theta_t)/np.sin(self.theta_r+self.theta_t))**2 + (np.tan(self.theta_r - self.theta_t)/np.tan(self.theta_r+self.theta_t))**2)
return reflectance_theta_prime #r(\xi_prime \cdot n)
else: #if Total Internal Reflection (TIR) occurs
return 1
class HexagonalDomain:
"""
computes the hexagonal domain
"""
def __init__(self,n):
"""
n (int): order of hexagonal grid
p_h (np.array): point where projected light ray enters the hexagonal domain
p_prime (np.array): point where light ray enters the hexagonal domain
xi_h (np.array): a unit vector of projected ray path
xi_prime (np.array): a vector of ray path
vertices_dict (dict): where keys are the vertices coordinates (str); values are the unique index (int) for each vertex
nodes_dict (dict): where keys are the unique index (int) in vertices_dict; and values are the (3,) np.array of the nodes coordinate
"""
self.i = rtc.i#np.array([1,0,0])
self.j = rtc.j#np.array([0,1,0])
self.k = rtc.k#np.array([0,0,1])
self.n = n
self.delta = rtc.delta
self.eps = rtc.eps
self.gamma = rtc.gamma
# self.p_h = p_h
# self.xi_h = xi_h
# self.p_prime = p_prime
# self.xi_prime = xi_prime
self.r_11 = self.delta/(2*self.gamma)
self.r_21 = self.eps/self.gamma
self.r_12 = -1*self.r_11
self.r_22 = self.r_21*1
self.r_1 = np.array([self.r_11,self.r_21,0])
self.r_2 = np.array([self.r_12,self.r_22,0])
self.r_1_hat = np.array([-self.r_21,self.r_11,0])
self.r_2_hat = np.array([-self.r_22,self.r_12,0])
self.x, self.y = self.get_hexagonal_vertices()
self.vertices_dict = self.get_vertices_index()
self.corner_points = self.get_corner_points()
def get_hexagonal_vertices(self):
"""
creates the hexagonal grid based on the order (n) supplied
"""
L = 2*self.n+1 #largest number of vertices at the center
x = []
y = []
for i in range(self.n+1): #inclusive of n
x0 = np.linspace(-self.n+i*self.delta/2,self.n-i*self.delta/2,num=L-i)
y0 = np.repeat(np.array([i]),x0.shape[0],axis=0)
x.append(x0)
y.append(y0*self.eps)
y = y + ([i*-1 for i in y[1:]])
x = x + (x[1:])
x = np.concatenate(x)
y = np.concatenate(y)
# plt.figure()
# plt.plot(x,y,'o')
# plt.show()
return x,y
def get_vertices_index(self):
"""
returns a dict where the i,j tuple vertices and they are unique, and values are the indices corresponding to the x,y array
so that we can search for the indices quickly using the i,j tuple information
"""
# vertices list of the triads on the horizontal surface
vertices_list = []
for i,j in zip(self.x,self.y):
vertices_list.append(np.array([i,j,0]))
vertices_list
#compute i and j
vertices_dict = {} #where keys are the i,j tuple vertices and they are unique, and values are the indices corresponding to the array
# so that we can search for the indices quickly using the i,j tuple information
for index,v in enumerate(vertices_list):
i = (v[0]/self.delta)
j = (v[1]/self.eps)
vertices_dict['{:.1f},{:.1f}'.format(i,j)] = index
return vertices_dict
def get_nodes(self,n_dist):
"""
n_dist (list of np.array): height of wave surface at each vertex
get the nodes (x,y,z) from the vertices (x,y,0)
"""
nodes_dict = {k: None for k in self.vertices_dict.values()}
for index in self.vertices_dict.values():
z = n_dist[index]
nodes_dict[index] = np.array([self.x[index],self.y[index],z])
self.n_min = np.min(n_dist) #record the min and max of nodes to check if ray is within this vertical range
self.n_max = np.max(n_dist)
self.n_dist = n_dist
self.nodes_dict = nodes_dict
return nodes_dict
def get_corner_points(self):
"""
Get the 4 upper corner points of the HexagonalDomain (from left to right),
since it's symmetrical about the middle line, we can extrapolate to obtaining 8 corner points (with 2 points duplicated)
"""
x1 = (0-self.n)*self.delta
x2 = (x1 + self.n*self.delta/2)
x4 = (0+self.n)*self.delta
x3 = (x4 - self.n*self.delta/2)
y1 = y4 = 0
y2 = y3 = 0 + self.n*self.eps
x_list = [x1,x2,x3,x4]
y_list = [y1,y2,y3,y4]
corner_pts = []
for x,y in zip(x_list,y_list):
corner_pts.append(np.array([x,y,0]))
corner_pts.append(np.array([x,-y,0]))
return corner_pts
class RayTracing:
"""
computes
"""
def __init__(self,p_prime,xi_prime,HD,P_prime=1):
"""
p_h (np.array): point where projected light ray enters the hexagonal domain
p_prime (np.array): point where light ray enters the hexagonal domain
xi_h (np.array): a unit vector of projected ray path
xi_prime (np.array): a vector of ray path
t (np.array): target point where ray path is directed towards the hexagonal domain
HD (class HexagonalDomain): class that contains attributes of the surface wave facet
P_prime (int): unit radiant flux of 1
"""
self.i = rtc.i#np.array([1,0,0])
self.j = rtc.j#np.array([0,1,0])
self.k = rtc.k#np.array([0,0,1])
self.delta = rtc.delta
self.eps = rtc.eps
self.gamma = rtc.gamma
self.p_h = np.array([p_prime[0],p_prime[1],0])
self.p_prime = p_prime
self.xi_prime = xi_prime
self.xi_h = np.array([self.xi_prime[0],self.xi_prime[1],0])/np.linalg.norm(np.array([self.xi_prime[0],self.xi_prime[1],0]))
self.t = self.get_target()
self.HD = HD
self.P_prime = P_prime
self.r_11 = self.delta/(2*self.gamma)
self.r_21 = self.eps/self.gamma
self.r_12 = -1*self.r_11
self.r_22 = self.r_21*1
self.r_1 = np.array([self.r_11,self.r_21,0])
self.r_2 = np.array([self.r_12,self.r_22,0])
self.r_1_hat = np.array([-self.r_21,self.r_11,0])
self.r_2_hat = np.array([-self.r_22,self.r_12,0])
def get_target(self):
v = np.array([[rtc.r_1[0],rtc.r_2[0],-self.xi_prime[0]],
[rtc.r_1[1],rtc.r_2[1],-self.xi_prime[1]],
[rtc.r_1[2],rtc.r_2[2],-self.xi_prime[2]]])
solve_plane_vector_itxn = np.dot(np.linalg.inv(v),self.p_prime)
t = self.p_prime + solve_plane_vector_itxn[2]*self.xi_prime
return t
def get_TIPs(self):
s_k = lambda c,r_k_hat: (np.dot(2*c*self.eps*self.j, r_k_hat) - np.dot(self.p_h,r_k_hat))/np.dot(self.xi_h,r_k_hat)
s_0 = lambda c: (c*self.eps - np.dot(self.p_h,self.j))/np.dot(self.xi_h, self.j)
s_j_dict = {k: [] for k in range(0,3)} #where keys are the k family and values are the associated s_k
for c in range(-self.HD.n,self.HD.n +1):
for k in range(0,3):
if k == 1:
r_k_hat = self.r_1_hat
s_j_dict[k].append(s_k(c,r_k_hat))
elif k == 2:
r_k_hat = self.r_2_hat
s_j_dict[k].append(s_k(c,r_k_hat))
else:
s_j_dict[k].append(s_0(c))
#only values between 0 and s_min (minimum of the positive values) are kept as they are within the hexagon
# print(s_j_dict)
for k,v in s_j_dict.items():
s = [i for i in v if i>=0]
if len(s) > 0:
s = s[:np.argmin(s)+1]
else:
s = []
s_j_dict[k] = s
# print(s_j_dict)
# s_j_dict = {k:[i for i in s_j_dict[k] if i>=0] for k in s_j_dict.keys()} #filter s values >=0
# s_j_dict = {k:s_j_dict[k][:np.argmin(s_j_dict[k])+1] for k in s_j_dict.keys()} # values are sorted in descending manner, select values until the minimum positive value
ordered_TIPs = sorted([(k,i) for k,v in s_j_dict.items() for i in v],key=lambda x: x[1]) #list of tuples, where first element represents the k family, and 2nd element represents the associated s_j value
ordered_TIPs = [TIP(k,index,s,self.p_h,self.xi_h) for index,(k,s) in enumerate(ordered_TIPs)]
return ordered_TIPs
def TIP_vertices(self,TIP_0,TIP_1):
"""
TIP_0 (class TIP)
TIP_1 (class TIP)
returns the triad facet vertices where both TIPs intersect the wave facet
>>> (a,b,c) = TIP_vertices(TIP1,TIP2)
"""
if TIP_0.k > TIP_1.k:
TIP_0, TIP_1 = TIP_1, TIP_0
triad_case = int(TIP_0.k + TIP_1.k)
if triad_case == 3: #r1r2
d_2 = TIP_1.d_k
d_1 = TIP_0.d_k
h = (d_2 - d_1)*self.delta/(4*self.eps)
a_1 = h
a_2 = 0.5*(d_1 + d_2)
a = np.array([a_1,a_2,0])
lambda_k_a_list = []
lambda_k_list = []
for i in range(1,3): #k=1,2
if i == 1:
d_k = d_1
r_k = self.r_1
y_k = TIP_0.coord
elif i == 2:
d_k = d_2
r_k = self.r_2
y_k = TIP_1.coord
lambda_k_a = (a - np.dot(d_k,self.j))
lambda_k_a = np.dot(lambda_k_a,r_k)
lambda_k_a_list.append(lambda_k_a)
lambda_k = (y_k -np.dot(d_k,self.j))
lambda_k = np.dot(lambda_k,r_k)
lambda_k_list.append(lambda_k)
sign_list = [] #sign for (lambda_1 - lambda_1_a), or (lambda_2 - lambda_2_a)
for i in range(0,len(lambda_k_list)):
if lambda_k_list[i] - lambda_k_a_list[i] < 0:
sign = -1
else:
sign = 1
sign_list.append(sign)
b_i = (a_1 + sign_list[0]*self.delta/2)
b_j = (a_2 + sign_list[0]*self.eps)
b = np.array([b_i,b_j,0])
c_i = (a_1 - sign_list[1]*self.delta/2)
c_j = (a_2 + sign_list[1]*self.eps)
c = np.array([c_i,c_j,0])
return (a,b,c)
elif triad_case == 1:
d_0 = TIP_0.d_k
d_1 = TIP_1.d_k
h = (d_0 - d_1)*self.delta/(2*self.eps)
a_1 = h
a_2 = d_0
a = np.array([a_1,a_2,0])
y_1 = TIP_1.coord
lambda_0 = np.dot(TIP_0.coord,self.i)
lambda_0_a = np.dot(a,self.i)
lambda_1_a = (a - np.dot(d_1,self.j))
lambda_1_a = np.dot(lambda_1_a,self.r_1)
lambda_1 = (y_1 -np.dot(d_1,self.j))
lambda_1 = np.dot(lambda_1,self.r_1)
if lambda_1 - lambda_1_a < 0:
sign_1 = -1
else:
sign_1 = 1
if lambda_0 - lambda_0_a < 0:
sign_0 = -1
else:
sign_0 = 1
b_i = (a_1 + sign_1*self.delta/2)
b_j = (a_2 + sign_1*self.eps)
b = np.array([b_i,b_j,0])
c_i = (a_1 + sign_0*self.delta)
c_j = a_2
c = np.array([c_i,c_j,0])
return (a,b,c)
else: #if case = 2
d_2 = TIP_1.d_k
d_0 = TIP_0.d_k
h = (d_2 - d_0)*self.delta/(2*self.eps)
a_1 = h
a_2 = d_0
a = np.array([a_1,a_2,0])
y_2 = TIP_1.coord
lambda_0 = np.dot(TIP_0.coord,self.i)
lambda_0_a = np.dot(a,self.i)
lambda_2_a = (a - np.dot(d_2,self.j))
lambda_2_a = np.dot(lambda_2_a,self.r_2)
lambda_2 = (y_2 - np.dot(d_2,self.j))
lambda_2 = np.dot(lambda_2,self.r_2)
if lambda_2 - lambda_2_a < 0:
sign_2 = -1
else:
sign_2 = 1
if lambda_0 - lambda_0_a < 0:
sign_0 = -1
else:
sign_0 = 1
b_i = (a_1 - sign_2*self.delta/2)
b_j = (a_2 + sign_2*self.eps)
b = np.array([b_i,b_j,0])
c_i = (a_1 + sign_0*self.delta)
c_j = a_2
c = np.array([c_i,c_j,0])
return (a,b,c)
def determine_nodes(self,intersect_vertices_list):
"""
intersect_vertices_list (list of np.arrays): Triad Vertices that intersect with ray path
vertices_list (list of np.arrays): Triad vertices of the hexagonal domain
"""
nodes_list = []
for triplets in intersect_vertices_list:
nodes = []
for a in triplets:
i = (a[0]/self.delta)
j = (a[1]/self.eps)
k = '{:.1f},{:.1f}'.format(i,j)
if k in self.HD.vertices_dict.keys(): #to ensure that we only consider vertices within the hexagonal domain
index = self.HD.vertices_dict[k]
v = self.HD.nodes_dict[index]
# n = self.HD.n_dist[index]
# v = a + np.array([0,0,n])
nodes.append(v)
if len(nodes) == 3: #remove vertices tha are outside the hexagonal domain
nodes_list.append(nodes)
return nodes_list
def get_normal_facet(self,intersect_vertices_list):
"""
intersect_vertices_list (list of tuple of np.arrays): Triad Vertices that intersect with ray path
"""
# v_list (list): nodes of v_1,v_2,v_3 (in order)
nodes_list = self.determine_nodes(intersect_vertices_list)
facets = []
for v_list in nodes_list:
WF = WaveFacet(v_list)
facets.append(WF)
return facets
def get_intercepted_facets(self,WaveFacet_list,ordered_TIPs):
"""
given the list of projected facets where TIPs lie on, get the facet where xi_prime intercepts with the wave facet
WaveFacet_list (list of WaveFacet class): contains the attributes - nodes, norm (arranged in order of ordered_TIPs)
ordered_TIPs (list of TIP class): TIPs ordered in order of s(j) from p_h along direction xi_h
"""
s_q = lambda v_1,norm: np.dot((v_1 - self.p_prime),norm)/np.dot(self.xi_prime,norm)
s_q_list = []
for WF in WaveFacet_list:
s = s_q(WF.nodes[0], WF.norm) #where WF.nodes[0] == v_1
s_min = np.dot(self.xi_prime,self.xi_h)
s_q_list.append(s*s_min)
normal_facets_index = []
for i in range(len(s_q_list)):
if (s_q_list[i] > ordered_TIPs[i].s) and (s_q_list[i] < ordered_TIPs[i+1].s):
normal_facets_index.append(i)
intercepted_facets = [WaveFacet_list[i] for i in normal_facets_index]
for wf in intercepted_facets:
wf.target = self.get_intercepted_points(wf)
return intercepted_facets
def get_intercepted_points(self,WF):
"""
returns the point where xi_prime hits the wave facet surface
WF (a WaveFacet class) where WF belongs to the list of intercepted_facets
"""
v_1 = WF.nodes[2] - WF.nodes[0]
v_2 = WF.nodes[1] - WF.nodes[0]
v = np.array([[v_1[0],v_2[0],-self.xi_prime[0]],
[v_1[1],v_2[1],-self.xi_prime[1]],
[v_1[2],v_2[2],-self.xi_prime[2]]])
solve_plane_vector_itxn = np.dot(np.linalg.inv(v),(self.p_prime-WF.nodes[0]))
t = self.p_prime + solve_plane_vector_itxn[2]*self.xi_prime
return t
def get_daughter_ray(self, WF):
"""
WF (a WaveFacet class) where WF belongs to the list of intercepted_facets
if angle of incidence exceeds critical angle, Total Internal Reflection (TIR) will occur --> transmittance = 0
returns a DaughterRay class
"""
m = 4/3 #water index of refraction
critical_angle = np.arcsin(1/m) #critical angle for light leaving from denser medium to less dense medium
if np.dot(self.xi_prime, WF.norm) < 0:
# air-incident case
xi_r = self.xi_prime - 2*np.dot(self.xi_prime,WF.norm)*WF.norm
c = np.dot(WF.norm,self.xi_prime) - (np.dot(self.xi_prime,WF.norm)**2 + m**2 -1)**0.5
# xi_t = (self.xi_prime - c*WF.norm)/m
xi_t = (self.xi_prime + c*WF.norm)/m
theta_prime = np.arccos(abs(np.dot(self.xi_prime, WF.norm))) #equiv to theta_r
theta_t = np.arcsin(np.sin(theta_prime)/m)
return DaughterRay(self.p_prime,self.xi_prime,theta_prime,theta_t, xi_r,xi_t,WF)
else:
#water incident case
xi_r = self.xi_prime - 2*np.dot(self.xi_prime,WF.norm)*WF.norm
theta_prime = np.arccos(abs(np.dot(self.xi_prime,WF.norm))) #equiv to theta_r
if theta_prime > critical_angle: #if angle of incidence exceeds critical angle, Total Internal Reflection (TIR) will occur --> transmittance = 0
return DaughterRay(self.p_prime,self.xi_prime,theta_prime, None, xi_r,None,WF)
else:
theta_t = np.arcsin(m*np.sin(theta_prime))
c = np.dot(m*self.xi_prime,WF.norm) - (np.dot(m*self.xi_prime,WF.norm)**2 - m**2 + 1)**0.5
# xi_t = m*self.xi_prime - c*WF.norm
xi_t = m*self.xi_prime + c*WF.norm
return DaughterRay(self.p_prime,self.xi_prime,theta_prime,theta_t, xi_r,xi_t,WF)
def main(self):
"""
Computes the workflow:
1. get TIPs
2. check if ray intercepts with any wave facets
3. get a list of daughter rays
"""
DR_list = []
ordered_TIPs = self.get_TIPs()
if len(ordered_TIPs) > 0: #check if TIPs are within the HD
intersect_vertices_list = []
for i in range(1,len(ordered_TIPs)):
v = self.TIP_vertices(ordered_TIPs[i],ordered_TIPs[i-1])
intersect_vertices_list.append(v)
facets = self.get_normal_facet(intersect_vertices_list) #list of projected facets where TIPs lie on
intercepted_facets = self.get_intercepted_facets(facets,ordered_TIPs)
if len(intercepted_facets) > 0:
for v in intercepted_facets:
DR = self.get_daughter_ray(v)
DR_list.append(DR)
return DR_list
def recursive_RayTracing(stack,store_list,HD):
"""
returns a list of typle: (idx, DaughterRay class),
where the idx represents the series of path that a parent ray takes until the ray is traced up until that point.
e.g. 0_r_t means that the parent ray is 0, and its reflected (r) daughter ray and the subsequent transmitted (t) daughter ray gave rise to the ray up until that point
Note that only rays which hits a ray facet are considered, if they dont hit a ray facet, then they dont produce subsequent rays and will not have an entry
"""
if len(stack) == 0:
# print('store_list len'.format(len(store_list)))
# print("End recursion")
return store_list
else:
# print(len(stack))
# print("Enter recursion")
idx, s_pop = stack.pop() #DR
RT = RayTracing(s_pop.WF.target,s_pop.xi_r,HD)
dr_list = RT.main()
daughter_idx = idx + '_r' # reflected ray is postfixed with r
# print('dr_list reflected:{}'.format(len(dr_list)))
if len(dr_list) > 0: #push into s if dr_list is not empty
# print('push reflected rays')
for dr in dr_list:
store_list.append((daughter_idx,dr)) #store daughter indx
stack.append((daughter_idx,dr))
if s_pop.xi_t is not None:
RT = RayTracing(s_pop.WF.target,s_pop.xi_t,HD)
dr_list = RT.main()
daughter_idx = idx + '_t' # transmitted ray is postfixed with r
# print('dr_list refracted:{}'.format(len(dr_list)))
if len(dr_list) > 0: #push into s if dr_list is not empty
# print('push refracted rays')
for dr in dr_list:
store_list.append((daughter_idx,dr))
stack.append((daughter_idx,dr))
# print('Length of list: {}'.format(len(store_list)))
# print(store_list)
return recursive_RayTracing(stack,store_list,HD)
def RayTrace_timeseries(solar_altitude,solar_azimuth,wind_speed,save_fp,n=7,iter=5000):
xi_prime = get_xi_prime(solar_altitude,solar_azimuth)
np.random.seed(seed=4)
t = np.array([rtc.delta/2,rtc.eps/2,0]) # near the middle of the hexagonal domain, did not put it in the origin as it sits at the intersection of triads
p_prime = t-xi_prime
dr_over_HD = {i:None for i in range(iter)}
for i in tqdm(range(iter),desc="Rays to trace:"):
HD = HexagonalDomain(n)
x,y = HD.x, HD.y
sigma = rtc.delta*(rtc.a_u/2*wind_speed)**0.5
n_dist = np.random.normal(loc=0,scale = sigma,size = x.shape[0])
HD.get_nodes(n_dist)
# multiple_scattering = []
# initialise first incident ray
S = deque()
L = []
RT = RayTracing(p_prime,xi_prime,HD)
dr_list = RT.main()
if len(dr_list) > 0: #push into s if dr_list is not empty
for j,dr in enumerate(dr_list):
S.append((str(j),dr)) # seed parent rays and store their index
L.append((str(j),dr))
# recursive ray tracing
all_daughter_rays = recursive_RayTracing(S,L,HD) #list of DRs from multiple scattering
# print('{}. Number of daughter rays: {}'.format(index,len(all_daughter_rays)))
dr_over_HD[i] = all_daughter_rays
# Save results
prefix = "solaralt{}_solarazi{}_windspeed{}".format(str(solar_altitude).zfill(2),
str(solar_azimuth).zfill(3),
str(wind_speed).zfill(2))
if save_fp is not None:
save_daughter_rays(dr_over_HD,save_fp = save_fp,prefix=prefix)
return dr_over_HD#organise_daughter_rays(dr_over_HD)
else:
organise_daughter_rays(dr_over_HD)
def RayTrace(solar_altitude,solar_azimuth,wind_speed,save_fp,n=7,step=0.3):
"""
solar_altitude (float): in degrees, angle between horizontal surface to location of "sun"
solar_azimuth (float): in degrees, angle between location of sun and east (+ve i direction)
wind_speed (float): wind speed (in m/s) measured at an anemometer height of 12.5 m above mean sea level
save_fp (str): filepath to folder
prefix (str): prefix appended to file name
n (int): order of HexagonalDomain
step (float): step (float): subdivisions to divide the slanted_length/horizontal_length
"""
HD = HexagonalDomain(n)
x,y = HD.x, HD.y
np.random.seed(seed=4)
sigma = rtc.delta*(rtc.a_u/2*wind_speed)**0.5
n_dist = np.random.normal(loc=0,scale = sigma,size = x.shape[0])
HD.get_nodes(n_dist) # will add the attributes n_dist and nodes_dict to class
# triang = mpl.tri.Triangulation(x, y) ## Triangulate parameter space to determine the triangles using a Delaunay triangulation
# fig, axes = plt.subplots(subplot_kw={'projection': '3d'},figsize=(8,30))
# axes.view_init(elev=90, azim=270)
# axes.set_xlabel('x')
# axes.set_ylabel('y')
# axes.set_zlabel('z')
# axes.plot_trisurf(triang,n_dist, linewidth=0.2, antialiased=True,cmap=plt.cm.Spectral,alpha=0.5) #3d surface
# plt.show()
BP = BoundaryPoints(HD,solar_altitude,solar_azimuth, step)
xi_prime = BP.get_xi_prime()
points_within_HD = BP.get_points_within_HD()
dr_over_HD = {i:None for i in range(len(points_within_HD))}
# multiple_scattering = []
for index, p_prime in tqdm(enumerate(points_within_HD),desc="Rays to trace:"):
# initialise first incident ray
S = deque()
L = []
RT = RayTracing(p_prime,xi_prime,HD)
dr_list = RT.main()
if len(dr_list) > 0: #push into s if dr_list is not empty
for j,dr in enumerate(dr_list):
S.append((str(j),dr)) # seed parent rays and store their index
L.append((str(j),dr))
# recursive ray tracing
all_daughter_rays = recursive_RayTracing(S,L,HD) #list of DRs from multiple scattering
# print('{}. Number of daughter rays: {}'.format(index,len(all_daughter_rays)))
dr_over_HD[index] = all_daughter_rays
# Save results
prefix = "solaralt{}_solarazi{}_windspeed{}".format(str(solar_altitude).zfill(2),
str(solar_azimuth).zfill(3),
str(wind_speed).zfill(2))
if save_fp is not None:
save_daughter_rays(dr_over_HD,save_fp = save_fp,prefix=prefix)
return dr_over_HD
def organise_daughter_rays(daughter_rays):
for index,dr_list in daughter_rays.items(): #where keys are the index of xi_prime rays, values are list of tuple: (idx, DaughterRay class)
# DR_dict = {i: {'DR': dict(),'WF': dict()} for i,_ in enumerate(dr_list)}#{0:{'DR':None,'WF':None},1:{'DR':None,'WF':None}}
DR_dict = {i: {'DR': dict(),'WF': dict()} for i,_ in dr_list}
# for i,dr in enumerate(dr_list):
for i,dr in dr_list:
for k,v in vars(dr).items():
if isinstance(v,float) or isinstance(v,np.ndarray):
DR_dict[i]['DR'][k] = v
for k,v in vars(dr.WF).items():
DR_dict[i]['WF'][k] = v
daughter_rays[index] = DR_dict
return daughter_rays
def save_daughter_rays(daughter_rays,save_fp,prefix):
"""
save daughter rays into json file
daughter_rays (dict): where keys are the index of xi_prime rays, values are list of DaughterRay class
save_fp (str): filepath to folder
prefix (str): prefix appended to file name
"""
if exists(save_fp) is False:
mkdir(save_fp)
for index,dr_list in daughter_rays.items(): #where keys are the index of xi_prime rays, values are list of DaughterRay class
# DR_dict = {i: {'DR': dict(),'WF': dict()} for i,_ in enumerate(dr_list)}#{0:{'DR':None,'WF':None},1:{'DR':None,'WF':None}}
DR_dict = {i: {'DR': dict(),'WF': dict()} for i,_ in dr_list}
# for i,dr in enumerate(dr_list):
for i,dr in dr_list:
for k,v in vars(dr).items():
if type(v) == np.ndarray:
DR_dict[i]['DR'][k] = v.tolist()
elif isinstance(v,float) or isinstance(v,int):
DR_dict[i]['DR'][k] = v
for k,v in vars(dr.WF).items():
if type(v) == np.ndarray:
DR_dict[i]['WF'][k] = v.tolist()
elif isinstance(v,float) or isinstance(v,int):
DR_dict[i]['WF'][k] = v
else:
DR_dict[i]['WF'][k] = [i.tolist() for i in v]
daughter_rays[index] = DR_dict
with open(join(save_fp,"{}_DaughterRays.json".format(prefix)), 'w') as fp:
json.dump(daughter_rays, fp)
return
def load_daughter_rays(save_fp):
"""
load daughter rays into a list of dictionaries
returns a list of dictionaries
save_fp (str): filepath to folder which contains all DR
keys are:
number index (int): in ascending order (from a unique ray)
number index (int): in ascending order (indices from multiple scattering)
DR (str): contains attributes of daughter rays
theta_r (float): angle of reflectance
theta_t (float): angle of refraction
xi_prime (list): unit vector of incidence ray
xi_r (list): unit vector of reflectance ray
xi_t (list): unit vector of transmitted ray
fresnel_reflectance (float): reflectance ratio (0 to 1)
fresnel_transmittance (float): transmittance ratio (0 to 1)
WF (str): contains attributes of the wave facet the daughter ray intercepts with
nodes (list of list): nodes of a wave facet (3 vertices)
norm (list): unit normal vector of a wave facet's normal
target (list): point on the horizontal surface which the ray strikes
"""
data_list = dict()
save_fp_list = [i for i in sorted(listdir(save_fp)) if i.endswith(".json")]
print(['{}:{}'.format(i,f.replace('_DaughterRays.json','')) for i,f in enumerate(save_fp_list)])
for fp in save_fp_list:
key_name = fp.replace('_DaughterRays.json','')
with open(join(save_fp,fp), 'r') as fp:
data = json.load(fp)
for i,v in data.items(): #where i is the xi_prime index, v is a dict
for j in v.keys(): # where j is the daughter ray index from multiple ray scattering
for dr_keys,dr_values in data[i][j]['DR'].items():
if isinstance(dr_values,list):
data[i][j]['DR'][dr_keys] = np.array(data[i][j]['DR'][dr_keys])
# data[i][j]['DR']['xi_r'] = np.array(data[i][j]['DR']['xi_r'])
# data[i][j]['DR']['xi_t'] = np.array(data[i][j]['DR']['xi_t'])
# data[i][j]['DR']['xi_prime'] = np.array(data[i][j]['DR']['xi_prime'])
data[i][j]['WF']['nodes'] = [np.array(i) for i in data[i][j]['WF']['nodes']]
data[i][j]['WF']['norm'] = np.array(data[i][j]['WF']['norm'])
data[i][j]['WF']['target'] = np.array(data[i][j]['WF']['target'])
# data_copy = {int(i):{int(j):v_2 for j,v_2 in v_1.items()} for i,v_1 in data.items()}
data_copy = {int(i):{j:v_2 for j,v_2 in v_1.items()} for i,v_1 in data.items()}
data_list[key_name] = data_copy
return data_list
class IrradianceReflectance:
"""
daughter_rays (dict): keys are:
indices (str): if indices are digits, they are parent rays from light source, else, they are daughter rays/descendants
DR (str)
p_prime
xi_prime: parent ray
xi_r: daughter ray
xi_t: daughter ray
theta_r
theta_t
fresnel_reflectance
fresnel_transmittance
WF (str): wave facet
nodes
norm
tilt
target: location where xi_prime intersects with wave facet to produce xi_r and xi_t
P_prime (int): unit radiant flux of 1
alpha (float) (0-inf): volume attenuation coefficient for the water to account for flux lost from the ray during water transmission. Setting alpha=0 in effect makes the water transparent.
Setting alpha = inf eliminates any multiple scattering effects arising from subsurface travels of daughter rays
======================================
TEST CASES
d = {0:{
'0':{'DR':{'xi_r':np.array([0,0,-1]),'fresnel_reflectance':0.5},'radiance':1},
'0_r':{'DR':{'xi_r':np.array([0,0,1]),'fresnel_reflectance':0.5,'xi_t':np.array([0,0,1]),'fresnel_transmittance':0.5},'radiance':0.5},
'0_r_r':{'DR':{'xi_r':np.array([0,0,-1]),'fresnel_reflectance':0.5,'xi_t':np.array([0,0,1]),'fresnel_transmittance':0.5},'radiance':0.25},
'0_r_r_r':{'DR':{'xi_r':np.array([0,0,-1]),'xi_t':np.array([0,0,1]),'fresnel_reflectance':0.5},'radiance':0.125},
'0_r_r_r_t':{'DR':{'xi_r':np.array([0,0,1]),'fresnel_reflectance':0.5},'radiance':0.0625},
'1':{'DR':{'xi_r':np.array([0,0,-1]),'fresnel_reflectance':0.5},'radiance':1},
'1_r':{'DR':{'xi_t':np.array([0,0,1]),'fresnel_reflectance':0.5,'xi_r':np.array([0,0,1]),'fresnel_transmittance':0.5},'radiance':0.5}
},
}
d = {0:{
'0':{'DR':{'xi_r':np.array([0,0,1]),'fresnel_reflectance':1},'radiance':1},
'1':{'DR':{'xi_r':np.array([0,0,1]),'fresnel_reflectance':1},'radiance':1},
'2':{'DR':{'xi_r':np.array([0,0,1]),'fresnel_reflectance':1},'radiance':1}
},
}
=======================================
>>> IR = IrradianceReflectance(data_list)
>>> IR.albedo() -> returns a dict of the reflectance for each parent ray (random sea surface realisation)
"""
def __init__(self, data_list, P_prime=1, alpha=0):
self.data_list = data_list
self.P_prime = P_prime
self.alpha = alpha
def compute_radiance(self,daughter_rays):
daughter_rays_copy = daughter_rays.copy()
def recursive_radiance(idx):
"""
recursion with memoisation. Since memoisation overwrites the results, to run with new analysis, one will need to reload the original daughter_rays
"""
if 'radiance' in daughter_rays_copy[idx].keys():
# end recursion condition
return daughter_rays_copy[idx]['radiance'] # memoisation to avoid computing repeatedly for other rays
elif idx.isdigit():