rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
except AttributeError:
except (AttributeError, TypeError):
def __call__(self,*args): for arg in args: try: n = len(arg) if (n==0): return self.zerocall(args) except AttributeError: pass return squeeze(arraymap(self.thefunc,args,self.otypes))
sources=['sigtoolsmodule.c','firfilter.c','medianfilter.c'],
sources=['sigtoolsmodule.c', 'firfilter.c','medianfilter.c'], depends = ['sigtools.h']
def configuration(parent_package='',top_path=None): from scipy.distutils.misc_util import Configuration config = Configuration('signal', parent_package, top_path) config.add_data_dir('tests') config.add_extension('sigtools', sources=['sigtoolsmodule.c','firfilter.c','medianfilter.c'], ) config.add_extension('spline...
def inverse(self, z):
def inverse(self, x):
def inverse(self, z): return N.power(x, 1. / self.power)
"""Associated Legendre functions of the second kind, Pmn(z) and its
"""Associated Legendre functions of the first kind, Pmn(z) and its
def lpmn(m,n,z): """Associated Legendre functions of the second kind, Pmn(z) and its derivative, Pmn'(z) of order m and degree n. Returns two arrays of size (m+1,n+1) containing Pmn(z) and Pmn'(z) for all orders from 0..m and degrees from 0..n. z can be complex. """ if not isscalar(m) or (abs(m)>n): raise ValueError,...
temp = coo_matrix((s, ij), dims=dims, nzmax=nzmax, \
temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtypechar not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M...
temp = coo_matrix(s, ijnew, dims=(M, N), nzmax=nzmax, dtype=dtype) temp = temp.tocsr()
temp = coo_matrix(s, ijnew, dims=dims, nzmax=nzmax, dtype=dtype).tocsr()
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape...
self.colind = temp.rowind
self.colind = temp.colind
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape...
def __init__(self, obj, ij, dims=None, nzmax=None, dtype=None):
def __init__(self, obj, ij_in, dims=None, nzmax=None, dtype=None):
def __init__(self, obj, ij, dims=None, nzmax=None, dtype=None): spmatrix.__init__(self) try: # Assume the first calling convention assert len(ij) == 2 if dims is None: M = int(amax(ij[0])) N = int(amax(ij[1])) self.shape = (M, N) else: # Use 2 steps to ensure dims has length 2. M, N = dims self.shape = (M, N) self.row ...
assert len(ij) == 2
if len(ij_in) != 2: if isdense( ij_in ) and (ij_in.shape[1] == 2): ij = (ij_in[:,0], ij_in[:,1]) else: raise AssertionError else: ij = ij_in
def __init__(self, obj, ij, dims=None, nzmax=None, dtype=None): spmatrix.__init__(self) try: # Assume the first calling convention assert len(ij) == 2 if dims is None: M = int(amax(ij[0])) N = int(amax(ij[1])) self.shape = (M, N) else: # Use 2 steps to ensure dims has length 2. M, N = dims self.shape = (M, N) self.row ...
self.row = asarray(ij[0], 'i') self.col = asarray(ij[1], 'i')
self.row = asarray(ij[0]) self.col = asarray(ij[1])
def __init__(self, obj, ij, dims=None, nzmax=None, dtype=None): spmatrix.__init__(self) try: # Assume the first calling convention assert len(ij) == 2 if dims is None: M = int(amax(ij[0])) N = int(amax(ij[1])) self.shape = (M, N) else: # Use 2 steps to ensure dims has length 2. M, N = dims self.shape = (M, N) self.row ...
raise "could not import pylab"
raise ImportError, "could not import pylab"
def main(): parser = OptionParser( usage = usage ) parser.add_option( "-c", "--compare", action = "store_true", dest = "compare", default = False, help = "compare with default scipy.sparse solver [default: %default]" ) parser.add_option( "-p", "--plot", action = "store_true", dest = "plot", default = False, help = "plo...
config = Configuration(None, parent_package, top_path, maintainer = "SciPy Developers", maintainer_email = "scipy-dev@scipy.org", description = "Scientific Algorithms Library for Python", url = "http://www.scipy.org", license = 'BSD', )
config = Configuration(None, parent_package, top_path)
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path, maintainer = "SciPy Developers", maintainer_email = "scipy-dev@scipy.org", description = "Scientific Algorithms Library for Python", url = "http://www.scipy.org"...
config.name = 'scipy'
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path, maintainer = "SciPy Developers", maintainer_email = "scipy-dev@scipy.org", description = "Scientific Algorithms Library for Python", url = "http://www.scipy.org"...
from version import version as version config.dict_append(version=version)
config.get_version('Lib/version.py')
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration(None, parent_package, top_path, maintainer = "SciPy Developers", maintainer_email = "scipy-dev@scipy.org", description = "Scientific Algorithms Library for Python", url = "http://www.scipy.org"...
setup( configuration=configuration )
from version import version as version setup( name = 'scipy', version = version, maintainer = "SciPy Developers", maintainer_email = "scipy-dev@scipy.org", description = "Scientific Algorithms Library for Python", url = "http://www.scipy.org", license = 'BSD', configuration=configuration )
def setup_package(): from numpy.distutils.core import setup from numpy.distutils.misc_util import Configuration old_path = os.getcwd() local_path = os.path.dirname(os.path.abspath(sys.argv[0])) os.chdir(local_path) sys.path.insert(0,local_path) sys.path.insert(0,os.path.join(local_path,'Lib')) # to retrive version t...
from scipy.distutils.core import setup setup(**configuration(top_path=''))
setup_package()
def configuration(parent_package='',top_path=None): from scipy.distutils.misc_util import Configuration config = Configuration() config.add_subpackage('Lib') return config.todict()
winfun = blackmanharris
winfunc = blackmanharris
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 = parzen
winfunc = parzen
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...
bytestr = str(var.itemsize()*Numeric.product(var.shape))
bytestr = str(var.itemsize*Numeric.product(var.shape))
def who(vardict=None): """Print the scipy arrays in the given dictionary (or globals() if None). """ if vardict is None: frame = sys._getframe().f_back vardict = frame.f_globals sta = [] cache = {} for name in vardict.keys(): if isinstance(vardict[name],Numeric.ArrayType): var = vardict[name] idv = id(var) if idv in ca...
def test(level=10): from numpy.test.testing import module_test module_test(__name__,__file__,level=level) def test_suite(level=1): from numpy.test.testing import module_test_suite return module_test_suite(__name__,__file__,level=level)
def test(level=10): from numpy.test.testing import module_test module_test(__name__,__file__,level=level)
config.add_data_files(('gistdata',xplt_files))
config.add_data_dir('gistdata') config.add_data_dir((os.path.join(config.path_in_package,'gistdata'), os.path.abspath(config.paths('src/g')[0])))
def get_playsource(extension,build_dir): if windows: playsource = winsource + allsource elif cygwin: playsource = unixsource + winsource + allsource elif macosx: playsource = unixsource + macsource + allsource else: playsource = unixsource + x11source + allsource sources = [os.path.join(local_path,n) for n in playsourc...
print bounds_info print data_bounds print ticks
def auto_ticks(data_bounds, bounds_info = default_bounds): """ Find locations for axis tick marks. Calculate the location for tick marks on an axis. data_bounds is a sequence of 2 numbers specifying the maximum and minimum values of the data along this axis. bounds_info is a sequence of 3 values that specify how the a...
ext_args['define_macros'] = [('ATLAS_INFO','"%s"' % atlas_version)]
if sys.platform=='win32': ext_args['define_macros'] = [('ATLAS_INFO','"\\"%s\\""' % atlas_version)] else: ext_args['define_macros'] = [('ATLAS_INFO','"%s"' % atlas_version)]
def configuration(parent_package='',parent_path=None): from scipy_distutils.core import Extension from scipy_distutils.misc_util import fortran_library_item, dot_join,\ SourceGenerator, get_path, default_config_dict, get_build_temp from scipy_distutils.system_info import get_info,dict_append,\ AtlasNotFoundError,Lapack...
assert_array_equal(y.imag,real(y))
assert_array_equal(y.imag,imag(y))
def check_cmplx(self): y = rand(10,)+1j*rand(10,) assert_array_equal(y.imag,real(y))
z = array([-1,0,1]))
z = array([-1,0,1])
def check_fail(self): z = array([-1,0,1])) res = iscomplex(z) assert(not sometrue(res))
z = array([-1,0,1j]))
z = array([-1,0,1j])
def check_pass(self): z = array([-1,0,1j])) res = isreal(z) assert_array_equal(res,[1,1,0])
class test_real_if_close(unittest.TestCase): def check_basic(self): a = randn(10) b = real_if_close(a+1e-15j) assert(array_is_real(b)) assert_array_equal(a,b)
def check_trailing_skip(self): a= array([0,0,1,0,2,3,0,4,0]) res = trim_zeros(a) assert_array_equal(res,array([1,0,2,3,0,4]))
peak = 2/(n+1.) a = (n-1)/2.0 F_peak = distributions.invgamma.cdf(peak,a)
a = (n-1)/2.0 if (n > 3): peak = 2/(n-3.0) F_peak = distributions.invgamma.cdf(peak,a) else: F_peak = -1.0 if (F_peak < alpha/2.0): peak = distributions.invgamma.ppf(0.5,a) F_peak = 0.5
def bayes_mvs(data,alpha=0.90): """Return Bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. Uses peak of conditional pdf as starti...
if (q1 < 0): q2 = alpha va = 0.0 else: va = fac*distributions.invgamma.ppf(q1,a)
if (q2 > 1): q2 = 1.0 va = fac*distributions.invgamma.ppf(q1,a)
def bayes_mvs(data,alpha=0.90): """Return Bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. Uses peak of conditional pdf as starti...
peak = sqrt(2./n) F_peak = distributions.gengamma.cdf(peak,a,-2)
if (n > 2): peak = special.gamma(a-0.5) / special.gamma(a) F_peak = distributions.gengamma.cdf(peak,a,-2) else: F_peak = -1.0 if (F_peak < alpha/2.0): peak = distributions.gengamma.ppf(0.5,a,-2) F_peak = 0.5
def bayes_mvs(data,alpha=0.90): """Return Bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. Uses peak of conditional pdf as starti...
if (q1 < 0): q2 = alpha sta = 0.0 else: sta = fac*distributions.gengamma.ppf(q1,a,-2)
if (q2 > 1): q2 = 1.0 sta = fac*distributions.gengamma.ppf(q1,a,-2)
def bayes_mvs(data,alpha=0.90): """Return Bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. Uses peak of conditional pdf as starti...
the_server=SocketServer.ThreadingTCPServer( (host, port), standard_sync_handler)
the_server=MyThreadingTCPServer( (host, port), standard_sync_handler)
def server(host=default_host,port=10000): import os global server_pid server_pid = os.getpid() sync_cluster.server_pid = server_pid print "starting server on %s:%s" % (host,port) print server_pid #the_server=SocketServer.TCPServer( (host, port), standard_sync_handler) #the_server=SocketServer.ForkingTCPServer( (host, p...
c_decl = "fortranname(%s)" % new_name
c_decl = "fortranname %s" % new_name
def rename_functions(interface_in,prefix,suffix): sub_list = all_subroutines(interface_in) interface = '' for sub in sub_list: name = function_name(sub) new_name = prefix+name+suffix c_decl = "fortranname(%s)" % new_name #renamed_sub = string.replace(sub, name ,new_name ,1) renamed_sub = sub renamed_sub = string.replac...
ord = 1 computes the largest row sum ord = -1 computes the smallest row sum ord = Inf computes the largest column sum ord = -Inf computes the smallest column sum
ord = 1 computes the largest column sum of absolute values ord = -1 computes the smallest column sum of absolute values ord = Inf computes the largest row sum of absolute values ord = -Inf computes the smallest row sum of absolute values
def norm(x, ord=2): """ norm(x, ord=2) -> n Matrix and vector norm. Inputs: x -- a rank-1 (vector) or rank-2 (matrix) array ord -- the order of norm. Comments: For vectors ord can be any real number including Inf or -Inf. ord = Inf, computes the maximum of the magnitudes ord = -Inf, computes minimum of the magnitu...
'iwrk':array([],intc),'u': array([],float),
'iwrk':array([],int32),'u': array([],float),
def splprep(x,w=None,u=None,ub=None,ue=None,k=3,task=0,s=None,t=None, full_output=0,nest=None,per=0,quiet=1): """Find the B-spline representation of an N-dimensional curve. Description: Given a list of N rank-1 arrays, x, which represent a curve in N-dimensional space parametrized by u, find a smooth approximating sp...
'iwrk':array([],intc)}
'iwrk':array([],int32)}
def splprep(x,w=None,u=None,ub=None,ue=None,k=3,task=0,s=None,t=None, full_output=0,nest=None,per=0,quiet=1): """Find the B-spline representation of an N-dimensional curve. Description: Given a list of N rank-1 arrays, x, which represent a curve in N-dimensional space parametrized by u, find a smooth approximating sp...
_curfit_cache['iwrk'] = empty((nest,),intc)
_curfit_cache['iwrk'] = empty((nest,),int32)
def splrep(x,y,w=None,xb=None,xe=None,k=3,task=0,s=1e-3,t=None, full_output=0,per=0,quiet=1): """Find the B-spline representation of 1-D curve. Description: Given the set of data points (x[i], y[i]) determine a smooth spline approximation of degree k on the interval xb <= x <= xe. The coefficients, c, and the knot p...
'wrk': array([],float), 'iwrk':array([],intc)}
'wrk': array([],float), 'iwrk':array([],int32)}
#def _curfit(x,y,w=None,xb=None,xe=None,k=3,task=0,s=None,t=None,
app.MainLoop() gui_thread_finished.set()
try: app.MainLoop() finally: gui_thread_finished.set()
def gui_thread(finished): """ Indirectly imports wxPython into the second thread """ import sys try: # If we can find a module named wxPython. Odds are (maybe 100%), # we don't want to start a new thread with a MainLoop() in it. if not sys.modules.has_key('wxPython'): #import must be done inside if statement!!! from g...
hasattr(x,'is_proxy')
return hasattr(x,'is_proxy')
def is_proxy(x): hasattr(x,'is_proxy')
def configuration(parent_package=''): package = 'odr' config = Configuration(package,parent_package) local_path = get_path(__name__)
def configuration(parent_package='', top_path=None): config = Configuration('odr', parent_package, top_path)
def configuration(parent_package=''): package = 'odr' config = Configuration(package,parent_package) local_path = get_path(__name__) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] atlas_info = get_info('atlas') #atlas_info = {} # uncomment if ATLAS is available but want to use # Fortran LAPACK/BLAS; useful for t...
libodr = [os.path.join(local_path, 'odrpack', x) for x in libodr_files]
libodr = [os.path.join('odrpack', x) for x in libodr_files]
def configuration(parent_package=''): package = 'odr' config = Configuration(package,parent_package) local_path = get_path(__name__) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] atlas_info = get_info('atlas') #atlas_info = {} # uncomment if ATLAS is available but want to use # Fortran LAPACK/BLAS; useful for t...
include_dirs=[local_path],
include_dirs=['.'],
def configuration(parent_package=''): package = 'odr' config = Configuration(package,parent_package) local_path = get_path(__name__) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] atlas_info = get_info('atlas') #atlas_info = {} # uncomment if ATLAS is available but want to use # Fortran LAPACK/BLAS; useful for t...
setup(**configuration())
setup(**configuration(top_path='').todict())
def configuration(parent_package=''): package = 'odr' config = Configuration(package,parent_package) local_path = get_path(__name__) libodr_files = ['d_odr.f', 'd_mprec.f', 'dlunoc.f'] atlas_info = get_info('atlas') #atlas_info = {} # uncomment if ATLAS is available but want to use # Fortran LAPACK/BLAS; useful for t...
typecode = _coerce_rules[(self._typecode,other._typecode)] data1, data2 = _convert_data(self.data, other.data, typecode)
typecode = _coerce_rules[(self._typecode,ocs._typecode)] data1, data2 = _convert_data(self.data, ocs.data, typecode)
def __sub__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self._typecode,other._typecode)] data1, data2 = _convert_data(self.data, other.data, typecode) func = getattr(sparsetools,_transtabl[typecode]+'cscadd') c,rowc,ptrc,ierr = f...
c,rowc,ptrc,ierr = func(data1,self.rowind,self.indptr,-data2,other.rowind,other.indptr)
c,rowc,ptrc,ierr = func(data1,self.rowind,self.indptr,-data2,ocs.rowind,ocs.indptr)
def __sub__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self._typecode,other._typecode)] data1, data2 = _convert_data(self.data, other.data, typecode) func = getattr(sparsetools,_transtabl[typecode]+'cscadd') c,rowc,ptrc,ierr = f...
typecode = _coerce_rules[(self._typecode,other._typecode)] data1, data2 = _convert_data(self.data, other.data, typecode)
typecode = _coerce_rules[(self._typecode,ocs._typecode)] data1, data2 = _convert_data(self.data, ocs.data, typecode)
def __rsub__(self, other): # implement other - self ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self._typecode,other._typecode)] data1, data2 = _convert_data(self.data, other.data, typecode) func = getattr(sparsetools,_transtabl[typecode]+'cs...
c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,other.rowind,other.indptr)
c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,ocs.rowind,ocs.indptr)
def __rsub__(self, other): # implement other - self ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self._typecode,other._typecode)] data1, data2 = _convert_data(self.data, other.data, typecode) func = getattr(sparsetools,_transtabl[typecode]+'cs...
target_dir = join(target_dir,'atlas321')
target_dir = os.path.join(target_dir,'atlas321')
def local_glob(path): return glob(os.path.join(local_path,path))
target = join(build_dir,target_dir,'clapack.pyf')
target = os.path.join(build_dir,target_dir,'clapack.pyf')
def get_clapack_source(ext, build_dir): name = ext.name.split('.')[-1] assert name=='clapack',`name` if atlas_version is None: target = join(build_dir,target_dir,'clapack.pyf') from distutils.dep_util import newer if newer(__file__,target): f = open(source,'w') f.write(tmpl_empty_clapack_pyf) f.close() else: target = e...
namelength = self.read_element()
namelength = self.read_element()[0]
def get_raw_array(self): namelength = self.read_element() # get field names names = self.read_element() splitnames = [names[i:i+namelength] for i in \ xrange(0,len(names),namelength)] self.obj_template._fieldnames = [x.tostring().strip('\x00') for x in splitnames] return super(Mat5StructMatrixGetter, self).get_raw_arra...
def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0):
def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0, maxiter=1000):
def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0): """Given a function and distinct initial points, search in the downhill direction (as defined by the initital points) and return new points xa, xb, xc that bracket the minimum of the function: f(xa) > f(xb) < f(xc) """ _gold = 1.618034 _verysmall_num = 1e-21...
if iter > 1000:
if iter > maxiter:
def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0): """Given a function and distinct initial points, search in the downhill direction (as defined by the initital points) and return new points xa, xb, xc that bracket the minimum of the function: f(xa) > f(xb) < f(xc) """ _gold = 1.618034 _verysmall_num = 1e-21...
if not _hold:
if not _hold and gist.plsys() < 2:
def matplot(x,y=None,axis=-1): if y is None: # no axis data y = x x = Numeric.arange(0,y.shape[axis]) x,y = Numeric.asarray(x), Numeric.asarray(y) assert(len(y.shape)==2) assert(len(x)==y.shape[axis]) otheraxis = (1+axis) % 2 sliceobj = [slice(None)]*2 if not _hold: gist.fma() clear_global_linetype() for k in range(y...
def subplot(Numy,Numx,win=0,lm=0*inches,rm=0*inches,tm=0*inches,bm=0*inches,ph=11*inches,pw=8.5*inches,dpi=75,ls=0.75*inches,rs=0.75*inches,ts=0.75*inches,bs=0.75*inches):
def subplot(Numy,Numx,win=0,lm=0*inches,rm=0*inches,tm=0*inches,bm=0*inches,ph=11*inches,pw=8.5*inches,dpi=75,ls=0.75*inches,rs=0.75*inches,ts=0.75*inches,bs=0.75*inches,color='black',frame=0): if type(color) is types.StringType: color = _colornum[color]
def subplot(Numy,Numx,win=0,lm=0*inches,rm=0*inches,tm=0*inches,bm=0*inches,ph=11*inches,pw=8.5*inches,dpi=75,ls=0.75*inches,rs=0.75*inches,ts=0.75*inches,bs=0.75*inches): # Use gist.plsys to change coordinate systems systems=[] ind = -1 Yspace = (ph-bm-tm)/float(Numy) Xspace = (pw-rm-lm)/float(Numx) for nY in range(Nu...
change_palette()
change_palette(palette)
def surf(x,y,z,win=None,shade=0,edges=1,edge_color="black",phi=-45,theta=30, zscale=1.0,palette=None,gnomon=0): """Plot a three-dimensional wire-frame (surface): z=f(x,y) """ if win is None: pl3d.window3() else: pl3d.window3(win) pl3d.set_draw3_(0) pl3d.orient3(phi=phi*pi/180,theta=theta*pi/180) pl3d.light3() change_pa...
return a_star, val_star
return a_star, val_star, valprime_star
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): maxiter = 10 i = 0 delta1 = 0.2 # cubic interpolant check delta2 = 0.1 # quadratic interpolant check phi_rec = phi0 a_rec = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi # Need to choose interpolation her...
global fc, gc fc = 0 gc = 0
global _ls_fc, _ls_gc, _ls_ingfk _ls_fc = 0 _ls_gc = 0 _ls_ingfk = None
def line_search(f, myfprime, xk, pk, gfk, old_fval, old_old_fval, args=(), c1=1e-4, c2=0.9, amax=50): """Find alpha that satisfies strong Wolfe conditions. Uses the line search algorithm to enforce strong Wolfe conditions Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-60 For the zoom phase it uses an algo...
global fc fc += 1
global _ls_fc _ls_fc += 1
def phi(alpha): global fc fc += 1 return f(xk+alpha*pk,*args)
global fc fc += len(xk)+1
global _ls_fc, _ls_ingfk _ls_fc += len(xk)+1
def phiprime(alpha): global fc fc += len(xk)+1 eps = myfprime[1] fprime = myfprime[0] newargs = (f,eps) + args return Num.dot(fprime(xk+alpha*pk,*newargs),pk)
return Num.dot(fprime(xk+alpha*pk,*newargs),pk)
_ls_ingfk = fprime(xk+alpha*pk,*newargs) return Num.dot(_ls_ingfk,pk)
def phiprime(alpha): global fc fc += len(xk)+1 eps = myfprime[1] fprime = myfprime[0] newargs = (f,eps) + args return Num.dot(fprime(xk+alpha*pk,*newargs),pk)
global gc gc += 1 return Num.dot(fprime(xk+alpha*pk,*args),pk)
global _ls_gc, _ls_ingfk _ls_gc += 1 _ls_ingfk = fprime(xk+alpha*pk,*args) return Num.dot(_ls_ingfk,pk)
def phiprime(alpha): global gc gc += 1 return Num.dot(fprime(xk+alpha*pk,*args),pk)
alpha_star, fval_star = zoom(alpha0, alpha1, phi_a0, phi_a1, derphi_a0, phi, phiprime, phi0, derphi0, c1, c2)
alpha_star, fval_star, fprime_star = \ zoom(alpha0, alpha1, phi_a0, phi_a1, derphi_a0, phi, phiprime, phi0, derphi0, c1, c2)
def phiprime(alpha): global gc gc += 1 return Num.dot(fprime(xk+alpha*pk,*args),pk)
alpha_star, fval_star = zoom(alpha1, alpha0, phi_a1, phi_a0, derphi_a1, phi, phiprime, phi0, derphi0, c1, c2)
alpha_star, fval_star, fprime_star = \ zoom(alpha1, alpha0, phi_a1, phi_a0, derphi_a1, phi, phiprime, phi0, derphi0, c1, c2)
def phiprime(alpha): global gc gc += 1 return Num.dot(fprime(xk+alpha*pk,*args),pk)
return alpha_star, fc, gc, fval_star, old_fval
if fprime_star is not None: fprime_star = _ls_ingfk return alpha_star, _ls_fc, _ls_gc, fval_star, old_fval, fprime_star
def phiprime(alpha): global gc gc += 1 return Num.dot(fprime(xk+alpha*pk,*args),pk)
old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1
def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, 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 (...
old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1
def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, 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 (...
alpha_k, fc, gc, old_fval, old_old_fval = \
alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, 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 (...
if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + gc + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + gc + 1
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
def fmin_bfgs(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, 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 (...
xk = x0
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function with nonlinear conjugate gradient algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak...
old_fval = f(xk,*args) old_old_fval = old_fval + 5000
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function with nonlinear conjugate gradient algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak...
alpha_k, fc, gc, old_fval, old_old_fval = \
alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function with nonlinear conjugate gradient algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak...
if app_fprime: gfkp1 = apply(approx_fprime,(xk,f,epsilon)+args) func_calls = func_calls + gc + len(x0) + 1 else: gfkp1 = apply(fprime,(xk,)+args) grad_calls = grad_calls + gc + 1
if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xk,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xk,)+args) grad_calls = grad_calls + 1
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function with nonlinear conjugate gradient algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak...
fval = apply(f,(xk,)+args)
fval = old_fval
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=1.49e-8, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function with nonlinear conjugate gradient algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak...
xsupi = 0
xsupi = zeros(len(x0), x0.typecode())
def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Description: Minimize the function, f, whose gradient is given by fprime using the Newton-CG method. fhess_p must compute the hessian times an arbitrary vector. If it is no...
if (curv <= 0):
if curv == 0.0: break elif curv < 0:
def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Description: Minimize the function, f, whose gradient is given by fprime using the Newton-CG method. fhess_p must compute the hessian times an arbitrary vector. If it is no...
if abs(p-p0) < tol:
if abs(p-p1) < tol:
def newton(func, x0, fprime=None, args=(), tol=1.48e-8, maxiter=50): """Given a function of a single variable and a starting point, find a nearby zero using Newton-Raphson. fprime is the derivative of the function. If not given, the Secant method is used. """ if fprime is not None: p0 = x0 for iter in range(maxiter)...
assert_array_almost_equal(f(3,[3],[-4]),[-36])
assert_array_almost_equal(f(3,[3],[-4]),[[-36]])
def check_gemm(self): for p in 'sd': f = getattr(fblas,p+'gemm',None) if f is None: continue assert_array_almost_equal(f(3,[3],[-4]),[-36]) assert_array_almost_equal(f(3,[3],[-4],3,[5]),[-21]) assert_array_almost_equal(f(1,[[1,2],[1,2]],[[3],[4]]),[[11],[11]]) assert_array_almost_equal(f(1,[[1,2]],[[3,3],[4,4]]),[[11,1...
assert_array_almost_equal(f(3j,[3-4j],[-4]),[-48-36j])
assert_array_almost_equal(f(3j,[3-4j],[-4]),[[-48-36j]])
def check_gemm(self): for p in 'sd': f = getattr(fblas,p+'gemm',None) if f is None: continue assert_array_almost_equal(f(3,[3],[-4]),[-36]) assert_array_almost_equal(f(3,[3],[-4],3,[5]),[-21]) assert_array_almost_equal(f(1,[[1,2],[1,2]],[[3],[4]]),[[11],[11]]) assert_array_almost_equal(f(1,[[1,2]],[[3,3],[4,4]]),[[11,1...
assert_array_almost_equal(f(1,[[1,2]],[[3],[4]]),[11])
assert_array_almost_equal(f(1,[[1,2]],[[3],[4]]),[[11]])
def check_gemm2(self): for p in 'sdcz': f = getattr(fblas,p+'gemm',None) if f is None: continue assert_array_almost_equal(f(1,[[1,2]],[[3],[4]]),[11]) assert_array_almost_equal(f(1,[[1,2],[1,2]],[[3],[4]]),[[11],[11]])
The entropy dual function equals the negative log likelihood.
The entropy dual function is proportional to the negative log likelihood.
def dual(self, params=None, ignorepenalty=False): """The entropy dual function is defined for conditional models as L(theta) = sum_w q(w) log Z(w; theta) - sum_{w,x} q(w,x) [theta . f(w,x)]
var = (a*b*1.0)*(a+b+1.0)/(a+b)**2.0
var = (a*b*1.0)/(a+b+1.0)/(a+b)**2.0
def _stats(self, a, b): mn = a *1.0 / (a + b) var = (a*b*1.0)*(a+b+1.0)/(a+b)**2.0 g1 = 2.0*(b-a)*sqrt((1.0+a+b)/(a*b)) / (2+a+b) g2 = 6.0*(a**3 + a**2*(1-2*b) + b**2*(1+b) - 2*a*b*(2+b)) g2 /= a*b*(a+b+2)*(a+b+3) return mn, var, g1, g2
return Date(freq, yaer=tempDate.year, quarter=monthToQuarter(tempDate.month))
return Date(freq, year=tempDate.year, quarter=monthToQuarter(tempDate.month))
def thisday(freq): freq = corelib.fmtFreq(freq) tempDate = mx.DateTime.now() # if it is Saturday or Sunday currently, freq==B, then we want to use Friday if freq == 'B' and tempDate.day_of_week >= 5: tempDate -= (tempDate.day_of_week - 4) if freq == 'B' or freq == 'D' or freq == 'S': return Date(freq, mxDate=tempDat...
x = asarray(x).squeeze()
x = asarray(x)
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 ...
if len(x) != len(seq): raise ValueError, "number of elements in source" \ " must be same as number of elements in" \ " destimation or 1"
else: if x.ndim == 2: if x.shape != (1, len(seq)): raise ValueError, \ "source and destination have incompatible "\ "dimensions" else: x = x.squeeze()
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 ...
fsim[0] = apply(func,(x0,)+args)
fsim[0] = func(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 ...
f = apply(func,(y,)+args)
f = func(y)
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 ...
funcalls = N+1 while (funcalls < maxfun and iterations < maxiter):
while (fcalls[0] < maxfun and iterations < maxiter):
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 ...
fxr = apply(func,(xr,)+args) funcalls = funcalls + 1
fxr = func(xr)
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 ...
fxe = apply(func,(xe,)+args) funcalls = funcalls + 1
fxe = func(xe)
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 ...
fxc = apply(func,(xc,)+args) funcalls = funcalls + 1
fxc = func(xc)
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 ...
fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1
fxcc = func(xcc)
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 ...
fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N
fsim[j] = func(sim[j])
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 ...
if funcalls >= maxfun:
if fcalls[0] >= maxfun:
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 ...
print " Function evaluations: %d" % funcalls
print " Function evaluations: %d" % fcalls[0]
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 ...
retlist = x, fval, iterations, funcalls, warnflag
retlist = x, fval, iterations, fcalls[0], warnflag
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 ...
app_fprime = 0 if fprime is None: app_fprime = 1
def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf, 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 ...
func_calls = 0 grad_calls = 0
func_calls, f = wrap_function(f, args) if fprime is None: grad_calls, myfprime = wrap_function(approx_fprime, (f, epsilon)) else: grad_calls, myfprime = wrap_function(fprime, args) gfk = myfprime(x0)
def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf, 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 ...
old_fval = f(x0,*args)
old_fval = f(x0)
def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf, 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 ...
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
def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf, 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 ...