rem
stringlengths 1
322k
| add
stringlengths 0
2.05M
| context
stringlengths 4
228k
| meta
stringlengths 156
215
|
---|---|---|---|
self.lower[self.lower == numpy.NINF] = -_double_max | self.lower = where(self.lower == numpy.NINF, -_double_max, self.lower) | 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 | cdc22b7f935df58d1b69463351bbb112522c34e1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cdc22b7f935df58d1b69463351bbb112522c34e1/anneal.py |
self.upper[self.upper == numpy.PINF] = _double_max | self.upper = where(self.upper == numpy.PINF, _double_max, self.upper) | 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 | cdc22b7f935df58d1b69463351bbb112522c34e1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cdc22b7f935df58d1b69463351bbb112522c34e1/anneal.py |
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 | cdc22b7f935df58d1b69463351bbb112522c34e1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cdc22b7f935df58d1b69463351bbb112522c34e1/anneal.py |
||
iter = 0 | iters = 0 | 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 | cdc22b7f935df58d1b69463351bbb112522c34e1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cdc22b7f935df58d1b69463351bbb112522c34e1/anneal.py |
iter += 1 | iters += 1 | 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 | cdc22b7f935df58d1b69463351bbb112522c34e1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cdc22b7f935df58d1b69463351bbb112522c34e1/anneal.py |
if (iter > maxiter): | if (iters > maxiter): | 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 | cdc22b7f935df58d1b69463351bbb112522c34e1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cdc22b7f935df58d1b69463351bbb112522c34e1/anneal.py |
schedule.feval, iter, schedule.accepted, retval | schedule.feval, iters, schedule.accepted, 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, iter, schedule.accepted, retval else: return best_state.x, retval | cdc22b7f935df58d1b69463351bbb112522c34e1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cdc22b7f935df58d1b69463351bbb112522c34e1/anneal.py |
indx = numpy.argsort( perm ) return numpy.take( flag, indx[:len( ar1 )] ) | 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 ) | 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 )] ) | 70bf077d4de719bbe527ecd1eb60e7c0c2b2957b /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/70bf077d4de719bbe527ecd1eb60e7c0c2b2957b/arraysetops.py |
if hasattr(object, '_ppimport_attr'): | if hasattr(object,'_ppimport_importer') or \ hasattr(object, '_ppimport_module'): object = object._ppimport_module elif hasattr(object, '_ppimport_attr'): | 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) | 04673d0b178cfe7f3719b4aaef1842210027fdb3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/04673d0b178cfe7f3719b4aaef1842210027fdb3/helpmod.py |
elif hasattr(object,'_ppimport_importer') or \ hasattr(object, '_ppimport_module'): object = object._ppimport_module | 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) | 04673d0b178cfe7f3719b4aaef1842210027fdb3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/04673d0b178cfe7f3719b4aaef1842210027fdb3/helpmod.py |
|
if hasattr(a,'_ppimport_module') or \ hasattr(a,'_ppimport_importer'): | if hasattr(a,'_ppimport_importer') or \ hasattr(a,'_ppimport_module'): | def __call__ (self, *args, **kwds): new_args = [] for a in args: if hasattr(a,'_ppimport_module') or \ | 04673d0b178cfe7f3719b4aaef1842210027fdb3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/04673d0b178cfe7f3719b4aaef1842210027fdb3/helpmod.py |
if hasattr(a,'_ppimport_attr'): | if hasattr(a,'_ppimport_attr'): | def __call__ (self, *args, **kwds): new_args = [] for a in args: if hasattr(a,'_ppimport_module') or \ | 04673d0b178cfe7f3719b4aaef1842210027fdb3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/04673d0b178cfe7f3719b4aaef1842210027fdb3/helpmod.py |
object = object._ppimport_module if hasattr(object,'_ppimport_attr'): | object = object._ppimport_module if hasattr(object,'_ppimport_attr'): | def _inspect_getfile(object): | 04673d0b178cfe7f3719b4aaef1842210027fdb3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/04673d0b178cfe7f3719b4aaef1842210027fdb3/helpmod.py |
def nnlf(self, *args): | def nnlf(self, theta, x): | 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) | 4fc3c3382d4f39d6cb250f55b2b024d3eef437e9 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/4fc3c3382d4f39d6cb250f55b2b024d3eef437e9/distributions.py |
x = args[-1] loc = args[-2] scale = args[-3] args = args[:-3] | loc = theta[-2] scale = theta[-1] args = tuple(theta[:-2]) | 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) | 4fc3c3382d4f39d6cb250f55b2b024d3eef437e9 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/4fc3c3382d4f39d6cb250f55b2b024d3eef437e9/distributions.py |
return self._nnlf(self, x, *args) + N*log(scale) | return self._nnlf(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) | 4fc3c3382d4f39d6cb250f55b2b024d3eef437e9 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/4fc3c3382d4f39d6cb250f55b2b024d3eef437e9/distributions.py |
nzmax = 0 | try: nzmax = self.nnz except AtrributeError: nzmax = 0 | def getnzmax(self): try: nzmax = self.nzmax except AttributeError: nzmax = 0 return nzmax | fcf4244ef83d409592ec270ea7ac7c461892444e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/fcf4244ef83d409592ec270ea7ac7c461892444e/Sparse.py |
self.vecfunc = sgf(self._single_call) | self.vecfunc = sgf(self._single_call,otypes='d') | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
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 | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
||
self.vecfunc = sgf(self._ppf_single_call) self.vecentropy = sgf(self._entropy) | 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') | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
self.generic_moment = sgf(self._mom0_sc) | self.generic_moment = sgf(self._mom0_sc,otypes='d') | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
self.generic_moment = sgf(self._mom1_sc) | self.generic_moment = sgf(self._mom1_sc,otypes='d') | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
def _cdf_single_call(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] | 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 | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
|
return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] | return self.veccdf(x,*args) | def _cdf(self, x, *args): return scipy.integrate.quad(self._pdf, self.a, x, args=args)[0] | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
insert(output,(1-cond0)*(cond1==cond1), self.badvalue) | insert(output,(1-cond0)+(1-cond1)*(q!=0.0), self.badvalue) | def ppf(self,q,*args,**kwds): """Percent point function (inverse of cdf) at q of the given RV. | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
self._cdfvec = sgf(self._cdfsingle) | self._cdfvec = sgf(self._cdfsingle,otypes='d') | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
self._ppf = new.instancemethod(sgf(_drv_ppf), self, rv_discrete) self._pmf = new.instancemethod(sgf(_drv_pmf), self, rv_discrete) self._cdf = new.instancemethod(sgf(_drv_cdf), self, rv_discrete) | self._ppf = new.instancemethod(sgf(_drv_ppf,otypes='d'), self, rv_discrete) self._pmf = new.instancemethod(sgf(_drv_pmf,otypes='d'), self, rv_discrete) self._cdf = new.instancemethod(sgf(_drv_cdf,otypes='d'), self, rv_discrete) | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
self._vecppf = new.instancemethod(sgf(_drv2_ppfsingle), | self._vecppf = new.instancemethod(sgf(_drv2_ppfsingle,otypes='d'), | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
self.generic_moment = new.instancemethod(sgf(_drv2_moment), | self.generic_moment = new.instancemethod(sgf(_drv2_moment, otypes='d'), | 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) | 6db89fd66aa882d8bb85d064d95c26c6ce2fcc55 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6db89fd66aa882d8bb85d064d95c26c6ce2fcc55/distributions.py |
Numeric_solve = linalg.solve_linear_equations | basic_solve = linalg.solve_linear_equations | 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 ' ==================================' | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
assert not a.iscontiguous() | assert not a.flags['CONTIGUOUS'] | 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 ' ==================================' | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
Numeric_inv = linalg.inverse | basic_inv = linalg.inverse | 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]) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
assert not a.iscontiguous() | assert not a.flags['CONTIGUOUS'] | 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]) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
Numeric_det = linalg.determinant | basic_det = linalg.determinant | 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) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
d2 = Numeric_det(a) | d2 = basic_det(a) | 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) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
Numeric_det = linalg.determinant | basic_det = linalg.determinant | 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) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
d2 = Numeric_det(a) | d2 = basic_det(a) | 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) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
Numeric_det = linalg.determinant | basic_det = linalg.determinant | 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]) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
assert not a.iscontiguous() | assert not a.flags['CONTIGUOUS'] | 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]) | 7a2c431004271fb01e28862a93afb11b83c27914 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7a2c431004271fb01e28862a93afb11b83c27914/test_basic.py |
indx = cols[:,newaxis]*ones((1,rN)) + \ rows[newaxis,:]*ones((cN,1)) - 1 | indx = cols[:,newaxis]*ones((1,rN),dtype=int) + \ rows[newaxis,:]*ones((cN,1),dtype=int) - 1 | 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) | 8d00c8ba3be23f175397c10a9c5aaf91cc8ce1ad /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/8d00c8ba3be23f175397c10a9c5aaf91cc8ce1ad/basic.py |
indx = cols[:,newaxis]*ones((1,rN)) + \ rows[newaxis,:]*ones((cN,1)) - 1 | indx = cols[:,newaxis]*ones((1,rN),dtype=int) + \ rows[newaxis,:]*ones((cN,1),dtype=int) - 1 | 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) | 8d00c8ba3be23f175397c10a9c5aaf91cc8ce1ad /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/8d00c8ba3be23f175397c10a9c5aaf91cc8ce1ad/basic.py |
lfit = Results(L.lstsq(self.wdesign, Z)[0]) | lfit = Results(L.lstsq(self.wdesign, Z)[0], 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) | af7b6951110ce17903406fde26c729dadde75f31 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/af7b6951110ce17903406fde26c729dadde75f31/regression.py |
lfit.Y = 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) | af7b6951110ce17903406fde26c729dadde75f31 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/af7b6951110ce17903406fde26c729dadde75f31/regression.py |
|
lfit = Results(N.dot(self.calc_beta, Z), | lfit = Results(N.dot(self.calc_beta, Z), Y, | def fit(self, Y, **keywords): """ Full \'fit\' of the model including estimate of covariance matrix, (whitened) residuals and scale. | af7b6951110ce17903406fde26c729dadde75f31 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/af7b6951110ce17903406fde26c729dadde75f31/regression.py |
lfit.Y = Y | def fit(self, Y, **keywords): """ Full \'fit\' of the model including estimate of covariance matrix, (whitened) residuals and scale. | af7b6951110ce17903406fde26c729dadde75f31 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/af7b6951110ce17903406fde26c729dadde75f31/regression.py |
|
def norm_resid(self): """ Residuals, normalized to have unit length. | af7b6951110ce17903406fde26c729dadde75f31 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/af7b6951110ce17903406fde26c729dadde75f31/regression.py |
||
norm_resid = self.resid * N.multiply.outer(N.ones(Y.shape[0]), sdd) | norm_resid = self.resid * N.multiply.outer(N.ones(self.Y.shape[0]), sdd) | def norm_resid(self): """ Residuals, normalized to have unit length. | af7b6951110ce17903406fde26c729dadde75f31 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/af7b6951110ce17903406fde26c729dadde75f31/regression.py |
if not adjusted: ratio *= ((Y.shape[0] - 1) / self.df_resid) | if not adjusted: ratio *= ((self.Y.shape[0] - 1) / self.df_resid) | 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 | af7b6951110ce17903406fde26c729dadde75f31 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/af7b6951110ce17903406fde26c729dadde75f31/regression.py |
from scipy.misc import _common_type ct = _common_type(obs,code_book) | from scipy.misc import x_common_type ct = x_common_type(obs,code_book) | 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 | 66282068cbd84edcddaa490e8207299a4f99045a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/66282068cbd84edcddaa490e8207299a4f99045a/vq.py |
print 'py' | 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 | 66282068cbd84edcddaa490e8207299a4f99045a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/66282068cbd84edcddaa490e8207299a4f99045a/vq.py |
|
im = asarray(im) | im = MLab.asarray(im) | 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 | c025bc502e82aee214768daca0484b6ed89d9139 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/c025bc502e82aee214768daca0484b6ed89d9139/signaltools.py |
lMean = correlate(im,ones(mysize),1) / MLab.prod(mysize) | lMean = correlate(im,MLab.ones(mysize),1) / MLab.prod(mysize) | 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 | c025bc502e82aee214768daca0484b6ed89d9139 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/c025bc502e82aee214768daca0484b6ed89d9139/signaltools.py |
lVar = correlate(im**2,ones(mysize),1) / MLab.prod(mysize) - lMean**2 | lVar = correlate(im**2,MLab.ones(mysize),1) / MLab.prod(mysize) - lMean**2 | 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 | c025bc502e82aee214768daca0484b6ed89d9139 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/c025bc502e82aee214768daca0484b6ed89d9139/signaltools.py |
noise = MLab.mean(ravel(lVar)) | noise = MLab.mean(MLab.ravel(lVar)) | 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 | c025bc502e82aee214768daca0484b6ed89d9139 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/c025bc502e82aee214768daca0484b6ed89d9139/signaltools.py |
gist.plsys(savesys) | if savesys > 0: gist.plsys(savesys) | 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 | f8186bdf4dbe42c50f54cf3a0062b5bc67aa51d8 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/f8186bdf4dbe42c50f54cf3a0062b5bc67aa51d8/Mplot.py |
[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)], | [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)], | 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) | cc0cc63c848c1f9bf06e9ff0673e6d5d1d89f766 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc0cc63c848c1f9bf06e9ff0673e6d5d1d89f766/test_basic.py |
[x,w] = P_roots(n) | [x,w] = p_roots(n) | 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 | 58a7ddfe107d57ab71db9e15ec1eb934835ca7e3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/58a7ddfe107d57ab71db9e15ec1eb934835ca7e3/quadrature.py |
return (kvp(v-1,z,n-1) - kvp(v+1,z,n-1))/2.0 | 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 | 25fdc9a434d27ad47c3e1b11ae461962bd71e2fe /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/25fdc9a434d27ad47c3e1b11ae461962bd71e2fe/basic.py |
return (ivp(v-1,z,n-1) - ivp(v+1,z,n-1))/2.0 | 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 | 25fdc9a434d27ad47c3e1b11ae461962bd71e2fe /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/25fdc9a434d27ad47c3e1b11ae461962bd71e2fe/basic.py |
x0 = asarray(x0) | x0 = asfarray(x0) | 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 | 0998927eeb572b45c05d84192cc1bd490bd9cad1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/0998927eeb572b45c05d84192cc1bd490bd9cad1/optimize.py |
extra_args = (func, p, xi) + args | extra_args = (func, p, xi, args) | 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 | 0998927eeb572b45c05d84192cc1bd490bd9cad1 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/0998927eeb572b45c05d84192cc1bd490bd9cad1/optimize.py |
tc = 1.0/max(abs(vals.real)) T = arange(0,8*tc,8*tc / float(N)) | tc = 1.0/max(abs(real(vals))) T = arange(0,10*tc,10*tc / float(N)) | 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 | 268e9b5bffbd8a297de272073e03dd07dffaa5bc /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/268e9b5bffbd8a297de272073e03dd07dffaa5bc/ltisys.py |
winfun = bohman | winfunc = bohman | 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) | 6d365e1efe06bcd9acb52e95effa641fc7813fbf /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6d365e1efe06bcd9acb52e95effa641fc7813fbf/signaltools.py |
winfun = nuttall | winfunc = nuttall | 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) | 6d365e1efe06bcd9acb52e95effa641fc7813fbf /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6d365e1efe06bcd9acb52e95effa641fc7813fbf/signaltools.py |
winfu = barthann | winfunc = barthann | 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) | 6d365e1efe06bcd9acb52e95effa641fc7813fbf /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/6d365e1efe06bcd9acb52e95effa641fc7813fbf/signaltools.py |
(1000,975):47641862536236518640933948075167736642053976275040L | (1000,975):47641862536236518640933948075167736642053976275040L, | 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]) | a13a6ebfbfdb688eadbeb3fdfe185e17515fc763 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/a13a6ebfbfdb688eadbeb3fdfe185e17515fc763/test_common.py |
print llx+width+deltax, ypos-deltay | 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 | b20fe2f8ff483286a18bc9dfd6b487a064310134 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b20fe2f8ff483286a18bc9dfd6b487a064310134/Mplot.py |
|
raise RunTimeError, "Infinity comparisons don't work for you." | raise RuntimeError, "Infinity comparisons don't work for you." | 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) | dec9d9c0137ab47d385ea8be78edc5e5e33bf2b3 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/dec9d9c0137ab47d385ea8be78edc5e5e33bf2b3/quadpack.py |
err_type, err_msg = sys.exc_info()[1] | err_type, err_msg = sys.exc_info()[:2] | 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 | 8c750fdeaf19e4ed95953ff790453cca4d7a40d7 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/8c750fdeaf19e4ed95953ff790453cca4d7a40d7/cow.py |
from scipy.basic.random import normal | from scipy.random import normal | 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 | 32ce80164cb0c9e068c7132831c43e7c023b2a7b /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/32ce80164cb0c9e068c7132831c43e7c023b2a7b/test_fblas.py |
y = scipy.squeeze(x) | y = _minsqueeze(x) | 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 | 3369f4b37045cebc122c3c4201d220da27c6a376 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3369f4b37045cebc122c3c4201d220da27c6a376/Mplot.py |
y = scipy.squeeze(y) x = scipy.squeeze(x) | y = _minsqueeze(y) x = _minsqueeze(x) | 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 | 3369f4b37045cebc122c3c4201d220da27c6a376 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3369f4b37045cebc122c3c4201d220da27c6a376/Mplot.py |
self.image_pixels_per_axis_unit =array(matrix.shape,Float)/axis_lengths | self.image_pixels_per_axis_unit =array((matrix.shape[1], matrix.shape[0]),Float)/axis_lengths | 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() | 5418e2ef7c1d6ad75b66d8f5ac3a7f580289bd32 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5418e2ef7c1d6ad75b66d8f5ac3a7f580289bd32/plot_objects.py |
image = wx.wxEmptyImage(self.matrix.shape[0],self.matrix.shape[1]) | image = wx.wxEmptyImage(self.matrix.shape[1],self.matrix.shape[0]) | 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 | 5418e2ef7c1d6ad75b66d8f5ac3a7f580289bd32 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5418e2ef7c1d6ad75b66d8f5ac3a7f580289bd32/plot_objects.py |
sz = sz* abs(self.scale) sz = sz.astype(Int) scaled_image = self.the_image.Scale(abs(sz[0]),abs(sz[1])) | sz = sz* self.scale sz = abs(sz.astype(Int)) scaled_image = self.the_image.Scale(sz[0],sz[1]) | 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() | 5418e2ef7c1d6ad75b66d8f5ac3a7f580289bd32 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5418e2ef7c1d6ad75b66d8f5ac3a7f580289bd32/plot_objects.py |
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.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 | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
x0 = ones(self.dims,'d') lrange = x0*self.lower urange = x0*self.upper | lrange = self.lower urange = self.upper | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
for n in range(self.Ninit): x0[:] = random.uniform(size=self.dims)*(urange-lrange) + lrange fval = self.func(x0,*self.args) | for _ in range(self.Ninit): x0 = random.uniform(size=self.dims)*(urange-lrange) + lrange fval = self.func(x0, *self.args) | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
if (p > random.uniform(0.0,1.0)): | if (p > random.uniform(0.0, 1.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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
self.c = self.m * exp(-self.n * self.quench / self.dims) | self.c = self.m * exp(-self.n * self.quench) | 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) | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
u = squeeze(random.uniform(0.0,1.0, size=len(x0))) | u = squeeze(random.uniform(0.0, 1.0, size=self.dims)) | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
self.T = self.T0*exp(-self.c * self.k**(self.quench/self.dims)) | self.T = self.T0*exp(-self.c * self.k**(self.quench)) | def update_temp(self): self.T = self.T0*exp(-self.c * self.k**(self.quench/self.dims)) self.k += 1 return | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
numbers = squeeze(random.uniform(-pi/2,pi/2, size=len(x0))) | numbers = squeeze(random.uniform(-pi/2, pi/2, size=self.dims)) | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
std = min(sqrt(self.T), (self.upper-self.lower)/3.0/self.learn_rate) | std = minimum(sqrt(self.T)*ones(self.dims), (self.upper-self.lower)/3.0/self.learn_rate) | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
xc = squeeze(random.normal(0,std*self.learn_rate, size=len(x0))) xnew = x0 + xc | xc = squeeze(random.normal(0, 1.0, size=self.dims)) xnew = x0 + xc*std*self.learn_rate | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
Outputs: (xmin, {Jmin, T, feval, iter, accept,} retval) | Outputs: (xmin, {Jmin, T, feval, iters, accept,} 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, iter, schedule.accepted, retval else: return best_state.x, retval | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
iter -- Number of cooling iterations | iters -- Number of cooling iterations | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
lower = asarray(lower) upper = asarray(upper) | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
|
schedule.init(dims=len(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, | schedule.init(dims=shape(x0),func=func,args=args,boltzmann=boltzmann,T0=T0, | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
feval = 0 done = 0 | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
|
fqueue = [100,300,500,700] iter=0 | fqueue = [100, 300, 500, 700] iters = 0 | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
xnew = schedule.update_guess(x0) fval = func(xnew,*args) | current_state.x = schedule.update_guess(last_state.x) current_state.cost = func(current_state.x,*args) | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
current_state.x = asarray(xnew).copy() current_state.cost = fval | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
|
if dE < 0: last_state.x = current_state.x.copy() last_state.cost = current_state.cost | last_state.x = current_state.x.copy() last_state.cost = current_state.cost | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
iter += 1 | iters += 1 | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
tmp = fqueue.pop(0) | fqueue.pop(0) | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
print "Warning: Cooled to %f at %f but this is not" \ % (squeeze(last_state.cost), squeeze(last_state.x)) \ | print "Warning: Cooled to %f at %s but this is not" \ % (squeeze(last_state.cost), str(squeeze(last_state.x))) \ | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
if (iter > maxiter): | if (iters > maxiter): | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
schedule.feval, iter, schedule.accepted, retval | schedule.feval, iters, schedule.accepted, 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, iter, schedule.accepted, retval else: return best_state.x, retval | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |
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') | 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 | 5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5d83f70d8d9b65f40e4932969c9d8113c8f4f8cd/anneal.py |