bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def init(self, **options): self.__dict__.update(options) self.lower = asarray(self.lower) self.lower[self.lower == numpy.NINF] = -_double_max self.upper = asarray(self.upper) self.upper[self.upper == numpy.PINF] = _double_max self.k = 0 self.accepted = 0 self.feval = 0 self.tests = 0
def init(self, **options): self.__dict__.update(options) self.lower = asarray(self.lower) self.lower = where(self.lower == numpy.NINF, -_double_max, self.lower) self.upper = asarray(self.upper) self.upper[self.upper == numpy.PINF] = _double_max self.k = 0 self.accepted = 0 self.feval = 0 self.tests = 0
100
def init(self, **options): self.__dict__.update(options) self.lower = asarray(self.lower) self.lower[self.lower == numpy.NINF] = -_double_max self.upper = asarray(self.upper) self.upper[self.upper == numpy.PINF] = _double_max self.k = 0 self.accepted = 0 self.feval = 0 self.tests = 0
def init(self, **options): self.__dict__.update(options) self.lower = asarray(self.lower) self.lower[self.lower == numpy.NINF] = -_double_max self.upper = asarray(self.upper) self.upper = where(self.upper == numpy.PINF, _double_max, self.upper) self.k = 0 self.accepted = 0 self.feval = 0 self.tests = 0
101
def update_guess(self, x0): std = minimum(sqrt(self.T)*ones(self.dims), (self.upper-self.lower)/3.0/self.learn_rate) x0 = asarray(x0) #xc = squeeze(random.normal(0, std*self.learn_rate, size=self.dims)) xc = squeeze(random.normal(0, 1.0, size=self.dims)) xnew = x0 + xc*std*self.learn_rate return xnew
defupdate_guess(self,x0):std=minimum(sqrt(self.T)*ones(self.dims),(self.upper-self.lower)/3.0/self.learn_rate)x0=asarray(x0)#xc=squeeze(random.normal(0,std*self.learn_rate,size=self.dims))xc=squeeze(random.normal(0,1.0,size=self.dims))xnew=x0+xc*std*self.learn_ratereturnxnew
102
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iter = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iters = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
103
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iter = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iter = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iters += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
104
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iter = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iter = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iters > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
105
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iter = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) lower = asarray(lower) upper = asarray(upper) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iter = 0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iters, schedule.accepted, retval else: return best_state.x, retval
106
def setmember1d( ar1, ar2 ): """Return an array of shape of ar1 containing 1 where the elements of ar1 are in ar2 and 0 otherwise.""" ar = numpy.concatenate( (ar1, ar2 ) ) perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) flag = ediff1d( aux, 1 ) == 0 indx = numpy.argsort( perm ) return numpy.take( flag, indx[:len( ar1 )] )
def setmember1d( ar1, ar2 ): """Return an array of shape of ar1 containing 1 where the elements of ar1 are in ar2 and 0 otherwise.""" ar = numpy.concatenate( (ar1, ar2 ) ) perm = numpy.argsort( ar ) aux = numpy.take( ar, perm ) flag = ediff1d( aux, 1 ) == 0 ii = numpy.where( flag * aux2 ) aux = perm[ii+1] perm[ii+1] = perm[ii] perm[ii] = aux indx = numpy.argsort( perm )[:len( ar1 )] return numpy.take( flag, indx )
107
def info(object=None,maxwidth=76,output=sys.stdout,): """Get help information for a function, class, or module. Example: >>> from scipy import * >>> info(polyval) polyval(p, x) Evaluate the polymnomial p at x. Description: If p is of length N, this function returns the value: p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] """ global _namedict, _dictlist if hasattr(object, '_ppimport_attr'): object = object._ppimport_attr elif hasattr(object,'_ppimport_importer') or \ hasattr(object, '_ppimport_module'): object = object._ppimport_module if object is None: info(info) elif isinstance(object, types.StringType): if _namedict is None: _namedict, _dictlist = makenamedict() numfound = 0 objlist = [] for namestr in _dictlist: try: obj = _namedict[namestr][object] if id(obj) in objlist: print >> output, "\n *** Repeat reference found in %s *** " % namestr else: objlist.append(id(obj)) print >> output, " *** Found in %s ***" % namestr info(obj) print >> output, "-"*maxwidth numfound += 1 except KeyError: pass if numfound == 0: print >> output, "Help for %s not found." % object else: print >> output, "\n *** Total of %d references found. ***" % numfound elif inspect.isfunction(object): name = object.func_name arguments = apply(inspect.formatargspec, inspect.getargspec(object)) if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif inspect.isclass(object): name = object.__name__ if hasattr(object, '__init__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__init__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc1 = inspect.getdoc(object) if doc1 is None: if hasattr(object,'__init__'): print >> output, inspect.getdoc(object.__init__) else: print >> output, inspect.getdoc(object) elif type(object) is types.InstanceType: ## check for __call__ method print >> output, "Instance of class: ", object.__class__.__name__ print >> output if hasattr(object, '__call__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__call__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" name = "<name>" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc = inspect.getdoc(object.__call__) if doc is not None: print >> output, inspect.getdoc(object.__call__) print >> output, inspect.getdoc(object) else: print >> output, inspect.getdoc(object) elif inspect.ismethod(object): name = object.__name__ arguments = apply(inspect.formatargspec, inspect.getargspec(object.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif hasattr(object, '__doc__'): print >> output, inspect.getdoc(object)
def info(object=None,maxwidth=76,output=sys.stdout,): """Get help information for a function, class, or module. Example: >>> from scipy import * >>> info(polyval) polyval(p, x) Evaluate the polymnomial p at x. Description: If p is of length N, this function returns the value: p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] """ global _namedict, _dictlist if hasattr(object,'_ppimport_importer') or \ hasattr(object, '_ppimport_module'): object = object._ppimport_module elif hasattr(object, '_ppimport_attr'): object = object._ppimport_attr elif hasattr(object,'_ppimport_importer') or \ hasattr(object, '_ppimport_module'): object = object._ppimport_module if object is None: info(info) elif isinstance(object, types.StringType): if _namedict is None: _namedict, _dictlist = makenamedict() numfound = 0 objlist = [] for namestr in _dictlist: try: obj = _namedict[namestr][object] if id(obj) in objlist: print >> output, "\n *** Repeat reference found in %s *** " % namestr else: objlist.append(id(obj)) print >> output, " *** Found in %s ***" % namestr info(obj) print >> output, "-"*maxwidth numfound += 1 except KeyError: pass if numfound == 0: print >> output, "Help for %s not found." % object else: print >> output, "\n *** Total of %d references found. ***" % numfound elif inspect.isfunction(object): name = object.func_name arguments = apply(inspect.formatargspec, inspect.getargspec(object)) if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif inspect.isclass(object): name = object.__name__ if hasattr(object, '__init__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__init__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc1 = inspect.getdoc(object) if doc1 is None: if hasattr(object,'__init__'): print >> output, inspect.getdoc(object.__init__) else: print >> output, inspect.getdoc(object) elif type(object) is types.InstanceType: ## check for __call__ method print >> output, "Instance of class: ", object.__class__.__name__ print >> output if hasattr(object, '__call__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__call__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" name = "<name>" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc = inspect.getdoc(object.__call__) if doc is not None: print >> output, inspect.getdoc(object.__call__) print >> output, inspect.getdoc(object) else: print >> output, inspect.getdoc(object) elif inspect.ismethod(object): name = object.__name__ arguments = apply(inspect.formatargspec, inspect.getargspec(object.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif hasattr(object, '__doc__'): print >> output, inspect.getdoc(object)
108
def info(object=None,maxwidth=76,output=sys.stdout,): """Get help information for a function, class, or module. Example: >>> from scipy import * >>> info(polyval) polyval(p, x) Evaluate the polymnomial p at x. Description: If p is of length N, this function returns the value: p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] """ global _namedict, _dictlist if hasattr(object, '_ppimport_attr'): object = object._ppimport_attr elif hasattr(object,'_ppimport_importer') or \ hasattr(object, '_ppimport_module'): object = object._ppimport_module if object is None: info(info) elif isinstance(object, types.StringType): if _namedict is None: _namedict, _dictlist = makenamedict() numfound = 0 objlist = [] for namestr in _dictlist: try: obj = _namedict[namestr][object] if id(obj) in objlist: print >> output, "\n *** Repeat reference found in %s *** " % namestr else: objlist.append(id(obj)) print >> output, " *** Found in %s ***" % namestr info(obj) print >> output, "-"*maxwidth numfound += 1 except KeyError: pass if numfound == 0: print >> output, "Help for %s not found." % object else: print >> output, "\n *** Total of %d references found. ***" % numfound elif inspect.isfunction(object): name = object.func_name arguments = apply(inspect.formatargspec, inspect.getargspec(object)) if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif inspect.isclass(object): name = object.__name__ if hasattr(object, '__init__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__init__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc1 = inspect.getdoc(object) if doc1 is None: if hasattr(object,'__init__'): print >> output, inspect.getdoc(object.__init__) else: print >> output, inspect.getdoc(object) elif type(object) is types.InstanceType: ## check for __call__ method print >> output, "Instance of class: ", object.__class__.__name__ print >> output if hasattr(object, '__call__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__call__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" name = "<name>" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc = inspect.getdoc(object.__call__) if doc is not None: print >> output, inspect.getdoc(object.__call__) print >> output, inspect.getdoc(object) else: print >> output, inspect.getdoc(object) elif inspect.ismethod(object): name = object.__name__ arguments = apply(inspect.formatargspec, inspect.getargspec(object.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif hasattr(object, '__doc__'): print >> output, inspect.getdoc(object)
def info(object=None,maxwidth=76,output=sys.stdout,): """Get help information for a function, class, or module. Example: >>> from scipy import * >>> info(polyval) polyval(p, x) Evaluate the polymnomial p at x. Description: If p is of length N, this function returns the value: p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1] """ global _namedict, _dictlist if hasattr(object, '_ppimport_attr'): object = object._ppimport_attr if object is None: info(info) elif isinstance(object, types.StringType): if _namedict is None: _namedict, _dictlist = makenamedict() numfound = 0 objlist = [] for namestr in _dictlist: try: obj = _namedict[namestr][object] if id(obj) in objlist: print >> output, "\n *** Repeat reference found in %s *** " % namestr else: objlist.append(id(obj)) print >> output, " *** Found in %s ***" % namestr info(obj) print >> output, "-"*maxwidth numfound += 1 except KeyError: pass if numfound == 0: print >> output, "Help for %s not found." % object else: print >> output, "\n *** Total of %d references found. ***" % numfound elif inspect.isfunction(object): name = object.func_name arguments = apply(inspect.formatargspec, inspect.getargspec(object)) if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif inspect.isclass(object): name = object.__name__ if hasattr(object, '__init__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__init__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc1 = inspect.getdoc(object) if doc1 is None: if hasattr(object,'__init__'): print >> output, inspect.getdoc(object.__init__) else: print >> output, inspect.getdoc(object) elif type(object) is types.InstanceType: ## check for __call__ method print >> output, "Instance of class: ", object.__class__.__name__ print >> output if hasattr(object, '__call__'): arguments = apply(inspect.formatargspec, inspect.getargspec(object.__call__.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" name = "<name>" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" doc = inspect.getdoc(object.__call__) if doc is not None: print >> output, inspect.getdoc(object.__call__) print >> output, inspect.getdoc(object) else: print >> output, inspect.getdoc(object) elif inspect.ismethod(object): name = object.__name__ arguments = apply(inspect.formatargspec, inspect.getargspec(object.im_func)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] arguments = ", ".join(arglist[1:]) else: arguments = "()" if len(name+arguments) > maxwidth: argstr = split_line(name, arguments, maxwidth) else: argstr = name + arguments print >> output, " " + argstr + "\n" print >> output, inspect.getdoc(object) elif hasattr(object, '__doc__'): print >> output, inspect.getdoc(object)
109
def __call__ (self, *args, **kwds): new_args = [] for a in args: if hasattr(a,'_ppimport_module') or \
def __call__ (self, *args, **kwds): new_args = [] for a in args: if hasattr(a,'_ppimport_module') or \
110
def __call__ (self, *args, **kwds): new_args = [] for a in args: if hasattr(a,'_ppimport_module') or \
def __call__ (self, *args, **kwds): new_args = [] for a in args: if hasattr(a,'_ppimport_module') or \
111
def _inspect_getfile(object):
def _inspect_getfile(object):
112
def nnlf(self, *args): # - sum (log pdf(x, theta)) # where theta are the parameters (including loc and scale) # try: x = args[-1] loc = args[-2] scale = args[-3] args = args[:-3] except IndexError: raise ValueError, "Not enough input arguments." if not self._argcheck(*args) or scale <= 0: return inf x = arr((x-loc) / scale) cond0 = (x <= self.a) | (x >= self.b) if (any(cond0)): return inf else: N = len(x) return self._nnlf(self, x, *args) + N*log(scale)
def nnlf(self, theta, x): # - sum (log pdf(x, theta)) # where theta are the parameters (including loc and scale) # try: x = args[-1] loc = args[-2] scale = args[-3] args = args[:-3] except IndexError: raise ValueError, "Not enough input arguments." if not self._argcheck(*args) or scale <= 0: return inf x = arr((x-loc) / scale) cond0 = (x <= self.a) | (x >= self.b) if (any(cond0)): return inf else: N = len(x) return self._nnlf(self, x, *args) + N*log(scale)
113
def nnlf(self, *args): # - sum (log pdf(x, theta)) # where theta are the parameters (including loc and scale) # try: x = args[-1] loc = args[-2] scale = args[-3] args = args[:-3] except IndexError: raise ValueError, "Not enough input arguments." if not self._argcheck(*args) or scale <= 0: return inf x = arr((x-loc) / scale) cond0 = (x <= self.a) | (x >= self.b) if (any(cond0)): return inf else: N = len(x) return self._nnlf(self, x, *args) + N*log(scale)
def nnlf(self, *args): # - sum (log pdf(x, theta)) # where theta are the parameters (including loc and scale) # try: loc = theta[-2] scale = theta[-1] args = tuple(theta[:-2]) except IndexError: raise ValueError, "Not enough input arguments." if not self._argcheck(*args) or scale <= 0: return inf x = arr((x-loc) / scale) cond0 = (x <= self.a) | (x >= self.b) if (any(cond0)): return inf else: N = len(x) return self._nnlf(self, x, *args) + N*log(scale)
114
def nnlf(self, *args): # - sum (log pdf(x, theta)) # where theta are the parameters (including loc and scale) # try: x = args[-1] loc = args[-2] scale = args[-3] args = args[:-3] except IndexError: raise ValueError, "Not enough input arguments." if not self._argcheck(*args) or scale <= 0: return inf x = arr((x-loc) / scale) cond0 = (x <= self.a) | (x >= self.b) if (any(cond0)): return inf else: N = len(x) return self._nnlf(self, x, *args) + N*log(scale)
def nnlf(self, *args): # - sum (log pdf(x, theta)) # where theta are the parameters (including loc and scale) # try: x = args[-1] loc = args[-2] scale = args[-3] args = args[:-3] except IndexError: raise ValueError, "Not enough input arguments." if not self._argcheck(*args) or scale <= 0: return inf x = arr((x-loc) / scale) cond0 = (x <= self.a) | (x >= self.b) if (any(cond0)): return inf else: N = len(x) return self._nnlf(self, x, *args) + N*log(scale)
115
def getnzmax(self): try: nzmax = self.nzmax except AttributeError: nzmax = 0 return nzmax
def getnzmax(self): try: nzmax = self.nzmax except AttributeError: try: nzmax = self.nnz except AtrributeError: nzmax = 0 return nzmax
116
def __init__(self, dist, xa=-10.0, xb=10.0, xtol=1e-14): self.dist = dist self.cdf = eval('%scdf'%dist) self.xa = xa self.xb = xb self.xtol = xtol self.vecfunc = sgf(self._single_call)
def __init__(self, dist, xa=-10.0, xb=10.0, xtol=1e-14): self.dist = dist self.cdf = eval('%scdf'%dist) self.xa = xa self.xb = xb self.xtol = xtol self.vecfunc = sgf(self._single_call)
117
def argsreduce(cond, *args): """Return a sequence of arguments converted to the dimensions of cond """ newargs = list(args) expand_arr = (cond==cond) for k in range(len(args)): newargs[k] = extract(cond,arr(args[k])*expand_arr) return newargs
defargsreduce(cond,*args):"""Returnasequenceofargumentsconvertedtothedimensionsofcond"""newargs=list(args)expand_arr=(cond==cond)forkinrange(len(args)):newargs[k]=extract(cond,arr(args[k])*expand_arr)returnnewargs
118
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = nan self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -scipy.inf if b is None: self.b = scipy.inf self.xa = xa self.xb = xb self.xtol = xtol self._size = 1 self.m = 0.0 self.moment_type = momtype self.vecfunc = sgf(self._ppf_single_call) self.vecentropy = sgf(self._entropy) self.expandarr = 1 if momtype == 0: self.generic_moment = sgf(self._mom0_sc) else: self.generic_moment = sgf(self._mom1_sc) cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2)
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = nan self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -scipy.inf if b is None: self.b = scipy.inf self.xa = xa self.xb = xb self.xtol = xtol self._size = 1 self.m = 0.0 self.moment_type = momtype self.vecfunc = sgf(self._ppf_single_call,otypes='d') self.vecentropy = sgf(self._entropy,otypes='d') self.veccdf = sgf(self._cdf_single_call,otypes='d') self.expandarr = 1 if momtype == 0: self.generic_moment = sgf(self._mom0_sc) else: self.generic_moment = sgf(self._mom1_sc) cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2)
119
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = nan self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -scipy.inf if b is None: self.b = scipy.inf self.xa = xa self.xb = xb self.xtol = xtol self._size = 1 self.m = 0.0 self.moment_type = momtype self.vecfunc = sgf(self._ppf_single_call) self.vecentropy = sgf(self._entropy) self.expandarr = 1 if momtype == 0: self.generic_moment = sgf(self._mom0_sc) else: self.generic_moment = sgf(self._mom1_sc) cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2)
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = nan self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -scipy.inf if b is None: self.b = scipy.inf self.xa = xa self.xb = xb self.xtol = xtol self._size = 1 self.m = 0.0 self.moment_type = momtype self.vecfunc = sgf(self._ppf_single_call) self.vecentropy = sgf(self._entropy) self.expandarr = 1 if momtype == 0: self.generic_moment = sgf(self._mom0_sc,otypes='d') else: self.generic_moment = sgf(self._mom1_sc) cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2)
120
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = nan self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -scipy.inf if b is None: self.b = scipy.inf self.xa = xa self.xb = xb self.xtol = xtol self._size = 1 self.m = 0.0 self.moment_type = momtype self.vecfunc = sgf(self._ppf_single_call) self.vecentropy = sgf(self._entropy) self.expandarr = 1 if momtype == 0: self.generic_moment = sgf(self._mom0_sc) else: self.generic_moment = sgf(self._mom1_sc) cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2)
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = nan self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -scipy.inf if b is None: self.b = scipy.inf self.xa = xa self.xb = xb self.xtol = xtol self._size = 1 self.m = 0.0 self.moment_type = momtype self.vecfunc = sgf(self._ppf_single_call) self.vecentropy = sgf(self._entropy) self.expandarr = 1 if momtype == 0: self.generic_moment = sgf(self._mom0_sc) else: self.generic_moment = sgf(self._mom1_sc,otypes='d') cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2)
121
def _rvs(self, *args): ## Use basic inverse cdf algorithm for RV generation as default. U = rand.sample(self._size) Y = self._ppf(U,*args) return Y
def def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] _rvs(self, def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] *args): def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] ## def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] Use def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] basic def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] inverse def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] cdf def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] algorithm def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] for def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] RV def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] generation def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] as def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] default. def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] U def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] = def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] rand.sample(self._size) def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] Y def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] = def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] self._ppf(U,*args) def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] return def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] Y def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0]
122
def _cdf(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0]
def _cdf(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0]
123
def ppf(self,q,*args,**kwds): """Percent point function (inverse of cdf) at q of the given RV.
def ppf(self,q,*args,**kwds): """Percent point function (inverse of cdf) at q of the given RV.
124
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle) self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle,otypes='d') self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
125
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle) self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle) self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
126
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle) self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle) self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
127
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle) self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
def __init__(self, a=0, b=scipy.inf, name=None, badvalue=None, moment_tol=1e-8,values=None,inc=1,longname=None, shapes=None, extradoc=None): if badvalue is None: badvalue = scipy.nan self.badvalue = badvalue self.a = a self.b = b self.invcdf_a = a self.invcdf_b = b self.name = name self.moment_tol = moment_tol self.inc = inc self._cdfvec = sgf(self._cdfsingle) self.return_integers = 1 self.vecentropy = vectorize(self._entropy)
128
def bench_random(self,level=5): from scipy.basic import linalg Numeric_solve = linalg.solve_linear_equations print print ' Solving system of linear equations' print ' =================================='
def bench_random(self,level=5): from scipy.basic import linalg basic_solve = linalg.solve_linear_equations print print ' Solving system of linear equations' print ' =================================='
129
def bench_random(self,level=5): from scipy.basic import linalg Numeric_solve = linalg.solve_linear_equations print print ' Solving system of linear equations' print ' =================================='
def bench_random(self,level=5): from scipy.basic import linalg Numeric_solve = linalg.solve_linear_equations print print ' Solving system of linear equations' print ' =================================='
130
def bench_random(self,level=5): from scipy.basic import linalg Numeric_inv = linalg.inverse print print ' Finding matrix inverse' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size]) # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i])
def bench_random(self,level=5): from scipy.basic import linalg basic_inv = linalg.inverse print print ' Finding matrix inverse' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size]) # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i])
131
def bench_random(self,level=5): from scipy.basic import linalg Numeric_inv = linalg.inverse print print ' Finding matrix inverse' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size]) # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i])
def bench_random(self,level=5): from scipy.basic import linalg Numeric_inv = linalg.inverse print print ' Finding matrix inverse' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size]) # large diagonal ensures non-singularity: for i in range(size): a[i,i] = 10*(.1+a[i,i])
132
def check_random(self): from scipy.basic import linalg Numeric_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) d1 = det(a) d2 = Numeric_det(a) assert_almost_equal(d1,d2)
def check_random(self): from scipy.basic import linalg basic_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) d1 = det(a) d2 = Numeric_det(a) assert_almost_equal(d1,d2)
133
def check_random(self): from scipy.basic import linalg Numeric_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) d1 = det(a) d2 = Numeric_det(a) assert_almost_equal(d1,d2)
def check_random(self): from scipy.basic import linalg Numeric_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) d1 = det(a) d2 = basic_det(a) assert_almost_equal(d1,d2)
134
def check_random_complex(self): from scipy.basic import linalg Numeric_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) + 2j*random([n,n]) d1 = det(a) d2 = Numeric_det(a) assert_almost_equal(d1,d2)
def check_random_complex(self): from scipy.basic import linalg basic_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) + 2j*random([n,n]) d1 = det(a) d2 = Numeric_det(a) assert_almost_equal(d1,d2)
135
def check_random_complex(self): from scipy.basic import linalg Numeric_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) + 2j*random([n,n]) d1 = det(a) d2 = Numeric_det(a) assert_almost_equal(d1,d2)
def check_random_complex(self): from scipy.basic import linalg Numeric_det = linalg.determinant n = 20 for i in range(4): a = random([n,n]) + 2j*random([n,n]) d1 = det(a) d2 = basic_det(a) assert_almost_equal(d1,d2)
136
def bench_random(self,level=5): from scipy.basic import linalg Numeric_det = linalg.determinant print print ' Finding matrix determinant' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic ' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size])
def bench_random(self,level=5): from scipy.basic import linalg basic_det = linalg.determinant print print ' Finding matrix determinant' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic ' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size])
137
def bench_random(self,level=5): from scipy.basic import linalg Numeric_det = linalg.determinant print print ' Finding matrix determinant' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic ' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size])
def bench_random(self,level=5): from scipy.basic import linalg Numeric_det = linalg.determinant print print ' Finding matrix determinant' print ' ==================================' print ' | contiguous | non-contiguous ' print '----------------------------------------------' print ' size | scipy | basic | scipy | basic ' for size,repeat in [(20,1000),(100,150),(500,2),(1000,1)][:-1]: repeat *= 2 print '%5s' % size, sys.stdout.flush() a = random([size,size])
138
def toeplitz(c,r=None): """ Construct a toeplitz matrix (i.e. a matrix with constant diagonals). Description: toeplitz(c,r) is a non-symmetric Toeplitz matrix with c as its first column and r as its first row. toeplitz(c) is a symmetric (Hermitian) Toeplitz matrix (r=c). See also: hankel """ isscalar = numpy.isscalar if isscalar(c) or isscalar(r): return c if r is None: r = c r[0] = conjugate(r[0]) c = conjugate(c) r,c = map(asarray_chkfinite,(r,c)) r,c = map(ravel,(r,c)) rN,cN = map(len,(r,c)) if r[0] != c[0]: print "Warning: column and row values don't agree; column value used." vals = r_[r[rN-1:0:-1], c] cols = mgrid[0:cN] rows = mgrid[rN:0:-1] indx = cols[:,newaxis]*ones((1,rN)) + \ rows[newaxis,:]*ones((cN,1)) - 1 return take(vals, indx)
def toeplitz(c,r=None): """ Construct a toeplitz matrix (i.e. a matrix with constant diagonals). Description: toeplitz(c,r) is a non-symmetric Toeplitz matrix with c as its first column and r as its first row. toeplitz(c) is a symmetric (Hermitian) Toeplitz matrix (r=c). See also: hankel """ isscalar = numpy.isscalar if isscalar(c) or isscalar(r): return c if r is None: r = c r[0] = conjugate(r[0]) c = conjugate(c) r,c = map(asarray_chkfinite,(r,c)) r,c = map(ravel,(r,c)) rN,cN = map(len,(r,c)) if r[0] != c[0]: print "Warning: column and row values don't agree; column value used." vals = r_[r[rN-1:0:-1], c] cols = mgrid[0:cN] rows = mgrid[rN:0:-1] indx = cols[:,newaxis]*ones((1,rN),dtype=int) + \ rows[newaxis,:]*ones((cN,1),dtype=int) - 1 return take(vals, indx)
139
def hankel(c,r=None): """ Construct a hankel matrix (i.e. matrix with constant anti-diagonals). Description: hankel(c,r) is a Hankel matrix whose first column is c and whose last row is r. hankel(c) is a square Hankel matrix whose first column is C. Elements below the first anti-diagonal are zero. See also: toeplitz """ isscalar = numpy.isscalar if isscalar(c) or isscalar(r): return c if r is None: r = zeros(len(c)) elif r[0] != c[-1]: print "Warning: column and row values don't agree; column value used." r,c = map(asarray_chkfinite,(r,c)) r,c = map(ravel,(r,c)) rN,cN = map(len,(r,c)) vals = r_[c, r[1:rN]] cols = mgrid[1:cN+1] rows = mgrid[0:rN] indx = cols[:,newaxis]*ones((1,rN)) + \ rows[newaxis,:]*ones((cN,1)) - 1 return take(vals, indx)
def hankel(c,r=None): """ Construct a hankel matrix (i.e. matrix with constant anti-diagonals). Description: hankel(c,r) is a Hankel matrix whose first column is c and whose last row is r. hankel(c) is a square Hankel matrix whose first column is C. Elements below the first anti-diagonal are zero. See also: toeplitz """ isscalar = numpy.isscalar if isscalar(c) or isscalar(r): return c if r is None: r = zeros(len(c)) elif r[0] != c[-1]: print "Warning: column and row values don't agree; column value used." r,c = map(asarray_chkfinite,(r,c)) r,c = map(ravel,(r,c)) rN,cN = map(len,(r,c)) vals = r_[c, r[1:rN]] cols = mgrid[1:cN+1] rows = mgrid[0:rN] indx = cols[:,newaxis]*ones((1,rN),dtype=int) + \ rows[newaxis,:]*ones((cN,1),dtype=int) - 1 return take(vals, indx)
140
def est_coef(self, Y): """ Estimate coefficients using lstsq, returning fitted values, Y and coefficients, but initialize is not called so no psuedo-inverse is calculated. """ Z = self.whiten(Y)
def est_coef(self, Y): """ Estimate coefficients using lstsq, returning fitted values, Y and coefficients, but initialize is not called so no psuedo-inverse is calculated. """ Z = self.whiten(Y)
141
def est_coef(self, Y): """ Estimate coefficients using lstsq, returning fitted values, Y and coefficients, but initialize is not called so no psuedo-inverse is calculated. """ Z = self.whiten(Y)
def est_coef(self, Y): """ Estimate coefficients using lstsq, returning fitted values, Y and coefficients, but initialize is not called so no psuedo-inverse is calculated. """ Z = self.whiten(Y)
142
def fit(self, Y, **keywords): """ Full \'fit\' of the model including estimate of covariance matrix, (whitened) residuals and scale.
def fit(self, Y, **keywords): """ Full \'fit\' of the model including estimate of covariance matrix, (whitened) residuals and scale.
143
def fit(self, Y, **keywords): """ Full \'fit\' of the model including estimate of covariance matrix, (whitened) residuals and scale.
def fit(self, Y, **keywords): """ Full \'fit\' of the model including estimate of covariance matrix, (whitened) residuals and scale.
144
def norm_resid(self): """ Residuals, normalized to have unit length.
defnorm_resid(self):"""Residuals,normalizedtohaveunitlength.
145
def norm_resid(self): """ Residuals, normalized to have unit length.
def norm_resid(self): """ Residuals, normalized to have unit length.
146
def Rsq(self, adjusted=False): """ Return the R^2 value for each row of the response Y. """ self.Ssq = N.std(self.Z,axis=0)**2 ratio = self.scale / self.Ssq if not adjusted: ratio *= ((Y.shape[0] - 1) / self.df_resid) return 1 - ratio
def Rsq(self, adjusted=False): """ Return the R^2 value for each row of the response Y. """ self.Ssq = N.std(self.Z,axis=0)**2 ratio = self.scale / self.Ssq if not adjusted: ratio *= ((self.Y.shape[0] - 1) / self.df_resid) return 1 - ratio
147
def vq(obs,code_book): """ Vector Quantization: assign features sets to codes in a code book. Description: Vector quantization determines which code in the code book best represents an observation of a target. The features of each observation are compared to each code in the book, and assigned the one closest to it. The observations are contained in the obs array. These features should be "whitened," or nomalized by the standard deviation of all the features before being quantized. The code book can be created using the kmeans algorithm or something similar. Note: This currently forces 32 bit math precision for speed. Anyone know of a situation where this undermines the accuracy of the algorithm? Arguments: obs -- 2D array. Each row of the array is an observation. The columns are the "features" seen during each observation The features must be whitened first using the whiten function or something equivalent. code_book -- 2D array. The code book is usually generated using the kmeans algorithm. Each row of the array holds a different code, and the columns are the features of the code. # c0 c1 c2 c3 code_book = [[ 1., 2., 3., 4.], #f0 [ 1., 2., 3., 4.], #f1 [ 1., 2., 3., 4.]]) #f2 Outputs: code -- 1D array. If obs is a NxM array, then a length M array is returned that holds the selected code book index for each observation. dist -- 1D array. The distortion (distance) between the observation and its nearest code Reference Test >>> code_book = array([[1.,1.,1.], ... [2.,2.,2.]]) >>> features = array([[ 1.9,2.3,1.7], ... [ 1.5,2.5,2.2], ... [ 0.8,0.6,1.7]]) >>> vq(features,code_book) (array([1, 1, 0],'i'), array([ 0.43588989, 0.73484692, 0.83066239])) """ try: import _vq from scipy.misc import _common_type ct = _common_type(obs,code_book) c_obs = obs.astype(ct) c_code_book = code_book.astype(ct) if ct == 'f': results = _vq.float_vq(c_obs,c_code_book) elif ct == 'd': results = _vq.double_vq(c_obs,c_code_book) else: results = py_vq(obs,code_book) except ImportError: print 'py' results = py_vq(obs,code_book) return results
def vq(obs,code_book): """ Vector Quantization: assign features sets to codes in a code book. Description: Vector quantization determines which code in the code book best represents an observation of a target. The features of each observation are compared to each code in the book, and assigned the one closest to it. The observations are contained in the obs array. These features should be "whitened," or nomalized by the standard deviation of all the features before being quantized. The code book can be created using the kmeans algorithm or something similar. Note: This currently forces 32 bit math precision for speed. Anyone know of a situation where this undermines the accuracy of the algorithm? Arguments: obs -- 2D array. Each row of the array is an observation. The columns are the "features" seen during each observation The features must be whitened first using the whiten function or something equivalent. code_book -- 2D array. The code book is usually generated using the kmeans algorithm. Each row of the array holds a different code, and the columns are the features of the code. # c0 c1 c2 c3 code_book = [[ 1., 2., 3., 4.], #f0 [ 1., 2., 3., 4.], #f1 [ 1., 2., 3., 4.]]) #f2 Outputs: code -- 1D array. If obs is a NxM array, then a length M array is returned that holds the selected code book index for each observation. dist -- 1D array. The distortion (distance) between the observation and its nearest code Reference Test >>> code_book = array([[1.,1.,1.], ... [2.,2.,2.]]) >>> features = array([[ 1.9,2.3,1.7], ... [ 1.5,2.5,2.2], ... [ 0.8,0.6,1.7]]) >>> vq(features,code_book) (array([1, 1, 0],'i'), array([ 0.43588989, 0.73484692, 0.83066239])) """ try: import _vq from scipy.misc import x_common_type ct = x_common_type(obs,code_book) c_obs = obs.astype(ct) c_code_book = code_book.astype(ct) if ct == 'f': results = _vq.float_vq(c_obs,c_code_book) elif ct == 'd': results = _vq.double_vq(c_obs,c_code_book) else: results = py_vq(obs,code_book) except ImportError: print 'py' results = py_vq(obs,code_book) return results
148
def vq(obs,code_book): """ Vector Quantization: assign features sets to codes in a code book. Description: Vector quantization determines which code in the code book best represents an observation of a target. The features of each observation are compared to each code in the book, and assigned the one closest to it. The observations are contained in the obs array. These features should be "whitened," or nomalized by the standard deviation of all the features before being quantized. The code book can be created using the kmeans algorithm or something similar. Note: This currently forces 32 bit math precision for speed. Anyone know of a situation where this undermines the accuracy of the algorithm? Arguments: obs -- 2D array. Each row of the array is an observation. The columns are the "features" seen during each observation The features must be whitened first using the whiten function or something equivalent. code_book -- 2D array. The code book is usually generated using the kmeans algorithm. Each row of the array holds a different code, and the columns are the features of the code. # c0 c1 c2 c3 code_book = [[ 1., 2., 3., 4.], #f0 [ 1., 2., 3., 4.], #f1 [ 1., 2., 3., 4.]]) #f2 Outputs: code -- 1D array. If obs is a NxM array, then a length M array is returned that holds the selected code book index for each observation. dist -- 1D array. The distortion (distance) between the observation and its nearest code Reference Test >>> code_book = array([[1.,1.,1.], ... [2.,2.,2.]]) >>> features = array([[ 1.9,2.3,1.7], ... [ 1.5,2.5,2.2], ... [ 0.8,0.6,1.7]]) >>> vq(features,code_book) (array([1, 1, 0],'i'), array([ 0.43588989, 0.73484692, 0.83066239])) """ try: import _vq from scipy.misc import _common_type ct = _common_type(obs,code_book) c_obs = obs.astype(ct) c_code_book = code_book.astype(ct) if ct == 'f': results = _vq.float_vq(c_obs,c_code_book) elif ct == 'd': results = _vq.double_vq(c_obs,c_code_book) else: results = py_vq(obs,code_book) except ImportError: print 'py' results = py_vq(obs,code_book) return results
def vq(obs,code_book): """ Vector Quantization: assign features sets to codes in a code book. Description: Vector quantization determines which code in the code book best represents an observation of a target. The features of each observation are compared to each code in the book, and assigned the one closest to it. The observations are contained in the obs array. These features should be "whitened," or nomalized by the standard deviation of all the features before being quantized. The code book can be created using the kmeans algorithm or something similar. Note: This currently forces 32 bit math precision for speed. Anyone know of a situation where this undermines the accuracy of the algorithm? Arguments: obs -- 2D array. Each row of the array is an observation. The columns are the "features" seen during each observation The features must be whitened first using the whiten function or something equivalent. code_book -- 2D array. The code book is usually generated using the kmeans algorithm. Each row of the array holds a different code, and the columns are the features of the code. # c0 c1 c2 c3 code_book = [[ 1., 2., 3., 4.], #f0 [ 1., 2., 3., 4.], #f1 [ 1., 2., 3., 4.]]) #f2 Outputs: code -- 1D array. If obs is a NxM array, then a length M array is returned that holds the selected code book index for each observation. dist -- 1D array. The distortion (distance) between the observation and its nearest code Reference Test >>> code_book = array([[1.,1.,1.], ... [2.,2.,2.]]) >>> features = array([[ 1.9,2.3,1.7], ... [ 1.5,2.5,2.2], ... [ 0.8,0.6,1.7]]) >>> vq(features,code_book) (array([1, 1, 0],'i'), array([ 0.43588989, 0.73484692, 0.83066239])) """ try: import _vq from scipy.misc import _common_type ct = _common_type(obs,code_book) c_obs = obs.astype(ct) c_code_book = code_book.astype(ct) if ct == 'f': results = _vq.float_vq(c_obs,c_code_book) elif ct == 'd': results = _vq.double_vq(c_obs,c_code_book) else: results = py_vq(obs,code_book) except ImportError: results = py_vq(obs,code_book) return results
149
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = MLab.asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
150
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,MLab.ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
151
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,MLab.ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
152
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize == None: mysize = [3] * len(im.shape) mysize = MLab.asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = MLab.mean(MLab.ravel(lVar)) # Compute result # f = lMean + (maximum(0, lVar - noise) ./ # maximum(lVar, noise)) * (im - lMean) # out = im - lMean im = lVar - noise im = MLab.maximum(im,0) lVar = MLab.maximum(lVar,noise) out = out / lVar out = out * im out = out + lMean return out
153
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) gist.plsys(savesys) nargs = len(args) if nargs == 0: y = scipy.squeeze(x) x = Numeric.arange(0,len(y)) if scipy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(scipy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if scipy.iscomplexobj(x) or scipy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = scipy.real(x) y = scipy.real(y) y = where(scipy.isfinite(y),y,0) y = scipy.squeeze(y) x = scipy.squeeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) if savesys > 0: gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) if savesys > 0: gist.plsys(savesys) nargs = len(args) if nargs == 0: y = scipy.squeeze(x) x = Numeric.arange(0,len(y)) if scipy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(scipy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if scipy.iscomplexobj(x) or scipy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = scipy.real(x) y = scipy.real(y) y = where(scipy.isfinite(y),y,0) y = scipy.squeeze(y) x = scipy.squeeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
154
def check_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, gamma(8)*gamma(8-4-3)/gamma(8-3)/gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi)* gamma(1+3-2)/gamma(1+0.5*3-2)/gamma(0.5+0.5*3)], [4, 0.5+4, 5./6+4, 1./9, (0.75)**4*sqrt(pi)* gamma(5./6+2./3*4)/gamma(0.5+4./3)*gamma(5./6+4./3)], ] for i, (a, b, c, x, v) in enumerate(values): cv = hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
def check_hyp2f1(self): # a collection of special cases taken from AMS 55 values = [[0.5, 1, 1.5, 0.2**2, 0.5/0.2*log((1+0.2)/(1-0.2))], [0.5, 1, 1.5, -0.2**2, 1./0.2*arctan(0.2)], [1, 1, 2, 0.2, -1/0.2*log(1-0.2)], [3, 3.5, 1.5, 0.2**2, 0.5/0.2/(-5)*((1+0.2)**(-5)-(1-0.2)**(-5))], [-3, 3, 0.5, sin(0.2)**2, cos(2*3*0.2)], [3, 4, 8, 1, gamma(8)*gamma(8-4-3)/gamma(8-3)/gamma(8-4)], [3, 2, 3-2+1, -1, 1./2**3*sqrt(pi)* gamma(1+3-2)/gamma(1+0.5*3-2)/gamma(0.5+0.5*3)], [5, 2, 5-2+1, -1, 1./2**5*sqrt(pi)* gamma(1+5-2)/gamma(1+0.5*5-2)/gamma(0.5+0.5*5)], [4, 0.5+4, 1.5-2*4, -1./3, (8./9)**(-2*4)*gamma(4./3)* gamma(1.5-2*4)/gamma(3./2)/gamma(4./3-2*4)], ] for i, (a, b, c, x, v) in enumerate(values): cv = hyp2f1(a, b, c, x) assert_almost_equal(cv, v, 8, err_msg='test #%d' % i)
155
def fixed_quad(func,a,b,args=(),n=5): """Compute a definite integral using fixed-order Gaussian quadrature. Description: Integrate func from a to b using Gaussian quadrature of order n. Inputs: func -- a Python function or method to integrate. a -- lower limit of integration b -- upper limit of integration args -- extra arguments to pass to function. n -- order of quadrature integration. Outputs: (val, None) val -- Gaussian quadrature approximation to the integral. """ [x,w] = P_roots(n) ainf, binf = map(scipy.isinf,(a,b)) if ainf or binf: raise ValueError, "Gaussian quadrature is only available for finite limits." y = (b-a)*(x+1)/2.0 + a return (b-a)/2.0*sum(w*func(y,*args)), None
def fixed_quad(func,a,b,args=(),n=5): """Compute a definite integral using fixed-order Gaussian quadrature. Description: Integrate func from a to b using Gaussian quadrature of order n. Inputs: func -- a Python function or method to integrate. a -- lower limit of integration b -- upper limit of integration args -- extra arguments to pass to function. n -- order of quadrature integration. Outputs: (val, None) val -- Gaussian quadrature approximation to the integral. """ [x,w] = p_roots(n) ainf, binf = map(scipy.isinf,(a,b)) if ainf or binf: raise ValueError, "Gaussian quadrature is only available for finite limits." y = (b-a)*(x+1)/2.0 + a return (b-a)/2.0*sum(w*func(y,*args)), None
156
def kvp(v,z,n=1): """Return the nth derivative of Kv(z) with respect to z. """ if not isinstance(n,types.IntType) or (n<0): raise ValueError, "n must be a non-negative integer." if n == 0: return kv(v,z) else: return (kvp(v-1,z,n-1) - kvp(v+1,z,n-1))/2.0
def kvp(v,z,n=1): """Return the nth derivative of Kv(z) with respect to z. """ if not isinstance(n,types.IntType) or (n<0): raise ValueError, "n must be a non-negative integer." if n == 0: return kv(v,z) else: return (kvp(v-1,z,n-1) + kvp(v+1,z,n-1))/(-2.0)
157
def ivp(v,z,n=1): """Return the nth derivative of Iv(z) with respect to z. """ if not isinstance(n,types.IntType) or (n<0): raise ValueError, "n must be a non-negative integer." if n == 0: return iv(v,z) else: return (ivp(v-1,z,n-1) - ivp(v+1,z,n-1))/2.0
def ivp(v,z,n=1): """Return the nth derivative of Iv(z) with respect to z. """ if not isinstance(n,types.IntType) or (n<0): raise ValueError, "n must be a non-negative integer." if n == 0: return iv(v,z) else: return (ivp(v-1,z,n-1) + ivp(v+1,z,n-1))/2.0
158
def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None, full_output=0, disp=1, retall=0): """Minimize a function using the downhill simplex algorithm. Description: Uses a Nelder-Mead simplex algorithm to find the minimum of function of one or more variables. Inputs: func -- the Python function or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist
def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None, full_output=0, disp=1, retall=0): """Minimize a function using the downhill simplex algorithm. Description: Uses a Nelder-Mead simplex algorithm to find the minimum of function of one or more variables. Inputs: func -- the Python function or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist
159
def _linesearch_powell(func, p, xi, args=(), tol=1e-3): # line-search algorithm using fminbound # find the minimium of the function # func(x0+ alpha*direc) global _powell_funcalls extra_args = (func, p, xi) + args alpha_min, fret, iter, num = brent(_myfunc, args=extra_args, full_output=1, tol=tol) xi = alpha_min*xi _powell_funcalls += num return squeeze(fret), p+xi, xi
def _linesearch_powell(func, p, xi, args=(), tol=1e-3): # line-search algorithm using fminbound # find the minimium of the function # func(x0+ alpha*direc) global _powell_funcalls extra_args = (func, p, xi, args) alpha_min, fret, iter, num = brent(_myfunc, args=extra_args, full_output=1, tol=tol) xi = alpha_min*xi _powell_funcalls += num return squeeze(fret), p+xi, xi
160
def impulse(system, X0=None, T=None, N=None): if isinstance(system, lti): sys = system else: sys = lti(*system) if X0 is None: B = sys.B else: B = sys.B + X0 if N is None: N = 100 if T is None: vals = linalg.eigvals(sys.A) tc = 1.0/max(abs(vals.real)) T = arange(0,8*tc,8*tc / float(N)) h = zeros(T.shape, sys.A.typecode()) for k in range(len(h)): eA = Mat(linalg.expm(sys.A*T[k])) B,C = map(Mat, (B,sys.C)) h[k] = squeeze(C*eA*B) return T, h
def impulse(system, X0=None, T=None, N=None): if isinstance(system, lti): sys = system else: sys = lti(*system) if X0 is None: B = sys.B else: B = sys.B + X0 if N is None: N = 100 if T is None: vals = linalg.eigvals(sys.A) tc = 1.0/max(abs(real(vals))) T = arange(0,10*tc,10*tc / float(N)) h = zeros(T.shape, sys.A.typecode()) for k in range(len(h)): eA = Mat(linalg.expm(sys.A*T[k])) B,C = map(Mat, (B,sys.C)) h[k] = squeeze(C*eA*B) return T, h
161
def get_window(window,Nx,fftbins=1): """Return a window of length Nx and type window. If fftbins is 1, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Window types: boxcar, triang, blackman, hamming, hanning, bartlett, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width). If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfun = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfun = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfu = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params)
def get_window(window,Nx,fftbins=1): """Return a window of length Nx and type window. If fftbins is 1, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Window types: boxcar, triang, blackman, hamming, hanning, bartlett, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width). If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfunc = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfun = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfu = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params)
162
def get_window(window,Nx,fftbins=1): """Return a window of length Nx and type window. If fftbins is 1, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Window types: boxcar, triang, blackman, hamming, hanning, bartlett, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width). If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfun = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfun = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfu = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params)
def get_window(window,Nx,fftbins=1): """Return a window of length Nx and type window. If fftbins is 1, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Window types: boxcar, triang, blackman, hamming, hanning, bartlett, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width). If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfun = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfunc = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfu = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params)
163
def get_window(window,Nx,fftbins=1): """Return a window of length Nx and type window. If fftbins is 1, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Window types: boxcar, triang, blackman, hamming, hanning, bartlett, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width). If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfun = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfun = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfu = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params)
def get_window(window,Nx,fftbins=1): """Return a window of length Nx and type window. If fftbins is 1, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Window types: boxcar, triang, blackman, hamming, hanning, bartlett, parzen, bohman, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width). If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfun = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfun = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfunc = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params)
164
def check_exact(self): resdict = {(10,2):45L, (10,5):252L, (1000,20):339482811302457603895512614793686020778700L, (1000,975):47641862536236518640933948075167736642053976275040L (-10,1):0L, (10,-1):0L, (-10,-3):0L,(10,11),0L} for key in resdict.keys(): assert_equal(comb(key[0],key[1],exact=1),resdict[key])
def check_exact(self): resdict = {(10,2):45L, (10,5):252L, (1000,20):339482811302457603895512614793686020778700L, (1000,975):47641862536236518640933948075167736642053976275040L, (-10,1):0L, (10,-1):0L, (-10,-3):0L,(10,11),0L} for key in resdict.keys(): assert_equal(comb(key[0],key[1],exact=1),resdict[key])
165
def legend(text,linetypes=None,lleft=None,color='black',tfont='helvetica',fontsize=14,nobox=0): """Construct and place a legend. Description: Build a legend and place it on the current plot with an interactive prompt. Inputs: text -- A list of strings which document the curves. linetypes -- If not given, then the text strings are associated with the curves in the order they were originally drawn. Otherwise, associate the text strings with the corresponding curve types given. See plot for description. """ global _hold viewp = gist.viewport() width = (viewp[1] - viewp[0]) / 10.0; if lleft is None: lleft = gist.mouse(0,0,"Click on point for lower left coordinate.") llx = lleft[0] lly = lleft[1] else: llx,lly = lleft[:2] savesys = gist.plsys() dx = width / 3.0 legarr = Numeric.arange(llx,llx+width,dx) legy = Numeric.ones(legarr.shape) dy = fontsize*points*1.15 deltay = fontsize*points / 2.8 deltax = fontsize*points / 2.8 ypos = lly + deltay; if linetypes is None: linetypes = _GLOBAL_LINE_TYPES[:] # copy them out gist.plsys(0) savehold = _hold _hold = 1 for k in range(len(text)): plot(legarr,ypos*legy,linetypes[k]) print llx+width+deltax, ypos-deltay if text[k] != "": gist.plt(text[k],llx+width+deltax,ypos-deltay, color=color,font=tfont,height=fontsize,tosys=0) ypos = ypos + dy _hold = savehold if nobox: pass else: gist.plsys(0) maxlen = MLab.max(map(len,text)) c1 = (llx-deltax,lly-deltay) c2 = (llx + width + deltax + fontsize*points* maxlen/1.8 + deltax, lly + len(text)*dy) linesx0 = [c1[0],c1[0],c2[0],c2[0]] linesy0 = [c1[1],c2[1],c2[1],c1[1]] linesx1 = [c1[0],c2[0],c2[0],c1[0]] linesy1 = [c2[1],c2[1],c1[1],c1[1]] gist.pldj(linesx0,linesy0,linesx1,linesy1,color=color) gist.plsys(savesys) return
def legend(text,linetypes=None,lleft=None,color='black',tfont='helvetica',fontsize=14,nobox=0): """Construct and place a legend. Description: Build a legend and place it on the current plot with an interactive prompt. Inputs: text -- A list of strings which document the curves. linetypes -- If not given, then the text strings are associated with the curves in the order they were originally drawn. Otherwise, associate the text strings with the corresponding curve types given. See plot for description. """ global _hold viewp = gist.viewport() width = (viewp[1] - viewp[0]) / 10.0; if lleft is None: lleft = gist.mouse(0,0,"Click on point for lower left coordinate.") llx = lleft[0] lly = lleft[1] else: llx,lly = lleft[:2] savesys = gist.plsys() dx = width / 3.0 legarr = Numeric.arange(llx,llx+width,dx) legy = Numeric.ones(legarr.shape) dy = fontsize*points*1.15 deltay = fontsize*points / 2.8 deltax = fontsize*points / 2.8 ypos = lly + deltay; if linetypes is None: linetypes = _GLOBAL_LINE_TYPES[:] # copy them out gist.plsys(0) savehold = _hold _hold = 1 for k in range(len(text)): plot(legarr,ypos*legy,linetypes[k]) if text[k] != "": gist.plt(text[k],llx+width+deltax,ypos-deltay, color=color,font=tfont,height=fontsize,tosys=0) ypos = ypos + dy _hold = savehold if nobox: pass else: gist.plsys(0) maxlen = MLab.max(map(len,text)) c1 = (llx-deltax,lly-deltay) c2 = (llx + width + deltax + fontsize*points* maxlen/1.8 + deltax, lly + len(text)*dy) linesx0 = [c1[0],c1[0],c2[0],c2[0]] linesy0 = [c1[1],c2[1],c2[1],c1[1]] linesx1 = [c1[0],c2[0],c2[0],c1[0]] linesy1 = [c2[1],c2[1],c1[1],c1[1]] gist.pldj(linesx0,linesy0,linesx1,linesy1,color=color) gist.plsys(savesys) return
166
def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points): infbounds = 0 if (b != Inf and a != -Inf): pass # standard integration elif (b == Inf and a != -Inf): infbounds = 1 bound = a elif (b == Inf and a == -Inf): infbounds = 2 bound = 0 # ignored elif (b != Inf and a == -Inf): infbounds = -1 bound = b else: raise RunTimeError, "Infinity comparisons don't work for you." if points is None: if infbounds == 0: return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit) else: return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit) else: if infbounds !=0: raise ValueError, "Infinity inputs cannot be used with break points." else: nl = len(points) the_points = numpy.zeros((nl+2,), float) the_points[:nl] = points return _quadpack._qagpe(func,a,b,the_points,args,full_output,epsabs,epsrel,limit)
def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points): infbounds = 0 if (b != Inf and a != -Inf): pass # standard integration elif (b == Inf and a != -Inf): infbounds = 1 bound = a elif (b == Inf and a == -Inf): infbounds = 2 bound = 0 # ignored elif (b != Inf and a == -Inf): infbounds = -1 bound = b else: raise RuntimeError, "Infinity comparisons don't work for you." if points is None: if infbounds == 0: return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit) else: return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit) else: if infbounds !=0: raise ValueError, "Infinity inputs cannot be used with break points." else: nl = len(points) the_points = numpy.zeros((nl+2,), float) the_points[:nl] = points return _quadpack._qagpe(func,a,b,the_points,args,full_output,epsabs,epsrel,limit)
167
def _send(self,package,addendum=None): """addendum is either None, or a list of addendums <= in length to the number of workers """ if addendum: N = len(addendum) assert(N <= len(self.workers)) else: N = len(self.workers) self.send_exc = {} self.had_send_error = [] for i in range(N): try: if not addendum: self.workers[i].send(package) else: self.workers[i].send(package,addendum[i]) except socket.error, msg: import sys err_type, err_msg = sys.exc_info()[1] self.had_send_error.append(self.workers[i]) try: self.send_exc[(err_type,err_msg)].append(self.workers[i].id) except: self.send_exc[(err_type,err_msg)] = [self.workers[i].id] # else - handle other errors? self.Nsent = N
def _send(self,package,addendum=None): """addendum is either None, or a list of addendums <= in length to the number of workers """ if addendum: N = len(addendum) assert(N <= len(self.workers)) else: N = len(self.workers) self.send_exc = {} self.had_send_error = [] for i in range(N): try: if not addendum: self.workers[i].send(package) else: self.workers[i].send(package,addendum[i]) except socket.error, msg: import sys err_type, err_msg = sys.exc_info()[:2] self.had_send_error.append(self.workers[i]) try: self.send_exc[(err_type,err_msg)].append(self.workers[i].id) except: self.send_exc[(err_type,err_msg)] = [self.workers[i].id] # else - handle other errors? self.Nsent = N
168
def get_data(self,x_stride=1,y_stride=1): mult = array(1, dtype = self.dtype) if self.dtype in ['F', 'D']: mult = array(1+1j, dtype = self.dtype) from scipy.basic.random import normal alpha = array(1., dtype = self.dtype) * mult beta = array(1.,dtype = self.dtype) * mult a = normal(0.,1.,(3,3)).astype(self.dtype) * mult x = arange(shape(a)[0]*x_stride,dtype=self.dtype) * mult y = arange(shape(a)[1]*y_stride,dtype=self.dtype) * mult return alpha,beta,a,x,y
def get_data(self,x_stride=1,y_stride=1): mult = array(1, dtype = self.dtype) if self.dtype in ['F', 'D']: mult = array(1+1j, dtype = self.dtype) from scipy.random import normal alpha = array(1., dtype = self.dtype) * mult beta = array(1.,dtype = self.dtype) * mult a = normal(0.,1.,(3,3)).astype(self.dtype) * mult x = arange(shape(a)[0]*x_stride,dtype=self.dtype) * mult y = arange(shape(a)[1]*y_stride,dtype=self.dtype) * mult return alpha,beta,a,x,y
169
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) if savesys > 0: gist.plsys(savesys) nargs = len(args) if nargs == 0: y = scipy.squeeze(x) x = Numeric.arange(0,len(y)) if scipy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(scipy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if scipy.iscomplexobj(x) or scipy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = scipy.real(x) y = scipy.real(y) y = where(scipy.isfinite(y),y,0) y = scipy.squeeze(y) x = scipy.squeeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) if savesys > 0: gist.plsys(savesys) nargs = len(args) if nargs == 0: y = _minsqueeze(x) x = Numeric.arange(0,len(y)) if scipy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(scipy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if scipy.iscomplexobj(x) or scipy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = scipy.real(x) y = scipy.real(y) y = where(scipy.isfinite(y),y,0) y = scipy.squeeze(y) x = scipy.squeeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
170
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) if savesys > 0: gist.plsys(savesys) nargs = len(args) if nargs == 0: y = scipy.squeeze(x) x = Numeric.arange(0,len(y)) if scipy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(scipy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if scipy.iscomplexobj(x) or scipy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = scipy.real(x) y = scipy.real(y) y = where(scipy.isfinite(y),y,0) y = scipy.squeeze(y) x = scipy.squeeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) if savesys > 0: gist.plsys(savesys) nargs = len(args) if nargs == 0: y = scipy.squeeze(x) x = Numeric.arange(0,len(y)) if scipy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(scipy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if scipy.iscomplexobj(x) or scipy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = scipy.real(x) y = scipy.real(y) y = where(scipy.isfinite(y),y,0) y = _minsqueeze(y) x = _minsqueeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
171
def __init__(self, matrix,x_bounds=None,y_bounds=None,**attr): property_object.__init__(self,attr) if not x_bounds: self.x_bounds = array((0,matrix.shape[1])) else: # works for both 2 element or N element x self.x_bounds = array((x_bounds[0],x_bounds[-1])) if not y_bounds: self.y_bounds = array((0,matrix.shape[0])) else: self.y_bounds = array((y_bounds[0],y_bounds[-1])) self.matrix = matrix self.the_image = self.form_image()
def __init__(self, matrix,x_bounds=None,y_bounds=None,**attr): property_object.__init__(self,attr) if not x_bounds: self.x_bounds = array((0,matrix.shape[1])) else: # works for both 2 element or N element x self.x_bounds = array((x_bounds[0],x_bounds[-1])) if not y_bounds: self.y_bounds = array((0,matrix.shape[0])) else: self.y_bounds = array((y_bounds[0],y_bounds[-1])) self.matrix = matrix self.the_image = self.form_image()
172
def form_image(self): # look up colormap if it si identified by a string if type(self.colormap) == type(''): try: colormap = colormap_map[self.colormap] except KeyError: raise KeyError, 'Invalid colormap name. Choose from %s' \ % `colormap_map.keys()` else: colormap = self.colormap # scale image if we're supposed to. if self.scale in ['yes','on']: scaled_mag = self.scale_magnitude(self.matrix,colormap) else: scaled_mag = self.matrix.astype('b') scaled_mag = clip(scaled_mag,0,len(colormap)-1) if float(maximum.reduce(ravel(colormap))) == 1.: cmap = colormap * 255 else: cmap = colormap pixels = take( cmap, scaled_mag) del scaled_mag bitmap = pixels.astype(UnsignedInt8).tostring() image = wx.wxEmptyImage(self.matrix.shape[0],self.matrix.shape[1]) image.SetData(bitmap) return image
def form_image(self): # look up colormap if it si identified by a string if type(self.colormap) == type(''): try: colormap = colormap_map[self.colormap] except KeyError: raise KeyError, 'Invalid colormap name. Choose from %s' \ % `colormap_map.keys()` else: colormap = self.colormap # scale image if we're supposed to. if self.scale in ['yes','on']: scaled_mag = self.scale_magnitude(self.matrix,colormap) else: scaled_mag = self.matrix.astype('b') scaled_mag = clip(scaled_mag,0,len(colormap)-1) if float(maximum.reduce(ravel(colormap))) == 1.: cmap = colormap * 255 else: cmap = colormap pixels = take( cmap, scaled_mag) del scaled_mag bitmap = pixels.astype(UnsignedInt8).tostring() image = wx.wxEmptyImage(self.matrix.shape[1],self.matrix.shape[0]) image.SetData(bitmap) return image
173
def draw(self,dc): sz = array((self.the_image.GetWidth(),self.the_image.GetHeight())) sz = sz* abs(self.scale) sz = sz.astype(Int) scaled_image = self.the_image.Scale(abs(sz[0]),abs(sz[1])) bitmap = scaled_image.ConvertToBitmap()
def draw(self,dc): sz = array((self.the_image.GetWidth(),self.the_image.GetHeight())) sz = sz* self.scale sz = abs(sz.astype(Int)) scaled_image = self.the_image.Scale(sz[0],sz[1]) bitmap = scaled_image.ConvertToBitmap()
174
def init(self, **options): self.__dict__.update(options) if self.lower == numpy.NINF: self.lower = -numpy.utils.limits.double_max if self.upper == numpy.PINF: self.upper = numpy.utils.limits.double_max self.k = 0 self.accepted = 0 self.feval = 0 self.tests = 0
def init(self, **options): self.__dict__.update(options) self.lower = asarray(self.lower) self.lower[self.lower == numpy.NINF] = -_double_max self.upper = asarray(self.upper) self.upper[self.upper == numpy.PINF] = _double_max self.k = 0 self.accepted = 0 self.feval = 0 self.tests = 0
175
def getstart_temp(self, best_state): assert(not self.dims is None) x0 = ones(self.dims,'d') lrange = x0*self.lower urange = x0*self.upper fmax = -300e8 fmin = 300e8 for n in range(self.Ninit): x0[:] = random.uniform(size=self.dims)*(urange-lrange) + lrange fval = self.func(x0,*self.args) self.feval += 1 if fval > fmax: fmax = fval if fval < fmin: fmin = fval best_state.cost = fval best_state.x = array(x0) self.T0 = (fmax-fmin)*1.5 return best_state.x
def getstart_temp(self, best_state): assert(not self.dims is None) lrange = self.lower urange = self.upper fmax = -300e8 fmin = 300e8 for n in range(self.Ninit): x0[:] = random.uniform(size=self.dims)*(urange-lrange) + lrange fval = self.func(x0,*self.args) self.feval += 1 if fval > fmax: fmax = fval if fval < fmin: fmin = fval best_state.cost = fval best_state.x = array(x0) self.T0 = (fmax-fmin)*1.5 return best_state.x
176
def getstart_temp(self, best_state): assert(not self.dims is None) x0 = ones(self.dims,'d') lrange = x0*self.lower urange = x0*self.upper fmax = -300e8 fmin = 300e8 for n in range(self.Ninit): x0[:] = random.uniform(size=self.dims)*(urange-lrange) + lrange fval = self.func(x0,*self.args) self.feval += 1 if fval > fmax: fmax = fval if fval < fmin: fmin = fval best_state.cost = fval best_state.x = array(x0) self.T0 = (fmax-fmin)*1.5 return best_state.x
def getstart_temp(self, best_state): assert(not self.dims is None) x0 = ones(self.dims,'d') lrange = x0*self.lower urange = x0*self.upper fmax = -300e8 fmin = 300e8 for _ in range(self.Ninit): x0 = random.uniform(size=self.dims)*(urange-lrange) + lrange fval = self.func(x0, *self.args) self.feval += 1 if fval > fmax: fmax = fval if fval < fmin: fmin = fval best_state.cost = fval best_state.x = array(x0) self.T0 = (fmax-fmin)*1.5 return best_state.x
177
def accept_test(self, dE): T = self.T self.tests += 1 if dE < 0: self.accepted += 1 return 1 p = exp(-dE*1.0/self.boltzmann/T) if (p > random.uniform(0.0,1.0)): self.accepted += 1 return 1 return 0
def accept_test(self, dE): T = self.T self.tests += 1 if dE < 0: self.accepted += 1 return 1 p = exp(-dE*1.0/self.boltzmann/T) if (p > random.uniform(0.0, 1.0)): self.accepted += 1 return 1 return 0
178
def init(self, **options): self.__dict__.update(options) if self.m is None: self.m = 1.0 if self.n is None: self.n = 1.0 self.c = self.m * exp(-self.n * self.quench / self.dims)
def init(self, **options): self.__dict__.update(options) if self.m is None: self.m = 1.0 if self.n is None: self.n = 1.0 self.c = self.m * exp(-self.n * self.quench)
179
def update_guess(self, x0): x0 = asarray(x0) u = squeeze(random.uniform(0.0,1.0, size=len(x0))) T = self.T y = sign(u-0.5)*T*((1+1.0/T)**abs(2*u-1)-1.0) xc = y*(self.upper - self.lower) xnew = x0 + xc return xnew
def update_guess(self, x0): x0 = asarray(x0) u = squeeze(random.uniform(0.0, 1.0, size=self.dims)) T = self.T y = sign(u-0.5)*T*((1+1.0/T)**abs(2*u-1)-1.0) xc = y*(self.upper - self.lower) xnew = x0 + xc return xnew
180
def update_temp(self): self.T = self.T0*exp(-self.c * self.k**(self.quench/self.dims)) self.k += 1 return
def update_temp(self): self.T = self.T0*exp(-self.c * self.k**(self.quench)) self.k += 1 return
181
def update_guess(self, x0): x0 = asarray(x0) numbers = squeeze(random.uniform(-pi/2,pi/2, size=len(x0))) xc = self.learn_rate * self.T * tan(numbers) xnew = x0 + xc return xnew
def update_guess(self, x0): x0 = asarray(x0) numbers = squeeze(random.uniform(-pi/2, pi/2, size=self.dims)) xc = self.learn_rate * self.T * tan(numbers) xnew = x0 + xc return xnew
182
def update_guess(self, x0): std = min(sqrt(self.T), (self.upper-self.lower)/3.0/self.learn_rate) x0 = asarray(x0) xc = squeeze(random.normal(0,std*self.learn_rate, size=len(x0))) xnew = x0 + xc return xnew
def update_guess(self, x0): std = minimum(sqrt(self.T)*ones(self.dims), (self.upper-self.lower)/3.0/self.learn_rate) x0 = asarray(x0) xc = squeeze(random.normal(0,std*self.learn_rate, size=len(x0))) xnew = x0 + xc return xnew
183
def update_guess(self, x0): std = min(sqrt(self.T), (self.upper-self.lower)/3.0/self.learn_rate) x0 = asarray(x0) xc = squeeze(random.normal(0,std*self.learn_rate, size=len(x0))) xnew = x0 + xc return xnew
def update_guess(self, x0): std = min(sqrt(self.T), (self.upper-self.lower)/3.0/self.learn_rate) x0 = asarray(x0) xc = squeeze(random.normal(0, 1.0, size=self.dims)) xnew = x0 + xc*std*self.learn_rate return xnew
184
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iters, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
185
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iters -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
186
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
deflower = asarray(lower) upper = asarray(upper) anneal(func,lower = asarray(lower) upper = asarray(upper) x0,lower = asarray(lower) upper = asarray(upper) args=(),lower = asarray(lower) upper = asarray(upper) schedule='fast',lower = asarray(lower) upper = asarray(upper) full_output=0,lower = asarray(lower) upper = asarray(upper) T0=None,lower = asarray(lower) upper = asarray(upper) Tf=1e-12,lower = asarray(lower) upper = asarray(upper) maxeval=None,lower = asarray(lower) upper = asarray(upper) maxaccept=None,lower = asarray(lower) upper = asarray(upper) maxiter=400,lower = asarray(lower) upper = asarray(upper) boltzmann=1.0,lower = asarray(lower) upper = asarray(upper) learn_rate=0.5,lower = asarray(lower) upper = asarray(upper) feps=1e-6,lower = asarray(lower) upper = asarray(upper) quench=1.0,lower = asarray(lower) upper = asarray(upper) m=1.0,lower = asarray(lower) upper = asarray(upper) n=1.0,lower = asarray(lower) upper = asarray(upper) lower=-100,lower = asarray(lower) upper = asarray(upper) upper=100,lower = asarray(lower) upper = asarray(upper) dwell=50):lower = asarray(lower) upper = asarray(upper) """Minimizelower = asarray(lower) upper = asarray(upper) alower = asarray(lower) upper = asarray(upper) functionlower = asarray(lower) upper = asarray(upper) usinglower = asarray(lower) upper = asarray(upper) simulatedlower = asarray(lower) upper = asarray(upper) annealing.lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) Schedulelower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) alower = asarray(lower) upper = asarray(upper) schedulelower = asarray(lower) upper = asarray(upper) classlower = asarray(lower) upper = asarray(upper) implementinglower = asarray(lower) upper = asarray(upper) thelower = asarray(lower) upper = asarray(upper) annealinglower = asarray(lower) upper = asarray(upper) schedule.lower = asarray(lower) upper = asarray(upper) Availablelower = asarray(lower) upper = asarray(upper) oneslower = asarray(lower) upper = asarray(upper) arelower = asarray(lower) upper = asarray(upper) 'fast',lower = asarray(lower) upper = asarray(upper) 'cauchy',lower = asarray(lower) upper = asarray(upper) 'boltzmann'lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) Inputs:lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) funclower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Functionlower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) belower = asarray(lower) upper = asarray(upper) optimizedlower = asarray(lower) upper = asarray(upper) x0lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Parameterslower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) belower = asarray(lower) upper = asarray(upper) optimizedlower = asarray(lower) upper = asarray(upper) overlower = asarray(lower) upper = asarray(upper) argslower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Extralower = asarray(lower) upper = asarray(upper) parameterslower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) functionlower = asarray(lower) upper = asarray(upper) schedulelower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Annealinglower = asarray(lower) upper = asarray(upper) schedulelower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) uselower = asarray(lower) upper = asarray(upper) (alower = asarray(lower) upper = asarray(upper) class)lower = asarray(lower) upper = asarray(upper) full_outputlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Returnlower = asarray(lower) upper = asarray(upper) optionallower = asarray(lower) upper = asarray(upper) outputslower = asarray(lower) upper = asarray(upper) T0lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Initiallower = asarray(lower) upper = asarray(upper) Temperaturelower = asarray(lower) upper = asarray(upper) (estimatedlower = asarray(lower) upper = asarray(upper) aslower = asarray(lower) upper = asarray(upper) 1.2lower = asarray(lower) upper = asarray(upper) timeslower = asarray(lower) upper = asarray(upper) thelower = asarray(lower) upper = asarray(upper) largestlower = asarray(lower) upper = asarray(upper) cost-functionlower = asarray(lower) upper = asarray(upper) deviationlower = asarray(lower) upper = asarray(upper) overlower = asarray(lower) upper = asarray(upper) randomlower = asarray(lower) upper = asarray(upper) pointslower = asarray(lower) upper = asarray(upper) inlower = asarray(lower) upper = asarray(upper) thelower = asarray(lower) upper = asarray(upper) range)lower = asarray(lower) upper = asarray(upper) Tflower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Finallower = asarray(lower) upper = asarray(upper) goallower = asarray(lower) upper = asarray(upper) temperaturelower = asarray(lower) upper = asarray(upper) maxevallower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Maximumlower = asarray(lower) upper = asarray(upper) functionlower = asarray(lower) upper = asarray(upper) evaluationslower = asarray(lower) upper = asarray(upper) maxacceptlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Maximumlower = asarray(lower) upper = asarray(upper) changeslower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) acceptlower = asarray(lower) upper = asarray(upper) maxiterlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Maximumlower = asarray(lower) upper = asarray(upper) coolinglower = asarray(lower) upper = asarray(upper) iterationslower = asarray(lower) upper = asarray(upper) learn_ratelower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) scalelower = asarray(lower) upper = asarray(upper) constantlower = asarray(lower) upper = asarray(upper) forlower = asarray(lower) upper = asarray(upper) adjustinglower = asarray(lower) upper = asarray(upper) guesseslower = asarray(lower) upper = asarray(upper) boltzmannlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Boltzmannlower = asarray(lower) upper = asarray(upper) constantlower = asarray(lower) upper = asarray(upper) inlower = asarray(lower) upper = asarray(upper) acceptancelower = asarray(lower) upper = asarray(upper) testlower = asarray(lower) upper = asarray(upper) (increaselower = asarray(lower) upper = asarray(upper) forlower = asarray(lower) upper = asarray(upper) lesslower = asarray(lower) upper = asarray(upper) stringentlower = asarray(lower) upper = asarray(upper) testlower = asarray(lower) upper = asarray(upper) atlower = asarray(lower) upper = asarray(upper) eachlower = asarray(lower) upper = asarray(upper) temperature).lower = asarray(lower) upper = asarray(upper) fepslower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Stoppinglower = asarray(lower) upper = asarray(upper) relativelower = asarray(lower) upper = asarray(upper) errorlower = asarray(lower) upper = asarray(upper) tolerancelower = asarray(lower) upper = asarray(upper) forlower = asarray(lower) upper = asarray(upper) thelower = asarray(lower) upper = asarray(upper) functionlower = asarray(lower) upper = asarray(upper) valuelower = asarray(lower) upper = asarray(upper) inlower = asarray(lower) upper = asarray(upper) lastlower = asarray(lower) upper = asarray(upper) fourlower = asarray(lower) upper = asarray(upper) coolings.lower = asarray(lower) upper = asarray(upper) quench,lower = asarray(lower) upper = asarray(upper) m,lower = asarray(lower) upper = asarray(upper) nlower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Parameterslower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) alterlower = asarray(lower) upper = asarray(upper) fast_salower = asarray(lower) upper = asarray(upper) schedulelower = asarray(lower) upper = asarray(upper) lower,lower = asarray(lower) upper = asarray(upper) upperlower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) lowerlower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) upperlower = asarray(lower) upper = asarray(upper) boundslower = asarray(lower) upper = asarray(upper) onlower = asarray(lower) upper = asarray(upper) x0lower = asarray(lower) upper = asarray(upper) (scalarlower = asarray(lower) upper = asarray(upper) orlower = asarray(lower) upper = asarray(upper) array).lower = asarray(lower) upper = asarray(upper) dwelllower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Thelower = asarray(lower) upper = asarray(upper) numberlower = asarray(lower) upper = asarray(upper) oflower = asarray(lower) upper = asarray(upper) timeslower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) searchlower = asarray(lower) upper = asarray(upper) thelower = asarray(lower) upper = asarray(upper) spacelower = asarray(lower) upper = asarray(upper) atlower = asarray(lower) upper = asarray(upper) eachlower = asarray(lower) upper = asarray(upper) temperature.lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) Outputs:lower = asarray(lower) upper = asarray(upper) (xmin,lower = asarray(lower) upper = asarray(upper) {Jmin,lower = asarray(lower) upper = asarray(upper) T,lower = asarray(lower) upper = asarray(upper) feval,lower = asarray(lower) upper = asarray(upper) iter,lower = asarray(lower) upper = asarray(upper) accept,}lower = asarray(lower) upper = asarray(upper) retval)lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) xminlower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Pointlower = asarray(lower) upper = asarray(upper) givinglower = asarray(lower) upper = asarray(upper) smallestlower = asarray(lower) upper = asarray(upper) valuelower = asarray(lower) upper = asarray(upper) foundlower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Flaglower = asarray(lower) upper = asarray(upper) indicatinglower = asarray(lower) upper = asarray(upper) stoppinglower = asarray(lower) upper = asarray(upper) condition:lower = asarray(lower) upper = asarray(upper) 0lower = asarray(lower) upper = asarray(upper) :lower = asarray(lower) upper = asarray(upper) Cooledlower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) globallower = asarray(lower) upper = asarray(upper) optimumlower = asarray(lower) upper = asarray(upper) 1lower = asarray(lower) upper = asarray(upper) :lower = asarray(lower) upper = asarray(upper) Cooledlower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) finallower = asarray(lower) upper = asarray(upper) temperaturelower = asarray(lower) upper = asarray(upper) 2lower = asarray(lower) upper = asarray(upper) :lower = asarray(lower) upper = asarray(upper) Maximumlower = asarray(lower) upper = asarray(upper) functionlower = asarray(lower) upper = asarray(upper) evaluationslower = asarray(lower) upper = asarray(upper) 3lower = asarray(lower) upper = asarray(upper) :lower = asarray(lower) upper = asarray(upper) Maximumlower = asarray(lower) upper = asarray(upper) coolinglower = asarray(lower) upper = asarray(upper) iterationslower = asarray(lower) upper = asarray(upper) reachedlower = asarray(lower) upper = asarray(upper) 4lower = asarray(lower) upper = asarray(upper) :lower = asarray(lower) upper = asarray(upper) Maximumlower = asarray(lower) upper = asarray(upper) acceptedlower = asarray(lower) upper = asarray(upper) querylower = asarray(lower) upper = asarray(upper) locationslower = asarray(lower) upper = asarray(upper) reachedlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) Jminlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Minimumlower = asarray(lower) upper = asarray(upper) valuelower = asarray(lower) upper = asarray(upper) oflower = asarray(lower) upper = asarray(upper) functionlower = asarray(lower) upper = asarray(upper) foundlower = asarray(lower) upper = asarray(upper) Tlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) finallower = asarray(lower) upper = asarray(upper) temperaturelower = asarray(lower) upper = asarray(upper) fevallower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Numberlower = asarray(lower) upper = asarray(upper) oflower = asarray(lower) upper = asarray(upper) functionlower = asarray(lower) upper = asarray(upper) evaluationslower = asarray(lower) upper = asarray(upper) iterlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Numberlower = asarray(lower) upper = asarray(upper) oflower = asarray(lower) upper = asarray(upper) coolinglower = asarray(lower) upper = asarray(upper) iterationslower = asarray(lower) upper = asarray(upper) acceptlower = asarray(lower) upper = asarray(upper) --lower = asarray(lower) upper = asarray(upper) Numberlower = asarray(lower) upper = asarray(upper) oflower = asarray(lower) upper = asarray(upper) testslower = asarray(lower) upper = asarray(upper) accepted.lower = asarray(lower) upper = asarray(upper) """lower = asarray(lower) upper = asarray(upper) x0lower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) asarray(x0)lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) schedulelower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) eval(schedule+'_sa()')lower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) initializelower = asarray(lower) upper = asarray(upper) thelower = asarray(lower) upper = asarray(upper) schedulelower = asarray(lower) upper = asarray(upper) schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0,lower = asarray(lower) upper = asarray(upper) learn_rate=learn_rate,lower = asarray(lower) upper = asarray(upper) lower=lower,lower = asarray(lower) upper = asarray(upper) upper=upper,lower = asarray(lower) upper = asarray(upper) m=m,lower = asarray(lower) upper = asarray(upper) n=n,lower = asarray(lower) upper = asarray(upper) quench=quench,lower = asarray(lower) upper = asarray(upper) dwell=dwell)lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) current_state,lower = asarray(lower) upper = asarray(upper) last_state,lower = asarray(lower) upper = asarray(upper) best_statelower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) _state(),lower = asarray(lower) upper = asarray(upper) _state(),lower = asarray(lower) upper = asarray(upper) _state()lower = asarray(lower) upper = asarray(upper) fevallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 0lower = asarray(lower) upper = asarray(upper) donelower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 0lower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) T0lower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) None:lower = asarray(lower) upper = asarray(upper) x0lower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) schedule.getstart_temp(best_state)lower = asarray(lower) upper = asarray(upper) else:lower = asarray(lower) upper = asarray(upper) best_state.xlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) Nonelower = asarray(lower) upper = asarray(upper) best_state.costlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 300e8lower = asarray(lower) upper = asarray(upper) last_state.xlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) asarray(x0).copy()lower = asarray(lower) upper = asarray(upper) fvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) func(x0,*args)lower = asarray(lower) upper = asarray(upper) schedule.fevallower = asarray(lower) upper = asarray(upper) +=lower = asarray(lower) upper = asarray(upper) 1lower = asarray(lower) upper = asarray(upper) last_state.costlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) fvallower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) last_state.costlower = asarray(lower) upper = asarray(upper) <lower = asarray(lower) upper = asarray(upper) best_state.cost:lower = asarray(lower) upper = asarray(upper) best_state.costlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) fvallower = asarray(lower) upper = asarray(upper) best_state.xlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) asarray(x0).copy()lower = asarray(lower) upper = asarray(upper) schedule.Tlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) schedule.T0lower = asarray(lower) upper = asarray(upper) fqueuelower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) [100,300,500,700]lower = asarray(lower) upper = asarray(upper) iter=0lower = asarray(lower) upper = asarray(upper) whilelower = asarray(lower) upper = asarray(upper) 1:lower = asarray(lower) upper = asarray(upper) forlower = asarray(lower) upper = asarray(upper) nlower = asarray(lower) upper = asarray(upper) inlower = asarray(lower) upper = asarray(upper) range(dwell):lower = asarray(lower) upper = asarray(upper) xnewlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) schedule.update_guess(x0)lower = asarray(lower) upper = asarray(upper) fvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) func(xnew,*args)lower = asarray(lower) upper = asarray(upper) schedule.fevallower = asarray(lower) upper = asarray(upper) +=lower = asarray(lower) upper = asarray(upper) 1lower = asarray(lower) upper = asarray(upper) current_state.xlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) asarray(xnew).copy()lower = asarray(lower) upper = asarray(upper) current_state.costlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) fvallower = asarray(lower) upper = asarray(upper) dElower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) current_state.costlower = asarray(lower) upper = asarray(upper) -lower = asarray(lower) upper = asarray(upper) last_state.costlower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) schedule.accept_test(dE):lower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) dElower = asarray(lower) upper = asarray(upper) <lower = asarray(lower) upper = asarray(upper) 0:lower = asarray(lower) upper = asarray(upper) last_state.xlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) current_state.x.copy()lower = asarray(lower) upper = asarray(upper) last_state.costlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) current_state.costlower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) last_state.costlower = asarray(lower) upper = asarray(upper) <lower = asarray(lower) upper = asarray(upper) best_state.cost:lower = asarray(lower) upper = asarray(upper) best_state.xlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) last_state.x.copy()lower = asarray(lower) upper = asarray(upper) best_state.costlower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) last_state.costlower = asarray(lower) upper = asarray(upper) schedule.update_temp()lower = asarray(lower) upper = asarray(upper) iterlower = asarray(lower) upper = asarray(upper) +=lower = asarray(lower) upper = asarray(upper) 1lower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) Stoppinglower = asarray(lower) upper = asarray(upper) conditionslower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) 0)lower = asarray(lower) upper = asarray(upper) lastlower = asarray(lower) upper = asarray(upper) savedlower = asarray(lower) upper = asarray(upper) valueslower = asarray(lower) upper = asarray(upper) oflower = asarray(lower) upper = asarray(upper) flower = asarray(lower) upper = asarray(upper) fromlower = asarray(lower) upper = asarray(upper) eachlower = asarray(lower) upper = asarray(upper) coolinglower = asarray(lower) upper = asarray(upper) steplower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) arelower = asarray(lower) upper = asarray(upper) alllower = asarray(lower) upper = asarray(upper) verylower = asarray(lower) upper = asarray(upper) similarlower = asarray(lower) upper = asarray(upper) (effectivelylower = asarray(lower) upper = asarray(upper) cooled)lower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) 1)lower = asarray(lower) upper = asarray(upper) Tflower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) setlower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) welower = asarray(lower) upper = asarray(upper) arelower = asarray(lower) upper = asarray(upper) belowlower = asarray(lower) upper = asarray(upper) itlower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) 2)lower = asarray(lower) upper = asarray(upper) maxevallower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) setlower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) welower = asarray(lower) upper = asarray(upper) arelower = asarray(lower) upper = asarray(upper) pastlower = asarray(lower) upper = asarray(upper) itlower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) 3)lower = asarray(lower) upper = asarray(upper) maxiterlower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) setlower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) welower = asarray(lower) upper = asarray(upper) arelower = asarray(lower) upper = asarray(upper) pastlower = asarray(lower) upper = asarray(upper) itlower = asarray(lower) upper = asarray(upper) #lower = asarray(lower) upper = asarray(upper) 4)lower = asarray(lower) upper = asarray(upper) maxacceptlower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) setlower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) welower = asarray(lower) upper = asarray(upper) arelower = asarray(lower) upper = asarray(upper) pastlower = asarray(lower) upper = asarray(upper) itlower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) fqueue.append(squeeze(last_state.cost))lower = asarray(lower) upper = asarray(upper) tmplower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) fqueue.pop(0)lower = asarray(lower) upper = asarray(upper) aflower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) asarray(fqueue)*1.0lower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) all(abs((af-af[0])/af[0])lower = asarray(lower) upper = asarray(upper) <lower = asarray(lower) upper = asarray(upper) feps):lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 0lower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) abs(af[-1]-best_state.cost)lower = asarray(lower) upper = asarray(upper) >lower = asarray(lower) upper = asarray(upper) feps*10:lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 5lower = asarray(lower) upper = asarray(upper) printlower = asarray(lower) upper = asarray(upper) "Warning:lower = asarray(lower) upper = asarray(upper) Cooledlower = asarray(lower) upper = asarray(upper) tolower = asarray(lower) upper = asarray(upper) %flower = asarray(lower) upper = asarray(upper) atlower = asarray(lower) upper = asarray(upper) %flower = asarray(lower) upper = asarray(upper) butlower = asarray(lower) upper = asarray(upper) thislower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) not"lower = asarray(lower) upper = asarray(upper) \lower = asarray(lower) upper = asarray(upper) %lower = asarray(lower) upper = asarray(upper) (squeeze(last_state.cost),lower = asarray(lower) upper = asarray(upper) squeeze(last_state.x))lower = asarray(lower) upper = asarray(upper) \lower = asarray(lower) upper = asarray(upper) +lower = asarray(lower) upper = asarray(upper) "lower = asarray(lower) upper = asarray(upper) thelower = asarray(lower) upper = asarray(upper) smallestlower = asarray(lower) upper = asarray(upper) pointlower = asarray(lower) upper = asarray(upper) found."lower = asarray(lower) upper = asarray(upper) breaklower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) (Tflower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) notlower = asarray(lower) upper = asarray(upper) None)lower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) (schedule.Tlower = asarray(lower) upper = asarray(upper) <lower = asarray(lower) upper = asarray(upper) Tf):lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 1lower = asarray(lower) upper = asarray(upper) breaklower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) (maxevallower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) notlower = asarray(lower) upper = asarray(upper) None)lower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) (schedule.fevallower = asarray(lower) upper = asarray(upper) >lower = asarray(lower) upper = asarray(upper) maxeval):lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 2lower = asarray(lower) upper = asarray(upper) breaklower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) (iterlower = asarray(lower) upper = asarray(upper) >lower = asarray(lower) upper = asarray(upper) maxiter):lower = asarray(lower) upper = asarray(upper) printlower = asarray(lower) upper = asarray(upper) "Warning:lower = asarray(lower) upper = asarray(upper) Maximumlower = asarray(lower) upper = asarray(upper) numberlower = asarray(lower) upper = asarray(upper) oflower = asarray(lower) upper = asarray(upper) iterationslower = asarray(lower) upper = asarray(upper) exceeded."lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 3lower = asarray(lower) upper = asarray(upper) breaklower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) (maxacceptlower = asarray(lower) upper = asarray(upper) islower = asarray(lower) upper = asarray(upper) notlower = asarray(lower) upper = asarray(upper) None)lower = asarray(lower) upper = asarray(upper) andlower = asarray(lower) upper = asarray(upper) (schedule.acceptedlower = asarray(lower) upper = asarray(upper) >lower = asarray(lower) upper = asarray(upper) maxaccept):lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) =lower = asarray(lower) upper = asarray(upper) 4lower = asarray(lower) upper = asarray(upper) breaklower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) iflower = asarray(lower) upper = asarray(upper) full_output:lower = asarray(lower) upper = asarray(upper) returnlower = asarray(lower) upper = asarray(upper) best_state.x,lower = asarray(lower) upper = asarray(upper) best_state.cost,lower = asarray(lower) upper = asarray(upper) schedule.T,lower = asarray(lower) upper = asarray(upper) \lower = asarray(lower) upper = asarray(upper) schedule.feval,lower = asarray(lower) upper = asarray(upper) iter,lower = asarray(lower) upper = asarray(upper) schedule.accepted,lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) else:lower = asarray(lower) upper = asarray(upper) returnlower = asarray(lower) upper = asarray(upper) best_state.x,lower = asarray(lower) upper = asarray(upper) retvallower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper) lower = asarray(lower) upper = asarray(upper)
187
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
188
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
189
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100, 300, 500, 700] iters = 0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
190
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
191
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
192
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
193
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iters += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
194
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
195
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
196
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iters > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
197
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iters, schedule.accepted, retval else: return best_state.x, retval
198
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: func -- Function to be optimized x0 -- Parameters to be optimized over args -- Extra parameters to function schedule -- Annealing schedule to use (a class) full_output -- Return optional outputs T0 -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tf -- Final goal temperature maxeval -- Maximum function evaluations maxaccept -- Maximum changes to accept maxiter -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmann -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). feps -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwell -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found T -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step # are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
def anneal(func, x0, args=(), schedule='fast', full_output=0, T0=None, Tf=1e-12, maxeval=None, maxaccept=None, maxiter=400, boltzmann=1.0, learn_rate=0.5, feps=1e-6, quench=1.0, m=1.0, n=1.0, lower=-100, upper=100, dwell=50): """Minimize a function using simulated annealing. Schedule is a schedule class implementing the annealing schedule. Available ones are 'fast', 'cauchy', 'boltzmann' Inputs: funcprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Function to be optimized x0print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Parameters to be optimized over argsprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Extra parameters to function scheduleprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Annealing schedule to use (a class) full_output -- Return optional outputs T0print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Initial Temperature (estimated as 1.2 times the largest cost-function deviation over random points in the range) Tfprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Final goal temperature maxevalprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Maximum function evaluations maxacceptprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Maximum changes to accept maxiterprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Maximum cooling iterations learn_rate -- scale constant for adjusting guesses boltzmannprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Boltzmann constant in acceptance test (increase for less stringent test at each temperature). fepsprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- Stopping relative error tolerance for the function value in last four coolings. quench, m, n -- Parameters to alter fast_sa schedule lower, upper -- lower and upper bounds on x0 (scalar or array). dwellprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- The number of times to search the space at each temperature. Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) xmin -- Point giving smallest value found retval -- Flag indicating stopping condition: 0 : Cooled to global optimum 1 : Cooled to final temperature 2 : Maximum function evaluations 3 : Maximum cooling iterations reached 4 : Maximum accepted query locations reached Jmin -- Minimum value of function found Tprint anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') -- final temperature feval -- Number of function evaluations iter -- Number of cooling iterations accept -- Number of tests accepted. """ x0 = asarray(x0) schedule = eval(schedule+'_sa()') # initialize the schedule schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, learn_rate=learn_rate, lower=lower, upper=upper, m=m, n=n, quench=quench, dwell=dwell) current_state, last_state, best_state = _state(), _state(), _state() feval = 0 done = 0 if T0 is None: x0 = schedule.getstart_temp(best_state) else: best_state.x = None best_state.cost = 300e8 last_state.x = asarray(x0).copy() fval = func(x0,*args) schedule.feval += 1 last_state.cost = fval if last_state.cost < best_state.cost: best_state.cost = fval best_state.x = asarray(x0).copy() schedule.T = schedule.T0 fqueue = [100,300,500,700] iter=0 while 1: for n in range(dwell): xnew = schedule.update_guess(x0) fval = func(xnew,*args) schedule.feval += 1 current_state.x = asarray(xnew).copy() current_state.cost = fval dE = current_state.cost - last_state.cost if schedule.accept_test(dE): if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost if last_state.cost < best_state.cost: best_state.x = last_state.x.copy() best_state.cost = last_state.cost schedule.update_temp() iter += 1 # Stopping conditions # 0) last saved values of f from each cooling step #print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,1.0,full_output=1,upper=3.0,lower=-3.0,feps=1e-4,maxiter=2000,schedule='boltzmann') func = lambda x: cos(14.5*x[0]-0.3) + (x[1]+0.2)*x[1] + (x[0]+0.2)*x[0] print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='cauchy') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='fast') print anneal(func,[1.0, 1.0],full_output=1,upper=[3.0, 3.0],lower=[-3.0, -3.0],feps=1e-4,maxiter=2000,schedule='boltzmann') are all very similar (effectively cooled) # 1) Tf is set and we are below it # 2) maxeval is set and we are past it # 3) maxiter is set and we are past it # 4) maxaccept is set and we are past it fqueue.append(squeeze(last_state.cost)) tmp = fqueue.pop(0) af = asarray(fqueue)*1.0 if all(abs((af-af[0])/af[0]) < feps): retval = 0 if abs(af[-1]-best_state.cost) > feps*10: retval = 5 print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ + " the smallest point found." break if (Tf is not None) and (schedule.T < Tf): retval = 1 break if (maxeval is not None) and (schedule.feval > maxeval): retval = 2 break if (iter > maxiter): print "Warning: Maximum number of iterations exceeded." retval = 3 break if (maxaccept is not None) and (schedule.accepted > maxaccept): retval = 4 break if full_output: return best_state.x, best_state.cost, schedule.T, \ schedule.feval, iter, schedule.accepted, retval else: return best_state.x, retval
199