/
Trace2D.py
309 lines (271 loc) · 8.57 KB
/
Trace2D.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
import numpy as np
from scipy.optimize import fsolve
from scipy.misc import derivative
import pylab as pl
import matplotlib
numerror = 0.00001
maxsteps = 10
def distance(pos1,pos2):
if pos1 == None or pos2 == None:
return 999999999
return np.sqrt((pos1[0]-pos2[0])**2+(pos1[1]-pos2[1])**2)
class World:
def __init__(self, box, n):
self.size = box
self.refractiveindex = n
def inside(self, pos):
if pos[0] < 0 or pos[0] > self.size[0] or pos[1] < 0 or pos[1] > self.size[1]:
return False
else:
return True
class Visualizer:
def __init__(self, world, source, objList, detector):
self.world = world
self.source = source
self.detector = detector
self.objects = objList
self.drawstatics()
def drawstatics(self):
pl.ion()
self.fig = pl.figure()
self.ax = self.fig.add_subplot(111)
source = matplotlib.patches.Rectangle(self.source.position, self.source.width, self.source.width*0.01, color='orange')
self.ax.add_patch(source)
det = matplotlib.patches.Rectangle(self.detector.position, self.detector.size, self.detector.size*0.01, color='grey')
self.ax.add_patch(det)
for obj in self.objects:
obj.visualize(self.world.size[0])
pl.xlim(0,self.world.size[0])
pl.ylim(0,self.world.size[1])
pl.axes().set_aspect('equal')
pl.draw()
class Source:
def __init__(self, pos, width, angdist, intdist):
self.position = pos
self.width = width
self.angles = angdist
self.intensities = intdist
self.start = 0
self.count = 0
def emit(self):
#pos = self.position + np.array([self.width/1000*(1000-self.count),0])
#pos = np.array([np.random.normal(self.position[0], self.width), 0])
pos = self.position + np.array([np.random.uniform() * self.width, 0])
self.count += 1
self.start = pos
vec = np.array([0,1])
return (pos,vec)
class Detector:
def __init__(self, pos, width, qe=1):
self.position = pos
self.size = width
self.efficiency = qe
self.lostrays = 0
self.detectedrays = 0
self.detectedvec = []
self.detectedpos = []
self.startedpos = []
def intersect(self, pos, vec):
intersectionx = vec[0]/vec[1]*(self.position[1]-pos[1])+pos[0]
if self.position[0] <= intersectionx <= self.position[0]+self.size:
return intersectionx
else:
return False
def showlog(self):
print(self.lostrays)
print(self.detectedrays)
print(self.detectedvec)
print(self.detectedpos)
def statistics(self):
return [ self.detectedvec, self.detectedpos, self.startedpos, self.detectedrays, self.lostrays ]
class Object:
def __init__(self, fsurf, bsurf, dfsurf=None, dbsurf=None, n=1.5):
self.frontsurface = fsurf
self.dfrontsurface = dfsurf
self.backsurface = bsurf
self.dbacksurface = dbsurf
self.refractiveindex = n
def intersection(self,pos,vec):
if vec[0] == 0:
secpos0_front = pos[0]
secpos0_back = pos[0]
else:
try:
secpos0_front = fsolve(lambda x : self.frontsurface(x) - (vec[1]/vec[0]*(x-pos[0])+pos[1]),pos[0])[0]
secpos0_back = fsolve(lambda x : self.backsurface(x) - (vec[1]/vec[0]*(x-pos[0])+pos[1]),[pos[0],pos[0],pos[0]])[0]
except RuntimeWarning:
return None
if self.frontsurface(secpos0_front) - (vec[1]/vec[0]*(secpos0_front-pos[0])+pos[1]) > numerror:
return None
if self.backsurface(secpos0_back) - (vec[1]/vec[0]*(secpos0_back-pos[0])+pos[1]) > numerror:
return None
secpos_front = np.array([secpos0_front, self.frontsurface(secpos0_front)])
secpos_back = np.array([secpos0_back, self.backsurface(secpos0_back)])
# Check which section point lies "in front" of the ray
k_front = vec[1]/(secpos_front-pos)[1]
k_back = vec[1]/(secpos_back-pos)[1]
#print k_front
#print k_back
#pl.plot
if k_front > 0 and k_back < 0:
secpos = secpos_front
elif k_front < 0 and k_back > 0:
secpos = secpos_back
elif k_front < 0 and k_back < 0:
return None
else:
# If both are possible, take the nearest
if distance(secpos_front,pos) < distance(secpos_back,pos):
secpos = secpos_front
else:
secpos = secpos_back
return secpos
def inside(self, pos):
if self.frontsurface(pos[0]) < pos[1] and self.backsurface(pos[0]) > pos[1]:
return True
else:
return False
def normal(self, pos):
if np.abs(self.frontsurface(pos[0]) - pos[1]) < np.abs(self.backsurface(pos[0]) - pos[1]):
if self.dfrontsurface == None:
df = derivative(self.frontsurface, pos[0], dx=1e-10)
else:
df = self.dfrontsurface(pos[0])
if df == 0:
return np.array([0,1])
m = -1/df
else:
if self.dbacksurface == None:
df = derivative(self.backsurface, pos[0], dx=1e-10)
else:
df = self.dbacksurface(pos[0])
if df == 0:
return np.array([0,1])
m = -1/df
normalvec = np.array([1,m])
normalvec = normalvec / np.linalg.norm(normalvec)
#z = pos + normalvec*0.01
#x = [pos[0],z[0]]
#y = [pos[1],z[1]]
#pl.plot(x,y,"r-")
return normalvec
def visualize(self, width):
x = np.linspace(0,width,1000)
pl.plot(x,self.frontsurface(x),"b-")
pl.plot(x,self.backsurface(x),"b-")
pl.fill_between(x, self.frontsurface(x), self.backsurface(x), facecolor='blue', alpha=0.15)
class Ray:
def __init__(self, world, source, objectList, detector, visualize=False):
self.pos = None
self.vec = None
self.active = False
self.world = world
self.currentn = world.refractiveindex
self.source = source
self.detector = detector
self.objectList = objectList
self.visualize = visualize
if self.visualize:
self.pathx = []
self.pathy = []
self.line, = pl.plot(self.pathx,self.pathy,"k-", alpha=0.25)
#self.dots, = pl.plot(self.pathx,self.pathy,"ko", alpha=0.25)
pl.draw()
def generate(self):
self.active = True
self.pos, self.vec = self.source.emit()
if self.visualize:
self.pathx.append(self.pos[0])
self.pathy.append(self.pos[1])
self.line.set_xdata(self.pathx)
self.line.set_ydata(self.pathy)
#self.dots.set_xdata(self.pathx)
#self.dots.set_ydata(self.pathy)
pl.draw()
def nextobjectintersection(self):
intersectionpoint = None
intersectionobject = None
for i,obj in enumerate(self.objectList):
point = obj.intersection(self.pos,self.vec)
if point == None:
continue
else:
if distance(self.pos,point) < distance(self.pos,intersectionpoint):
intersectionpoint = point
intersectionobject = i
if intersectionpoint == None:
return [None, None]
else:
return [intersectionpoint, intersectionobject]
def refract(self,n1,n2,normalvec):
u = np.array([self.vec[0],self.vec[1]])
n = np.array([normalvec[0],normalvec[1]])
w = (np.dot(u,n))**2 + (n2/n1)**2 - 1
#total refelection
if w < 0:
#print 'tot ref.'
v = u - 2*np.dot(n,u)*n
self.currentn = n1
#refraction
else:
k = np.sign(np.dot(u,n)) * np.sqrt(w) - np.dot(u,n)
v = (u + k*n) / np.linalg.norm(u + k*n)
self.currentn = n2
if self.visualize:
self.pathx.append(self.pos[0])
self.pathy.append(self.pos[1])
self.line.set_xdata(self.pathx)
self.line.set_ydata(self.pathy)
#self.dots.set_xdata(self.pathx)
#self.dots.set_ydata(self.pathy)
pl.draw()
#z = self.pos + v*0.01
#x = [self.pos[0],z[0]]
#y = [self.pos[1],z[1]]
#pl.plot(x,y,"r-")
#set ray's new vec and move it a tiny bit into the new direction
self.vec = v
self.pos = self.pos + self.vec*1e-3
def checkdetector(self):
dectpos = self.detector.intersect(self.pos,self.vec)
if dectpos:
self.active = False
self.detector.detectedrays += 1
self.detector.detectedvec.append(self.vec)
self.detector.detectedpos.append(dectpos)
self.detector.startedpos.append(self.source.start)
if self.visualize:
self.pathx.append(dectpos)
self.pathy.append(self.detector.position[1])
self.line.set_xdata(self.pathx)
self.line.set_ydata(self.pathy)
#self.dots.set_xdata(self.pathx)
#self.dots.set_ydata(self.pathy)
pl.draw()
def checkoutbound(self):
#if not self.world.inside(self.pos,self.vec):
if self.active:
self.active = False
self.detector.lostrays += 1
def trace(self):
self.generate()
step = 0
while self.active and step < maxsteps:
step += 1
# Get next intersection
nextpos, nextobj = self.nextobjectintersection()
#print nextpos
# If there is no intersection, check for detection or leaving the world
if nextpos == None or self.world.inside(nextpos) == False:
self.checkdetector()
self.checkoutbound()
#Change pos and then vec according to snell's law
else:
obj = self.objectList[nextobj]
if self.currentn == self.world.refractiveindex:
newn = obj.refractiveindex
else:
newn = self.world.refractiveindex
self.pos = nextpos
normalvec = obj.normal(nextpos)
self.refract(self.currentn,newn,normalvec)