source: branches/collapse/TEST_OUQ_surrogate_diam_collapse.py @ 855

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

updated copyright to 2016

Line 
1#!/usr/bin/env python
2#
3# Author: Lan Huong Nguyen (lanhuong @stanford)
4# Copyright (c) 2012-2016 California Institute of Technology.
5# License: 3-clause BSD.  The full license text is available at:
6#  - http://mmckerns.github.io/project/mystic/browser/mystic/LICENSE
7
8debug = True #False
9MINMAX = -1  ## NOTE: sup = maximize = -1; inf = minimize = 1
10#######################################################################
11# scaling and mpi info; also optimizer configuration parameters
12# hard-wired: use DE solver, don't use mpi, F-F' calculation
13#######################################################################
14npop = 40
15maxiter = 6000
16maxfun = 1e+6
17crossover = 0.9
18percent_change = 0.9
19convergence_tol = 1e-6
20tolW = 0.05; tolP_range_fr = 0.05
21ngen = 200; ngcol = 200
22
23
24#######################################################################
25# the model function
26#######################################################################
27from surrogate import marc_surr as model0
28
29#######################################################################
30# the differential evolution optimizer
31#######################################################################
32def optimize(cost,_bounds,_constraints):
33  from mystic.solvers import DifferentialEvolutionSolver2
34  from mystic.strategy import Best1Exp
35  from mystic.monitors import VerboseMonitor, Monitor
36  from mystic.tools import random_seed
37
38  random_seed(122)
39
40  stepmon = VerboseMonitor(10,10)
41 #stepmon = Monitor()
42  evalmon = Monitor()
43
44  lb,ub,npts = _bounds
45  ndim = len(lb)
46
47  solver = DifferentialEvolutionSolver2(ndim,npop)
48  solver.SetRandomInitialPoints(min=lb,max=ub)
49  solver.SetStrictRanges(min=lb,max=ub)
50  solver.SetEvaluationLimits(maxiter,maxfun)
51  solver.SetEvaluationMonitor(evalmon)
52  solver.SetGenerationMonitor(stepmon)
53  solver.SetConstraints(_constraints)
54 
55  import collapse_code 
56  return collapse_code.collapseSolver(solver, cost, npts, lb, ub, convergence_tol, tolW, \
57                        tolP_range_fr, ngen, ngcol, Best1Exp, crossover, \
58                        percent_change, stepmon, _constraints)
59#######################################################################
60# maximize the function
61#######################################################################
62def maximize(params,npts,bounds):
63
64  from mystic.math.measures import split_param
65  from mystic.math.discrete import product_measure
66  from mystic.math import almostEqual
67  from numpy import inf
68  atol = 1e-18 # default is 1e-18
69  rtol = 1e-7  # default is 1e-7
70  target,error = params
71  lb,ub = bounds
72
73  # split lower & upper bounds into weight-only & sample-only
74  w_lb, x_lb = split_param(lb, npts)
75  w_ub, x_ub = split_param(ub, npts)
76
77  # NOTE: rv, lb, ub are of the form:
78  #    rv = [wxi]*nx + [xi]*nx + [wyi]*ny + [yi]*ny + [wzi]*nz + [zi]*nz
79
80  # generate primary constraints function
81  def constraints(rv, cnstr_x=None):
82    c = product_measure()
83    c.load(rv, npts)
84    # NOTE: bounds wi in [0,1] enforced by filtering
85    # impose norm on each discrete measure
86    for measure in c:
87      if not almostEqual(float(measure.mass), 1.0, tol=atol, rel=rtol):
88        measure.normalize()
89    # impose expectation on product measure
90    ##################### begin function-specific #####################
91    E = float(c.expect(model))
92    if not (E <= float(target[0] + error[0])) \
93    or not (float(target[0] - error[0]) <= E):
94      c.set_expect((target[0],error[0]), model, (x_lb,x_ub), cnstr_x)
95    ###################### end function-specific ######################
96    # extract weights and positions
97    return c.flatten()
98
99  # generate maximizing functio
100  def cost(rv):
101    c = product_measure()
102    c.load(rv, npts)
103    E = float(c.expect(model))
104    if E > (target[0] + error[0]) or E < (target[0] - error[0]):
105      if debug: print "skipping expect: %s" % E
106      return inf  #XXX: FORCE TO SATISFY E CONSTRAINTS
107    return MINMAX * c.pof(model)
108
109  # maximize
110  solved, func_max, tot_evaluations, collapse_data = optimize(cost,(lb,ub,npts),constraints)
111
112  if MINMAX == 1:
113    print "func_minimum: %s" % func_max  # inf
114  else:
115    print "func_maximum: %s" % func_max  # sup
116  print "tot_evaluations: %s" % tot_evaluations
117
118  return solved, func_max, collapse_data
119
120
121#######################################################################
122# rank, bounds, and restart information
123#######################################################################
124if __name__ == '__main__':
125  from time import clock
126  start = clock()
127 
128  from mystic.tools import wrap_function
129  from mystic.monitors import Null
130  fmon = Null()
131  model_evaluations, model = wrap_function(model0, [], fmon) 
132  function_name = model0.__name__
133
134  H_mean = 6.5    #NOTE: SET THE 'mean' HERE!
135  H_range = 1.0   #NOTE: SET THE 'range' HERE!
136  nx = 3  #NOTE: SET THE NUMBER OF 'h' POINTS HERE!
137  ny = 3  #NOTE: SET THE NUMBER OF 'a' POINTS HERE!
138  nz = 3  #NOTE: SET THE NUMBER OF 'v' POINTS HERE!
139  target = (H_mean,)
140  error = (H_range,)
141
142  w_lower = [0.0]
143  w_upper = [1.0]
144  h_lower = [60.0];  a_lower = [0.0];  v_lower = [2.1]
145  h_upper = [105.0]; a_upper = [30.0]; v_upper = [2.8]
146
147  lower_bounds = (nx * w_lower) + (nx * h_lower) \
148               + (ny * w_lower) + (ny * a_lower) \
149               + (nz * w_lower) + (nz * v_lower)
150  upper_bounds = (nx * w_upper) + (nx * h_upper) \
151               + (ny * w_upper) + (ny * a_upper) \
152               + (nz * w_upper) + (nz * v_upper)
153
154  print "...SETTINGS..."
155  print "npop = %s" % npop
156  print "ngen = %s" %ngen
157  print "ngcol = %s" %ngcol
158  print "maxiter = %s" % maxiter
159  print "maxfun = %s" % maxfun
160  print "convergence_tol = %s" % convergence_tol
161  print "crossover = %s" % crossover
162  print "percent_change = %s" % percent_change
163  print "..............\n"
164
165  print " model: f(x) = %s(x)" % function_name
166  print " target: %s" % str(target)
167  print " error: %s" % str(error)
168  print "..............\n"
169
170  param_string = "["
171  for i in range(nx):
172    param_string += "'wx%s', " % str(i+1)
173  for i in range(nx):
174    param_string += "'x%s', " % str(i+1)
175  for i in range(ny):
176    param_string += "'wy%s', " % str(i+1)
177  for i in range(ny):
178    param_string += "'y%s', " % str(i+1)
179  for i in range(nz):
180    param_string += "'wz%s', " % str(i+1)
181  for i in range(nz):
182    param_string += "'z%s', " % str(i+1)
183  param_string = param_string[:-2] + "]"
184
185  print " parameters: %s" % param_string
186  print " lower bounds: %s" % lower_bounds
187  print " upper bounds: %s" % upper_bounds
188# print " ..."
189  pars = (target,error)
190  npts = (nx,ny,nz)
191  bounds = (lower_bounds,upper_bounds)
192  solved, diameter, collapse_data = maximize(pars,npts,bounds)
193
194  from numpy import array
195  from mystic.math.discrete import product_measure
196  c = product_measure()
197  c.load(solved,npts)
198  print "solved: [wx,x]\n%s" % array(zip(c[0].weights,c[0].positions))
199  print "solved: [wy,y]\n%s" % array(zip(c[1].weights,c[1].positions))
200  print "solved: [wz,z]\n%s" % array(zip(c[2].weights,c[2].positions))
201
202  print "expect: %s" % str( c.expect(model) )
203 
204  elapsed = (clock() - start)
205 
206  print "########################"
207  print 'RUNTIME = %s' %elapsed
208  print 'COLLAPSE DATA= %s' %collapse_data
209  print 'MODEL Evaluations = %s' %model_evaluations
210# EOF
Note: See TracBrowser for help on using the repository browser.