source: mystic/examples/example06.py @ 855

Revision 855, 2.2 KB checked in by mmckerns, 5 months ago (diff)

updated copyright to 2016

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2#
3# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
4# Copyright (c) 1997-2016 California Institute of Technology.
5# License: 3-clause BSD.  The full license text is available at:
6#  - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/mystic/LICENSE
7"""
8Example:
9    - Solve 8th-order Chebyshev polynomial coefficients with Powell's method.
10    - Plot of fitting to Chebyshev polynomial.
11
12Demonstrates:
13    - standard models
14    - minimal solver interface
15"""
16
17# Powell's Directonal solver
18from mystic.solvers import fmin_powell
19
20# Chebyshev polynomial and cost function
21from mystic.models.poly import chebyshev8, chebyshev8cost
22from mystic.models.poly import chebyshev8coeffs
23
24# tools
25from mystic.math import poly1d
26from mystic.tools import getch
27import pylab
28pylab.ion()
29
30# draw the plot
31def plot_exact():
32    pylab.title("fitting 8th-order Chebyshev polynomial coefficients")
33    pylab.xlabel("x")
34    pylab.ylabel("f(x)")
35    import numpy
36    x = numpy.arange(-1.2, 1.2001, 0.01)
37    exact = chebyshev8(x)
38    pylab.plot(x,exact,'b-')
39    pylab.legend(["Exact"])
40    pylab.axis([-1.4,1.4,-2,8],'k-')
41    pylab.draw()
42    return
43 
44# plot the polynomial
45def plot_solution(params,style='y-'):
46    import numpy
47    x = numpy.arange(-1.2, 1.2001, 0.01)
48    f = poly1d(params)
49    y = f(x)
50    pylab.plot(x,y,style)
51    pylab.legend(["Exact","Fitted"])
52    pylab.axis([-1.4,1.4,-2,8],'k-')
53    pylab.draw()
54    return
55
56
57if __name__ == '__main__':
58
59    print "Powell's Method"
60    print "==============="
61
62    # initial guess
63    import random
64    from mystic.tools import random_seed
65    random_seed(123)
66    ndim = 9
67    x0 = [random.uniform(-100,100) for i in range(ndim)]
68
69    # draw frame and exact coefficients
70    plot_exact()
71
72    # use Powell's method to solve 8th-order Chebyshev coefficients
73    solution = fmin_powell(chebyshev8cost,x0)
74
75    # use pretty print for polynomials
76    print poly1d(solution)
77
78    # compare solution with actual 8th-order Chebyshev coefficients
79    print "\nActual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs)
80
81    # plot solution versus exact coefficients
82    plot_solution(solution)
83    getch() #XXX: or pylab.show() ?
84
85# end of file
Note: See TracBrowser for help on using the repository browser.