Exemplo n.º 1
0
 def UseMonitor(self, min=None, max=None):
     from mystic.monitors import Monitor
     if type(min) is bool: self._minmon = Monitor() if min else None
     elif min is not None: self._minmon = min
     if type(max) is bool: self._maxmon = Monitor() if max else None
     elif max is not None: self._maxmon = max
     return
Exemplo n.º 2
0
def test_nested_solver(nested, solver):

    from mystic.monitors import Monitor
    evalmon = Monitor()
    stepmon = Monitor()

    from mystic.math.measures import mean, spread

    @with_spread(5.0)
    @with_mean(5.0)
    def constraints(x):
        return x

    def cost(x):
        return abs(sum(x) - 5.0)

    from numpy import array
    nested = nested(5, 4)
    nested.SetEvaluationMonitor(evalmon)
    nested.SetGenerationMonitor(stepmon)
    nested.SetConstraints(constraints)
    nested.SetNestedSolver(solver)
    nested.Solve(cost, disp=False)
    y = nested.Solution()

    assert almostEqual(mean(y), 5.0, tol=1e-15)
    assert almostEqual(spread(y), 5.0, tol=1e-15)
    assert almostEqual(cost(y), 4 * (5.0), tol=1e-6)
Exemplo n.º 3
0
def optimize(cost,lb,ub):
  from pathos.pools import ProcessPool as Pool
  from mystic.solvers import DifferentialEvolutionSolver2
  from mystic.termination import CandidateRelativeTolerance as CRT
  from mystic.strategy import Best1Exp
  from mystic.monitors import VerboseMonitor, Monitor
  from mystic.tools import random_seed

  random_seed(123)

 #stepmon = VerboseMonitor(100)
  stepmon = Monitor()
  evalmon = Monitor()

  ndim = len(lb) # [(1 + RVend) - RVstart] + 1

  solver = DifferentialEvolutionSolver2(ndim,npop)
  solver.SetRandomInitialPoints(min=lb,max=ub)
  solver.SetStrictRanges(min=lb,max=ub)
  solver.SetEvaluationLimits(maxiter,maxfun)
  solver.SetEvaluationMonitor(evalmon)
  solver.SetGenerationMonitor(stepmon)
  solver.SetMapper(Pool().map)

  tol = convergence_tol
  solver.Solve(cost,termination=CRT(tol,tol),strategy=Best1Exp, \
               CrossProbability=crossover,ScalingFactor=percent_change)

  print("solved: %s" % solver.bestSolution)
  scale = 1.0
  diameter_squared = -solver.bestEnergy / scale  #XXX: scale != 0
  func_evals = solver.evaluations
  return diameter_squared, func_evals
Exemplo n.º 4
0
def test_inner_solver(nested, solver):

    from mystic.monitors import Monitor
    evalmon = Monitor()
    stepmon = Monitor()

    from mystic.math.measures import mean, spread

    @with_spread(5.0)
    @with_mean(5.0)
    def constraints(x):
        return x

    def cost(x):
        return abs(sum(x) - 5.0)

    from numpy import array
    solver = solver(5)
    lb, ub = [0, 0, 0, 0, 0], [100, 100, 100, 100, 100]
    solver.SetRandomInitialPoints(lb, ub)
    solver.SetConstraints(constraints)
    solver.SetStrictRanges(lb, ub)
    nested = nested(5, 4)
    nested.SetEvaluationMonitor(evalmon)
    nested.SetGenerationMonitor(stepmon)
    nested.SetNestedSolver(solver)
    nested.Solve(cost, disp=False)
    y = nested.Solution()

    assert almostEqual(mean(y), 5.0, tol=1e-15)
    assert almostEqual(spread(y), 5.0, tol=1e-15)
    assert almostEqual(cost(y), 4 * (5.0), tol=1e-6)
Exemplo n.º 5
0
def dakota(cost, lb, ub):
    from mystic.solvers import DifferentialEvolutionSolver2
    from mystic.termination import CandidateRelativeTolerance as CRT
    from mystic.strategy import Best1Exp
    from mystic.monitors import VerboseMonitor, Monitor
    from mystic.tools import getch, random_seed

    random_seed(123)

    #stepmon = VerboseMonitor(100)
    stepmon = Monitor()
    evalmon = Monitor()

    ndim = len(lb)  # [(1 + RVend) - RVstart] + 1

    solver = DifferentialEvolutionSolver2(ndim, npop)
    solver.SetRandomInitialPoints(min=lb, max=ub)
    solver.SetStrictRanges(min=lb, max=ub)
    solver.SetEvaluationLimits(maxiter, maxfun)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)

    tol = convergence_tol
    solver.Solve(cost,termination=CRT(tol,tol),strategy=Best1Exp, \
                 CrossProbability=crossover,ScalingFactor=percent_change)

    print(solver.bestSolution)
    diameter = -solver.bestEnergy / scale
    func_evals = solver.evaluations
    return diameter, func_evals
Exemplo n.º 6
0
def local_optimize(cost,x0,lb,ub):
  from mystic.solvers import PowellDirectionalSolver
  from mystic.termination import NormalizedChangeOverGeneration as NCOG
  from mystic.monitors import VerboseMonitor, Monitor

  maxiter = 1000
  maxfun = 1e+6
  convergence_tol = 1e-4

 #def func_unpickle(filename):
 #  """ standard pickle.load of function from a File """
 #  import dill as pickle
 #  return pickle.load(open(filename,'r'))

 #stepmon = VerboseMonitor(100)
  stepmon = Monitor()
  evalmon = Monitor()

  ndim = len(lb)

  solver = PowellDirectionalSolver(ndim)
  solver.SetInitialPoints(x0)
  solver.SetStrictRanges(min=lb,max=ub)
  solver.SetEvaluationLimits(maxiter,maxfun)
  solver.SetEvaluationMonitor(evalmon)
  solver.SetGenerationMonitor(stepmon)

  tol = convergence_tol
 #cost = func_unpickle(cost)  #XXX: regenerate cost function from file
  solver.Solve(cost, termination=NCOG(tol))

  solved_params = solver.bestSolution
  solved_energy = solver.bestEnergy
  func_evals = solver.evaluations
  return solved_params, solved_energy, func_evals
Exemplo n.º 7
0
def test_multi_liner(solver):

    from mystic.monitors import Monitor
    evalmon = Monitor()
    stepmon = Monitor()

    from mystic.math.measures import mean, spread

    @with_spread(5.0)
    @with_mean(5.0)
    def constraints(x):
        return x

    def cost(x):
        return abs(sum(x) - 5.0)

    from numpy import array
    x = array([1, 2, 3, 4, 5])
    solver = solver(len(x))
    solver.SetInitialPoints(x)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)
    solver.SetConstraints(constraints)
    solver.Solve(cost, disp=False)
    y = solver.Solution()

    assert almostEqual(mean(y), 5.0, tol=1e-15)
    assert almostEqual(spread(y), 5.0, tol=1e-15)
    assert almostEqual(cost(y), 4 * (5.0), tol=1e-6)
Exemplo n.º 8
0
def local_optimize(cost, x0, lb, ub):
    from mystic.solvers import PowellDirectionalSolver
    from mystic.termination import NormalizedChangeOverGeneration as NCOG
    from mystic.monitors import VerboseMonitor, Monitor

    maxiter = 1000
    maxfun = 1e+6
    convergence_tol = 1e-4

    #stepmon = VerboseMonitor(100)
    stepmon = Monitor()
    evalmon = Monitor()

    ndim = len(lb)

    solver = PowellDirectionalSolver(ndim)
    solver.SetInitialPoints(x0)
    solver.SetStrictRanges(min=lb, max=ub)
    solver.SetEvaluationLimits(maxiter, maxfun)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)

    tol = convergence_tol
    solver.Solve(cost, termination=NCOG(tol))

    solved_params = solver.bestSolution
    solved_energy = solver.bestEnergy
    func_evals = solver.evaluations
    return solved_params, solved_energy, func_evals
Exemplo n.º 9
0
 def __update_allSolvers(self, results):
     'replace allSolvers with solvers found in results'
     #NOTE: apparently, monitors internal to the solver don't work as well
     # reconnect monitors; save all solvers
     fcalls = [getattr(s, '_fcalls', [0])[0] for s in self._allSolvers]
     from mystic.monitors import Monitor
     while results:  #XXX: option to not save allSolvers? skip this and _copy
         _solver, _stepmon, _evalmon = results.pop()
         lr = len(results)
         sm, em = Monitor(), Monitor()
         s = self._allSolvers[lr]
         ls, le = len(s._stepmon), len(s._evalmon)
         # gather old and new results in monitors
         _solver._stepmon[:] = s._stepmon
         sm._x, sm._y, sm._id, sm._info = _stepmon
         _solver._stepmon[ls:] = sm[ls:]
         del sm
         _solver._evalmon[:] = s._evalmon
         em._x, em._y, em._id, em._info = _evalmon
         _solver._evalmon[le:] = em[le:]
         del em
         if not _solver._fcalls[0]:  #FIXME: HACK workaround dropped _fcalls
             lm = len(_solver._evalmon)  # ...but only works if has evalmon
             _solver._fcalls[0] = fcalls[lr] or \
                                  (lm if _solver.Terminated() else 0)
             #(le if s.Terminated() else 0)
         self._allSolvers[lr] = _solver  #XXX: update not replace?
     return
Exemplo n.º 10
0
    def optimize(cost, bounds, tolerance, _constraints):
        (lb, ub) = bounds
        from mystic.solvers import DifferentialEvolutionSolver2
        from mystic.termination import VTR
        from mystic.strategy import Best1Exp
        from mystic.monitors import VerboseMonitor, Monitor
        from mystic.tools import random_seed
        if debug: random_seed(123)
        evalmon = Monitor()
        stepmon = Monitor()
        if debug: stepmon = VerboseMonitor(10)

        ndim = len(lb)
        solver = DifferentialEvolutionSolver2(ndim, npop)
        solver.SetRandomInitialPoints(min=lb, max=ub)
        solver.SetStrictRanges(min=lb, max=ub)
        solver.SetEvaluationLimits(maxiter, maxfun)
        solver.SetEvaluationMonitor(evalmon)
        solver.SetGenerationMonitor(stepmon)
        solver.Solve(cost,termination=VTR(tolerance),strategy=Best1Exp, \
                     CrossProbability=crossover,ScalingFactor=percent_change, \
                     constraints = _constraints)

        solved = solver.Solution()
        diameter_squared = solver.bestEnergy
        func_evals = len(evalmon)
        return solved, diameter_squared, func_evals
Exemplo n.º 11
0
def _boundbox(monitor, fx=None, mins=None, maxs=None, **kwds):
    '''produce a bounding-box to facilitate interpolation at the given points

    Input:
      monitor: a mystic monitor instance
      fx: a function f(x) to evaluate at new points; if None, use f(x) = nan
      mins: a list of floats defining minima of the bounding box, or None
      maxs: a list of floats defining maxima of the bounding box, or None
      all: if True, include the initial monitor points in the return

    Output:
      a mystic monitor instance containing the requested boundbox points

    NOTE:
      if mins is None, then use the minima found in the monitor instance.
      Similarly for maxs.
    '''
    all = kwds['all'] if 'all' in kwds else False

    import numpy as np
    f = (lambda x: np.nan) if fx is None else fx

    from mystic.monitors import Monitor                #XXX: copy or not?
    mon = Monitor() if monitor is None else monitor[:] #XXX: what if empty?
    _mon = Monitor()

    x = np.array(mon._x)
    # get 'mins'&'maxs' to use for 'axes' to define bounding box
    if len(x):
        mins = x.T.min(axis=-1) if mins is None else np.array(mins)
        #if not hasattr(mins, '__len__'): mins = (mins,)
    else:
        mins = None
    if len(x):
        maxs = x.T.max(axis=-1) if maxs is None else np.array(maxs)
        #if not hasattr(maxs, '__len__'): maxs = (maxs,)
    else:
        maxs = None

    # add points at corners of boundbox (don't include existing points)
    if (mins is None) or (maxs is None) or not mins.shape or not maxs.shape:
        # skip bounding box if 'min'&'max' points are already in monitors
        pass
    else:
        r = np.stack(np.meshgrid(*zip(mins,maxs)),-1).reshape(-1,len(x.T))
        n = [_mon(i,f(i)) for i in r if not _isin(i,x)]
        del r, n
    del mins, maxs, x
    return mon + _mon if all else _mon #XXX: or mon.extend(_mon)?
Exemplo n.º 12
0
    def SetGenerationMonitor(self, monitor, new=False):
        """select a callable to monitor (x, f(x)) after each solver iteration

input::
    - a monitor instance or monitor type used to track (x, f(x)). Any data
      collected in an existing generation monitor will be prepended, unless
      new is True."""
        from mystic.monitors import Null, Monitor  #, CustomMonitor
        if monitor is None: monitor = Null()
        current = Null() if new else self._stepmon
        if current is monitor: current = Null()
        if isinstance(monitor, Monitor):  # is Monitor()
            self._stepmon = monitor
            self._stepmon.prepend(current)
        elif isinstance(monitor, Null) or monitor == Null:  # is Null() or Null
            self._stepmon = Monitor()  #XXX: don't allow Null
            self._stepmon.prepend(current)
        elif hasattr(monitor, '__module__'):  # is CustomMonitor()
            if monitor.__module__ in ['mystic._genSow']:
                self._stepmon = monitor  #FIXME: need .prepend(current)
        else:
            raise TypeError("'%s' is not a monitor instance" % monitor)
        self.energy_history = None  # sync with self._stepmon
        self.solution_history = None  # sync with self._stepmon
        return
Exemplo n.º 13
0
    def UseMonitor(self, min=None, max=None):
        """track parameter trajectories with a monitor(s)

        Input:
          min: monitor instance to track minima; if True, use a new Monitor
          max: monitor instance to track maxima; if True, use a new Monitor

        Output:
          None
        """
        from mystic.monitors import Monitor
        if type(min) is bool: self._minmon = Monitor() if min else None
        elif min is not None: self._minmon = min
        if type(max) is bool: self._maxmon = Monitor() if max else None
        elif max is not None: self._maxmon = max
        return
Exemplo n.º 14
0
def write_monitor(steps, energy, id=[]):
    from mystic.monitors import Monitor
    mon = Monitor()
    mon._x = steps[:]
    mon._y = energy[:]
    mon._id = id[:]
    return mon
Exemplo n.º 15
0
    def _configure(self, model, bounds, stop=None, **kwds):
        """configure ensemble solver from objective and other solver options"""
        monitor = kwds.get('monitor', None)
        evalmon = kwds.get('evalmon', None)
        penalty = kwds.get('penalty', None)
        constraints = kwds.get('constraints', None)

        from mystic.monitors import Monitor
        # configure monitor
        monitor = Monitor() if monitor is None else monitor

        # get dimensions
        ndim = len(bounds)
        _min, _max = zip(*bounds)

        # configure ensemble solver
        self.solver = self.sprayer(ndim, self.npts)
        self.solver.SetNestedSolver(self.seeker)
        self.solver.SetMapper(self.map)
        self.solver.SetObjective(model)
        self.solver.SetConstraints(constraints)
        self.solver.SetPenalty(penalty)
        if stop: self.solver.SetTermination(stop)
        if evalmon is not None: self.solver.SetEvaluationMonitor(evalmon)
        if monitor is not None: self.solver.SetGenerationMonitor(monitor) #NOTE: may be xy,-z
        self.solver.SetStrictRanges(min=_min, max=_max)
        return
Exemplo n.º 16
0
 def func(x, z=None):
     if not hasattr(mask, '__call__'):
         _mask = mask
     else:
         _mask = mask(x, z)
     if z is None and hasattr(x, '_x') and hasattr(x, '_y'):
         from copy import copy
         m = copy(x)
         mon = True
     else:
         from mystic.monitors import Monitor
         m = Monitor()
         m._x, m._y = x, z
         mon = False
     ax = True if hasattr(m._x, 'tolist') else False
     ay = True if hasattr(m._y, 'tolist') else False
     from numpy import asarray
     m._x = asarray(m._x)[_mask]
     m._y = asarray(m._y)[_mask]
     if not ax: m._x = m._x.tolist()
     if not ay: m._y = m._y.tolist()
     if mon:
         try:
             ai = True if hasattr(m._id, 'tolist') else False
             m._id = array(m._id)[_mask]
             if not ai: m._id = m._id.tolist()
         except IndexError:
             pass  #XXX: m._id = []
         return m
     return m._x, m._y
Exemplo n.º 17
0
def write_monitor(steps, energy, id=[], k=None):
    from mystic.monitors import Monitor
    mon = Monitor()
    mon.k = k
    mon._x.extend(steps)
    mon._y.extend(mon._k(energy, iter))
    mon._id.extend(id)
    return mon
Exemplo n.º 18
0
def optimize(cost,_bounds,_constraints):
  from mystic.solvers import DifferentialEvolutionSolver2
  from mystic.termination import ChangeOverGeneration as COG
  from mystic.strategy import Best1Exp
  from mystic.monitors import VerboseMonitor, Monitor
  from mystic.tools import random_seed
  from mystic.termination import Or, CollapseWeight, CollapsePosition, state


  if debug:
      random_seed(123) # or 666 to force impose_unweighted reweighting
      stepmon = VerboseMonitor(1,1)
  else:
      stepmon = VerboseMonitor(10) if verbose else Monitor()
  stepmon._npts = npts
  evalmon = Monitor()

  lb,ub = _bounds
  ndim = len(lb)

  solver = DifferentialEvolutionSolver2(ndim,npop)
  solver.SetRandomInitialPoints(min=lb,max=ub)
  solver.SetStrictRanges(min=lb,max=ub)
  solver.SetEvaluationLimits(maxiter,maxfun)
  solver.SetEvaluationMonitor(evalmon)
  solver.SetGenerationMonitor(stepmon)
  solver.SetConstraints(_constraints)

  tol = convergence_tol
  term = Or(COG(tol,ngen), CollapseWeight(), CollapsePosition())
  solver.Solve(cost,termination=term,strategy=Best1Exp, disp=verbose, \
               CrossProbability=crossover,ScalingFactor=percent_change)
 #while collapse and solver.Collapse(verbose): #XXX: total_evaluations?
 #    if debug: print(state(solver._termination).keys())
 #    solver.Solve() #XXX: cost, term, strategy, cross, scale ?
 #    if debug: solver.SaveSolver('debug.pkl')

  solved = solver.bestSolution
 #print("solved: %s" % solver.Solution())
  func_max = MINMAX * solver.bestEnergy       #NOTE: -solution assumes -Max
 #func_max = 1.0 + MINMAX*solver.bestEnergy   #NOTE: 1-sol => 1-success = fail
  func_evals = solver.evaluations
  from mystic.munge import write_support_file
  write_support_file(stepmon, npts=npts)
  return solved, func_max, func_evals
Exemplo n.º 19
0
def fmin_powell(cost, x0, full=1, disp=1, monitor=0):
    """ change default behavior for selected optimizers """
    from mystic.solvers import fmin_powell as solver
    from mystic.monitors import Monitor, VerboseMonitor
    if monitor: mon = VerboseMonitor(10)
    else: mon = Monitor()
    npop = 10*len(x0)
    solved = solver(cost, x0, npop=npop, full_output=full,
                                         disp=disp, itermon=mon, handler=0)
    # return: solution, energy, generations, fevals
    return solved[0], solved[1], solved[3], solved[4]
Exemplo n.º 20
0
def run_once():
    simplex = Monitor()
    solver = fmin(2)
    solver.SetRandomInitialPoints([0, 0], [7, 7])
    solver.SetGenerationMonitor(simplex)
    solver.Solve(CostFunction, termination=CRT())
    sol = solver.Solution()

    for x in simplex.x:
        sam.putarray('x', x)
        sam.eval("plot(x([1,2,3,1],1),x([1,2,3,1],2),'k-')")
Exemplo n.º 21
0
def extrapolate(x, z=None, method=None, mins=None, maxs=None, **kwds):
    '''extrapolate a bounding-box for the given points

    Input:
      x: an array of shape (npts, dim) or (npts,)
      z: an array of shape (npts,)
      method: a function f(x) to generate new points; if None, use f(x) = nan
      mins: a list of floats defining minima of the bounding box, or None
      maxs: a list of floats defining maxima of the bounding box, or None
      all: if True, include the initial (x,z) points in the return

    Output:
      a tuple of (x,z) containing the requested boundbox points

    NOTE:
      if z is None, return a tuple (x,) with the requested boundbox points.

    NOTE:
      if mins is None, then use the minima found in x. Similarly for maxs.

    NOTE:
      method can take a function, None, a boolean, or a string. If method is
      True, interpolate a cost function using interpf with method='thin_plate'
      (or 'rbf' if scipy is not found). If method is False, return the original
      input. Alternately, method can be any one of ('rbf','linear','cubic',
      'nearest','inverse','gaussian','multiquadric','quintic','thin_plate').
    '''
    kwds.setdefault('all', True)
    import numpy as np
    output = True
    if z is None:
        z = np.nan * np.ones(len(x))
        output = False
        method = None  # ignore method
    xtype = getattr(x, 'dtype', None)
    ztype = getattr(z, 'dtype', None)
    if xtype: x = x.tolist()
    if ztype: z = z.tolist()
    if method:
        if method is True:
            method = 'thin_plate'
        if not hasattr(method, '__call__'):
            method = _to_objective(interpf(x, z, method=method))
    from mystic.monitors import Monitor
    mon = Monitor()
    mon._x = x
    mon._y = z
    if (method is None) or method:
        mon = _boundbox(mon, fx=method, mins=mins, maxs=maxs, **kwds)
    x = np.array(mon._x, dtype=xtype) if xtype else mon._x
    z = np.array(mon._y, dtype=ztype) if ztype else mon._y
    return (x, z) if output else x
Exemplo n.º 22
0
def de_solve(CF):
    solver = DifferentialEvolutionSolver(ND, NP)
    solver.enable_signal_handler()
    stepmon = Monitor()
    solver.SetRandomInitialPoints(min=minrange, max=maxrange)
    solver.SetStrictRanges(min=minrange, max=maxrange)
    solver.SetEvaluationLimits(generations=MAX_GENERATIONS)
    solver.SetGenerationMonitor(stepmon)
    termination = ChangeOverGeneration(generations=generations)
    solver.Solve(CF, termination=termination, strategy=Rand1Exp, \
                 sigint_callback = plot_sol(solver))
    solution = solver.Solution()
    return solution, stepmon
Exemplo n.º 23
0
def run_once(x0, x1):
    simplex = Monitor()
    xinit = [x0, x1]

    solver = fmin(len(xinit))
    solver.SetInitialPoints(xinit)
    solver.SetGenerationMonitor(simplex)
    solver.Solve(rosen, termination=CRT())
    sol = solver.Solution()

    for x in simplex.x:
        sam.putarray('x', x)
        sam.eval("plot(x([1,2,3,1],1),x([1,2,3,1],2),'w-')")
Exemplo n.º 24
0
def mystic_optimize(point):
    from mystic.monitors import Monitor, VerboseMonitor
    from mystic.tools import getch, random_seed
    random_seed(123)
    from mystic.solvers import NelderMeadSimplexSolver as fmin
    from mystic.termination import CandidateRelativeTolerance as CRT
    simplex, esow = VerboseMonitor(50), Monitor()
    solver = fmin(len(point))
    solver.SetInitialPoints(point)
    solver.SetEvaluationMonitor(esow)
    solver.SetGenerationMonitor(simplex)
    solver.Solve(cost_function, CRT())
    solution = solver.Solution()
    return solution
Exemplo n.º 25
0
def mystic_optimize(point):
    from mystic.monitors import Monitor, VerboseMonitor
    from mystic.solvers import NelderMeadSimplexSolver as fmin
    from mystic.termination import CandidateRelativeTolerance as CRT
    simplex, esow = VerboseMonitor(50), Monitor()
    solver = fmin(len(point))
    solver.SetInitialPoints(point)
    min = [-100,-100,-100]; max = [100,100,100]
    solver.SetStrictRanges(min,max)
    solver.SetEvaluationMonitor(esow)
    solver.SetGenerationMonitor(simplex)
    solver.Solve(cost_function, CRT(1e-7,1e-7))
    solution = solver.Solution()
    return solution
Exemplo n.º 26
0
def mystic_optimize2(point):
    from mystic.monitors import Monitor, VerboseMonitor
    from mystic.tools import getch, random_seed
    random_seed(123)
    from mystic.solvers import DifferentialEvolutionSolver as de
    from mystic.termination import ChangeOverGeneration as COG
    NPOP = 50
    simplex, esow = VerboseMonitor(50), Monitor()
    solver = de(len(point),NPOP)
    solver.SetInitialPoints(point)
    solver.SetEvaluationMonitor(esow)
    solver.SetGenerationMonitor(simplex)
    solver.Solve(cost_function, COG(generations=100), \
                 CrossProbability=0.5, ScalingFactor=0.5)
    solution = solver.Solution()
    return solution
Exemplo n.º 27
0
def optimizeDE(cost,
               xmin,
               xmax,
               npop=40,
               maxiter=1000,
               maxfun=1e+6,
               convergence_tol=1e-5,
               ngen=100,
               crossover=0.9,
               percent_change=0.9,
               MINMAX=1,
               x0=[],
               radius=0.2,
               parallel=False,
               nodes=16):
    from mystic.solvers import DifferentialEvolutionSolver2
    from mystic.termination import ChangeOverGeneration as COG
    from mystic.strategy import Best1Exp
    from mystic.monitors import VerboseMonitor, Monitor
    from pathos.helpers import freeze_support
    freeze_support()  # help Windows use multiprocessing

    stepmon = VerboseMonitor(20)  # step for showing live update
    evalmon = Monitor()
    ndim = len(xmin)

    solver = DifferentialEvolutionSolver2(ndim, npop)
    if parallel:
        solver.SetMapper(Pool(nodes).map)
    if x0 == []:
        solver.SetRandomInitialPoints(xmin, xmax)
    else:
        solver.SetInitialPoints(x0, radius)
    solver.SetStrictRanges(xmin, xmax)
    solver.SetEvaluationLimits(maxiter, maxfun)
    solver.SetEvaluationMonitor(evalmon)
    solver.SetGenerationMonitor(stepmon)
    tol = convergence_tol
    solver.Solve(cost,
                 termination=COG(tolerance=tol, generations=ngen),
                 strategy=Best1Exp,
                 CrossProbability=crossover,
                 ScalingFactor=percent_change)
    solved = solver.bestSolution
    func_max = MINMAX * solver.bestEnergy
    func_evals = solver.evaluations
    return solved, func_max, func_evals
Exemplo n.º 28
0
def run_once_xv():
    simplex = Monitor()
    y1 = y0*random.uniform(0.5,1.5)
    z1 = z0*random.uniform(0.5,1.5)
    xinit = [random.uniform(x0-40,x0+40), y1, z1, random.uniform(v0-0.1,v0+0.1)]

    solver = fmin(len(xinit))
    solver.SetInitialPoints(xinit)
    solver.SetGenerationMonitor(simplex)
    solver.Solve(cost_function, termination=CRT())
    sol = solver.Solution()
    print(sol)

    for x in simplex.x:
        sam.putarray('x',x)
        sam.eval("plot(x([1,2,3,1],1),x([1,2,3,1],2),'w-','LineWidth',2)")
    return sol
Exemplo n.º 29
0
 def SetGenerationMonitor(self, monitor, new=False):
     """select a callable to monitor (x, f(x)) after each solver iteration"""
     from mystic.monitors import Null, Monitor  #, CustomMonitor
     current = Null() if new else self._stepmon
     if isinstance(monitor, Monitor):  # is Monitor()
         self._stepmon = monitor
         self._stepmon.prepend(current)
     elif isinstance(monitor, Null) or monitor == Null:  # is Null() or Null
         self._stepmon = Monitor()  #XXX: don't allow Null
         self._stepmon.prepend(current)
     elif hasattr(monitor, '__module__'):  # is CustomMonitor()
         if monitor.__module__ in ['mystic._genSow']:
             self._stepmon = monitor  #FIXME: need .prepend(current)
     else:
         raise TypeError("'%s' is not a monitor instance" % monitor)
     self.energy_history = None  # sync with self._stepmon
     self.solution_history = None  # sync with self._stepmon
     return
Exemplo n.º 30
0
    def _configure(self, model, bounds, stop=None, monitor=None):
        from mystic.monitors import Monitor
        # configure monitor
        monitor = Monitor() if monitor is None else monitor

        # get dimensions
        ndim = len(bounds)
        _min, _max = zip(*bounds)

        # configure ensemble solver
        self.solver = self.sprayer(ndim, self.npts)
        self.solver.SetNestedSolver(self.seeker)
        self.solver.SetMapper(self.map)
        self.solver.SetObjective(model)
        if stop: self.solver.SetTermination(stop)
        self.solver.SetGenerationMonitor(monitor)  #NOTE: may be xy,-z
        self.solver.SetStrictRanges(min=_min, max=_max)
        return