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... |
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... |
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... |
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... |
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 ... |
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 ... |
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 |... |
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 |... |
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.isscal... |
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: toepli... |
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. ... |
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. ... | |
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... |
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... |
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... |
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... |
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 onl... |
[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... |
[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 -- ... |
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 ... |
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 _... |
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... |
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, blackmanharri... |
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, blackmanharri... |
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, blackmanharri... |
(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 t... | |
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 el... |
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... |
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) * mul... |
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 onl... |
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 onl... |
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])) els... |
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. i... |
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:... |
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:... |
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 t... |
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 t... |
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 t... | |
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 t... |
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 t... | |
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 t... |
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 t... |
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 t... | |
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 t... |
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 t... |
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 t... |
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 t... |
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 t... |
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 t... |
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... | 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 t... | |
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 ... |
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 ... |
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 ... | |
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 ... | |
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 ... |
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 ... |
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 l... |
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 incl... |
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) / ... |
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 co... |
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'] = ope... |
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... | 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: ... |
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: ... |
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 onl... |
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 onl... |
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): sel... | 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: retur... | |
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)... | 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 ... |
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 ... |
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.coli... | 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 ... | |
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.