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 | """ |
---|

8 | Example: |
---|

9 | - Minimize Rosenbrock's Function with Nelder-Mead. |
---|

10 | - Dynamic plot of parameter convergence to function minimum. |
---|

11 | |
---|

12 | Demonstrates: |
---|

13 | - standard models |
---|

14 | - minimal solver interface |
---|

15 | - parameter trajectories using callback |
---|

16 | - solver interactivity |
---|

17 | """ |
---|

18 | |
---|

19 | # Nelder-Mead solver |
---|

20 | from mystic.solvers import fmin |
---|

21 | |
---|

22 | # Rosenbrock function |
---|

23 | from mystic.models import rosen |
---|

24 | |
---|

25 | # tools |
---|

26 | from mystic.tools import getch |
---|

27 | import pylab |
---|

28 | pylab.ion() |
---|

29 | |
---|

30 | # draw the plot |
---|

31 | def plot_frame(): |
---|

32 | pylab.title("Rosenbrock parameter convergence") |
---|

33 | pylab.xlabel("Nelder-Mead solver iterations") |
---|

34 | pylab.ylabel("parameter value") |
---|

35 | pylab.draw() |
---|

36 | return |
---|

37 | |
---|

38 | iter = 0 |
---|

39 | step, xval, yval, zval = [], [], [], [] |
---|

40 | # plot the parameter trajectories |
---|

41 | def plot_params(params): |
---|

42 | global iter, step, xval, yval, zval |
---|

43 | step.append(iter) |
---|

44 | xval.append(params[0]) |
---|

45 | yval.append(params[1]) |
---|

46 | zval.append(params[2]) |
---|

47 | pylab.plot(step,xval,'b-') |
---|

48 | pylab.plot(step,yval,'g-') |
---|

49 | pylab.plot(step,zval,'r-') |
---|

50 | pylab.legend(["x", "y", "z"]) |
---|

51 | pylab.draw() |
---|

52 | iter += 1 |
---|

53 | return |
---|

54 | |
---|

55 | |
---|

56 | if __name__ == '__main__': |
---|

57 | |
---|

58 | # initial guess |
---|

59 | x0 = [0.8,1.2,0.7] |
---|

60 | |
---|

61 | # suggest that the user interacts with the solver |
---|

62 | print "NOTE: while solver is running, press 'Ctrl-C' in console window" |
---|

63 | getch() |
---|

64 | plot_frame() |
---|

65 | |
---|

66 | # use Nelder-Mead to minimize the Rosenbrock function |
---|

67 | solution = fmin(rosen,x0,disp=1,callback=plot_params,handler=True) |
---|

68 | print solution |
---|

69 | |
---|

70 | # don't exit until user is ready |
---|

71 | getch() |
---|

72 | |
---|

73 | # end of file |
---|