source: mystic/examples/example09.py @ 855

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