polynomial.html
001|
002| from sys import argv, exc_info
003| from traceback import extract_tb
004| from os import path
005| from math import pi, radians,degrees, sin,cos,tan, acos,atan2
006| from PIL import ImageFont
007| from logger import logger, info, debug, trace
008| from goodies import divisions, intervals
009| from techstuff import PolyN, PolyChart
010| from canvas import Canvas
011| from webpage import KWARG
012|
013| BasePath = r'C:\CJS\prj\Python\app\maths'
014| ImgsPath = path.join(BasePath, 'img')
015| Log = logger('POLYN')
016|
017| CMND = ''
018| ARGS = {
019|
020| 'eq':'0.1x^3-0.66666x^2-1.3x+0.14',
021| 'fdiv':'300', 'fmin':'-10.0', 'fmax':'+10.0',
022|
023|
024|
025|
026| }
027|
028|
029| def do_polyn_chart (**kwargs):
030| fpath = KWARG('fpath', ImgsPath, str, kwargs)
031| fname = KWARG('fname', 'polyn.png', str, kwargs)
032| terms = KWARG('terms', '1, -4, 2', str, kwargs)
033| img_w = KWARG('w', 500, int, kwargs)
034| img_h = KWARG('h', 500, int, kwargs)
035| x_min = KWARG('x0', -10.0, float, kwargs)
036| x_max = KWARG('x1', +10.0, float, kwargs)
037| y_min = KWARG('y0', -20.0, float, kwargs)
038| y_max = KWARG('y1', +20.0, float, kwargs)
039| grid1 = KWARG('grid1', 5.0, float, kwargs)
040| grid2 = KWARG('grid2', 1.0, float, kwargs)
041| fmin = KWARG('fmin', x_min, float, kwargs)
042| fmax = KWARG('fmax', x_max, float, kwargs)
043| fdiv = KWARG('fdiv', 200, int, kwargs)
044| lw = KWARG('lw', 3, int, kwargs)
045| Log.info('polyn-chart:: %s' % str(list(kwargs.keys())))
046| Log.info('fpath="%s"' % fpath)
047| Log.info('fname="%s"' % fname)
048| Log.info('dims=(%d, %d)' % (img_w,img_h))
049| Log.info('xwin=(%.2f, %.2f)' % (x_min,x_max))
050| Log.info('ywin=(%.2f, %.2f)' % (y_min,y_max))
051| Log.info('grid=(%.2f, %.2f)' % (grid1,grid2))
052| Log.info('fdiv=%d' % fdiv)
053| Log.info('flim=[%+.2f, %+.2f]' % (fmin,fmax))
054| Log.info('terms=[%s]' % terms)
055| Log.info()
056| factors = [float(t.strip()) for t in terms.split(',')]
057|
058|
059| p1 = PolyN(factors)
060| p2 = p1.derivative()
061| p3 = p2.derivative()
062| p4 = p3.derivative()
063| coeffs = [p1.coeffs, p2.coeffs, p3.coeffs, p4.coeffs]
064| Log.info(p1)
065| Log.info(p2)
066| Log.info(p3)
067| Log.info(p4)
068| Log.info()
069|
070|
071| props = dict( fname=fname, fpath=fpath
072| , xlim=(x_min,x_max), xt=(grid1,grid2)
073| , step=0.05
074| , ylim=(y_min,y_max), yt=(grid1,grid2)
075| )
076| cht = PolyChart(coeffs, **props)
077| cht.make()
078| Log.info()
079| return 'Done'
080|
081|
082|
083| class polynomial (object):
084| '''Polynomial Parser class.'''
085| def __init__ (self, expression):
086| self.expr = expression
087| self.stack = ''
088| self.terms = {}
089| self._parse()
090|
091| def __str__ (self): return self.expr
092| def __len__ (self): return len(self.stack)
093|
094| def _parse (self):
095| Log.debug('PARSE %s' % str(self.expr))
096| self.stack = [c for c in self.expr if not c.isspace()]
097| while len(self):
098| self._term()
099| Log.debug('end PARSE')
100| Log.debug()
101|
102| def _term (self):
103| '''term := (+|-)[<number>][x[^<digit>]]'''
104| Log.debug('Term')
105| s = self._plusminus()
106| v = self._number()
107| x = self._factor()
108| self.terms[x] = (s,v)
109|
110| def _number (self):
111| '''number := <digits>[.<digits>]'''
112| Log.debug('Number')
113| digits = []
114| while len(self):
115| digit = self._digit()
116| if digit:
117| digits.append(digit)
118| else:
119| break
120|
121| if len(digits):
122| return float(''.join(digits))
123|
124| return 1.0
125|
126| def _factor (self):
127| '''factor := x[^<digit>]'''
128| Log.debug('Factor')
129|
130| if len(self.stack) == 0:
131| return 0
132|
133| if self.stack[0] == 'x':
134| self.stack.pop(0)
135|
136| if len(self.stack) == 0:
137| return 1
138|
139| if self.stack[0] == '^':
140| self.stack.pop(0)
141| exp = int(self.stack.pop(0))
142| return exp
143|
144| return 1
145|
146| return 0
147|
148| def _plusminus (self):
149| Log.debug('PlusMinus')
150|
151| if len(self.stack) == 0:
152| return +1
153|
154| if self.stack[0] in ['+','-']:
155| sgn = self.stack.pop(0)
156| return (-1 if sgn=='-' else +1)
157|
158| return +1
159|
160| def _digit (self):
161| Log.debug('Digit')
162|
163| if len(self.stack) == 0:
164| return None
165|
166| if self.stack[0] in ['0','1','2','3','4','5','6','7','8','9','.']:
167| return self.stack.pop(0)
168|
169| return None
170|
171|
172| def do_polynomial (**kwargs):
173| fpath = KWARG('fpath', ImgsPath, str, kwargs)
174| fname = KWARG('fname', 'polynomial.png', str, kwargs)
175| img_w = KWARG('w', 500, int, kwargs)
176| img_h = KWARG('h', 500, int, kwargs)
177| x_min = KWARG('x0', -10.0, float, kwargs)
178| x_max = KWARG('x1', +10.0, float, kwargs)
179| y_min = KWARG('y0', -20.0, float, kwargs)
180| y_max = KWARG('y1', +20.0, float, kwargs)
181| grid1 = KWARG('grid1', 5.0, float, kwargs)
182| grid2 = KWARG('grid2', 1.0, float, kwargs)
183| fmin = KWARG('fmin', x_min, float, kwargs)
184| fmax = KWARG('fmax', x_max, float, kwargs)
185| fdiv = KWARG('fdiv', 200, int, kwargs)
186| lw = KWARG('lw', 3, int, kwargs)
187| expr = KWARG('eq', '+x^4 - x^3 + x^2 - x^1 - 1', str, kwargs)
188| Log.info('polynomial:: %s' % str(list(kwargs.keys())))
189| Log.info('fpath="%s"' % fpath)
190| Log.info('fname="%s"' % fname)
191| Log.info('dims=(%d, %d)' % (img_w,img_h))
192| Log.info('xwin=(%.2f, %.2f)' % (x_min,x_max))
193| Log.info('ywin=(%.2f, %.2f)' % (y_min,y_max))
194| Log.info('grid=(%.2f, %.2f)' % (grid1,grid2))
195| Log.info('fdiv=%d' % fdiv)
196| Log.info('flim=[%+.2f, %+.2f]' % (fmin,fmax))
197| Log.info('expr=(%s)' % expr)
198| Log.info()
199| filename = path.join(fpath, fname)
200| dims = (img_w, img_h)
201| view = ((x_min,x_max), (y_min,y_max))
202|
203| Log.info('Parse: %s' % expr)
204| poly = polynomial(expr)
205| for exp in sorted(poly.terms.keys(), reverse=True):
206| sgn,nbr = poly.terms[exp]
207| Log.info('%+.3f * x^%d' % (sgn*nbr,exp))
208| Log.info()
209|
210| Log.info('Evaluate...')
211| pts = []
212| for x in divisions(fmin,fmax,fdiv):
213| y = 0.0
214| for exp in poly.terms.keys():
215| sgn,nbr = poly.terms[exp]
216| y += ((sgn*nbr)*pow(x,exp))
217| Log.info('%.5f = %.5f' % (x,y))
218| pts.append((x,y))
219| Log.info()
220|
221| im = Canvas(dims=dims, view=view)
222| if grid2: im.grid(grid2,grid2, lw=1, c=(221,221,255))
223| if grid1: im.grid(grid1,grid1, lw=2, c=(221,221,255))
224| im.axis(lw=2, c=(95,95,95))
225|
226| pt0 = None
227| for pt in pts:
228| if pt0:
229| im.line(pt0,pt, c=(0,0,255), lw=lw)
230| pt0 = pt
231|
232| im.save(filename)
233| Log.info('wrote: %s' % filename)
234| Log.info()
235| return 'Done'
236|
237|
238|
239| Function = lambda fx3,fx2,fx1,fx0: lambda x:((fx3*x*x*x)+(fx2*x*x)+(fx1*x)+(fx0))
240|
241| def do_xy_graph_1 (**kwargs):
242| fpath = KWARG('fpath', ImgsPath, str, kwargs)
243| fname = KWARG('fname', 'graph-1.png', str, kwargs)
244| img_w = KWARG('w', 800, int, kwargs)
245| img_h = KWARG('h', 800, int, kwargs)
246| x_min = KWARG('x0', -5.0, float, kwargs)
247| x_max = KWARG('x1', +5.0, float, kwargs)
248| y_min = KWARG('y0', -5.0, float, kwargs)
249| y_max = KWARG('y1', +5.0, float, kwargs)
250| grid1 = KWARG('grid1', 1.0, float, kwargs)
251| grid2 = KWARG('grid2', 0.1, float, kwargs)
252| fmin = KWARG('fmin', x_min, float, kwargs)
253| fmax = KWARG('fmax', x_max, float, kwargs)
254| fdiv = KWARG('fdiv', 200, int, kwargs)
255| fx3 = KWARG('fx3', +1.000, float, kwargs)
256| fx2 = KWARG('fx2', -1.000, float, kwargs)
257| fx1 = KWARG('fx1', +0.000, float, kwargs)
258| fx0 = KWARG('fx0', +0.000, float, kwargs)
259| Log.info('xy-graph-1:: %s' % str(list(kwargs.keys())))
260| Log.info('fname="%s"' % fname)
261| Log.info('fpath="%s"' % fpath)
262| Log.info('dims=(%d, %d)' % (img_w,img_h))
263| Log.info('xwin=(%.2f, %.2f)' % (x_min,x_max))
264| Log.info('ywin=(%.2f, %.2f)' % (y_min,y_max))
265| Log.info('grid=(%.2f, %.2f)' % (grid1,grid2))
266| Log.info('fdiv=%d' % fdiv)
267| Log.info('flim=[%+.2f, %+.2f]' % (fmin,fmax))
268| Log.info('coef=[%+.2f, %+.2f, %+.2f, %+.2f]' % (fx3,fx2,fx1,fx0))
269| Log.info()
270| filename = path.join(fpath, fname)
271| dims = (img_w, img_h)
272| view = ((x_min,x_max), (y_min,y_max))
273| func = Function(fx3,fx2,fx1,fx0)
274|
275| def get_points ():
276| return [(x,func(x)) for x in divisions(fmin,fmax,fdiv)]
277|
278| def get_complex_points (yi=0.0):
279| return [(x,func(complex(x,yi)).real) for x in divisions(fmin,fmax,2*fdiv)]
280|
281| im = Canvas(dims=dims, view=view)
282| if grid2: im.grid(grid2,grid2, lw=1, c=(221,221,255))
283| if grid1: im.grid(grid1,grid1, lw=2, c=(221,221,255))
284| im.axis(lw=2, c=(95,95,95))
285|
286| for pt in get_complex_points(yi=+0.25): im.point13(pt, c=(0,0,255))
287| for pt in get_complex_points(yi=-0.50): im.point13(pt, c=(0,0,255))
288| for pt in get_complex_points(yi=+1.00): im.point13(pt, c=(0,0,255))
289| for pt in get_points(): im.point37(pt, c=(255,0,0))
290|
291| im.save(filename)
292| Log.info('wrote: %s' % filename)
293| Log.info()
294| return 'Done'
295|
296|
297| def do_complex_graph_1 (**kwargs):
298| fpath = KWARG('fpath', ImgsPath, str, kwargs)
299| fname = KWARG('fname', 'complex-1.png', str, kwargs)
300| img_w = KWARG('w', 800, int, kwargs)
301| img_h = KWARG('h', 800, int, kwargs)
302| x_min = KWARG('x0', -50.0, float, kwargs)
303| x_max = KWARG('x1', +50.0, float, kwargs)
304| y_min = KWARG('y0', -50.0, float, kwargs)
305| y_max = KWARG('y1', +50.0, float, kwargs)
306| grid1 = KWARG('grid1', 10.0, float, kwargs)
307| grid2 = KWARG('grid2', 1.0, float, kwargs)
308| fmin = KWARG('fmin', -10.0, float, kwargs)
309| fmax = KWARG('fmax', +10.0, float, kwargs)
310| fdiv = KWARG('fdiv', 200, int, kwargs)
311| fx3 = KWARG('fx3', +1.000, float, kwargs)
312| fx2 = KWARG('fx2', -1.000, float, kwargs)
313| fx1 = KWARG('fx1', +1.000, float, kwargs)
314| fx0 = KWARG('fx0', -1.000, float, kwargs)
315| Log.info('complex-graph-1:: %s' % str(list(kwargs.keys())))
316| Log.info('fname="%s"' % fname)
317| Log.info('fpath="%s"' % fpath)
318| Log.info('dims=(%d, %d)' % (img_w,img_h))
319| Log.info('xwin=(%+.2f, %+.2f)' % (x_min,x_max))
320| Log.info('ywin=(%+.2f, %+.2f)' % (y_min,y_max))
321| Log.info('fdiv=%d' % fdiv)
322| Log.info('flim=[%+.2f, %+.2f]' % (fmin,fmax))
323| Log.info('coef=[%+.2f, %+.2f, %+.2f, %+.2f]' % (fx3,fx2,fx1,fx0))
324| Log.info()
325| filename = path.join(fpath, fname)
326| dims = (img_w, img_h)
327| view = ((x_min,x_max), (y_min,y_max))
328| func = Function(fx3,fx2,fx1,fx0)
329|
330| def get_points (yi=0.0):
331| return [func(complex(x,yi)) for x in divisions(fmin,fmax,fdiv)]
332|
333| im = Canvas(dims=dims, view=view)
334| if grid2: im.grid(grid2,grid2, lw=1, c=(221,221,255))
335| if grid1: im.grid(grid1,grid1, lw=2, c=(221,221,255))
336| im.axis(lw=2, c=(95,95,95))
337|
338| for yi in divisions(0.0, +2.5, 7):
339| for pt in get_points(yi=yi):
340| if yi == 0:
341| im.point13((pt.real,pt.imag), c=(0,0,0))
342| else:
343| co = (255,0,0) if yi < 0 else (0,0,255)
344| im.point9((pt.real,pt.imag), c=co)
345|
346| im.save(filename)
347| Log.info('wrote: %s' % filename)
348| Log.info()
349| return 'Done'
350|
351|
352| def do_complex_graph_2 (**kwargs):
353| fpath = KWARG('fpath', ImgsPath, str, kwargs)
354| fname = KWARG('fname', 'complex-2.png', str, kwargs)
355| img_w = KWARG('w', 800, int, kwargs)
356| img_h = KWARG('h', 800, int, kwargs)
357| x_min = KWARG('x0', -50.0, float, kwargs)
358| x_max = KWARG('x1', +50.0, float, kwargs)
359| y_min = KWARG('y0', -50.0, float, kwargs)
360| y_max = KWARG('y1', +50.0, float, kwargs)
361| grid1 = KWARG('grid1', 10.0, float, kwargs)
362| grid2 = KWARG('grid2', 1.0, float, kwargs)
363| fmin = KWARG('fmin', -10.0, float, kwargs)
364| fmax = KWARG('fmax', +10.0, float, kwargs)
365| fdiv = KWARG('fdiv', 200, int, kwargs)
366| fx3 = KWARG('fx3', +1.000, float, kwargs)
367| fx2 = KWARG('fx2', -1.000, float, kwargs)
368| fx1 = KWARG('fx1', +1.000, float, kwargs)
369| fx0 = KWARG('fx0', -1.000, float, kwargs)
370| Log.info('complex-graph-2:: %s' % str(list(kwargs.keys())))
371| Log.info('fname="%s"' % fname)
372| Log.info('fpath="%s"' % fpath)
373| Log.info('dims=(%d, %d)' % (img_w,img_h))
374| Log.info('xwin=(%+.2f, %+.2f)' % (x_min,x_max))
375| Log.info('ywin=(%+.2f, %+.2f)' % (y_min,y_max))
376| Log.info('fdiv=%d' % fdiv)
377| Log.info('flim=[%+.2f, %+.2f]' % (fmin,fmax))
378| Log.info('coef=[%+.2f, %+.2f, %+.2f, %+.2f]' % (fx3,fx2,fx1,fx0))
379| Log.info()
380| filename = path.join(fpath, fname)
381| dims = (img_w, img_h)
382| view = ((x_min,x_max), (y_min,y_max))
383|
384| def get_points (yi=0.0):
385| cx3 = complex(fx3, yi)
386| cx2 = complex(fx2, yi)
387| cx1 = complex(fx1, yi)
388| cx0 = complex(fx0, yi)
389| func = Function(cx3,cx2,cx1,cx0)
390| return [func(complex(x,yi)) for x in divisions(fmin, fmax, fdiv)]
391|
392| im = Canvas(dims=dims, view=view)
393| if grid2: im.grid(grid2,grid2, lw=1, c=(221,221,255))
394| if grid1: im.grid(grid1,grid1, lw=2, c=(221,221,255))
395| im.axis(lw=2, c=(95,95,95))
396|
397| for yi in divisions(0.0, +2.5, 7):
398| for pt in get_points(yi=yi):
399| if yi == 0:
400| im.point13((pt.real,pt.imag), c=(0,0,0))
401| else:
402| co = (255,0,0) if yi < 0 else (0,0,255)
403| im.point9((pt.real,pt.imag), c=co)
404|
405| im.save(filename)
406| Log.info('wrote: %s' % filename)
407| Log.info()
408| return 'Done'
409|
410|
411| def do_test (**kwargs):
412| fpath = KWARG('fpath', BasePath, str, kwargs)
413| fname = KWARG('fname', 'polynomial.out', str, kwargs)
414| Log.info('test:: %s' % str(list(kwargs.keys())))
415| Log.info('fpath="%s"' % fpath)
416| Log.info('fname="%s"' % fname)
417| Log.info()
418|
419| Log.info()
420| return 'Done'
421|
422| def dispatch (cmd, **kwargs):
423| Log.info('command: %s' % cmd)
424| for kw in kwargs:
425| Log.info('argument[%s]: %s' % (kw,kwargs[kw]))
426| Log.info()
427| if cmd == 'xy.1': return do_xy_graph_1(**kwargs)
428| if cmd == 'cp.1': return do_complex_graph_1(**kwargs)
429| if cmd == 'cp.2': return do_complex_graph_2(**kwargs)
430| if cmd == 'poly1': return do_polynomial(**kwargs)
431| if cmd == 'poly2': return do_polyn_chart(**kwargs)
432| if cmd == 'test': return do_test(**kwargs)
433| return 'Nothing to do!'
434|
435| if __name__ == '__main__':
436| print('autorun: %s' % argv[0])
437| Log.start(path.join(BasePath,'polynomial.log'))
438| Log.level(debug())
439| cmd = argv[1] if 1 < len(argv) else CMND
440| kwargs = ARGS
441| for a in argv[2:]:
442| nv = a.split('=', 1)
443| kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
444| Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
445| try:
446| print('CMD: %s' % cmd)
447| print()
448| obj = dispatch(cmd, **kwargs)
449| print()
450| print(obj)
451| Log.info()
452| Log.info(obj)
453| except:
454| etype, evalue, tb = exc_info()
455| ts = extract_tb(tb)
456| Log.error()
457| Log.error('%s: %s' % (etype.__name__,str(evalue)))
458| Log.error()
459| for t in ts[-5:]:
460| Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
461| Log.error(' %s' % t[3])
462| Log.error()
463| raise
464| finally:
465| Log.end()
466|
467| '''eof'''
468|