Changeset 536


Ignore:
Timestamp:
07/29/12 22:10:39 (4 years ago)
Author:
mmckerns
Message:

added guard against null and empty logs in munge; added isNull;
allow non-boolean returns from termination to provide information for restarts

Location:
mystic/mystic
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • mystic/mystic/differential_evolution.py

    r519 r536  
    286286 
    287287        self.energy_history.append(self.bestEnergy) 
     288        termination(self) #XXX: initialize termination conditions, if needed 
    288289        self._stepmon(self.bestSolution[:], self.bestEnergy, id) 
    289         self.generations = 0  #XXX: above currently *not* counted as an iteration 
     290        self.generations = 0 #XXX: above currently *not* counted as an iteration 
    290291        if callback is not None: 
    291292            callback(self.bestSolution) 
     
    493494 
    494495        self.energy_history.append(self.bestEnergy) 
     496        termination(self) #XXX: initialize termination conditions, if needed 
    495497       #FIXME: StepMonitor works for 'pp'? 
    496498        self._stepmon(self.bestSolution[:], self.bestEnergy, id) 
  • mystic/mystic/monitors.py

    r480 r536  
    7575    def __setattr__(self, name, value): return self 
    7676    def __delattr__(self, name): return self 
     77    def __len__(self): return  #XXX ? 
    7778 
    7879class Monitor(object): 
     
    99100        self._info = [] 
    100101       #self._all = all 
     102 
     103    def __len__(self): 
     104        return len(self.x) 
    101105 
    102106    def info(self, message): 
  • mystic/mystic/munge.py

    r477 r536  
    11from mystic.tools import list_or_tuple_or_ndarray as sequence 
     2from mystic.tools import isNull 
    23 
    34# logfile reader 
     
    4647 
    4748def raw_to_converge(steps, energy): 
    48   if not sequence(steps[0][0]): 
    49     steps = [[step] for step in steps]  # needed when steps = [1,2,3,...] 
    50   steps = [zip(*step) for step in steps] # also can be used to revert 'steps' 
     49  if len(steps) > 0: 
     50    if not sequence(steps[0][0]): 
     51      steps = [[step] for step in steps]  # needed when steps = [1,2,3,...] 
     52    steps = [zip(*step) for step in steps] # also can be used to revert 'steps' 
    5153  return steps, energy 
    5254 
     
    5860 
    5961def write_raw_file(mon,log_file='paramlog.py',**kwds): 
     62  if isNull(mon): return  #XXX: throw error? warning? ??? 
    6063  steps, energy = read_monitor(mon) 
    6164  f = open(log_file,'w') 
     
    6972 
    7073def write_support_file(mon,log_file='paramlog.py'): 
     74  if isNull(mon): return  #XXX: throw error? warning? ??? 
    7175  monitor = write_monitor( *raw_to_support( *read_monitor(mon) ) ) 
    7276  write_raw_file(monitor,log_file,header="written in 'support' format") 
     
    7478 
    7579def write_converge_file(mon,log_file='paramlog.py'): 
     80  if isNull(mon): return  #XXX: throw error? warning? ??? 
    7681  monitor = write_monitor( *raw_to_converge( *read_monitor(mon) ) ) 
    7782  write_raw_file(monitor,log_file,header="written in 'converge' format") 
     
    131136 
    132137def __orig_write_support_file(mon,log_file='paramlog.py'): 
     138  if isNull(mon): return  #XXX: throw error? warning? ??? 
    133139  steps, energy = read_monitor(mon) 
    134140  log = [] 
    135   for p in range(len(steps[0])): 
    136     q = [] 
    137     for s in range(len(steps)): 
    138       q.append(steps[s][p]) 
    139     log.append(q)   
     141  if len(steps) > 0: 
     142    for p in range(len(steps[0])): 
     143      q = [] 
     144      for s in range(len(steps)): 
     145        q.append(steps[s][p]) 
     146      log.append(q)   
    140147  monitor = write_monitor(log, energy) 
    141148  write_raw_file(monitor,log_file) 
  • mystic/mystic/scipy_optimize.py

    r528 r536  
    215215            allvecs = [sim[0]] 
    216216        fsim[0] = func(x0) 
     217        termination(self) #XXX: initialize termination conditions, if needed 
    217218        self._stepmon(sim[0], fsim[0], id) # sim = all; "best" is sim[0] 
    218219 
     
    586587        self.popEnergy[0] = fval  #XXX: pointless? 
    587588        self.energy_history.append(self.bestEnergy) 
     589        termination(self) #XXX: initialize termination conditions, if needed 
    588590        self._stepmon(x, fval, id) # get initial values 
    589591 
  • mystic/mystic/termination.py

    r484 r536  
    77import numpy 
    88from numpy import absolute 
     9from __builtin__ import bool as _bool 
    910abs = absolute 
    1011Inf = numpy.Inf 
     12null = "" 
    1113 
    1214# a module level singleton. 
     
    1820 
    1921cost[-1] <= tolerance""" 
    20     def _VTR(inst): 
     22    doc = "VTR with %s" % {'tolerance':tolerance, 'target':target} 
     23    def _VTR(inst, bool=True): 
     24         if bool: bool = _bool 
     25         else: bool = lambda x:x 
    2126         hist = inst.energy_history 
    22          return abs(hist[-1] - target) <= tolerance 
     27         if not len(hist): return bool(null) 
     28         if abs(hist[-1] - target) <= tolerance: msg = doc 
     29         else: msg = null 
     30         return bool(msg) 
     31   #_VTR.__doc__ = "%s(**%s)" % tuple(doc.split(" with ")) 
     32    _VTR.__doc__ = doc 
    2333    return _VTR 
    2434 
     
    2737 
    2838cost[-g] - cost[-1] <= tolerance, where g=generations""" 
     39    doc = "ChangeOverGeneration with %s" % {'tolerance':tolerance, 
     40                                            'generations':generations} 
    2941    def _ChangeOverGeneration(inst): 
    3042         hist = inst.energy_history 
    3143         lg = len(hist) 
    32          if lg <= generations: return False 
    33          return (hist[-generations]-hist[-1]) <= tolerance 
     44         if lg <= generations: return "" 
     45         if (hist[-generations]-hist[-1]) <= tolerance: return doc 
     46         return "" 
     47    _ChangeOverGeneration.__doc__ = doc 
    3448    return _ChangeOverGeneration 
    3549 
     
    3953(cost[-g] - cost[-1]) /  0.5*(abs(cost[-g]) + abs(cost[-1])) <= tolerance""" 
    4054    eta = 1e-20 
     55    doc = "NormalizedChangeOverGeneration with %s" % {'tolerance':tolerance, 
     56                                                      'generations':generations} 
    4157    def _NormalizedChangeOverGeneration(inst): 
    4258         hist = inst.energy_history 
    4359         lg = len(hist) 
    44          if lg <= generations: return False 
     60         if lg <= generations: return "" 
    4561         diff = tolerance*(abs(hist[-generations])+abs(hist[-1])) + eta 
    46          return 2.0*(hist[-generations]-hist[-1]) <= diff 
     62         if 2.0*(hist[-generations]-hist[-1]) <= diff: return doc 
     63         return "" 
     64    _NormalizedChangeOverGeneration.__doc__ = doc 
    4765    return _NormalizedChangeOverGeneration 
    4866               
     
    5270abs(xi-x0) <= xtol & abs(fi-f0) <= ftol, where x=params & f=cost""" 
    5371    #NOTE: this termination expects nPop > 1 
     72    doc = "CandidateRelativeTolerance with %s" % {'xtol':xtol, 'ftol':ftol} 
    5473    def _CandidateRelativeTolerance(inst): 
    5574         sim = numpy.array(inst.population) 
    5675         fsim = numpy.array(inst.popEnergy) 
    5776         if not len(fsim[1:]): 
    58              print "Warning: Invalid termination condition (nPop < 2)" 
    59              return True 
     77             warn = "Warning: Invalid termination condition (nPop < 2)" 
     78             print warn 
     79             return warn 
    6080         #   raise ValueError, "Invalid termination condition (nPop < 2)" 
    6181         #FIXME: abs(inf - inf) will raise a warning... 
     
    6484         answer = answer and max(abs(fsim[0]-fsim[1:])) <= ftol 
    6585         numpy.seterr(invalid=errdict['invalid']) #FIXME: turn on warnings 
    66          return answer 
     86         if answer: return doc 
     87         return "" 
     88    _CandidateRelativeTolerance.__doc__ = doc 
    6789    return _CandidateRelativeTolerance 
    6890 
     
    7193 
    7294sum(abs(last_params - current_params)) <= tolerance""" 
     95    doc = "SolutionImprovement with %s" % {'tolerance':tolerance} 
    7396    def _SolutionImprovement(inst): 
    7497        best = numpy.array(inst.bestSolution) 
     
    7699        update = best - trial #XXX: if inf - inf ? 
    77100        answer = numpy.add.reduce(abs(update)) <= tolerance 
    78         return answer 
     101        if answer: return doc 
     102        return "" 
     103    _SolutionImprovement.__doc__ = doc 
    79104    return _SolutionImprovement 
    80105 
     
    87112    #  original --> if generations: then return cost[-g] - cost[-1] < 0 
    88113    #           --> else: return fval != 0 and abs((best - fval)/fval) < tol 
     114    doc = "NormalizedCostTarget with %s" % {'fval':fval, 'tolerance':tolerance, 
     115                                            'generations':generations} 
    89116    def _NormalizedCostTarget(inst): 
    90117         if generations and fval == None: 
     
    92119             lg = len(hist) 
    93120             #XXX: throws error when hist is shorter than generations ? 
    94              return lg > generations and (hist[-generations]-hist[-1]) <= 0 
    95          if not generations and fval == None: return True 
    96          return abs(inst.bestEnergy-fval) <= abs(tolerance * fval) 
     121             if lg > generations and (hist[-generations]-hist[-1]) <= 0: 
     122                 return doc 
     123             return "" 
     124         if not generations and fval == None: return doc 
     125         if abs(inst.bestEnergy-fval) <= abs(tolerance * fval): return doc 
     126         return "" 
     127    _NormalizedCostTarget.__doc__ = doc 
    97128    return _NormalizedCostTarget 
    98129 
     
    103134 
    104135cost[-g] - cost[-1] <= gtol, where g=generations *or* cost[-1] <= ftol.""" 
     136    doc = "VTRChangeOverGeneration with %s" % {'ftol':ftol, 'gtol':gtol, 
     137                                               'generations':generations, 
     138                                               'target':target} 
    105139    def _VTRChangeOverGeneration(inst): 
    106140         hist = inst.energy_history 
    107141         lg = len(hist) 
    108142         #XXX: throws error when hist is shorter than generations ? 
    109          return (lg > generations and (hist[-generations]-hist[-1]) <= gtol)\ 
    110                 or ( abs(hist[-1] - target) <= ftol ) 
     143         if (lg > generations and (hist[-generations]-hist[-1]) <= gtol)\ 
     144                or ( abs(hist[-1] - target) <= ftol ): return doc 
     145         return "" 
     146    _VTRChangeOverGeneration.__doc__ = doc 
    111147    return _VTRChangeOverGeneration 
    112148 
     
    115151 
    116152abs(params - params[0]) <= tolerance""" 
     153    doc = "PopulationSpread with %s" % {'tolerance':tolerance} 
    117154    def _PopulationSpread(inst): 
    118155         sim = numpy.array(inst.population) 
     
    120157         #    print "Warning: Invalid termination condition (nPop < 2)" 
    121158         #    return True 
    122          return numpy.all(abs(sim - sim[0]) <= abs(tolerance * sim[0])) 
     159         if numpy.all(abs(sim - sim[0]) <= abs(tolerance * sim[0])): return doc 
     160         return "" 
     161    _PopulationSpread.__doc__ = doc 
    123162    return _PopulationSpread 
    124163 
     
    127166 
    128167sum( abs(gradient)**norm )**(1.0/norm) <= tolerance""" 
     168    doc = "GradientNormTolerance with %s" % {'tolerance':tolerance, 'norm':norm} 
    129169    def _GradientNormTolerance(inst): 
    130170        try: 
    131171            gfk = inst.gfk #XXX: need to ensure that gfk is an array ? 
    132172        except: 
    133             print "Warning: Invalid termination condition (no gradient)" 
    134             return True 
     173            warn = "Warning: Invalid termination condition (no gradient)" 
     174            print warn 
     175            return warn 
    135176        if norm == Inf: 
    136177            gnorm = numpy.amax(abs(gfk)) 
     
    141182           #XXX: as norm < -large, gnorm approaches amin(abs(gfk)) --> then -inf 
    142183            gnorm = numpy.sum(abs(gfk)**norm,axis=0)**(1.0/norm) 
    143         return gnorm <= tolerance 
     184        if gnorm <= tolerance: return doc 
     185        return "" 
     186    _GradientNormTolerance.__doc__ = doc 
    144187    return _GradientNormTolerance 
    145188 
  • mystic/mystic/tools.py

    r470 r536  
    251251from monitors import Null 
    252252 
     253def isNull(mon): 
     254    if isinstance(mon, Null): # is Null() 
     255        return True 
     256    if mon == Null:  # is Null 
     257        return True 
     258    return False 
     259 
    253260 
    254261if __name__=='__main__': 
Note: See TracChangeset for help on using the changeset viewer.