rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
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 |
|
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] |
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. |
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) |
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) |
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) |
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) |
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 ' ==================================' |
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 ' ==================================' |
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]) |
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]) |
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) |
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) |
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) |
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) |
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]) |
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]) |
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) |
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) |
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) |
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) |
|
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. |
lfit.Y = Y | def fit(self, Y, **keywords): """ Full \'fit\' of the model including estimate of covariance matrix, (whitened) residuals and scale. |
|
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. |
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 |
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 |
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 |
|
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 |
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 |
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 |
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 |
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 |
[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) |
[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 |
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 |
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 |
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 |
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 |
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 |
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) |
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) |
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) |
(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]) |
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 |
|
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) |
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 |
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 |
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 |
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 |
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() |
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 |
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() |
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 |
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 |
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 |
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) |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 |
|
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 |
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 |
|
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 |
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 |
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 |
|
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 |
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 |
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 |
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 |
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 |
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 |
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 |
|
def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, | def fmin_bfgs(f, x0, fprime=None, args=(), maxgtol=1e-5, epsilon=_epsilon, | def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 198. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. avegtol -- minimum average value of gradient for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be. maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if non-zero """ app_fprime = 0 if fprime is None: app_fprime = 1 x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls = 0 grad_calls = 0 k = 0 N = len(x0) gtol = N*avegtol I = MLab.eye(N) Hk = I old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 if app_fprime: gfk = apply(approx_fprime,(x0,f,epsilon)+args) myfprime = (approx_fprime,epsilon) func_calls = func_calls + len(x0) + 1 else: gfk = apply(fprime,(x0,)+args) myfprime = fprime grad_calls = grad_calls + 1 xk = x0 if retall: allvecs = [x0] sk = [2*gtol] warnflag = 0 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
avegtol -- minimum average value of gradient for stopping | maxgtol -- maximum allowable gradient magnitude for stopping | def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 198. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. avegtol -- minimum average value of gradient for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be. maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if non-zero """ app_fprime = 0 if fprime is None: app_fprime = 1 x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls = 0 grad_calls = 0 k = 0 N = len(x0) gtol = N*avegtol I = MLab.eye(N) Hk = I old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 if app_fprime: gfk = apply(approx_fprime,(x0,f,epsilon)+args) myfprime = (approx_fprime,epsilon) func_calls = func_calls + len(x0) + 1 else: gfk = apply(fprime,(x0,)+args) myfprime = fprime grad_calls = grad_calls + 1 xk = x0 if retall: allvecs = [x0] sk = [2*gtol] warnflag = 0 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be. | def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 198. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. avegtol -- minimum average value of gradient for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be. maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if non-zero """ app_fprime = 0 if fprime is None: app_fprime = 1 x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls = 0 grad_calls = 0 k = 0 N = len(x0) gtol = N*avegtol I = MLab.eye(N) Hk = I old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 if app_fprime: gfk = apply(approx_fprime,(x0,f,epsilon)+args) myfprime = (approx_fprime,epsilon) func_calls = func_calls + len(x0) + 1 else: gfk = apply(fprime,(x0,)+args) myfprime = fprime grad_calls = grad_calls + 1 xk = x0 if retall: allvecs = [x0] sk = [2*gtol] warnflag = 0 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
|
gtol = N*avegtol | def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 198. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. avegtol -- minimum average value of gradient for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be. maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if non-zero """ app_fprime = 0 if fprime is None: app_fprime = 1 x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls = 0 grad_calls = 0 k = 0 N = len(x0) gtol = N*avegtol I = MLab.eye(N) Hk = I old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 if app_fprime: gfk = apply(approx_fprime,(x0,f,epsilon)+args) myfprime = (approx_fprime,epsilon) func_calls = func_calls + len(x0) + 1 else: gfk = apply(fprime,(x0,)+args) myfprime = fprime grad_calls = grad_calls + 1 xk = x0 if retall: allvecs = [x0] sk = [2*gtol] warnflag = 0 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
|
while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): | while (Num.maximum.reduce(abs(gfk)) > gtol) and (k < maxiter): | def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 198. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. avegtol -- minimum average value of gradient for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be. maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if non-zero """ app_fprime = 0 if fprime is None: app_fprime = 1 x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls = 0 grad_calls = 0 k = 0 N = len(x0) gtol = N*avegtol I = MLab.eye(N) Hk = I old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 if app_fprime: gfk = apply(approx_fprime,(x0,f,epsilon)+args) myfprime = (approx_fprime,epsilon) func_calls = func_calls + len(x0) + 1 else: gfk = apply(fprime,(x0,)+args) myfprime = fprime grad_calls = grad_calls + 1 xk = x0 if retall: allvecs = [x0] sk = [2*gtol] warnflag = 0 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
warnflag = 2 break A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] | print "Divide by zero encountered: Hessian calculation reset." Hk = I else: A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] | def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 198. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. avegtol -- minimum average value of gradient for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be. maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if non-zero """ app_fprime = 0 if fprime is None: app_fprime = 1 x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls = 0 grad_calls = 0 k = 0 N = len(x0) gtol = N*avegtol I = MLab.eye(N) Hk = I old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 if app_fprime: gfk = apply(approx_fprime,(x0,f,epsilon)+args) myfprime = (approx_fprime,epsilon) func_calls = func_calls + len(x0) + 1 else: gfk = apply(fprime,(x0,)+args) myfprime = fprime grad_calls = grad_calls + 1 xk = x0 if retall: allvecs = [x0] sk = [2*gtol] warnflag = 0 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break A1 = I - sk[:,Num.NewAxis] * yk[Num.NewAxis,:] * rhok A2 = I - yk[:,Num.NewAxis] * sk[Num.NewAxis,:] * rhok Hk = Num.dot(A1,Num.dot(Hk,A2)) + rhok * sk[:,Num.NewAxis] \ * sk[Num.NewAxis,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
x = fmin_bfgs(rosen, x0, avegtol=1e-4, maxiter=100) | x = fmin_bfgs(rosen, x0, gtol=1e-4, maxiter=100) | def _scalarfunc(*params): params = squeeze(asarray(params)) return func(params,*args) |
return a.var() | n = len(a) return a.var()*(n/(n-1.)) | def tvar(a, limits=None, inclusive=(1,1)): """Returns the sample variance of values in an array, (i.e., using N-1), ignoring values strictly outside the sequence passed to 'limits'. Note: either limit in the sequence, or the value of limits itself, can be set to None. The inclusive list/tuple determines whether the lower and upper limiting bounds (respectively) are open/exclusive (0) or closed/inclusive (1). """ a = asarray(a) a = a.astype(float).ravel() if limits is None: return a.var() am = mask_to_limits(a, limits, inclusive) return masked_var(am) |
n = float(len(ravel(a))) | n = float(len(a)) | def tsem(a, limits=None, inclusive=(True,True)): """Returns the standard error of the mean for the values in an array, (i.e., using N for the denominator), ignoring values strictly outside the sequence passed to 'limits'. Note: either limit in the sequence, or the value of limits itself, can be set to None. The inclusive list/tuple determines whether the lower and upper limiting bounds (respectively) are open/exclusive (0) or closed/inclusive (1). """ a = asarray(a).ravel() if limits is None: n = float(len(ravel(a))) return a.std()/sqrt(n) am = mask_to_limits(a.ravel(), limits, inclusive) sd = sqrt(masked_var(am)) return sd / am.count() |
correction = np.sqrt(float(n-1) / n) return a.std(axis)/a.mean(axis) * correction | return a.std(axis)/a.mean(axis) | def variation(a, axis=0): """Computes the coefficient of variation, the ratio of the biased standard deviation to the mean. Parameters ---------- a : array axis : int or None References ---------- [CRCProbStat2000] section 2.2.20 """ a, axis = _chk_asarray(a, axis) n = a.shape[axis] correction = np.sqrt(float(n-1) / n) return a.std(axis)/a.mean(axis) * correction |
rpb = (y1m - y0m)*np.sqrt(phat * (1-phat)) / (y.std() * np.sqrt((n-1)/float(n))) | rpb = (y1m - y0m)*np.sqrt(phat * (1-phat)) / y.std() | def pointbiserialr(x, y): # comment: I am changing the semantics somewhat. The original function is # fairly general and accepts an x sequence that has any type of thing in it as # along as there are only two unique items. I am going to restrict this to # a boolean array for my sanity. """Calculates a point biserial correlation coefficient and the associated p-value. The point biserial correlation is used to measure the relationship between a binary variable, x, and a continuous variable, y. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply a determinative relationship. Parameters ---------- x : array of bools y : array of floats Returns ------- (point-biserial r, 2-tailed p-value) References ---------- http://www.childrens-mercy.org/stats/definitions/biserial.htm """ ## Test data: http://support.sas.com/ctx/samples/index.jsp?sid=490&tab=output # x = [1,0,1,1,1,1,0,1,0,0,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1] # y = [14.8,13.8,12.4,10.1,7.1,6.1,5.8,4.6,4.3,3.5,3.3,3.2,3.0,2.8,2.8,2.5, # 2.4,2.3,2.1,1.7,1.7,1.5,1.3,1.3,1.2,1.2,1.1,0.8,0.7,0.6,0.5,0.2,0.2, # 0.1] # rpb = 0.36149 x = np.asarray(x, dtype=bool) y = np.asarray(y, dtype=float) n = len(x) # phat is the fraction of x values that are True phat = x.sum() / float(len(x)) y0 = y[~x] # y-values where x is False y1 = y[x] # y-values where x is True y0m = y0.mean() y1m = y1.mean() rpb = (y1m - y0m)*np.sqrt(phat * (1-phat)) / (y.std() * np.sqrt((n-1)/float(n))) df = n-2 # fixme: see comment about TINY in pearsonr() TINY = 1e-20 t = rpb*np.sqrt(df/((1.0-rpb+TINY)*(1.0+rpb+TINY))) prob = betai(0.5*df, 0.5, df/(df+t*t)) return rpb, prob |
def __init__(self,file_name,permission='r',format='n'): if type(file_name) == type(''): if sys.platform=='win32' and 'b' not in permission: print "Warning: Generally fopen is used for opening binary\n" + \ "files, which on this system requires attaching a 'b' \n" + \ "to the permission flag." | def __init__(self,file_name,permission='rb',format='n'): if 'b' not in permission: permission += 'b' if type(file_name) in (types.StringType, types.UnicodeType): | def __init__(self,file_name,permission='r',format='n'): if type(file_name) == type(''): if sys.platform=='win32' and 'b' not in permission: print "Warning: Generally fopen is used for opening binary\n" + \ "files, which on this system requires attaching a 'b' \n" + \ "to the permission flag." self.__dict__['fid'] = open(file_name,permission) elif 'fileno' in file_name.__methods__: # first argument is an open file self.__dict__['fid'] = file_name if format in ['native','n','default']: self.__dict__['bs'] = 0 self.__dict__['format'] = 'native' elif format in ['ieee-le','l','little-endian','le']: self.__dict__['bs'] = not LittleEndian self.__dict__['format'] = 'ieee-le' elif format in ['ieee-be','b','big-endian','be']: self.__dict__['bs'] = LittleEndian self.__dict__['format'] = 'ieee-be' else: raise ValueError, "Unrecognized format: " + format |
shape = tuple(count) count = product(shape) | shape = list(count) minus_ones = shape.count(-1) if minus_ones == 0: count = product(shape) elif minus_ones == 1: now = self.fid.tell() self.fid.seek(0,2) end = self.fid.tell() self.fid.seek(now) remaining_bytes = end - now know_dimensions_size = -product(count) * getsize_type(stype)[0] unknown_dimension_size, illegal = divmod(remaining_bytes, know_dimensions_size) if illegal: raise ValueError("unknown dimension doesn't match filesize") shape[shape.index(-1)] = unknown_dimension_size count = product(shape) else: raise ValueError( "illegal count; can only specify one unknown dimension") shape = tuple(shape) | def read(self,count,stype,rtype=None,bs=None): """Read data from file and return it in a Numeric array. |
if type(fmt) == type(''): | if type(fmt) in (types.StringType, types.UnicodeType): | def fort_write(self,fmt,*args): """Write a Fortran binary record. |
fid = open(test_name,'r') | fid = open(test_name,'rb') | def loadmat(name, dict=None, appendmat=1): """Load the MATLAB mat file saved in level 1.0 format. If name is a full path name load it in. Otherwise search for the file on the sys.path list and load the first one found (the current directory is searched first). Only Level 1.0 MAT files are supported so far. Inputs: name -- name of the mat file (don't need .mat extension) dict -- the dictionary to insert into. If none the variables will be returned in a dictionary. appendmat -- non-zero to append the .mat extension to the end of the given filename. Outputs: If dict is None, then a dictionary of names and objects representing the stored arrays is returned. """ if appendmat and name[-4:] == ".mat": name = name[:-4] if os.sep in name: full_name = name if appendmat: full_name = name + ".mat" else: full_name = None junk,name = os.path.split(name) for path in sys.path: test_name = os.path.join(path,name) if appendmat: test_name += ".mat" try: fid = open(test_name,'r') fid.close() full_name = test_name except IOError: pass if full_name is None: raise IOError, "%s not found on the path." % name permis = 'r' if sys.platform=='win32': permis = 'rb' fid = fopen(full_name,permis) test_vals = fid.fread(4,'byte') if not (0 in test_vals): fid.close() raise ValueError, "Version 5.0 file format not supported." testtype = struct.unpack('i',test_vals.tostring()) # Check to see if the number is positive and less than 5000. if testtype[0] < 0 or testtype[0] > 4999: # wrong byte-order if LittleEndian: format = 'ieee-be' else: format = 'ieee-le' else: # otherwise we are O.K. if LittleEndian: format = 'ieee-le' else: format = 'ieee-be' fid.close() fid = fopen(full_name, permis, format) length = fid.size() fid.rewind() # back to the begining defnames = [] thisdict = {} while 1: if (fid.tell() == length): break header = fid.fread(5,'int') if len(header) != 5: fid.close() print "Warning: Read error in file." break M,rest = divmod(header[0],1000) O,rest = divmod(rest,100) P,rest = divmod(rest,10) T = rest if (M > 1): fid.close() raise ValueError, "Unsupported binary format." if (O != 0): fid.close() raise ValuError, "Hundreds digit of first integer should be zero." if (P == 4): fid.close() raise ValueError, "No support for 16-bit unsigned integers." if (T not in [0,1]): fid.close() raise ValueError, "Cannot handle sparse matrices, yet." storage = {0:'d',1:'f',2:'i',3:'s',5:'b'}[P] varname = fid.fread(header[-1],'char')[:-1] varname = varname.tostring() defnames.append(varname) numels = header[1]*header[2] if T == 0: # Text data data = r1array(fid.fread(numels,storage)) if header[3]: # imaginary data data2 = fid.fread(numels,storage) if data.typecode() == 'f' and data2.typecode() == 'f': new = zeros(data.shape,'F') new.real = data new.imag = data2 data = new del(new) del(data2) if len(data) > 1: data.shape = (header[2], header[1]) thisdict[varname] = transpose(squeeze(data)) else: thisdict[varname] = data else: data = r1array(fid.fread(numels,storage,'char')) if len(data) > 1: data.shape = (header[2], header[1]) thisdict[varname] = transpose(squeeze(data)) else: thisdict[varname] = data fid.close() if dict is not None: print "Names defined = ", defnames dict.update(thisdict) else: return thisdict |
permis = 'r' if sys.platform=='win32': permis = 'rb' fid = fopen(full_name,permis) | fid = fopen(full_name,'rb') | def loadmat(name, dict=None, appendmat=1): """Load the MATLAB mat file saved in level 1.0 format. If name is a full path name load it in. Otherwise search for the file on the sys.path list and load the first one found (the current directory is searched first). Only Level 1.0 MAT files are supported so far. Inputs: name -- name of the mat file (don't need .mat extension) dict -- the dictionary to insert into. If none the variables will be returned in a dictionary. appendmat -- non-zero to append the .mat extension to the end of the given filename. Outputs: If dict is None, then a dictionary of names and objects representing the stored arrays is returned. """ if appendmat and name[-4:] == ".mat": name = name[:-4] if os.sep in name: full_name = name if appendmat: full_name = name + ".mat" else: full_name = None junk,name = os.path.split(name) for path in sys.path: test_name = os.path.join(path,name) if appendmat: test_name += ".mat" try: fid = open(test_name,'r') fid.close() full_name = test_name except IOError: pass if full_name is None: raise IOError, "%s not found on the path." % name permis = 'r' if sys.platform=='win32': permis = 'rb' fid = fopen(full_name,permis) test_vals = fid.fread(4,'byte') if not (0 in test_vals): fid.close() raise ValueError, "Version 5.0 file format not supported." testtype = struct.unpack('i',test_vals.tostring()) # Check to see if the number is positive and less than 5000. if testtype[0] < 0 or testtype[0] > 4999: # wrong byte-order if LittleEndian: format = 'ieee-be' else: format = 'ieee-le' else: # otherwise we are O.K. if LittleEndian: format = 'ieee-le' else: format = 'ieee-be' fid.close() fid = fopen(full_name, permis, format) length = fid.size() fid.rewind() # back to the begining defnames = [] thisdict = {} while 1: if (fid.tell() == length): break header = fid.fread(5,'int') if len(header) != 5: fid.close() print "Warning: Read error in file." break M,rest = divmod(header[0],1000) O,rest = divmod(rest,100) P,rest = divmod(rest,10) T = rest if (M > 1): fid.close() raise ValueError, "Unsupported binary format." if (O != 0): fid.close() raise ValuError, "Hundreds digit of first integer should be zero." if (P == 4): fid.close() raise ValueError, "No support for 16-bit unsigned integers." if (T not in [0,1]): fid.close() raise ValueError, "Cannot handle sparse matrices, yet." storage = {0:'d',1:'f',2:'i',3:'s',5:'b'}[P] varname = fid.fread(header[-1],'char')[:-1] varname = varname.tostring() defnames.append(varname) numels = header[1]*header[2] if T == 0: # Text data data = r1array(fid.fread(numels,storage)) if header[3]: # imaginary data data2 = fid.fread(numels,storage) if data.typecode() == 'f' and data2.typecode() == 'f': new = zeros(data.shape,'F') new.real = data new.imag = data2 data = new del(new) del(data2) if len(data) > 1: data.shape = (header[2], header[1]) thisdict[varname] = transpose(squeeze(data)) else: thisdict[varname] = data else: data = r1array(fid.fread(numels,storage,'char')) if len(data) > 1: data.shape = (header[2], header[1]) thisdict[varname] = transpose(squeeze(data)) else: thisdict[varname] = data fid.close() if dict is not None: print "Names defined = ", defnames dict.update(thisdict) else: return thisdict |
winnum = xplt.window() | winnum = gist.window() | 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 if "hold" in keywds.keys(): _hold = keywds['hold'] if _hold or override: pass else: gist.fma() gist.animate(0) winnum = xplt.window() if winnum < 0: xplt.window(0) nargs = len(args) if nargs == 0: y = x x = Numeric.arange(0,len(y)) if scipy.array_iscomplex(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) 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.array_iscomplex(x) or scipy.array_iscomplex(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) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark) 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 |
xplt.window(0) | gist.window(0) | 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 if "hold" in keywds.keys(): _hold = keywds['hold'] if _hold or override: pass else: gist.fma() gist.animate(0) winnum = xplt.window() if winnum < 0: xplt.window(0) nargs = len(args) if nargs == 0: y = x x = Numeric.arange(0,len(y)) if scipy.array_iscomplex(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) 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.array_iscomplex(x) or scipy.array_iscomplex(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) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return |
def setdiag(self, values, k=0): """Fills the diagonal elements {a_ii} with the values from the given sequence. If k != 0, fills the off-diagonal elements {a_{i,i+k}} instead. """ M, N = self.shape if len(values) > min(M, N+k): raise ValueError, "sequence of target values is too long" for i, v in enumerate(values): self[i, i+k] = v return | def mean(self, axis=None): """Average the matrix over the given axis. If the axis is None, average over both rows and columns, returning a scalar. """ if axis==0: mean = self.sum(0) mean *= 1.0 / self.shape[0] return mean elif axis==1: mean = self.sum(1) mean *= 1.0 / self.shape[1] return mean elif axis is None: return self.sum(None) * 1.0 / (self.shape[0]*self.shape[1]) else: raise ValueError, "axis out of bounds" |
|
def setdiag(self, values, k=0): M, N = self.shape assert len(values) >= max(M, N) for i in xrange(min(M, N-k)): self[i, i+k] = values[i] return | def setdiag(self, values, k=0): M, N = self.shape assert len(values) >= max(M, N) for i in xrange(min(M, N-k)): self[i, i+k] = values[i] return |
|
if isdense(x): | if isinstance(x, lil_matrix): if x.shape == (1, self.shape[1]): self.rows[i] = x.rows[0] self.data[i] = x.data[0] elif x.shape == (1, len(seq)): for k, col in enumerate(seq): self[i, col] = x[0, k] else: raise ValueError, "source and destination must have" \ " the same shape" return elif isinstance(x, csr_matrix): if x.shape != (1, self.shape[1]): raise ValueError, "sparse matrix source must be (1 x n)" self.rows[i] = x.colind.tolist() self.data[i] = x.data.tolist() else: | def __setitem__(self, index, x): try: assert len(index) == 2 except (AssertionError, TypeError): raise IndexError, "invalid index" i, j = index if isinstance(i, int): if not (i>=0 and i<self.shape[0]): raise IndexError, "lil_matrix index out of range" else: if isinstance(i, slice): seq = xrange(i.start or 0, i.stop or self.shape[1], i.step or 1) elif operator.isSequenceType(i): seq = i else: raise IndexError, "invalid index" try: if not len(x) == len(seq): raise ValueError, "number of elements in source must be" \ " same as number of elements in destimation" except TypeError: # Either x or seq is not a sequence. Note that a sparse matrix # is also not a sequence under this definition. # Currently we don't support setting to/from non-sequence types. # This could be enhanced, though, to allow a scalar source, # and/or a sparse vector. raise TypeError, "unsupported type for lil_matrix.__setitem__" else: # Sequence: call __setitem__ recursively, once for each row for i in xrange(len(seq)): self[seq[i], index[1]] = x[i] return |
x = asarray(x).squeeze() | try: x = asarray(x).squeeze() except Error, e: raise TypeError, "unsupported type for" \ " lil_matrix.__setitem__" | def __setitem__(self, index, x): try: assert len(index) == 2 except (AssertionError, TypeError): raise IndexError, "invalid index" i, j = index if isinstance(i, int): if not (i>=0 and i<self.shape[0]): raise IndexError, "lil_matrix index out of range" else: if isinstance(i, slice): seq = xrange(i.start or 0, i.stop or self.shape[1], i.step or 1) elif operator.isSequenceType(i): seq = i else: raise IndexError, "invalid index" try: if not len(x) == len(seq): raise ValueError, "number of elements in source must be" \ " same as number of elements in destimation" except TypeError: # Either x or seq is not a sequence. Note that a sparse matrix # is also not a sequence under this definition. # Currently we don't support setting to/from non-sequence types. # This could be enhanced, though, to allow a scalar source, # and/or a sparse vector. raise TypeError, "unsupported type for lil_matrix.__setitem__" else: # Sequence: call __setitem__ recursively, once for each row for i in xrange(len(seq)): self[seq[i], index[1]] = x[i] return |
elif isinstance(x, lil_matrix): if x.shape != (1, self.shape[1]): raise ValueError, "sparse matrix source must be (1 x n)" self.rows[i] = x.rows[0] self.data[i] = x.data[0] elif isinstance(x, csr_matrix): if x.shape != (1, self.shape[1]): raise ValueError, "sparse matrix source must be (1 x n)" self.rows[i] = x.colind.tolist() self.data[i] = x.data.tolist() else: raise TypeError, "unsupported type for" \ " lil_matrix.__setitem__" | def __setitem__(self, index, x): try: assert len(index) == 2 except (AssertionError, TypeError): raise IndexError, "invalid index" i, j = index if isinstance(i, int): if not (i>=0 and i<self.shape[0]): raise IndexError, "lil_matrix index out of range" else: if isinstance(i, slice): seq = xrange(i.start or 0, i.stop or self.shape[1], i.step or 1) elif operator.isSequenceType(i): seq = i else: raise IndexError, "invalid index" try: if not len(x) == len(seq): raise ValueError, "number of elements in source must be" \ " same as number of elements in destimation" except TypeError: # Either x or seq is not a sequence. Note that a sparse matrix # is also not a sequence under this definition. # Currently we don't support setting to/from non-sequence types. # This could be enhanced, though, to allow a scalar source, # and/or a sparse vector. raise TypeError, "unsupported type for lil_matrix.__setitem__" else: # Sequence: call __setitem__ recursively, once for each row for i in xrange(len(seq)): self[seq[i], index[1]] = x[i] return |
|
return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0] | print "data-ftype: %s compared to data %s" % (ftype, data.dtype.char) print "Calling _superlu.%sgssv" % ftype return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0] | def solve(A, b, permc_spec=2): if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'): raise ValueError, "sparse matrix must be able to return CSC format--"\ "A.tocsc()--or CSR format--A.tocsr()" if not hasattr(A, 'shape'): raise ValueError, "sparse matrix must be able to return shape" \ " (rows, cols) = A.shape" M, N = A.shape if (M != N): raise ValueError, "matrix must be square" if isUmfpack and useUmfpack: mat = _toCS_umfpack( A ) if mat.dtype.char not in 'dD': raise ValueError, "convert matrix data to double, please, using"\ " .astype(), or set sparse.useUmfpack = False" family = {'d' : 'di', 'D' : 'zi'} umf = umfpack.UmfpackContext( family[mat.dtype.char] ) return umf.linsolve( umfpack.UMFPACK_A, mat, b, autoTranspose = True ) else: mat, csc = _toCS_superLU( A ) ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr gssv = eval('_superlu.' + ftype + 'gssv') return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0] |