polynomial_ml.html


001| ####################################################################################################
002| from sys import argv
003| from os import path
004| from mlchart import mlchart
005| from goodies import intervals
006| ####################################################################################################
007| BasePath = r'C:\CJS\prj\Python\app\maths'
008| ImgsPath = path.join(BasePath, 'img')
009| 
010| # f(x) = 1.2x^4 + 2.5x^3 - 3.14x^2 - 5.25x - 1.66
011| Coefficients1 = [+1.2, +2.5, -3.14, -5.25, -1.66]
012| # g(x) = f'(x) = 4.8x^3 + 7.5x^2 - 6.28x - 5.25
013| Coefficients2 = [+4.8, +7.5, -6.28, -5.25]
014| # h(x) = g'(x) = f''(x) = 14.4x^2 + 15.0x - 6.28
015| Coefficients3 = [+14.4, +15.0, -6.28]
016| # j(x) = h'(x) = g''(x) = f'''(x) = 28.8x + 15.0
017| Coefficients4 = [+28.8, +15.0]
018| 
019| ##================================================================================================##
020| # A simple version for f(x) = (ax^2 + bx + c)...
021| # (This is what started all this.)
022| quadratic = lambda a,b,c: lambda x:((a*pow(x,2))+(b*x)+c)
023| 
024| ##================================================================================================##
025| def polyn (coeffs):
026|     '''Return a polynomial function (that generates a list of term-values).'''
027|     # Function to create one term...
028|     poly1 = lambda c,e:lambda x:(c*pow(x,e))
029|     # Create a list of terms...
030|     terms = [poly1(c,ix) for ix,c in enumerate(reversed(coeffs))]
031|     # Return a function that applies x to those terms to create values...
032|     return lambda x:[f(x) for f in reversed(terms)]
033| 
034| def polyn_demo (coeffs):
035|     '''Demonstrate the polyn function.'''
036|     prettyprint = lambda g: ('[%s]' % ' '.join(['%+.2f'%n for n in g]))
037|     print('Poly-N: %s' % prettyprint(coeffs))
038|     print()
039|     # Create the polynomial...
040|     ftn = polyn(coeffs)
041|     # Calculate x=[0,1,2,3,4] (print each one)...
042|     for x in range(5):
043|         terms = ftn(x)
044|         print('x=%d:%s = %+.4f' % (x, prettyprint(terms),sum(terms)))
045|     print()
046| 
047| def test_polyn_1 ():
048|     '''Test Unit #1.'''
049|     polyn_demo([1])                 # 1
050|     polyn_demo([1, 0])              # x
051|     polyn_demo([1, 0, 0])           # x^2
052|     polyn_demo([1, 0, 0, 0])        # x^3
053|     polyn_demo([1, 0, 0, 0, 0])     # x^4
054|     polyn_demo([1, 2, 3])           # x^2 + 2x + 3
055| 
056| def test_polyn_2 ():
057|     '''Test Unit #2.'''
058|     polyn_demo(Coefficients1)
059|     polyn_demo(Coefficients2)
060| 
061| 
062| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
063| class PolyN (object):
064|     '''Polynomial generator class.'''
065|     def __init__ (self, coeffs):
066|         ''''Create a new polynomial object.'''
067|         # Function to generate one term...
068|         poly = lambda c,e:lambda x:(c*pow(x,e))
069|         # Keep a copy of the coefficients...
070|         self.coeffs = coeffs
071|         # Generate a list of terms...
072|         terms = [poly(c,ix) for ix,c in enumerate(reversed(coeffs))]
073|         # Bind the list of terms in a function...
074|         self.expr = lambda x:[f(x) for f in reversed(terms)]
075|         # Evaluate f(0) for default values...
076|         self(0)
077| 
078|     def __call__ (self, x):
079|         '''Evaluate f(x); return result.'''
080|         # Generate a list of values...
081|         self.vals = self.expr(x)
082|         # Sum the values to get (and return) a result...
083|         self.result = sum(self.vals)
084|         return self.result
085| 
086|     def derivative (self):
087|         '''Return a new PolyN instance that's a derivative of this.'''
088|         # Generate a new list of coefficients...
089|         # (Note: The tail term always ends up zero.)
090|         dx = [(t[0]*t[1]) for t in enumerate(reversed(self.coeffs))]
091|         # Return a new instance...
092|         # (Truncating that zero tail term.)
093|         # ((The truncation auto-decrements the exponents b/c they're positional!))
094|         return PolyN([t for t in reversed(dx[1:])])
095| 
096|     def __str__ (self):
097|         '''Pretty print the polynomial.'''
098|         # Treat an empty coefficients list as a special case...
099|         if len(self.coeffs) == 0:
100|             return '<zero>'
101|         # Generate a list of string versions of the terms...
102|         ts = ['(%+.2f)x^%d' % (c,ix) for ix,c in enumerate(reversed(self.coeffs))]
103|         # Join and return the strings...
104|         return ' '.join(reversed(ts))
105| 
106|     def __repr__ (self):
107|         '''Return the coefficients as a string.'''
108|         return str(self.coeffs)
109| 
110| def test_PolyN_1 ():
111|     '''Test Unit #1.'''
112|     p1 = PolyN(Coefficients1)
113|     print(p1)
114|     for x in [(-2.0+(n/20)) for n in range(81)]:
115|         print('%.4f: %f' % (x,p1(x)))
116|         print()
117| 
118| def test_PolyN_2 ():
119|     '''Test Unit #2.'''
120|     p1 = PolyN(Coefficients1)
121|     p2 = p1.derivative()
122|     p3 = p2.derivative()
123|     p4 = p3.derivative()
124|     p5 = p4.derivative()
125|     p6 = p5.derivative()
126|     print(p1)
127|     print(p2)
128|     print(p3)
129|     print(p4)
130|     print(p5)
131|     print(p6)
132| 
133| 
134| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
135| class polyn_chart (mlchart):
136|     '''Polynomial Chart making class.'''
137|     colors = ['#ff0000', '#009f00', '#0000cc', '#9f9f00', '#009f9f', '#9f009f', '#7f7f7f']
138| 
139|     def __init__ (self, coeffs_list, **kwargs):
140|         ''''Create a new polynomial chart object.'''
141|         super().__init__()
142|         self.ftns = [PolyN(cs) for cs in coeffs_list]
143|         self.incr = kwargs['step'] if 'step' in kwargs else 0.1
144|         self.dims = (6.0, 6.0)
145|         self.margins = dict(left=0.130, right=0.975, bottom=0.12, top=0.92)
146|         self.title = 'Polynomial Curves by PolyN'
147|         self.x_title = 'X Axis'
148|         self.y_title = 'Y Axis'
149|         self.x_limit = kwargs['xlim'] if 'xlim' in kwargs else (-10.0, +10.0)
150|         self.y_limit = kwargs['ylim'] if 'ylim' in kwargs else (-10.0, +10.0)
151|         self.x_grids = kwargs['xt'] if 'xt' in kwargs else (5.0, 1.00)
152|         self.y_grids = kwargs['yt'] if 'yt' in kwargs else (5.0, 1.00)
153|         self.x_tickf = '%+.1f'
154|         self.y_tickf = '%+.1f'
155|         self.fpath = kwargs['fpath'] if 'fpath' in kwargs else ImgsPath
156|         self.fname = kwargs['fname'] if 'fname' in kwargs else 'polyn.png'
157| 
158|     def plotter (self):
159|         xs = list(intervals(self.x_limit[0], self.x_limit[1], self.incr))
160|         for ix,ftn in enumerate(self.ftns):
161|             ys = [ftn(x) for x in xs]
162|             self.ax.plot(xs,ys, c=self.colors[ix], lw=2.0, alpha=0.8, zorder=11+ix)
163|         #self.ax.legend(loc='lower right', shadow=True)
164| 
165|     def make_x_axis_spcl (self):
166|         for tick in self.ax.xaxis.get_major_ticks():
167|             tick.label1.set_rotation('vertical')
168|             tick.label1.set_size(9)
169| 
170| def test_polyn_chart ():
171|     coeffs = [Coefficients1, Coefficients2, Coefficients3, Coefficients4]
172|     props = dict(xlim=(-3.0,+3.0),xt=(1.0,0.1), step=0.05, ylim=(-10.0,+10.0),yt=(5.0,1.00))
173|     cht = polyn_chart(coeffs, **props)
174|     cht.make()
175| 
176| def do_polynomial_chart (*args):
177|     print(args)
178|     print()
179|     # Chart properties...
180|     props = dict( fpath=BasePath
181|                 , xlim=(-5.0,+10.0), xt=(5.0,1.00)
182|                 , step=0.05
183|                 , ylim=(-20.0,+10.0), yt=(10.0,1.00)
184|                 )
185|     # Polynomial coefficients (list of)...
186|     p1 = PolyN([+0.1, -0.5, -0.85, +1.3, -3.14])
187|     p2 = p1.derivative()
188|     p3 = p2.derivative()
189|     p4 = p3.derivative()
190|     print(p1)
191|     print(p2)
192|     print(p3)
193|     print(p4)
194|     coeffs = [p1.coeffs, p2.coeffs, p3.coeffs, p4.coeffs]
195|     cht = polyn_chart(coeffs, **props)
196|     cht.make()
197| 
198| ##================================================================================================##
199| '''
199| autorun: ml_polynomial.py
199| 
199| ()
199| 
199| (+0.10)x10^4 (-0.50)x10^3 (-0.85)x10^2 (+1.30)x10^1 (-3.14)x10^0
199| (+0.40)x10^3 (-1.50)x10^2 (-1.70)x10^1 (+1.30)x10^0
199| (+1.20)x10^2 (-3.00)x10^1 (-1.70)x10^0
199| 
199| '''

200| ##================================================================================================##
201| if __name__ == '__main__':
202|     print('autorun: %s' % argv[0])
203|     print()
204|     #
205|     #test_polyn_1()
206|     #test_polyn_2()
207|     #
208|     #test_PolyN_1()
209|     #test_PolyN_2()
210|     #
211|     #test_polyn_chart()
212|     do_polynomial_chart(*argv[1:])
213|     #
214|     print()
215| ####################################################################################################
216| '''eof'''
217|