@two-slit.html


001| ####################################################################################################
002| from sys import argv, exc_info
003| from traceback import extract_tb
004| from os import path
005| from math import sqrt, sin
006| from logger import logger,info,debug,trace, LogFilenameTimestamp
007| from webpage import KWARG
008| from goodies import intervals, divisions
009| from mlchart import mlchart
010| ####################################################################################################
011| #TODO: attenuate by k/h^2 (k unknown)
012| #TODO: attenuate by angle from slit
013| ####################################################################################################
014| BasePath = r'C:\CJS\prj\Python\charts'
015| ImgsPath = path.join(BasePath,'img')
016| Log = logger('TWO-SLIT')
017| 
018| CMND = '/2' ## test
019| ARGS = {
020|     #'fname': 'two-slit.png',
021|     'fpath': BasePath,
022| }
023| 
024| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
025| class two_slit_chart (mlchart):
026|     def __init__ (self, title):
027|         super().__init__()
028|         self.dims = (8.0, 4.0)
029|         self.margins = dict(left=0.100, right=0.970, bottom=0.12, top=0.93)
030|         self.title = title
031|         self.x_title = 'Location'
032|         self.y_title = 'Probability'
033|         self.x_limit = (-4.0, +4.0)
034|         self.y_limit = (-1.2, +1.2)
035|         self.x_grids = (1.0, 0.20)
036|         self.y_grids = (1.0, 0.10)
037|         self.x_tickf = '%+d'
038|         self.y_tickf = '%+.2f'
039|         self.fpath = ImgsPath
040|         self.fname = 'two-slit.png'
041| 
042|     def _make_x_axis_spcl (self):
043|         for tick in self.ax.xaxis.get_major_ticks():
044|             tick.label1.set_rotation('vertical')
045|             tick.label1.set_size(9)
046| 
047| 
048| ##================================================================================================##
049| def do_model_2 (**kwargs):
050|     """Generate a chart using a simple. Three emitters per point; no decay."""
051|     fpath = KWARG('fpath', ImgsPath, str, kwargs)
052|     fname = KWARG('fname', 'two-slit-2.png', str, kwargs)
053|     x1 = KWARG('x1', -1.00, float, kwargs)      # left slit position
054|     x2 = KWARG('x2', +1.00, float, kwargs)      # right slit position
055|     emit = KWARG('emit', 3, int, kwargs)        # number of emitters
056|     slit = KWARG('slit', 0.033, float, kwargs)  # slit width/2
057|     freq = KWARG('freq', 10.0, float, kwargs)   # frequency
058|     dist = KWARG('dist', 1.33, float, kwargs)   # length from slits to screen
059|     Log.info('model-2:: %s' % str(list(kwargs.keys())))
060|     Log.debug('fpath="%s"' % fpath)
061|     Log.debug('fname="%s"' % fname)
062|     Log.debug('slits=(%+.2f, %+.2f)' % (x1,x2))
063|     Log.debug('slit-width=%f' % slit)
064|     Log.debug('nbr-slits=%d' % emit)
065|     Log.debug('frequency=%f' % freq)
066|     Log.debug('distance=%f' % dist)
067|     Log.info()
068| 
069|     class model_2_chart (two_slit_chart):
070|         def __init__ (self, xs, ys1, ys2):
071|             super().__init__('Two-Slit - %d emitters/slit (%.3f width) f=%.3f, d=%.3f' % (emit,2*slit,freq,dist))
072|             self.xs = xs
073|             self.ys1 = ys1
074|             self.ys2 = ys2
075|             self.fpath = fpath
076|             self.fname = fname
077| 
078|         def plotter (self):
079|             self.ax.arrow(x1,+1, 0,-0.5, width=0.06, overhang=0.1, color='#009900', length_includes_head=True, zorder=300)
080|             self.ax.arrow(x2,+1, 0,-0.5, width=0.06, overhang=0.1, color='#009900', length_includes_head=True, zorder=300)
081|             self.ax.plot(self.xs,self.ys1, c='#0000ff', label=r'$\Psi$', lw=1.3, alpha=0.70, zorder=101)
082|             self.ax.plot(self.xs,self.ys2, c='#ff0000', label=r'$\Psi^2$', lw=2.0, alpha=0.80, zorder=102)
083|             self.ax.legend(loc='lower left', ncol=1, shadow=True)
084| 
085|     def calculate (x):
086|         f1,f2 = 0.0, 0.0
087|         for px in divisions(-slit, +slit, emit-1):
088|             dx1 = abs(x-(x1+px))                # delta x from slit 1
089|             dx2 = abs(x-(x2+px))                # delta x from slit 2
090|             h1 = sqrt(pow(dx1,2)+pow(dist,2))   # distance from slit 1 to x
091|             h2 = sqrt(pow(dx2,2)+pow(dist,2))   # distance from slit 2 to x
092|             f1 += sin(freq*h1)                  # frequency from slit 1
093|             f2 += sin(freq*h2)                  # frequency from slit 2
094|             Log.trace('%+.3f: %+9.6f' % (px, f1+f2))
095|         Log.debug('%+.3f: %+9.6f' % (x, f1+f2))
096|         return (x, f1+f2)
097| 
098|     # Generate data...
099|     data = [calculate(x) for x in intervals(-4.0, +4.0, 0.02)]
100|     xs = [datum[0] for datum in data]
101|     ys = [datum[1] for datum in data]
102|     # Normalize the data...
103|     m = max([abs(y) for y in ys])
104|     ys1 = [y/m for y in ys]
105|     # Square the (normalized) data...
106|     ys2 = [pow(y,2) for y in ys1]
107| 
108|     # Make a chart...
109|     cht = model_2_chart(xs, ys1, ys2)
110|     cht.make()
111| 
112|     Log.info()
113|     return 'Done'
114| 
115| ##================================================================================================##
116| def do_model_1 (**kwargs):
117|     """Generate a chart using the simplest model. Two points, no decay."""
118|     fpath = KWARG('fpath', ImgsPath, str, kwargs)
119|     fname = KWARG('fname', 'two-slit-1.png', str, kwargs)
120|     x1 = KWARG('x1', -1.00, float, kwargs)      # left slit position
121|     x2 = KWARG('x2', +1.00, float, kwargs)      # right slit position
122|     freq = KWARG('freq', 10.0, float, kwargs)   # frequency
123|     dist = KWARG('dist', 1.33, float, kwargs)   # length from slits to screen
124|     incr = KWARG('incr', 0.02, float, kwargs)   # increments from wall
125|     Log.info('model-1:: %s' % str(list(kwargs.keys())))
126|     Log.debug('fpath="%s"' % fpath)
127|     Log.debug('fname="%s"' % fname)
128|     Log.debug('slits=(%+.2f, %+.2f)' % (x1,x2))
129|     Log.debug('frequency=%f' % freq)
130|     Log.debug('distance=%f' % dist)
131|     Log.debug('wall-increment=%f' % incr)
132|     Log.info()
133|     o_dist = dist
134| 
135|     class model_1_chart (two_slit_chart):
136|         def __init__ (self, xs, ys1, ys2, yss3):
137|             super().__init__('Two-Slit - Single Emitter (f=%.3f, d=%.3f)' % (freq,o_dist))
138|             self.xs = xs
139|             self.ys1 = ys1
140|             self.ys2 = ys2
141|             self.yss3 = yss3
142|             self.fpath = fpath
143|             self.fname = fname
144| 
145|         def plotter (self):
146|             self.ax.arrow(x1,+1, 0,-0.5, width=0.06, overhang=0.1, color='#009900', length_includes_head=True, zorder=300)
147|             self.ax.arrow(x2,+1, 0,-0.5, width=0.06, overhang=0.1, color='#009900', length_includes_head=True, zorder=300)
148|             self.ax.plot(self.xs,self.ys1, c='#0000ff', label=r'$\Psi$', lw=1.3, alpha=0.70, zorder=101)
149|             self.ax.plot(self.xs,self.ys2, c='#ff0000', label=r'$\Psi^2$', lw=2.0, alpha=0.80, zorder=102)
150|             for ix,ys in enumerate(self.yss3):
151|                 self.ax.plot(self.xs,ys, c='#000000', label=('w-%d'%(1+ix)), lw=0.7, alpha=(0.60-(0.05*ix)), zorder=(11+ix))
152|             self.ax.legend(loc='lower left', ncol=5, shadow=True)
153| 
154|     def calculate (x):
155|         dx1 = abs(x-x1)                     # delta x from slit 1
156|         dx2 = abs(x-x2)                     # delta x from slit 2
157|         h1 = sqrt(pow(dx1,2)+pow(dist,2))   # distance from slit 1 to x
158|         h2 = sqrt(pow(dx2,2)+pow(dist,2))   # distance from slit 2 to x
159|         f1 = sin(freq*h1)                   # frequency from slit 1
160|         f2 = sin(freq*h2)                   # frequency from slit 2
161|         return (x, f1+f2)
162| 
163|     # Generate data...
164|     data = [calculate(x) for x in intervals(-4.0, +4.0, 0.02)]
165|     xs = [datum[0] for datum in data]
166|     ys = [datum[1] for datum in data]
167|     # Normalize the data...
168|     m = max([abs(y) for y in ys])
169|     ys1 = [y/m for y in ys]
170|     # Square the (normalized) data...
171|     ys2 = [pow(y,2) for y in ys1]
172|     # Closer traces...
173|     traces = []
174|     for wx in range(8):
175|         dist -= incr
176|         data = [calculate(x) for x in intervals(-4.0, +4.0, 0.02)]
177|         ys0 = [datum[1] for datum in data]
178|         m = max([abs(y) for y in ys0])
179|         traces.append([y/m for y in ys0])
180| 
181|     # Make a chart...
182|     cht = model_1_chart(xs, ys1, ys2, traces)
183|     cht.make()
184| 
185|     Log.info()
186|     return 'Done'
187| 
188| ##================================================================================================##
189| def do_test (**kwargs):
190|     """Do a test."""
191|     fpath = KWARG('fpath', BasePath, str, kwargs)
192|     fname = KWARG('fname', 'test.out', str, kwargs)
193|     Log.info('test:: %s' % str(list(kwargs.keys())))
194|     Log.debug('fpath="%s"' % fpath)
195|     Log.debug('fname="%s"' % fname)
196|     Log.info()
197|     Log.info()
198|     return 'Done'
199| ####################################################################################################
200| def dispatch (cmd, **kwargs):
201|     """Dispatch to a module function based on CMD."""
202|     Log.info('CMD: %s' % cmd)
203|     for kw in kwargs:
204|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
205|     Log.info()
206|     if cmd == '/1': return do_model_1(**kwargs)
207|     if cmd == '/2': return do_model_2(**kwargs)
208|     if cmd == 'test': return do_test(**kwargs)
209|     return 'Nothing to do!'
210| ####################################################################################################
211| if __name__ == '__main__':
212|     print('autorun: %s' % argv[0])
213|     #Log.start(path.join(BasePath,LogFilenameTimestamp('app_%s.log')))
214|     Log.start(path.join(BasePath,'two-slit.log'))
215|     Log.level(trace())
216|     Log.info(argv[0])
217|     Log.info()
218|     cmd = argv[1] if 1 < len(argv) else CMND
219|     kwargs = ARGS
220|     for a in argv[2:]:
221|         nv = a.split('=', 2)
222|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
223|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
224|     try:
225|         obj = dispatch(cmd, **kwargs)
226|         print()
227|         print(obj)
228|         Log.info()
229|         Log.info(obj)
230|     except:
231|         etype, evalue, tb = exc_info()
232|         ts = extract_tb(tb)
233|         Log.error()
234|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
235|         Log.error()
236|         for t in ts[-5:]:
237|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
238|             Log.error(' %s' % t[3])
239|             Log.error()
240|         raise
241|     finally:
242|         Log.end()
243| ####################################################################################################
244| """eof"""
245|