fourier.html
001| '''Fourier Waves, Curves, and Wheels.
001|
001| Classes:
001| Wheel -Wheel parameters object (single wheel).
001| ParamSet -Wheel Parameter Set object.
001|
001| Functions:
001| create_image (pts:list, params) -> Image
001| fourier_curve_image (**kwargs) -> Image
001| fourier_sines_image (**kwargs) -> Image
001| fourier_visualization (**kwargs) -> Image
001| dispatch (cmd:str, **kwargs) -> str
001|
001| Command:
001| /c do_fourier_curve
001| /w do_sine_wave
001| /f do_fourier_visual
001| /t do_test
001|
001| TODO: resolution of curve (tough! determined now by freq)
001| TODO: disable phase
001| TODO: field functions (e.g. phase:+20)
001| TODO: random (really?)
001| TODO: <<what was I just thinking?>>
001| '''
002|
003| from sys import argv, stdout, exc_info
004| from traceback import extract_tb
005| from os import path
006| from time import time
007| from math import sin, cos, radians, pi
008| from cmath import exp
009| from PIL import Image, ImageDraw, ImageFont
010| from logger import logger, info, debug, trace
011| from files import linefile, jsonfile
012| from canvas import Canvas
013| from goodies import KWARG
014|
015| Log = logger('Fourier')
016| BasePath = r'C:\CJS\prj\Python\app\fourier'
017| DataPath = path.join(BasePath, 'dat')
018| ImgsPath = path.join(BasePath, 'img')
019|
020| CMND = ''
021| ARGS = {
022|
023|
024|
025|
026|
027|
028|
029|
030|
031|
032|
033|
034| 'fpath': BasePath,
035|
036| }
037|
038|
039| class Wheel:
040| '''Wheel parameters object (single wheel).'''
041| def __init__ (self, freq, ampl, phase):
042| self.freq = freq
043| self.ampl = ampl
044| self.phase = phase
045|
046| def __call__ (self):
047| return (self.freq, self.ampl, self.phase)
048|
049| def __str__ (self):
050| return f'{self.freq}, {self.ampl}, {self.phase}'
051|
052| def __repr__ (self):
053| return '{Wheel:{freq:%f, ampl:%f, phase:%f}}' % self()
054|
055|
056| class ParamSet:
057| '''Wheel Parameters object.
057|
057| Commandline Parameters:
057| tpath/tname - text file with wheel configuration
057| dpath/dname - JSON file with multiple wheel configs
057| pname - name of config in JSON file (default: "main")
057|
057| '''
058| PMax = 25
059| DfltDim = 800
060| DfltWin = 4.0
061| DfltPts = 2000
062| DfltLnW = 1
063|
064| def __init__ (self, **kwargs):
065| '''New Input Parameters Set instance.'''
066| self.kwargs = kwargs
067| self.wheels = []
068| self.xs = []
069| self.xdim = KWARG('xdim', self.DfltDim, int, self.kwargs)
070| self.ydim = KWARG('ydim', self.DfltDim, int, self.kwargs)
071| self.xwin = KWARG('xwin', self.DfltWin, float, self.kwargs)
072| self.ywin = KWARG('ywin', self.DfltWin, float, self.kwargs)
073| self.npts = KWARG('npts', self.DfltPts, int, self.kwargs)
074| self.lw = KWARG('lw' , self.DfltLnW, int, self.kwargs)
075| self.tname = KWARG('tname', '', str, self.kwargs)
076| self.fpath = KWARG('tpath', '', str, self.kwargs)
077| self.dname = KWARG('dname', '', str, self.kwargs)
078| self.dpath = KWARG('dpath', '', str, self.kwargs)
079| self.pname = KWARG('pname', 'main', str, self.kwargs)
080| self._dispatch()
081|
082|
083| for wheel in self.params:
084|
085| args = wheel.replace(' ','').split(',')
086| freq = float(args[0])
087| ampl = float(args[1]) if 1 < len(args) else 1.0
088| faze = float(args[2]) if 2 < len(args) else 0.0
089|
090| self.wheels.append(Wheel(freq, ampl, faze))
091|
092| if self.PMax <= len(self.wheels):
093| break
094|
095| def _dispatch (self):
096| '''Parse wheels configuration based on provided inputs.'''
097|
098| if self._load_text_file():
099| return
100|
101| if self._load_json_file():
102| return
103|
104| ws = KWARG('ws', '', str, self.kwargs)
105| self.params = [w.strip() for w in ws.split(';')]
106|
107| def _load_text_file (self):
108| '''Load a text file with wheel configuration.'''
109| if len(self.tname) == 0:
110| return False
111|
112| fn = path.join(self.fpath, self.tname) if 0<len(self.fpath) else self.tname
113| Log.info('text-filename: "%s"' % fn)
114| fo = linefile(fn)
115| fo.load()
116| self.params = [line for line in fo if 0<len(line)]
117| return True
118|
119| def _load_json_file (self):
120| '''Load a JSON file with multiple wheel configurations.'''
121| if len(self.dname) == 0:
122| return False
123|
124| fn = path.join(self.dpath, self.dname) if 0<len(self.dpath) else self.dname
125| Log.info('json-filename: "%s"' % fn)
126| fo = jsonfile(fn)
127| fo.load()
128| cfg = fo.data['wheelsets'][self.pname]
129| self.params = cfg['wheels']
130| self.xdim = KWARG('xdim', self.DfltDim, int, cfg)
131| self.ydim = KWARG('ydim', self.DfltDim, int, cfg)
132| self.xwin = KWARG('xwin', self.DfltWin, float, cfg)
133| self.ywin = KWARG('ywin', self.DfltWin, float, cfg)
134| self.npts = KWARG('npts', self.DfltPts, int, cfg)
135| self.lw = KWARG('lw' , self.DfltLnW, int, cfg)
136| return True
137|
138| def __bool__ (self) -> bool:
139| '''We are TRUE if we have wheels.'''
140| return (0 < len(self.wheels))
141|
142| def __len__ (self) -> int:
143| '''Return number of configured wheels.'''
144| return len(self.wheels)
145|
146| def __getitem__ (self, which:int) -> tuple[float,float,float]:
147| '''Return a specific wheel (by index).'''
148| assert isinstance(which, int), TypeError(f'Wheel index ({which}) must be an integer.')
149| return self.wheels[which]
150|
151| def __iter__ (self):
152| '''Return an iterator.'''
153| return iter(self.wheels)
154|
155| def __str__ (self) -> str:
156| '''Return a nice string version.'''
157| return f'PSet: wheels={len(self)}'
158|
159| def __repr__ (self) -> str:
160| '''Return a JSON-like string.'''
161| t = (len(self), self.pname, self.dname, id(self.kwargs), id(self.params))
162| return '{PSet:{count:%d, pname:"%s", dname:"%s", kwargs:"%08x", params:"%08x"}}' % t
163|
164|
165|
166| def create_image (pts:list, params) -> Image:
167| '''Create, draw, and return PIL Image.'''
168| Log.info(f'dims=[{params.xdim} by {params.ydim}]')
169| Log.info(f'wndw=[{params.xwin:+.2f} by {params.ywin:+.2f}]')
170| Log.info(f'lw = {params.lw}')
171| Log.info(f'npts = {params.npts}')
172|
173| img = Image.new('RGB', (params.xdim, params.ydim), (0,0,0))
174| draw = ImageDraw.Draw(img)
175|
176| center = (params.xdim//2, params.ydim//2)
177| xscale, yscale = ((params.xdim/2.0)/params.xwin, (params.ydim/2.0)/params.ywin)
178| Fx = lambda x: center[0]+(float(x)*xscale)
179| Fy = lambda y: center[1]+(float(y)*yscale)
180|
181|
182| xi = params.xdim//20
183| yi = params.ydim//(10 if params.ydim < params.xdim else 20)
184|
185| cg = (0,0x5f,0)
186| for ix in range(10):
187| x = xi * ix
188| y = yi * ix
189| draw.line(((center[0]+x, 0),(center[0]+x, params.ydim)), fill=cg, width=1)
190| draw.line(((center[0]-x, 0),(center[0]-x, params.ydim)), fill=cg, width=1)
191| draw.line(((0, center[1]+y),(params.xdim, center[1]+y)), fill=cg, width=1)
192| draw.line(((0, center[1]-y),(params.xdim, center[1]-y)), fill=cg, width=1)
193|
194|
195| ca = (0,0x9f,0)
196| draw.line(((center[0], 0),(center[0], params.ydim)), fill=ca, width=2)
197| draw.line(((0, center[1]),(params.xdim, center[1])), fill=ca, width=2)
198|
199|
200| if isinstance(pts[0], complex):
201|
202| pt0 = pts[0]
203| for pt in pts[1:]:
204| pt0 = (Fx(pt0.real), Fy(pt0.imag))
205| pt1 = (Fx(pt.real) , Fy(pt.imag) )
206| draw.line((pt0,pt1), fill=(255,0,0), width=params.lw)
207| pt0 = pt
208| if isinstance(pts[0], float):
209|
210| pt0 = (params.xs[0], pts[0])
211| for pt in zip(params.xs[1:],pts[1:]):
212| pt0 = (Fx(pt0[0]), Fy(pt0[1]))
213| pt1 = (Fx(pt[0]) , Fy(pt[1]) )
214| draw.line((pt0, pt1), fill=(255,0,0), width=params.lw)
215| pt0 = pt
216|
217|
218| ulc = (0,0)
219| urc = (params.xdim-1, 0)
220| llc = (0, params.ydim-1)
221| lrc = (params.xdim-1, params.ydim-1)
222| for ix in range(5):
223| c0 = (0x99,0x99,0x99) if ix < 3 else (0x66, 0x66, 0x66)
224| c1 = (0x99,0x99,0x99) if ix < 3 else (0xcc, 0xcc, 0xcc)
225| draw.line(((ulc[0]+ix,ulc[1]+ix),(urc[0]-ix,urc[1]+ix)), fill=c0, width=1)
226| draw.line(((urc[0]-ix,urc[1]+ix),(lrc[0]-ix,lrc[1]-ix)), fill=c1, width=1)
227| draw.line(((llc[0]+ix,llc[1]-ix),(lrc[0]-ix,lrc[1]-ix)), fill=c1, width=1)
228| draw.line(((ulc[0]+ix,ulc[1]+ix),(llc[0]+ix,llc[1]-ix)), fill=c0, width=1)
229|
230|
231| return img
232|
233|
234| def fourier_curve_image (**kwargs) -> Image:
235| '''Generate Fourier Curves Image.'''
236| rotator = lambda a: complex(cos(radians(a)), sin(radians(a)))
237| spinner = lambda f: lambda c: c*rotator(f)
238| params = ParamSet(**kwargs)
239| ticks = time()
240|
241| Log.info('fourier-sines-image:: %s' % str(list(kwargs.keys())))
242| Log.debug(f'number-of-wheels: {len(params)}')
243| Log.debug(f'number-of-points: {params.npts}')
244| Log.info()
245|
246|
247| wheels = []
248| points = []
249| for pset in params:
250| wheels.append(spinner(pset.freq))
251| points.append(complex(pset.ampl,0) * rotator(pset.phase))
252|
253|
254| plot = [sum(points)]
255| for _ in range(0, params.npts):
256| for ix,wheel in enumerate(wheels):
257| points[ix] = wheel(points[ix])
258| plot.append(sum(points))
259|
260|
261| for px,pt in enumerate(plot):
262| Log.trace(f'{px:03d}: {pt}')
263| Log.trace()
264|
265|
266| img = create_image(plot, params)
267|
268| Log.info()
269| Log.info('Ticks: %f' % (time()-ticks))
270| return img
271|
272|
273| def fourier_sines_image (**kwargs) -> Image:
274| '''Generate Fourier Sine Wave Image.'''
275| oscillator = lambda freq,amp,faz: lambda ang:(sin(radians((freq*ang)+faz))*amp)
276| params = ParamSet(**kwargs)
277| ticks = time()
278|
279| k = KWARG('k', 4, int, kwargs)
280| dx = KWARG('dx', 0.01, float, kwargs)
281| npts = 2 + int((2 * k) / dx)
282|
283| Log.info('fourier-sines-image:: %s' % str(list(kwargs.keys())))
284| Log.debug(f'number-of-wheels: {len(params)}')
285| Log.debug(f'number-of-points: {npts}')
286| Log.debug(f'cycles-multiple: {k}')
287| Log.debug(f'x-axis-dx: {dx}')
288| Log.debug(f'x-axis: {-k} to {+k}')
289| Log.info()
290|
291|
292| params.xdim = 800
293| params.ydim = 240
294| params.xwin = k*1.02
295| params.ywin = 1.2
296| params.lw = 2
297|
298|
299| wheels = [oscillator(*pset()) for pset in params]
300|
301|
302| params.xs = [-k+(n*dx) for n in range(npts)]
303| rads = [180.0 * x for x in params.xs]
304| points = [[w(a) for a in rads] for w in wheels]
305|
306|
307| plot = [sum(ps) for ps in zip(*points)]
308| pmax = max(plot)
309| pmin = min(plot)
310| yscale = 1.0/(max(abs(pmax), abs(pmin)))
311| plot = [pt*yscale for pt in plot]
312|
313|
314| for ix,t in enumerate(zip(params.xs,plot)):
315| px,py = t
316| Log.trace(f'{ix:03d}: ({px}, {py})')
317| Log.trace()
318|
319|
320| img = create_image(plot, params)
321|
322| Log.info()
323| Log.info('Ticks: %f' % (time()-ticks))
324| return img
325|
326|
327| def fourier_visualization (**kwargs) -> Image:
328| '''Generate Fourier Visualization Image.'''
329| xdim = KWARG('xdim', 800, int, kwargs)
330| ydim = KWARG('ydim', 800, int, kwargs)
331| xwin = KWARG('xwin', 1.1, float, kwargs)
332| ywin = KWARG('ywin', 1.1, float, kwargs)
333| freq1 = KWARG('f1', 2.0, float, kwargs)
334| freq2 = KWARG('f2', 3.0, float, kwargs)
335| freq3 = KWARG('f3', 5.0, float, kwargs)
336| windf = KWARG('wf', 1.0, float, kwargs)
337| fx2 = KWARG('f2x', 0, int, kwargs)
338| fx3 = KWARG('f3x', 0, int, kwargs)
339| steps = KWARG('steps', 500, int, kwargs)
340| cycles = KWARG('cycles', 12, int, kwargs)
341| lw = KWARG('lw', 1, int, kwargs)
342| ticks = time()
343|
344| Log.info('fourier-visualization:: %s' % str(list(kwargs.keys())))
345| Log.info('dims=(%d, %d)' % (xdim,ydim))
346| Log.info('xwin=(%+.2f, %+.2f)' % (-xwin,+xwin))
347| Log.info('ywin=(%+.2f, %+.2f)' % (-ywin,+ywin))
348| Log.info('freq1=%.6f' % freq1)
349| Log.info('freq2=%.6f (use:%d)' % (freq2,fx2))
350| Log.info('freq3=%.6f (use:%d)' % (freq3,fx3))
351| Log.info('windf=%.6f' % windf)
352| Log.info('steps=%d' % steps)
353| Log.info('cycls=%d' % cycles)
354|
355| dims = (xdim, ydim)
356| view = ((-xwin,+xwin), (-ywin,+ywin))
357| fnt = ImageFont.truetype('arial.ttf', size=25)
358| i2pi = complex(0,1)*complex(2,0)*complex(pi,0)
359| cf1 = complex(freq1)
360| cf2 = complex(freq2)
361| cf3 = complex(freq3)
362| wf = complex(windf)
363| angles = [float(s)/float(steps) for s in range(int(steps*cycles))]
364| T = lambda c:(c.real, c.imag)
365|
366| im = Canvas(dims=dims, view=view)
367| im.grid(0.1,0.1, lw=1, c=(221,221,255))
368| im.grid(1.0,1.0, lw=2, c=(191,191,221))
369| im.axis(lw=2, c=(95,95,95))
370| im.text((-xwin+0.03, +ywin-0.03), 'f1=%.4f'%freq1, fnt, c=(0,0,255))
371| im.text((-xwin+0.03, +ywin-0.15), 'f2=%.4f'%freq2, fnt, c=(0,0,255))
372| im.text((-xwin+0.03, +ywin-0.27), 'f3=%.4f'%freq3, fnt, c=(0,0,255))
373| im.text((-xwin+0.03, -ywin+0.15), 'fw=%.4f'%windf, fnt, c=(191,0,0))
374|
375| p0 = None
376| for a in angles:
377| ang = complex(a,0)
378| v1 = exp(i2pi*ang*cf1)
379| v2 = exp(i2pi*ang*cf2)
380| v3 = exp(i2pi*ang*cf3)
381| c = exp(i2pi*ang*wf) * ((3.0+v1.real+v2.real+v3.real)/6.0)
382| p1 = T(c)
383| if p0:
384| im.line(p0,p1, c=(255,0,0), lw=lw)
385| p0 = p1
386|
387| im.border([(0,0,0)], lw=2)
388| Log.info()
389| Log.info('Ticks: %f' % (time()-ticks))
390| return im.im
391|
392|
393|
394| def do_fourier_curve (**kwargs) -> str:
395| """CMND: Create a Fourier curves image."""
396| fpath = KWARG('fpath', ImgsPath, str, kwargs)
397| fname = KWARG('fname', 'curve.png', str, kwargs)
398| tpath = KWARG('tpath', DataPath, str, kwargs)
399| tname = KWARG('tname', 'fourier.text', str, kwargs)
400| dpath = KWARG('dpath', DataPath, str, kwargs)
401| dname = KWARG('dname', 'fourier.json', str, kwargs)
402| pname = KWARG('pname', '', str, kwargs)
403| Log.info('fourier-curve:: %s' % str(list(kwargs.keys())))
404| Log.debug('fpath="%s"' % fpath)
405| Log.debug('fname="%s"' % fname)
406| Log.debug('tpath="%s"' % tpath)
407| Log.debug('tname="%s"' % tname)
408| Log.debug('dpath="%s"' % dpath)
409| Log.debug('dname="%s"' % dname)
410| Log.debug('pname="%s"' % pname)
411| Log.info()
412|
413|
414| img = fourier_curve_image(**kwargs)
415|
416|
417| fn = path.join(fpath, f'curve-{pname}.png' if 0<len(pname) else fname)
418| img.save(fn, 'PNG')
419| Log.info('wrote: %s' % fn)
420|
421| Log.info()
422| return 'Done'
423|
424|
425| def do_sine_wave (**kwargs) -> str:
426| """CMND: Create a sinewave image."""
427| fpath = KWARG('fpath', ImgsPath, str, kwargs)
428| fname = KWARG('fname', 'wave.png', str, kwargs)
429| tpath = KWARG('tpath', DataPath, str, kwargs)
430| tname = KWARG('tname', 'fourier.text', str, kwargs)
431| dpath = KWARG('dpath', DataPath, str, kwargs)
432| dname = KWARG('dname', 'fourier.json', str, kwargs)
433| pname = KWARG('pname', '', str, kwargs)
434| Log.info('fourier-wave:: %s' % str(list(kwargs.keys())))
435| Log.debug('fpath="%s"' % fpath)
436| Log.debug('fname="%s"' % fname)
437| Log.debug('tpath="%s"' % tpath)
438| Log.debug('tname="%s"' % tname)
439| Log.debug('dpath="%s"' % dpath)
440| Log.debug('dname="%s"' % dname)
441| Log.debug('pname="%s"' % pname)
442| Log.info()
443|
444|
445| img = fourier_sines_image(**kwargs)
446|
447|
448| fn = path.join(fpath, f'wave-{pname}.png' if 0<len(pname) else fname)
449| img.save(fn, 'PNG')
450| Log.info('wrote: %s' % fn)
451|
452| Log.info()
453| return 'Done'
454|
455|
456| def do_fourier_visual (**kwargs) -> str:
457| """CMND: Create a Fourier Visualization image."""
458| fpath = KWARG('fpath', ImgsPath, str, kwargs)
459| fname = KWARG('fname', 'fourier-wheel.png', str, kwargs)
460| Log.info('fourier-wheel:: %s' % str(list(kwargs.keys())))
461| Log.debug('fpath="%s"' % fpath)
462| Log.debug('fname="%s"' % fname)
463| Log.info()
464|
465|
466| img = fourier_visualization(**kwargs)
467|
468|
469| fn = path.join(fpath, fname) if fpath else fname
470| img.save(fn, 'PNG')
471| Log.info('wrote: %s' % fn)
472|
473| Log.info()
474| return 'Done'
475|
476|
477| def do_test (**kwargs) -> str:
478| """CMND: Do a test."""
479| fpath = KWARG('fpath', BasePath, str, kwargs)
480| fname = KWARG('fname', 'test.png', str, kwargs)
481| tpath = KWARG('tpath', BasePath, str, kwargs)
482| tname = KWARG('tname', 'test.text', str, kwargs)
483| dpath = KWARG('dpath', BasePath, str, kwargs)
484| dname = KWARG('dname', 'test.json', str, kwargs)
485| pname = KWARG('pname', '', str, kwargs)
486| Log.info('test:: %s' % str(list(kwargs.keys())))
487| Log.debug('fpath="%s"' % fpath)
488| Log.debug('fname="%s"' % fname)
489| Log.debug('tpath="%s"' % tpath)
490| Log.debug('tname="%s"' % tname)
491| Log.debug('dpath="%s"' % dpath)
492| Log.debug('dname="%s"' % dname)
493| Log.debug('pname="%s"' % pname)
494| Log.info()
495|
496| Log.info()
497| return 'Done'
498|
499| def dispatch (cmd:str, **kwargs) -> str:
500| """Dispatch to a module function based on CMD."""
501| Log.info('CMD: %s' % cmd)
502| for kw in kwargs:
503| Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
504| Log.info()
505| if cmd == '/w': return do_sine_wave(**kwargs)
506| if cmd == '/c': return do_fourier_curve(**kwargs)
507| if cmd == '/f': return do_fourier_visual(**kwargs)
508| if cmd == '/t': return do_test(**kwargs)
509| return 'Nothing to do!'
510|
511| if __name__ == "__main__":
512| Log.start(path.join(BasePath,'fourier.log'))
513| Log.level(trace())
514| Log.info(argv[0])
515| Log.info()
516| cmd = argv[1] if 1 < len(argv) else CMND
517| kwargs = ARGS
518| for a in argv[2:]:
519| nv = a.split('=', 1)
520| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
521| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
522| try:
523| print('CMD: %s' % cmd)
524| print()
525| obj = dispatch(cmd, **kwargs)
526| print()
527| print(obj)
528| Log.info()
529| Log.info(obj)
530| except:
531| etype, evalue, tb = exc_info()
532| ts = extract_tb(tb)
533| Log.error()
534| Log.error('%s: %s' % (etype.__name__,str(evalue)))
535| Log.error()
536| for t in ts[-5:]:
537| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
538| Log.error(' %s' % t[3])
539| Log.error()
540| raise
541| finally:
542| Log.end()
543|
544|
545| '''eof'''
546|