@gaussian.html
001| """Gaussian in Two Dimensions.
001|
001| Commands:
001| chart - Generate a selected view of a selected function.
001| views - Do all the views of a selected function.
001| all - Do all the views of all the functions.
001| test - Test
001|
001| Functions:
001| gauss2d [lambda] (x,y) - Two-dimensional Gaussian functions
001| gaussian2d (x,y)
001| gaussian2d_dx (x,y)
001| gaussian2d_dy (x,y)
001| gaussian2d_dx2 (x,y)
001| gaussian2d_dy2 (x,y)
001| gaussian2d_dxdy (x,y)
001|
001| make_chart (xs,ys,zs, view-index, fname, fpath)
001| generate_chart (f, **kwargs)
001|
001| generate_all_charts (f, fname, fpath)
001| generate_all_functions (first, fpath)
001|
001| Data:
001| amplitude - Gaussian amplitude parameter
001| width - Gaussian width parameter
001|
001| xmin,xmax - Chart X extent
001| ymin,ymax - Chart Y extent
001| zmin,zmax - Chart Z extent
001|
001| Views - List of views (azimuth, elevation)
001| Gaussians - List of functions
001|
001| ATTN: 1D stuff is in @exp.py! (move?)
001| """
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from math import exp, sqrt
007| import numpy as np
008| import matplotlib.pyplot as plt
009| from matplotlib.ticker import MultipleLocator, NullFormatter, FormatStrFormatter
010| from matplotlib.colors import LightSource
011| from logger import logger,info,debug,trace, LogFilenameTimestamp
012| from webpage import KWARG
013| from goodies import divisions
014|
015| BasePath = r'C:\CJS\prj\Python\blog\proj'
016| ImgsPath = path.join(BasePath,'img')
017| Filename = 'gassian-2d_%d.png'
018| Log = logger('GAUSS')
019|
020| CMND = ''
021| ARGS = {
022|
023|
024|
025|
026| 'fpath': BasePath,
027| }
028|
029|
030| amplitude = 4.0
031| width = sqrt(2)
032|
033| xmin,xmax = -5.0, +5.0
034| ymin,ymax = -5.0, +5.0
035| zmin,zmax = -5.0, +5.0
036|
037| Views = [
038| (-90.0, 0.0),
039| ( -0.0, 0.0),
040| (-90.0, +20.0),
041| (-60.0, +20.0),
042| (-45.0, +20.0),
043| (-30.0, +20.0),
044| ]
045|
046|
047| gauss2d = lambda x,y: exp(-(pow(x,2)+pow(y,2))/pow(width,2))
048|
049|
050| def gaussian2d (x, y):
051| """Gaussian base function G(x,y)."""
052| g = gauss2d(x,y)
053| h = amplitude
054| return (h * g)
055|
056|
057| def gaussian2d_dx (x, y):
058| """Gaussian first derivative over X. d/dx G(x,y)"""
059| g = gauss2d(x,y)
060| h = ((-2*amplitude*x)/pow(width,2))
061| return h*g
062|
063| def gaussian2d_dy (x, y):
064| """Gaussian first derivative over Y. d/dy G(x,y)"""
065| g = gauss2d(x,-y)
066| h = ((-2*amplitude*(-y))/pow(width,2))
067| return h*g
068|
069|
070| def gaussian2d_dx2 (x, y):
071| """Gaussian second derivative over X. d2/dx2 G(x,y)"""
072| g = gauss2d(x,y)
073| h = (((4*amplitude*pow(x,2))-(2*amplitude*pow(width,2)))/pow(width,4))
074| return h*g
075|
076| def gaussian2d_dy2 (x, y):
077| """Gaussian second derivative over Y. d2/dy2 G(x,y)"""
078| g = gauss2d(x,-y)
079| h = (((4*amplitude*pow(-y,2))-(2*amplitude*pow(width,2)))/pow(width,4))
080| return h*g
081|
082|
083| def gaussian2d_dxdy (x, y):
084| """Function + Function."""
085| dx = gaussian2d_dx2(x,y)
086| dy = gaussian2d_dy2(x,y)
087| return dx+dy
088|
089|
090| Gaussians = [gaussian2d, gaussian2d_dx, gaussian2d_dy, gaussian2d_dx2, gaussian2d_dy2, gaussian2d_dxdy]
091|
092| GaussianNames = [g.__name__ for g in Gaussians]
093|
094| def FindFunction (name):
095| fs = [g for g in Gaussians if g.__name__ == name]
096| return fs[0]
097|
098| def FindFunction2 (name):
099| ix = GassianNames.index(name)
100| return Gaussians[ix]
101|
102|
103| def make_chart (xs, ys, zs, view, fname='gaussian-2.png', fpath=ImgsPath):
104| fig = plt.figure()
105| fig.set_figwidth(12.0)
106| fig.set_figheight(8.0)
107| fig.subplots_adjust(left=0.00, bottom=0.00, right=1.00, top=1.00)
108|
109| ax = fig.add_subplot(projection='3d')
110|
111|
112|
113| ax.view_init(azim=view[0], elev=view[1])
114| ax.set_box_aspect(None, zoom=1.25)
115|
116| ax.set_xlim(xmin, xmax)
117| ax.set_ylim(ymin, ymax)
118| ax.set_zlim(zmin, zmax)
119|
120|
121|
122| ax.xaxis.set_major_locator(MultipleLocator(1.0))
123| ax.yaxis.set_major_locator(MultipleLocator(1.0))
124| ax.zaxis.set_major_locator(MultipleLocator(1.0))
125| ax.xaxis.set_major_formatter(NullFormatter())
126| ax.yaxis.set_major_formatter(NullFormatter())
127| ax.zaxis.set_major_formatter(NullFormatter())
128|
129| ax.tick_params(direction='out')
130| ax.grid(color='#7f7fbf')
131|
132| ls = LightSource(-120, 30)
133| ax.plot_wireframe(xs, ys, zs, color='#000000', lw=0.5, rcount=30,ccount=30)
134| ax.plot_surface(xs, ys, zs, color='#c0b0a0', rcount=100,ccount=100, shade=True, lightsource=ls, alpha=0.80)
135| ax.plot([xmin,xmax],[0.0,0.0], c='#ff0000', lw=2.0, alpha=1.0)
136| ax.plot([0.0,0.0],[ymin,ymax], c='#0000ff', lw=2.0, alpha=1.0)
137|
138| fn = path.join(fpath, fname)
139| fig.savefig(fn)
140| Log.info('wrote: %s' % fn)
141| Log.info()
142| plt.close(fig)
143|
144|
145| def generate_chart (f=gaussian2d, **kwargs):
146| """Generate a Gaussian chart."""
147| fpath = KWARG('fpath', ImgsPath, str, kwargs)
148| fname = KWARG('fname', Filename, str, kwargs)
149| vx = KWARG('vx', 1, int, kwargs)
150| steps = KWARG('steps', 500, int, kwargs)
151| Log.info('generate-chart:: %s' % str(list(kwargs.keys())))
152| Log.debug('fpath="%s"' % fpath)
153| Log.debug('fname="%s"' % fname)
154| Log.debug('view-index=%d' % vx)
155|
156| xs = np.ndarray((steps+1,steps+1), float)
157| ys = np.ndarray((steps+1,steps+1), float)
158| zs = np.ndarray((steps+1,steps+1), float)
159| ix = 0
160| for x in divisions(xmin, xmax, steps):
161| iy = 0
162| for y in divisions(ymin, ymax, steps):
163| xs[ix,iy]= x
164| ys[ix,iy]= y
165| zs[ix,iy]= f(x,y)
166| iy += 1
167| ix += 1
168|
169| make_chart(xs,ys,zs, Views[vx-1], fname=(fname % vx), fpath=fpath)
170|
171|
172| def generate_all_charts (f=gaussian2d, fname=Filename, fpath=ImgsPath):
173| for vx in range(len(Views)):
174| generate_chart(f, vx=1+vx, fname=fname, fpath=fpath)
175|
176|
177| def generate_all_functions (first=0, fpath=ImgsPath):
178| for gx in range(first, len(Gaussians)):
179| f = Gaussians[gx]
180| n = '%s_%%d.png' % f.__name__
181| generate_all_charts(f, fname=n, fpath=fpath)
182|
183|
184|
185| def do_generate_chart (**kwargs):
186| """CMND. Generate a selected view of a selected function."""
187| fpath = KWARG('fpath', ImgsPath, str, kwargs)
188| ftn = KWARG('ftn', '', str, kwargs)
189| gx = KWARG('gx', 0, int, kwargs)
190| ix = KWARG('ix', 0, int, kwargs)
191| Log.info('do-generate-chart:: %s' % str(list(kwargs.keys())))
192| Log.debug('fpath="%s"' % fpath)
193| Log.debug('selectors=function#%d, view#%d' % (gx,ix))
194| Log.debug('function-name="%s" (overrides selector)' % ftn)
195| Log.info()
196| if len(ftn):
197| f = FindFunction(ftn)
198| n = '%s_%%d.png' % ftn
199| else:
200| f = Gaussians[gx]
201| n = '%s_%%d.png' % f.__name__
202| generate_chart(f, vx=ix, fname=n, fpath=fpath)
203| Log.info()
204| return 'Done'
205|
206| def do_all_views (**kwargs):
207| """CMND: Do all the views of a selected function."""
208| fpath = KWARG('fpath', ImgsPath, str, kwargs)
209| ftn = KWARG('ftn', '', str, kwargs)
210| gx = KWARG('gx', 0, int, kwargs)
211| Log.info('do-all-views:: %s' % str(list(kwargs.keys())))
212| Log.debug('fpath="%s"' % fpath)
213| Log.debug('selector=function#%d' % gx)
214| Log.debug('function-name="%s" (overrides selector)' % ftn)
215| Log.info()
216| if len(ftn):
217| f = FindFunction(ftn)
218| n = '%s_%%d.png' % ftn
219| else:
220| f = Gaussians[gx]
221| n = '%s_%%d.png' % f.__name__
222| generate_all_charts(f=f, fname=n, fpath=fpath)
223| Log.info()
224| return 'Done'
225|
226| def do_all_functions (**kwargs):
227| """CMND: Do all the views of all the functions."""
228| fpath = KWARG('fpath', ImgsPath, str, kwargs)
229| first = KWARG('first', 0, int, kwargs)
230| Log.info('do-all-functions:: %s' % str(list(kwargs.keys())))
231| Log.debug('fpath="%s"' % fpath)
232| Log.debug('first=%d' % first)
233| Log.info()
234| generate_all_functions(first=first, fpath=fpath)
235| Log.info()
236| return 'Done'
237|
238| def do_test (**kwargs):
239| """CMND: Do a test."""
240| fpath = KWARG('fpath', BasePath, str, kwargs)
241| fname = KWARG('fname', 'test.out', str, kwargs)
242| Log.info('do-test:: %s' % str(list(kwargs.keys())))
243| Log.debug('fpath="%s"' % fpath)
244| Log.debug('fname="%s"' % fname)
245| Log.info()
246| Log.info()
247| return 'Done'
248|
249| def dispatch (cmd, **kwargs):
250| """Dispatch to a module function based on CMD."""
251| Log.info('CMD: %s' % cmd)
252| for kw in kwargs:
253| Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
254| Log.info()
255| if cmd == 'chart': return do_generate_chart(**kwargs)
256| if cmd == 'views': return do_all_views(**kwargs)
257| if cmd == 'all': return do_all_functions(**kwargs)
258| if cmd == 'test': return do_test(**kwargs)
259| return 'Nothing to do!'
260|
261| if __name__ == '__main__':
262| print('autorun: %s' % argv[0])
263| Log.start(path.join(BasePath,'gaussian.log'))
264| Log.level(debug())
265| Log.info(argv[0])
266| Log.info()
267| cmd = argv[1] if 1 < len(argv) else CMND
268| kwargs = ARGS
269| for a in argv[2:]:
270| nv = a.split('=', 2)
271| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
272| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
273| try:
274| obj = dispatch(cmd, **kwargs)
275| print()
276| print(obj)
277| Log.info()
278| Log.info(obj)
279| except:
280| etype, evalue, tb = exc_info()
281| ts = extract_tb(tb)
282| Log.error()
283| Log.error('%s: %s' % (etype.__name__,str(evalue)))
284| Log.error()
285| for t in ts[-5:]:
286| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
287| Log.error(' %s' % t[3])
288| Log.error()
289| raise
290| finally:
291| Log.end()
292|
293| """eof"""
294|