Ignore:
Timestamp:
09/14/12 16:42:47 (4 years ago)
Author:
mmckerns
Message:

update Lan's collapse code to as used in SURF final report;
add Lan's semilog plotter script

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/collapse/TEST_OUQ_surrogate_diam.py

    r542 r560  
    11#!/usr/bin/env python 
    22 
    3 debug = False 
     3debug = True #False 
    44MINMAX = -1  ## NOTE: sup = maximize = -1; inf = minimize = 1 
    55####################################################################### 
     
    88####################################################################### 
    99npop = 40 
    10 maxiter = 1000 
     10maxiter = 6000 
    1111maxfun = 1e+6 
    12 convergence_tol = 1e-6; ngen = 40 
    1312crossover = 0.9 
    1413percent_change = 0.9 
     14convergence_tol = 1e-6 
     15tolW = 0.05; tolP_range_fr = 0.05 
     16ngen = 200; ngcol = 200 
    1517 
    1618 
     
    1820# the model function 
    1921####################################################################### 
    20 from surrogate import marc_surr as model 
    21  
     22from surrogate import marc_surr as model0 
    2223 
    2324####################################################################### 
     
    2627def optimize(cost,_bounds,_constraints): 
    2728  from mystic.solvers import DifferentialEvolutionSolver2 
    28  #from mystic.termination import ChangeOverGeneration as COG 
    29   from mystic.termination import Or 
    30   from collapse_termination import CLPS_Weight as WCLPS 
    31   from collapse_termination import CLPS_Location as LCLPS 
    3229  from mystic.strategy import Best1Exp 
    3330  from mystic.monitors import VerboseMonitor, Monitor 
    3431  from mystic.tools import random_seed 
    3532 
    36  #random_seed(123) 
    37  
    38   stepmon = VerboseMonitor(2) 
     33  random_seed(122) 
     34 
     35  stepmon = VerboseMonitor(10,10) 
    3936 #stepmon = Monitor() 
    4037  evalmon = Monitor() 
     
    5047  solver.SetGenerationMonitor(stepmon) 
    5148  solver.SetConstraints(_constraints) 
    52  
     49  
     50  ############################################################################## 
     51   
     52                 ## THE FOLLOWING TERMINATION AND CONSTRAINTS ## 
     53                 ## CAN BE MOVED TO A NEW MODULE AND IMPORTED ## 
     54   
     55  ######################### TERMINATION CONDITIONS ############################# 
     56  from mystic.termination import Or   
     57  from mystic.termination import ChangeOverGeneration as COG 
     58  from collapse_termination_v2 import CLPS_Weight as WCLPS 
     59  from collapse_termination_v2 import CLPS_Position as PCLPS   
     60  from mystic.math.measures import _nested_split   
     61   
    5362  tol = convergence_tol 
    54   _WCLPS = WCLPS(npts, tolG=tol, generations=ngen) 
    55   _LCLPS = LCLPS(npts, tolL=[1,1,0.03], tolG=tol, generations=ngen) #FIXME 
    56   CLPS = Or( _WCLPS, _LCLPS ) 
    57   solver.Solve(cost,termination=CLPS,strategy=Best1Exp, \ 
    58                CrossProbability=crossover,ScalingFactor=percent_change) 
    59  
     63  _COG = COG(tol,ngen) 
     64   
     65  w_lb, x_lb = _nested_split(lb, npts) 
     66  w_ub, x_ub = _nested_split(ub, npts) 
     67  range_x = [] 
     68  for i in range(len(x_lb)): 
     69      range_x.append(abs(x_lb[i][0] - x_ub[i][0]))   
     70  tolP = [ele*tolP_range_fr for ele in range_x]  
     71  if debug: print 'tolP = %s' %tolP 
     72   
     73  indexW_ids = [range(nx) for nx in npts]  # list of indices for CLPS_Weight termination check 
     74  indexP_ids = []  # list of indices for CLPS_Position termination check   
     75   
     76  x = [] 
     77  _WCLPS = [] 
     78  _PCLPS = [] 
     79   
     80  for m in range(len(indexW_ids)): 
     81      for idx in indexW_ids[m]: 
     82          _WCLPS.append(WCLPS(npts, tol_weight = tolW, generations=ngcol, axisW = m, indexW = idx)) 
     83           
     84  for m in range(len(indexP_ids)): 
     85      for pair in indexP_ids[m]: 
     86          _PCLPS.append( PCLPS(npts, tol_position=tolP, generations=ngcol, \ 
     87                                axisP = m, index1 = pair[0], index2  = pair[1]))  
     88  x.extend(_WCLPS) 
     89  x.extend(_PCLPS) 
     90  x.append(_COG) 
     91  trm = Or(*x) 
     92   
     93  ######################## NEW CONSTRAINTS AFTER COLLAPSE ###################### 
     94   
     95  list_vanished_weights = [] # list of [measure, index] lists 
     96  list_collapsed_pairs = [] # list of [measure, pair] lists, where pair = [index1, index2]   
     97   
     98  for i in range(len(npts)): 
     99    c = [] 
     100    for idx in range(npts[i]): 
     101        for jdx in range(idx,npts[i]): 
     102            if idx !=jdx: 
     103                c.append([idx, jdx]) 
     104    indexP_ids.append(c)   
     105   
     106  def _set_weight_to_zero(rv, npts, axisW, indexW): 
     107    from mystic.math.dirac_measure import product_measure 
     108    c = product_measure() 
     109    c.load(rv, npts) 
     110    c[axisW][indexW].weight = 0 
     111    return c.flatten() 
     112   
     113  def _set_same_positions(rv, npts, axisP, index1, index2): 
     114    from mystic.math.dirac_measure import product_measure 
     115    c = product_measure() 
     116    c.load(rv, npts) 
     117    c[axisP][index1].weight += c[axisP][index2].weight 
     118    c[axisP][index2].weight = 0 
     119    c[axisP][index2].position = c[axisP][index1].position 
     120    return c.flatten()  
     121   
     122  def new_constraints(rv, list_collapsed_pairs, list_vanished_weights): 
     123    for ele in list_vanished_weights: 
     124      rv = _set_weight_to_zero(rv, npts, axisW = ele[0], indexW = ele[1]) 
     125    for mem in list_collapsed_pairs: 
     126      rv = _set_same_positions(rv, npts, axisP = mem[0], \ 
     127              index1 = mem[1][0], index2 = mem[1][1])             
     128    return _constraints(rv)    
     129   
     130  ############################################################################## 
     131   
     132   
     133  ############################ RUN THE SOLVER ################################## 
     134  collapse_data = {} 
     135  tot_evaluations = 0 # total number of function eveluations 
     136  while _COG(solver) != True:          
     137    solver.Solve(cost,termination=trm,strategy=Best1Exp, \ 
     138               CrossProbability=crossover,ScalingFactor=percent_change)  
     139    tot_evaluations += solver.evaluations     
     140    collapse_data[stepmon._step] = trm(solver, True) 
     141     
     142    if debug: 
     143      print 'last_itr_evaluations = %s' %solver.evaluations 
     144      print "Generation  %d " %stepmon._step  
     145     
     146    int_trm = trm(solver, info = 'self')   
     147    for ele in range(len(int_trm)): 
     148      cond = int_trm[ele] 
     149      string = cond(solver, info = True) 
     150      string1 = string.replace(',', ' ') 
     151      string2 = string1.replace('&', ' ') 
     152      string3 = string2.replace(':', ' ') 
     153      lst = string3.split() 
     154       
     155      if lst[0] == 'CLPS_Weight': 
     156          for i in range(len(lst)): 
     157              if lst[i] == 'measure': 
     158                  axisW = int(lst[i+1]) 
     159                  if lst[i+2] == 'index': indexW = int(lst[i+3]) 
     160                   
     161          if debug: 
     162            print 'axisW = %s' %axisW 
     163            print 'indexW = %s' %indexW 
     164           
     165          list_vanished_weights.append([axisW, indexW])  
     166          indexW_ids[axisW].remove(indexW) 
     167                  
     168      if lst[0] == 'CLPS_Position': 
     169          for i in range(len(lst)):   
     170              if lst[i] == 'measure':         
     171                  axisP = int(lst[i+1]) 
     172                  if lst[i+2] == 'indices':  
     173                      index1 = int(lst[i+3].lstrip('(')) 
     174                      index2 = int(lst[i+4].rstrip(')')) 
     175          if debug: 
     176            print "axisP = %s" %axisP 
     177            print "index1 = %s" %index1 
     178            print "index2 = %s" %index2 
     179           
     180          list_collapsed_pairs.append([axisP, [index1, index2]]) 
     181          indexP_ids[axisP].remove([index1,index2])           
     182       
     183      ##### AFTER COLLAPSE OCCURRED CHANGE THE TERMINATION AND CONSTRAINTS ##### 
     184                     
     185      def _new_constraints(rv): 
     186        return new_constraints(rv, list_collapsed_pairs, list_vanished_weights)       
     187      solver.SetConstraints(_new_constraints) 
     188       
     189      x = [] 
     190      _WCLPS = [] 
     191      _PCLPS = [] 
     192      for m in range(len(indexW_ids)): 
     193          for idx in indexW_ids[m]: 
     194              _WCLPS.append(WCLPS(npts, generations=ngcol, axisW = m, indexW = idx)) 
     195               
     196      for m in range(len(indexP_ids)): 
     197          for pair in indexP_ids[m]: 
     198              _PCLPS.append( PCLPS(npts, tol_position=tolP, generations=ngcol, \ 
     199                                    axisP = m, index1 = pair[0], index2  = pair[1]))  
     200      x.extend(_WCLPS) 
     201      x.extend(_PCLPS) 
     202      x.append(_COG) 
     203      trm = Or(*x) 
     204       
     205      if debug: 
     206        print 'list_vanished_weights = ' 
     207        print  list_vanished_weights 
     208        print 'list_collapsed_pairs = ' 
     209        print  list_collapsed_pairs                          
     210   
    60211  solved = solver.bestSolution 
    61212 #print "solved: %s" % solver.Solution() 
     
    65216  from mystic.munge import write_support_file 
    66217  write_support_file(stepmon) 
    67   return solved, func_max, func_evals 
     218  ''' 
     219  if collapse_data: 
     220    f = open('collapse_data.txt','w') 
     221    f.write('COLLAPSE DATA = %s' %collapse_data) 
     222    f.close()''' 
     223  return solved, func_max, tot_evaluations, collapse_data 
    68224 
    69225 
     
    90246 
    91247  # generate primary constraints function 
    92   def constraints(rv): 
     248  def constraints(rv, cnstr_x=None): 
    93249    c = product_measure() 
    94250    c.load(rv, npts) 
     
    103259    if not (E <= float(target[0] + error[0])) \ 
    104260    or not (float(target[0] - error[0]) <= E): 
    105       c.set_expect((target[0],error[0]), model, (x_lb,x_ub)) 
     261      c.set_expect((target[0],error[0]), model, (x_lb,x_ub), cnstr_x) 
    106262    ###################### end function-specific ###################### 
    107263    # extract weights and positions 
    108264    return c.flatten() 
    109265 
    110   # generate maximizing function 
     266  # generate maximizing functio 
    111267  def cost(rv): 
    112268    c = product_measure() 
     
    119275 
    120276  # maximize 
    121   solved, func_max, func_evals = optimize(cost,(lb,ub,npts),constraints) 
     277  solved, func_max, tot_evaluations, collapse_data = optimize(cost,(lb,ub,npts),constraints) 
    122278 
    123279  if MINMAX == 1: 
     
    125281  else: 
    126282    print "func_maximum: %s" % func_max  # sup 
    127   print "func_evals: %s" % func_evals 
    128  
    129   return solved, func_max 
     283  print "tot_evaluations: %s" % tot_evaluations 
     284 
     285  return solved, func_max, collapse_data 
    130286 
    131287 
     
    134290####################################################################### 
    135291if __name__ == '__main__': 
    136   function_name = model.__name__ 
     292  from time import clock 
     293  start = clock() 
     294   
     295  from mystic.tools import wrap_function 
     296  from mystic.monitors import Null 
     297  fmon = Null() 
     298  model_evaluations, model = wrap_function(model0, [], fmon)   
     299  function_name = model0.__name__ 
    137300 
    138301  H_mean = 6.5    #NOTE: SET THE 'mean' HERE! 
    139302  H_range = 1.0   #NOTE: SET THE 'range' HERE! 
    140   nx = 2  #NOTE: SET THE NUMBER OF 'h' POINTS HERE! 
    141   ny = 2  #NOTE: SET THE NUMBER OF 'a' POINTS HERE! 
    142   nz = 2  #NOTE: SET THE NUMBER OF 'v' POINTS HERE! 
     303  nx = 5  #NOTE: SET THE NUMBER OF 'h' POINTS HERE! 
     304  ny = 5  #NOTE: SET THE NUMBER OF 'a' POINTS HERE! 
     305  nz = 5  #NOTE: SET THE NUMBER OF 'v' POINTS HERE! 
    143306  target = (H_mean,) 
    144307  error = (H_range,) 
     
    158321  print "...SETTINGS..." 
    159322  print "npop = %s" % npop 
     323  print "ngen = %s" %ngen 
     324  print "ngcol = %s" %ngcol 
    160325  print "maxiter = %s" % maxiter 
    161326  print "maxfun = %s" % maxfun 
     
    192357  npts = (nx,ny,nz) 
    193358  bounds = (lower_bounds,upper_bounds) 
    194   solved, diameter = maximize(pars,npts,bounds) 
     359  solved, diameter, collapse_data = maximize(pars,npts,bounds) 
    195360 
    196361  from numpy import array 
     
    203368 
    204369  print "expect: %s" % str( c.get_expect(model) ) 
    205  
     370   
     371  elapsed = (clock() - start) 
     372   
     373  print "########################" 
     374  print 'RUNTIME = %s' %elapsed 
     375  print 'COLLAPSE DATA= %s' %collapse_data 
     376  print 'MODEL Evaluations = %s' %model_evaluations 
    206377# EOF 
Note: See TracChangeset for help on using the changeset viewer.