source: mystic/examples/example07.py @ 855

Revision 855, 2.1 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 DE.
10    - Plot of fitting to Chebyshev polynomial.
11
12Demonstrates:
13    - standard models
14    - minimal solver interface
15    - built-in random initial guess
16"""
17
18# Differential Evolution solver
19from mystic.solvers import diffev
20
21# Chebyshev polynomial and cost function
22from mystic.models.poly import chebyshev8, chebyshev8cost
23from mystic.models.poly import chebyshev8coeffs
24
25# tools
26from mystic.math import poly1d
27from mystic.tools import getch, random_seed
28import pylab
29pylab.ion()
30
31# draw the plot
32def plot_exact():
33    pylab.title("fitting 8th-order Chebyshev polynomial coefficients")
34    pylab.xlabel("x")
35    pylab.ylabel("f(x)")
36    import numpy
37    x = numpy.arange(-1.2, 1.2001, 0.01)
38    exact = chebyshev8(x)
39    pylab.plot(x,exact,'b-')
40    pylab.legend(["Exact"])
41    pylab.axis([-1.4,1.4,-2,8],'k-')
42    pylab.draw()
43    return
44 
45# plot the polynomial
46def plot_solution(params,style='y-'):
47    import numpy
48    x = numpy.arange(-1.2, 1.2001, 0.01)
49    f = poly1d(params)
50    y = f(x)
51    pylab.plot(x,y,style)
52    pylab.legend(["Exact","Fitted"])
53    pylab.axis([-1.4,1.4,-2,8],'k-')
54    pylab.draw()
55    return
56
57
58if __name__ == '__main__':
59
60    print "Differential Evolution"
61    print "======================"
62
63    # set range for random initial guess
64    ndim = 9
65    x0 = [(-100,100)]*ndim
66    random_seed(321)
67
68    # draw frame and exact coefficients
69    plot_exact()
70
71    # use DE to solve 8th-order Chebyshev coefficients
72    npop = 10*ndim
73    solution = diffev(chebyshev8cost,x0,npop)
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()
84
85# end of file
Note: See TracBrowser for help on using the repository browser.