source: mystic/examples/example08.py @ 855

Revision 855, 3.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    - Callable plot of fitting to Chebyshev polynomial.
11    - Monitor Chi-Squared for Chebyshev polynomial.
12
13Demonstrates:
14    - standard models
15    - expanded solver interface
16    - built-in random initial guess
17    - customized monitors and termination conditions
18    - customized DE mutation strategies
19    - use of monitor to retrieve results information
20"""
21
22# Differential Evolution solver
23from mystic.solvers import DifferentialEvolutionSolver2
24
25# Chebyshev polynomial and cost function
26from mystic.models.poly import chebyshev8, chebyshev8cost
27from mystic.models.poly import chebyshev8coeffs
28
29# tools
30from mystic.termination import VTR
31from mystic.strategy import Best1Exp
32from mystic.monitors import VerboseMonitor
33from mystic.tools import getch, random_seed
34from mystic.math import poly1d
35import pylab
36pylab.ion()
37
38# draw the plot
39def plot_exact():
40    pylab.title("fitting 8th-order Chebyshev polynomial coefficients")
41    pylab.xlabel("x")
42    pylab.ylabel("f(x)")
43    import numpy
44    x = numpy.arange(-1.2, 1.2001, 0.01)
45    exact = chebyshev8(x)
46    pylab.plot(x,exact,'b-')
47    pylab.legend(["Exact"])
48    pylab.axis([-1.4,1.4,-2,8],'k-')
49    pylab.draw()
50    return
51 
52# plot the polynomial
53def plot_solution(params,style='y-'):
54    import numpy
55    x = numpy.arange(-1.2, 1.2001, 0.01)
56    f = poly1d(params)
57    y = f(x)
58    pylab.plot(x,y,style)
59    pylab.legend(["Exact","Fitted"])
60    pylab.axis([-1.4,1.4,-2,8],'k-')
61    pylab.draw()
62    return
63
64
65if __name__ == '__main__':
66
67    print "Differential Evolution"
68    print "======================"
69
70    # set range for random initial guess
71    ndim = 9
72    x0 = [(-100,100)]*ndim
73    random_seed(123)
74
75    # draw frame and exact coefficients
76    plot_exact()
77
78    # configure monitor
79    stepmon = VerboseMonitor(50)
80
81    # use DE to solve 8th-order Chebyshev coefficients
82    npop = 10*ndim
83    solver = DifferentialEvolutionSolver2(ndim,npop)
84    solver.SetRandomInitialPoints(min=[-100]*ndim, max=[100]*ndim)
85    solver.SetGenerationMonitor(stepmon)
86    solver.enable_signal_handler()
87    solver.Solve(chebyshev8cost, termination=VTR(0.01), strategy=Best1Exp, \
88                 CrossProbability=1.0, ScalingFactor=0.9, \
89                 sigint_callback=plot_solution)
90    solution = solver.Solution()
91
92    # use monitor to retrieve results information
93    iterations = len(stepmon)
94    cost = stepmon.y[-1]
95    print "Generation %d has best Chi-Squared: %f" % (iterations, cost)
96
97    # use pretty print for polynomials
98    print poly1d(solution)
99
100    # compare solution with actual 8th-order Chebyshev coefficients
101    print "\nActual Coefficients:\n %s\n" % poly1d(chebyshev8coeffs)
102
103    # plot solution versus exact coefficients
104    plot_solution(solution)
105    getch()
106
107# end of file
Note: See TracBrowser for help on using the repository browser.