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', sources = ['splinemodule.c','S_bspline_util.c','D_bspline_util.c', 'C_bspline_util.c','Z_bspline_util.c','bspline_util.c'], ) return config |
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, "m must be <= n." if not isscalar(n) or (n<0): raise ValueError, "n must be a non-negative integer." if not isscalar(z): raise ValueError, "z must be scalar." if (m < 0): mp = -m mf,nf = mgrid[0:mp+1,0:n+1] sv = errprint(0) fixarr = where(mf>nf,0.0,(-1)**mf * gamma(nf-mf+1) / gamma(nf+mf+1)) sv = errprint(sv) else: mp = m if any(iscomplex(z)): p,pd = specfun.clpmn(mp,n,real(z),imag(z)) else: p,pd = specfun.lpmn(mp,n,z) if (m < 0): p = p * fixarr pd = pd * fixarr return p,pd |
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, N = s.shape dtype = s.dtypechar func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix((s, ij), dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor" |
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 = (ocsc.shape[1], ocsc.shape[0]) |
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 = (ocsc.shape[1], ocsc.shape[0]) |
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 = asarray(ij[0], 'i') self.col = asarray(ij[1], 'i') self.data = asarray(obj, dtype=dtype) self.dtypechar = self.data.dtypechar if nzmax is None: nzmax = len(self.data) self.nzmax = nzmax self._check() except Exception, e: raise e, "invalid input format" |
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 = asarray(ij[0], 'i') self.col = asarray(ij[1], 'i') self.data = asarray(obj, dtype=dtype) self.dtypechar = self.data.dtypechar if nzmax is None: nzmax = len(self.data) self.nzmax = nzmax self._check() except Exception, e: raise e, "invalid input format" |
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 = asarray(ij[0], 'i') self.col = asarray(ij[1], 'i') self.data = asarray(obj, dtype=dtype) self.dtypechar = self.data.dtypechar if nzmax is None: nzmax = len(self.data) self.nzmax = nzmax self._check() except Exception, e: raise e, "invalid input format" |
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 = "plot time statistics [default: %default]" ) parser.add_option( "-d", "--default-url", action = "store_true", dest = "default_url", default = False, help = "use default url [default: %default]" ) parser.add_option( "-f", "--format", type = type( '' ), dest = "format", default = 'triplet', help = "matrix format [default: %default]" ) (options, args) = parser.parse_args() if (len( args ) >= 1): matrixNames = args; else: parser.print_help(), return sizes, nnzs, times, errors = [], [], [], [] legends = ['umfpack', 'sparse.solve'] for ii, matrixName in enumerate( matrixNames ): print '*' * 50 mtx = readMatrix( matrixName, options ) sizes.append( mtx.shape ) nnzs.append( mtx.nnz ) tts = nm.zeros( (2,), dtype = nm.double ) times.append( tts ) err = nm.zeros( (2,2), dtype = nm.double ) errors.append( err ) print 'size : %s (%d nnz)' % (mtx.shape, mtx.nnz) sol0 = nm.ones( (mtx.shape[0],), dtype = nm.double ) rhs = mtx * sol0 umfpack = um.UmfpackContext() tt = time.clock() sol = umfpack( um.UMFPACK_A, mtx, rhs, autoTranspose = True ) tts[0] = time.clock() - tt print "umfpack : %.2f s" % tts[0] error = mtx * sol - rhs err[0,0] = nla.norm( error ) print '||Ax-b|| :', err[0,0] error = sol0 - sol err[0,1] = nla.norm( error ) print '||x - x_{exact}|| :', err[0,1] if options.compare: tt = time.clock() sol = sp.solve( mtx, rhs ) tts[1] = time.clock() - tt print "sparse.solve : %.2f s" % tts[1] error = mtx * sol - rhs err[1,0] = nla.norm( error ) print '||Ax-b|| :', err[1,0] error = sol0 - sol err[1,1] = nla.norm( error ) print '||x - x_{exact}|| :', err[1,1] if options.plot: try: import pylab except ImportError: raise "could not import pylab" times = nm.array( times ) print times pylab.plot( times[:,0], 'b-o' ) if options.compare: pylab.plot( times[:,1], 'r-s' ) else: del legends[1] print legends ax = pylab.axis() y2 = 0.5 * (ax[3] - ax[2]) xrng = range( len( nnzs ) ) for ii in xrng: yy = y2 + 0.4 * (ax[3] - ax[2])\ * nm.sin( ii * 2 * nm.pi / (len( xrng ) - 1) ) if options.compare: pylab.text( ii+0.02, yy, '%s\n%.2e err_umf\n%.2e err_sp' % (sizes[ii], nm.sum( errors[ii][0,:] ), nm.sum( errors[ii][1,:] )) ) else: pylab.text( ii+0.02, yy, '%s\n%.2e err_umf' % (sizes[ii], nm.sum( errors[ii][0,:] )) ) pylab.plot( [ii, ii], [ax[2], ax[3]], 'k:' ) pylab.xticks( xrng, ['%d' % (nnzs[ii] ) for ii in xrng] ) pylab.xlabel( 'nnz' ) pylab.ylabel( 'time [s]' ) pylab.legend( legends ) pylab.axis( [ax[0] - 0.05, ax[1] + 1, ax[2], ax[3]] ) pylab.show() |
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", license = 'BSD', ) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('Lib') config.name = 'scipy' # used in generated file names config.add_data_files(('scipy','*.txt')) from version import version as version config.dict_append(version=version) return config |
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", license = 'BSD', ) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('Lib') config.name = 'scipy' # used in generated file names config.add_data_files(('scipy','*.txt')) from version import version as version config.dict_append(version=version) return config |
|
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", license = 'BSD', ) config.set_options(ignore_setup_xxx_py=True, assume_default_configuration=True, delegate_options_to_subpackages=True, quiet=True) config.add_subpackage('Lib') config.name = 'scipy' # used in generated file names config.add_data_files(('scipy','*.txt')) from version import version as version config.dict_append(version=version) return config |
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 try: setup( configuration=configuration ) finally: del sys.path[0] os.chdir(old_path) return |
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, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width), slepian (needs width) If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfunc = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfunc = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfunc = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar elif winstr in ['slepian', 'slep', 'optimal', 'dss']: winfunc = slepian else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params) |
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, blackmanharris, nuttall, barthann, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width), slepian (needs width) If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['triangle', 'triang', 'tri']: winfunc = triang elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['blackmanharris', 'blackharr','bkh']: winfun = blackmanharris elif winstr in ['parzen', 'parz', 'par']: winfun = parzen elif winstr in ['bohman', 'bman', 'bmn']: winfunc = bohman elif winstr in ['nuttall', 'nutl', 'nut']: winfunc = nuttall elif winstr in ['barthann', 'brthan', 'bth']: winfunc = barthann elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian elif winstr in ['boxcar', 'box', 'ones']: winfunc = boxcar elif winstr in ['slepian', 'slep', 'optimal', 'dss']: winfunc = slepian else: raise ValueError, "Unknown window type." params = (Nx,)+args + (sym,) else: winfunc = kaiser params = (Nx,beta,sym) return winfunc(*params) |
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 cache.keys(): namestr = name + " (%s)" % cache[idv] original=0 else: cache[idv] = name namestr = name original=1 shapestr = " x ".join(map(str, var.shape)) bytestr = str(var.itemsize()*Numeric.product(var.shape)) sta.append([namestr, shapestr, bytestr, typename(var.dtypechar), original]) maxname = 0 maxshape = 0 maxbyte = 0 totalbytes = 0 for k in range(len(sta)): val = sta[k] if maxname < len(val[0]): maxname = len(val[0]) if maxshape < len(val[1]): maxshape = len(val[1]) if maxbyte < len(val[2]): maxbyte = len(val[2]) if val[4]: totalbytes += int(val[2]) max = Numeric.maximum if len(sta) > 0: sp1 = max(10,maxname) sp2 = max(10,maxshape) sp3 = max(10,maxbyte) prval = "Name %s Shape %s Bytes %s Type" % (sp1*' ', sp2*' ', sp3*' ') print prval + "\n" + "="*(len(prval)+5) + "\n" for k in range(len(sta)): val = sta[k] print "%s %s %s %s %s %s %s" % (val[0], ' '*(sp1-len(val[0])+4), val[1], ' '*(sp2-len(val[1])+5), val[2], ' '*(sp3-len(val[2])+5), val[3]) print "\nUpper bound on total bytes = %d" % totalbytes return |
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 playsource] |
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 axis end points and tick interval are calculated. An array of tick mark locations is returned from the function. The first and last tick entries are the axis end points. data_bounds -- (lower,upper). The maximum and minimum values of the data long this axis. If any of the settings in bounds_info are 'auto' or 'fit', the axis properties are calculated automatically from these settings. bounds_info -- (lower,upper,interval). Each entry can either be a numerical value or a string. If a number,the axis property is set to that value. If the entry is 'auto', the property is calculated automatically. lower and upper can also be 'fit' in which case the axis end points are set equal to the values in data_bounds. """ # pretty ugly code... # man, this needs some testing. if is_number(bounds_info[0]): lower = bounds_info[0] else: lower = data_bounds[0] if is_number(bounds_info[1]): upper = bounds_info[1] else: upper = data_bounds[1] interval = bounds_info[2] #print 'raw interval:', interval if interval in ['linear','auto']: rng = abs(upper - lower) if rng == 0.: # anything more intelligent to do here? interval = .5 lower,upper = data_bounds + array((-.5,.5)) if is_base2(rng) and is_base2(upper) and rng > 4: if rng == 2: interval = 1 elif rng == 4: interval = 4 else: interval = rng / 4 # maybe we want it 8 else: interval = auto_interval((lower,upper)) elif type(interval) in [type(0.0),type(0)]: pass else: #print 'interval: ', interval raise ValueError, interval + " is an unknown value for interval: " \ " expects 'auto' or 'linear', or a number" # If the lower or upper bound are set to 'auto', # calculate them based on the newly chosen interval. #print 'interval:', interval auto_lower,auto_upper = auto_bounds(data_bounds,interval) if bounds_info[0] == 'auto': lower = auto_lower if bounds_info[1] == 'auto': upper = auto_upper # if the lower and upper bound span 0, make sure ticks # will hit exactly on zero. if lower < 0 and upper > 0: hi_ticks = arange(0,upper+interval,interval) low_ticks = - arange(interval,-lower+interval,interval) ticks = concatenate((low_ticks[::-1],hi_ticks)) else: # othersize the ticks start and end on the lower and # upper values. ticks = arange(lower,upper+interval,interval) if bounds_info[0] == 'fit': ticks[0] = lower if bounds_info[1] == 'fit': ticks[-1] = upper print bounds_info print data_bounds print ticks return ticks |
|
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,LapackNotFoundError,BlasNotFoundError,\ LapackSrcNotFoundError,BlasSrcNotFoundError package = 'linalg' from interface_gen import generate_interface config = default_config_dict(package,parent_package) local_path = get_path(__name__,parent_path) abs_local_path = os.path.abspath(local_path) no_atlas = 0 atlas_info = get_info('atlas_threads') if ('ATLAS_WITHOUT_LAPACK',None) in atlas_info.get('define_macros',[]): atlas_info = get_info('lapack_atlas_threads') or atlas_info if not atlas_info: atlas_info = get_info('atlas') if atlas_info: if ('ATLAS_WITHOUT_LAPACK',None) in atlas_info.get('define_macros',[]): atlas_info = get_info('lapack_atlas') or atlas_info #atlas_info = {} # uncomment if ATLAS is available but want to use # Fortran LAPACK/BLAS; useful for testing f_libs = [] atlas_version = None temp_path = os.path.join(get_build_temp(),'linalg','atlas_version') dir_util.mkpath(temp_path,verbose=1) atlas_version_file = os.path.join(temp_path,'atlas_version') if atlas_info: if os.path.isfile(atlas_version_file): atlas_version = open(atlas_version_file).read() print 'ATLAS version',atlas_version if atlas_info and atlas_version is None: # Try to determine ATLAS version shutil.copy(os.path.join(local_path,'atlas_version.c'),temp_path) cur_dir = os.getcwd() os.chdir(temp_path) cmd = '%s %s --verbose build_ext --inplace --force'%\ (sys.executable, os.path.join(abs_local_path,'setup_atlas_version.py')) print cmd s,o=run_command(cmd) if not s: cmd = sys.executable+' -c "import atlas_version"' print cmd s,o=run_command(cmd) if not s: m = re.match(r'ATLAS version (?P<version>\d+[.]\d+[.]\d+)',o) if m: atlas_version = m.group('version') print 'ATLAS version',atlas_version if atlas_version is None: if re.search(r'undefined symbol: ATL_buildinfo',o,re.M): atlas_version = '3.2.1_pre3.3.6' print 'ATLAS version',atlas_version else: print o else: print o os.chdir(cur_dir) if atlas_version is None: print 'Failed to determine ATLAS version' else: f = open(atlas_version_file,'w') f.write(atlas_version) f.close() if atlas_info: if ('ATLAS_WITH_LAPACK_ATLAS',None) in atlas_info.get('define_macros',[]): lapack_info = get_info('lapack') if not lapack_info: warnings.warn(LapackNotFoundError.__doc__) lapack_src_info = get_info('lapack_src') if not lapack_src_info: raise LapackSrcNotFoundError,LapackSrcNotFoundError.__doc__ dict_append(lapack_info,libraries=['lapack_src']) f_libs.append(fortran_library_item(\ 'lapack_src',lapack_src_info['sources'], )) dict_append(atlas_info,**lapack_info) elif ('ATLAS_WITHOUT_LAPACK',None) in atlas_info.get('define_macros',[]): lapack_info = get_info('lapack') if not lapack_info: warnings.warn(LapackNotFoundError.__doc__) lapack_src_info = get_info('lapack_src') if not lapack_src_info: raise LapackSrcNotFoundError,LapackSrcNotFoundError.__doc__ dict_append(lapack_info,libraries=['lapack_src']) f_libs.append(fortran_library_item(\ 'lapack_src',lapack_src_info['sources'], )) dict_append(lapack_info,**atlas_info) atlas_info = lapack_info blas_info,lapack_info = {},{} if not atlas_info: warnings.warn(AtlasNotFoundError.__doc__) no_atlas = 1 blas_info = get_info('blas') #blas_info = {} # test building BLAS from sources. if not blas_info: warnings.warn(BlasNotFoundError.__doc__) blas_src_info = get_info('blas_src') if not blas_src_info: raise BlasSrcNotFoundError,BlasSrcNotFoundError.__doc__ dict_append(blas_info,libraries=['blas_src']) f_libs.append(fortran_library_item(\ 'blas_src',blas_src_info['sources'] + \ [os.path.join(local_path,'src','fblaswrap.f')], )) lapack_info = get_info('lapack') #lapack_info = {} # test building LAPACK from sources. if not lapack_info: warnings.warn(LapackNotFoundError.__doc__) lapack_src_info = get_info('lapack_src') if not lapack_src_info: raise LapackSrcNotFoundError,LapackSrcNotFoundError.__doc__ dict_append(lapack_info,libraries=['lapack_src']) f_libs.append(fortran_library_item(\ 'lapack_src',lapack_src_info['sources'], )) dict_append(atlas_info,**lapack_info) dict_append(atlas_info,**blas_info) target_dir = '' skip_names = {'clapack':[],'flapack':[],'cblas':[],'fblas':[]} if skip_single_routines: target_dir = 'dbl' skip_names['clapack'].extend(\ 'sgesv cgesv sgetrf cgetrf sgetrs cgetrs sgetri cgetri'\ ' sposv cposv spotrf cpotrf spotrs cpotrs spotri cpotri'\ ' slauum clauum strtri ctrtri'.split()) skip_names['flapack'].extend(skip_names['clapack']) skip_names['flapack'].extend(\ 'sgesdd cgesdd sgelss cgelss sgeqrf cgeqrf sgeev cgeev'\ ' sgegv cgegv ssyev cheev slaswp claswp sgees cgees' ' sggev cggev'.split()) skip_names['cblas'].extend('saxpy caxpy'.split()) skip_names['fblas'].extend(skip_names['cblas']) skip_names['fblas'].extend(\ 'srotg crotg srotmg srot csrot srotm sswap cswap sscal cscal'\ ' csscal scopy ccopy sdot cdotu cdotc snrm2 scnrm2 sasum scasum'\ ' isamax icamax sgemv cgemv chemv ssymv strmv ctrmv'\ ' sgemm cgemm'.split()) if using_lapack_blas: target_dir = os.path.join(target_dir,'blas') skip_names['fblas'].extend(\ 'drotmg srotmg drotm srotm'.split()) if atlas_version=='3.2.1_pre3.3.6': target_dir = os.path.join(target_dir,'atlas321') skip_names['clapack'].extend(\ 'sgetri dgetri cgetri zgetri spotri dpotri cpotri zpotri'\ ' slauum dlauum clauum zlauum strtri dtrtri ctrtri ztrtri'.split()) elif atlas_version>'3.4.0' and atlas_version<='3.5.12': skip_names['clapack'].extend('cpotrf zpotrf'.split()) # atlas_version: ext_args = {'name':dot_join(parent_package,package,'atlas_version'), 'sources':[os.path.join(local_path,'atlas_version.c')]} if no_atlas: ext_args['define_macros'] = [('NO_ATLAS_INFO',1)] else: ext_args['libraries'] = [atlas_info['libraries'][-1]] ext_args['library_dirs'] = atlas_info['library_dirs'][:] if atlas_version is None: ext_args['define_macros'] = [('NO_ATLAS_INFO',2)] else: ext_args['define_macros'] = [('ATLAS_INFO','"%s"' % atlas_version)] ext = Extension(**ext_args) config['ext_modules'].append(ext) # In case any of atlas|lapack|blas libraries are not available def generate_empty_pyf(target,sources,generator,skips): name = os.path.basename(target)[:-4] f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() # fblas: def generate_fblas_pyf(target,sources,generator,skips): generator('fblas',sources[0],target,skips) if not (blas_info or atlas_info): generate_fblas_pyf = generate_empty_pyf sources = ['generic_fblas.pyf', 'generic_fblas1.pyf', 'generic_fblas2.pyf', 'generic_fblas3.pyf', os.path.join('src','fblaswrap.f')] sources = [os.path.join(local_path,s) for s in sources] fblas_pyf = SourceGenerator(generate_fblas_pyf, os.path.join(target_dir,'fblas.pyf'), sources,generate_interface, skip_names['fblas']) ext_args = {'name':dot_join(parent_package,package,'fblas'), 'sources':[fblas_pyf,sources[-1]], 'depends': sources[:4]} dict_append(ext_args,**atlas_info) ext = Extension(**ext_args) ext.need_fcompiler_opts = 1 config['ext_modules'].append(ext) # cblas: def generate_cblas_pyf(target,sources,generator,skips): generator('cblas',sources[0],target,skips) if no_atlas: generate_cblas_pyf = generate_empty_pyf sources = ['generic_cblas.pyf', 'generic_cblas1.pyf'] sources = [os.path.join(local_path,s) for s in sources] cblas_pyf = SourceGenerator(generate_cblas_pyf, os.path.join(target_dir,'cblas.pyf'), sources,generate_interface, skip_names['cblas']) ext_args = {'name':dot_join(parent_package,package,'cblas'), 'sources':[cblas_pyf], 'depends':sources} dict_append(ext_args,**atlas_info) ext = Extension(**ext_args) ext.need_fcompiler_opts = 1 config['ext_modules'].append(ext) # flapack: def generate_flapack_pyf(target,sources,generator,skips): generator('flapack',sources[0],target,skips) if not (lapack_info or atlas_info): generate_flapack_pyf = generate_empty_pyf sources = ['generic_flapack.pyf','flapack_user_routines.pyf'] sources = [os.path.join(local_path,s) for s in sources] flapack_pyf = SourceGenerator(generate_flapack_pyf, os.path.join(target_dir,'flapack.pyf'), sources,generate_interface, skip_names['flapack']) ext_args = {'name':dot_join(parent_package,package,'flapack'), 'sources':[flapack_pyf], 'depends':sources} dict_append(ext_args,**atlas_info) ext = Extension(**ext_args) ext.need_fcompiler_opts = 1 config['ext_modules'].append(ext) # clapack: def generate_clapack_pyf(target,sources,generator,skips): generator('clapack',sources[0],target,skips) if no_atlas: generate_clapack_pyf = generate_empty_pyf sources = ['generic_clapack.pyf'] sources = [os.path.join(local_path,s) for s in sources] clapack_pyf = SourceGenerator(generate_clapack_pyf, os.path.join(target_dir,'clapack.pyf'), sources,generate_interface, skip_names['clapack']) ext_args = {'name':dot_join(parent_package,package,'clapack'), 'sources':[clapack_pyf], 'depends':sources} dict_append(ext_args,**atlas_info) ext = Extension(**ext_args) ext.need_fcompiler_opts = 1 config['ext_modules'].append(ext) # _flinalg: flinalg = [] for f in ['det.f','lu.f', #'wrappers.c','inv.f', ]: flinalg.append(os.path.join(local_path,'src',f)) ext_args = {'name':dot_join(parent_package,package,'_flinalg'), 'sources':flinalg} dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) # calc_lwork: ext_args = {'name':dot_join(parent_package,package,'calc_lwork'), 'sources':[os.path.join(local_path,'src','calc_lwork.f')], } dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) config['fortran_libraries'].extend(f_libs) return config |
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 starting center. Returns (peak, (a, b)) for each of mean, variance and standard deviation. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta mp = xbar # fac = n*C/2.0 peak = 2/(n+1.) a = (n-1)/2.0 F_peak = distributions.invgamma.cdf(peak,a) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): # non-symmetric area q2 = alpha va = 0.0 else: va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) vp = peak*fac # fac = sqrt(fac) peak = sqrt(2./n) F_peak = distributions.gengamma.cdf(peak,a,-2) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): q2 = alpha sta = 0.0 else: sta = fac*distributions.gengamma.ppf(q1,a,-2) stb = fac*distributions.gengamma.ppf(q2,a,-2) stp = peak*fac return (mp,(ma,mb)),(vp,(va,vb)),(stp,(sta,stb)) |
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 starting center. Returns (peak, (a, b)) for each of mean, variance and standard deviation. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta mp = xbar # fac = n*C/2.0 peak = 2/(n+1.) a = (n-1)/2.0 F_peak = distributions.invgamma.cdf(peak,a) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): # non-symmetric area q2 = alpha va = 0.0 else: va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) vp = peak*fac # fac = sqrt(fac) peak = sqrt(2./n) F_peak = distributions.gengamma.cdf(peak,a,-2) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): q2 = alpha sta = 0.0 else: sta = fac*distributions.gengamma.ppf(q1,a,-2) stb = fac*distributions.gengamma.ppf(q2,a,-2) stp = peak*fac return (mp,(ma,mb)),(vp,(va,vb)),(stp,(sta,stb)) |
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 starting center. Returns (peak, (a, b)) for each of mean, variance and standard deviation. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta mp = xbar # fac = n*C/2.0 peak = 2/(n+1.) a = (n-1)/2.0 F_peak = distributions.invgamma.cdf(peak,a) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): # non-symmetric area q2 = alpha va = 0.0 else: va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) vp = peak*fac # fac = sqrt(fac) peak = sqrt(2./n) F_peak = distributions.gengamma.cdf(peak,a,-2) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): q2 = alpha sta = 0.0 else: sta = fac*distributions.gengamma.ppf(q1,a,-2) stb = fac*distributions.gengamma.ppf(q2,a,-2) stp = peak*fac return (mp,(ma,mb)),(vp,(va,vb)),(stp,(sta,stb)) |
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 starting center. Returns (peak, (a, b)) for each of mean, variance and standard deviation. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta mp = xbar # fac = n*C/2.0 peak = 2/(n+1.) a = (n-1)/2.0 F_peak = distributions.invgamma.cdf(peak,a) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): # non-symmetric area q2 = alpha va = 0.0 else: va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) vp = peak*fac # fac = sqrt(fac) peak = sqrt(2./n) F_peak = distributions.gengamma.cdf(peak,a,-2) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): q2 = alpha sta = 0.0 else: sta = fac*distributions.gengamma.ppf(q1,a,-2) stb = fac*distributions.gengamma.ppf(q2,a,-2) stp = peak*fac return (mp,(ma,mb)),(vp,(va,vb)),(stp,(sta,stb)) |
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, port), standard_sync_handler) the_server=SocketServer.ThreadingTCPServer( (host, port), standard_sync_handler) __name__ = '__main__' the_server.serve_forever() |
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.replace(renamed_sub, '\n' , '\n ' + c_decl +'\n' ,1) interface = interface + renamed_sub + '\n\n' return interface |
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 magnitudes ord is finite, computes sum(abs(x)**ord)**(1.0/ord) For matrices ord can only be + or - 1, 2, Inf. ord = 2 computes the largest singular value ord = -2 computes the smallest singular value 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 """ x = asarray(x) nd = len(x.shape) Inf = scipy_base.Inf if nd == 1: if ord == Inf: return scipy_base.amax(abs(x)) elif ord == -Inf: return scipy_base.amin(abs(x)) else: return scipy_base.sum(abs(x)**ord)**(1.0/ord) elif nd == 2: if ord == 2: return scipy_base.amax(decomp.svd(x)[1]) elif ord == -2: return scipy_base.amin(decomp.svd(x)[1]) elif ord == 1: return scipy_base.amax(scipy_base.sum(abs(x))) elif ord == Inf: return scipy_base.amax(scipy_base.sum(abs(x),axis=1)) elif ord == -1: return scipy_base.amin(scipy_base.sum(abs(x))) elif ord == -Inf: return scipy_base.amin(scipy_base.sum(abs(x),axis=1)) else: raise ValueError, "Invalid norm order for matrices." else: raise ValueError, "Improper number of dimensions to norm." |
'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 spline curve g(u). Uses the FORTRAN routine parcur from FITPACK Inputs: x -- A list of sample vector arrays representing the curve. u -- An array of parameter values. If not given, these values are calculated automatically as (M = len(x[0])): v[0] = 0 v[i] = v[i-1] + distance(x[i],x[i-1]) u[i] = v[i] / v[M-1] ub, ue -- The end-points of the parameters interval. Defaults to u[0] and u[-1]. k -- Degree of the spline. Cubic splines are recommended. Even values of k should be avoided especially with a small s-value. 1 <= k <= 5. task -- If task==0 find t and c for a given smoothing factor, s. If task==1 find t and c for another value of the smoothing factor, s. There must have been a previous call with task=0 or task=1 for the same set of data. If task=-1 find the weighted least square spline for a given set of knots, t. s -- A smoothing condition. The amount of smoothness is determined by satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x) is the smoothed interpolation of (x,y). The user can use s to control the tradeoff between closeness and smoothness of fit. Larger s means more smoothing while smaller values of s indicate less smoothing. Recommended values of s depend on the weights, w. If the weights represent the inverse of the standard-deviation of y, then a good s value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is the number of datapoints in x, y, and w. t -- The knots needed for task=-1. full_output -- If non-zero, then return optional outputs. nest -- An over-estimate of the total number of knots of the spline to help in determining the storage space. By default nest=m/2. Always large enough is nest=m+k+1. per -- If non-zero, data points are considered periodic with period x[m-1] - x[0] and a smooth periodic spline approximation is returned. Values of y[m-1] and w[m-1] are not used. quiet -- Non-zero to suppress messages. Outputs: (tck, u, {fp, ier, msg}) tck -- (t,c,k) a tuple containing the vector of knots, the B-spline coefficients, and the degree of the spline. u -- An array of the values of the parameter. fp -- The weighted sum of squared residuals of the spline approximation. ier -- An integer flag about splrep success. Success is indicated if ier<=0. If ier in [1,2,3] an error occurred but was not raised. Otherwise an error is raised. msg -- A message corresponding to the integer flag, ier. Remarks: SEE splev for evaluation of the spline and its derivatives. """ if task<=0: _parcur_cache = {'t': array([],float), 'wrk': array([],float), 'iwrk':array([],intc),'u': array([],float), 'ub':0,'ue':1} x=myasarray(x) idim,m=x.shape if per: for i in range(idim): if x[i][0]!=x[i][-1]: if quiet<2:print 'Warning: Setting x[%d][%d]=x[%d][0]'%(i,m,i) x[i][-1]=x[i][0] if not 0<idim<11: raise TypeError,'0<idim<11 must hold' if w is None: w=ones(m,float) else: w=myasarray(w) ipar=(u is not None) if ipar: _parcur_cache['u']=u if ub is None: _parcur_cache['ub']=u[0] else: _parcur_cache['ub']=ub if ue is None: _parcur_cache['ue']=u[-1] else: _parcur_cache['ue']=ue else: _parcur_cache['u']=zeros(m,float) if not (1<=k<=5): raise TypeError, '1<=k=%d<=5 must hold'%(k) if not (-1<=task<=1): raise TypeError, 'task must be either -1,0, or 1' if (not len(w)==m) or (ipar==1 and (not len(u)==m)): raise TypeError,'Mismatch of input dimensions' if s is None: s=m-sqrt(2*m) if t is None and task==-1: raise TypeError, 'Knots must be given for task=-1' if t is not None: _parcur_cache['t']=myasarray(t) n=len(_parcur_cache['t']) if task==-1 and n<2*k+2: raise TypeError, 'There must be at least 2*k+2 knots for task=-1' if m<=k: raise TypeError, 'm>k must hold' if nest is None: nest=m+2*k if (task>=0 and s==0) or (nest<0): if per: nest=m+2*k else: nest=m+k+1 nest=max(nest,2*k+3) u=_parcur_cache['u'] ub=_parcur_cache['ub'] ue=_parcur_cache['ue'] t=_parcur_cache['t'] wrk=_parcur_cache['wrk'] iwrk=_parcur_cache['iwrk'] t,c,o=_fitpack._parcur(ravel(transpose(x)),w,u,ub,ue,k,task,ipar,s,t, nest,wrk,iwrk,per) _parcur_cache['u']=o['u'] _parcur_cache['ub']=o['ub'] _parcur_cache['ue']=o['ue'] _parcur_cache['t']=t _parcur_cache['wrk']=o['wrk'] _parcur_cache['iwrk']=o['iwrk'] ier,fp,n=o['ier'],o['fp'],len(t) u=o['u'] c.shape=idim,n-k-1 tcku = [t,list(c),k],u if ier<=0 and not quiet: print _iermess[ier][0] print "\tk=%d n=%d m=%d fp=%f s=%f"%(k,len(t),m,fp,s) if ier>0 and not full_output: if ier in [1,2,3]: print "Warning: "+_iermess[ier][0] else: try: raise _iermess[ier][1],_iermess[ier][0] except KeyError: raise _iermess['unknown'][1],_iermess['unknown'][0] if full_output: try: return tcku,fp,ier,_iermess[ier][0] except KeyError: return tcku,fp,ier,_iermess['unknown'][0] else: return tcku |
'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 spline curve g(u). Uses the FORTRAN routine parcur from FITPACK Inputs: x -- A list of sample vector arrays representing the curve. u -- An array of parameter values. If not given, these values are calculated automatically as (M = len(x[0])): v[0] = 0 v[i] = v[i-1] + distance(x[i],x[i-1]) u[i] = v[i] / v[M-1] ub, ue -- The end-points of the parameters interval. Defaults to u[0] and u[-1]. k -- Degree of the spline. Cubic splines are recommended. Even values of k should be avoided especially with a small s-value. 1 <= k <= 5. task -- If task==0 find t and c for a given smoothing factor, s. If task==1 find t and c for another value of the smoothing factor, s. There must have been a previous call with task=0 or task=1 for the same set of data. If task=-1 find the weighted least square spline for a given set of knots, t. s -- A smoothing condition. The amount of smoothness is determined by satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x) is the smoothed interpolation of (x,y). The user can use s to control the tradeoff between closeness and smoothness of fit. Larger s means more smoothing while smaller values of s indicate less smoothing. Recommended values of s depend on the weights, w. If the weights represent the inverse of the standard-deviation of y, then a good s value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is the number of datapoints in x, y, and w. t -- The knots needed for task=-1. full_output -- If non-zero, then return optional outputs. nest -- An over-estimate of the total number of knots of the spline to help in determining the storage space. By default nest=m/2. Always large enough is nest=m+k+1. per -- If non-zero, data points are considered periodic with period x[m-1] - x[0] and a smooth periodic spline approximation is returned. Values of y[m-1] and w[m-1] are not used. quiet -- Non-zero to suppress messages. Outputs: (tck, u, {fp, ier, msg}) tck -- (t,c,k) a tuple containing the vector of knots, the B-spline coefficients, and the degree of the spline. u -- An array of the values of the parameter. fp -- The weighted sum of squared residuals of the spline approximation. ier -- An integer flag about splrep success. Success is indicated if ier<=0. If ier in [1,2,3] an error occurred but was not raised. Otherwise an error is raised. msg -- A message corresponding to the integer flag, ier. Remarks: SEE splev for evaluation of the spline and its derivatives. """ if task<=0: _parcur_cache = {'t': array([],float), 'wrk': array([],float), 'iwrk':array([],intc),'u': array([],float), 'ub':0,'ue':1} x=myasarray(x) idim,m=x.shape if per: for i in range(idim): if x[i][0]!=x[i][-1]: if quiet<2:print 'Warning: Setting x[%d][%d]=x[%d][0]'%(i,m,i) x[i][-1]=x[i][0] if not 0<idim<11: raise TypeError,'0<idim<11 must hold' if w is None: w=ones(m,float) else: w=myasarray(w) ipar=(u is not None) if ipar: _parcur_cache['u']=u if ub is None: _parcur_cache['ub']=u[0] else: _parcur_cache['ub']=ub if ue is None: _parcur_cache['ue']=u[-1] else: _parcur_cache['ue']=ue else: _parcur_cache['u']=zeros(m,float) if not (1<=k<=5): raise TypeError, '1<=k=%d<=5 must hold'%(k) if not (-1<=task<=1): raise TypeError, 'task must be either -1,0, or 1' if (not len(w)==m) or (ipar==1 and (not len(u)==m)): raise TypeError,'Mismatch of input dimensions' if s is None: s=m-sqrt(2*m) if t is None and task==-1: raise TypeError, 'Knots must be given for task=-1' if t is not None: _parcur_cache['t']=myasarray(t) n=len(_parcur_cache['t']) if task==-1 and n<2*k+2: raise TypeError, 'There must be at least 2*k+2 knots for task=-1' if m<=k: raise TypeError, 'm>k must hold' if nest is None: nest=m+2*k if (task>=0 and s==0) or (nest<0): if per: nest=m+2*k else: nest=m+k+1 nest=max(nest,2*k+3) u=_parcur_cache['u'] ub=_parcur_cache['ub'] ue=_parcur_cache['ue'] t=_parcur_cache['t'] wrk=_parcur_cache['wrk'] iwrk=_parcur_cache['iwrk'] t,c,o=_fitpack._parcur(ravel(transpose(x)),w,u,ub,ue,k,task,ipar,s,t, nest,wrk,iwrk,per) _parcur_cache['u']=o['u'] _parcur_cache['ub']=o['ub'] _parcur_cache['ue']=o['ue'] _parcur_cache['t']=t _parcur_cache['wrk']=o['wrk'] _parcur_cache['iwrk']=o['iwrk'] ier,fp,n=o['ier'],o['fp'],len(t) u=o['u'] c.shape=idim,n-k-1 tcku = [t,list(c),k],u if ier<=0 and not quiet: print _iermess[ier][0] print "\tk=%d n=%d m=%d fp=%f s=%f"%(k,len(t),m,fp,s) if ier>0 and not full_output: if ier in [1,2,3]: print "Warning: "+_iermess[ier][0] else: try: raise _iermess[ier][1],_iermess[ier][0] except KeyError: raise _iermess['unknown'][1],_iermess['unknown'][0] if full_output: try: return tcku,fp,ier,_iermess[ier][0] except KeyError: return tcku,fp,ier,_iermess['unknown'][0] else: return tcku |
_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 points, t, are returned. Uses the FORTRAN routine curfit from FITPACK. Inputs: x, y -- The data points defining a curve y = f(x). w -- Strictly positive rank-1 array of weights the same length as x and y. The weights are used in computing the weighted least-squares spline fit. If the errors in the y values have standard-deviation given by the vector d, then w should be 1/d. Default is ones(len(x)). xb, xe -- The interval to fit. If None, these default to x[0] and x[-1] respectively. k -- The order of the spline fit. It is recommended to use cubic splines. Even order splines should be avoided especially with small s values. 1 <= k <= 5 task -- If task==0 find t and c for a given smoothing factor, s. If task==1 find t and c for another value of the smoothing factor, s. There must have been a previous call with task=0 or task=1 for the same set of data (t will be stored an used internally) If task=-1 find the weighted least square spline for a given set of knots, t. These should be interior knots as knots on the ends will be added automatically. s -- A smoothing condition. The amount of smoothness is determined by satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x) is the smoothed interpolation of (x,y). The user can use s to control the tradeoff between closeness and smoothness of fit. Larger s means more smoothing while smaller values of s indicate less smoothing. Recommended values of s depend on the weights, w. If the weights represent the inverse of the standard-deviation of y, then a good s value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is the number of datapoints in x, y, and w. default : s=m-sqrt(2*m) t -- The knots needed for task=-1. If given then task is automatically set to -1. full_output -- If non-zero, then return optional outputs. per -- If non-zero, data points are considered periodic with period x[m-1] - x[0] and a smooth periodic spline approximation is returned. Values of y[m-1] and w[m-1] are not used. quiet -- Non-zero to suppress messages. Outputs: (tck, {fp, ier, msg}) tck -- (t,c,k) a tuple containing the vector of knots, the B-spline coefficients, and the degree of the spline. fp -- The weighted sum of squared residuals of the spline approximation. ier -- An integer flag about splrep success. Success is indicated if ier<=0. If ier in [1,2,3] an error occurred but was not raised. Otherwise an error is raised. msg -- A message corresponding to the integer flag, ier. Remarks: See splev for evaluation of the spline and its derivatives. Example: x = linspace(0, 10, 10) y = sin(x) tck = splrep(x, y) x2 = linspace(0, 10, 200) y2 = splev(x2, tck) plot(x, y, 'o', x2, y2) """ if task<=0: _curfit_cache = {} x,y=map(myasarray,[x,y]) m=len(x) if w is None: w=ones(m,float) else: w=myasarray(w) if not len(w) == m: raise TypeError,' len(w)=%d is not equal to m=%d'%(len(w),m) if (m != len(y)) or (m != len(w)): raise TypeError, 'Lengths of the first three arguments (x,y,w) must be equal' if not (1<=k<=5): raise TypeError, 'Given degree of the spline (k=%d) is not supported. (1<=k<=5)'%(k) if m<=k: raise TypeError, 'm>k must hold' if xb is None: xb=x[0] if xe is None: xe=x[-1] if not (-1<=task<=1): raise TypeError, 'task must be either -1,0, or 1' if s is None: s = m-sqrt(2*m) if t is not None: task = -1 if task == -1: if t is None: raise TypeError, 'Knots must be given for task=-1' numknots = len(t) _curfit_cache['t'] = empty((numknots + 2*k+2,),float) _curfit_cache['t'][k+1:-k-1] = t nest = len(_curfit_cache['t']) elif task == 0: if per: nest = max(m+2*k,2*k+3) else: nest = max(m+k+1,2*k+3) t = empty((nest,),float) _curfit_cache['t'] = t if task <= 0: _curfit_cache['wrk'] = empty((m*(k+1)+nest*(7+3*k),),float) _curfit_cache['iwrk'] = empty((nest,),intc) try: t=_curfit_cache['t'] wrk=_curfit_cache['wrk'] iwrk=_curfit_cache['iwrk'] except KeyError: raise TypeError, "must call with task=1 only after"\ " call with task=0,-1" if not per: n,c,fp,ier = dfitpack.curfit(task, x, y, w, t, wrk, iwrk, xb, xe, k, s) else: n,c,fp,ier = dfitpack.percur(task, x, y, w, t, wrk, iwrk, k, s) tck = [t[:n],c[:n-k-1],k] if ier<=0 and not quiet: print _iermess[ier][0] print "\tk=%d n=%d m=%d fp=%f s=%f"%(k,len(t),m,fp,s) if ier>0 and not full_output: if ier in [1,2,3]: print "Warning: "+_iermess[ier][0] else: try: raise _iermess[ier][1],_iermess[ier][0] except KeyError: raise _iermess['unknown'][1],_iermess['unknown'][0] if full_output: try: return tck,fp,ier,_iermess[ier][0] except KeyError: return tck,fp,ier,_iermess['unknown'][0] else: return tck |
'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 gui_thread_guts import second_thread_app # Variable used to see if the wxApp is # running in the main or secondary thread # Used to determine if proxies should be generated. global running_in_second_thread,app,gui_thread_finished app = second_thread_app(0) running_in_second_thread = 1 app.MainLoop() #when the main loop exits, we need to single the # exit_gui_thread function that it is OK to shut down. gui_thread_finished.set() finally: finished.set() |
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 testing blas_libs = [] if not atlas_info: warnings.warn(AtlasNotFoundError.__doc__) blas_info = get_info('blas') if blas_info: libodr_files.append('d_lpk.f') blas_libs.extend(blas_info['libraries']) else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') else: libodr_files.append('d_lpk.f') blas_libs.extend(atlas_info['libraries']) libodr = [os.path.join(local_path, 'odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=libodr) sources = ['__odrpack.c'] config.add_extension('__odrpack', sources=sources, libraries=['odrpack']+blas_libs, include_dirs=[local_path], library_dirs=atlas_info['library_dirs'], ) return config |
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 testing blas_libs = [] if not atlas_info: warnings.warn(AtlasNotFoundError.__doc__) blas_info = get_info('blas') if blas_info: libodr_files.append('d_lpk.f') blas_libs.extend(blas_info['libraries']) else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') else: libodr_files.append('d_lpk.f') blas_libs.extend(atlas_info['libraries']) libodr = [os.path.join(local_path, 'odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=libodr) sources = ['__odrpack.c'] config.add_extension('__odrpack', sources=sources, libraries=['odrpack']+blas_libs, include_dirs=[local_path], library_dirs=atlas_info['library_dirs'], ) return config |
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 testing blas_libs = [] if not atlas_info: warnings.warn(AtlasNotFoundError.__doc__) blas_info = get_info('blas') if blas_info: libodr_files.append('d_lpk.f') blas_libs.extend(blas_info['libraries']) else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') else: libodr_files.append('d_lpk.f') blas_libs.extend(atlas_info['libraries']) libodr = [os.path.join(local_path, 'odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=libodr) sources = ['__odrpack.c'] config.add_extension('__odrpack', sources=sources, libraries=['odrpack']+blas_libs, include_dirs=[local_path], library_dirs=atlas_info['library_dirs'], ) return config |
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 testing blas_libs = [] if not atlas_info: warnings.warn(AtlasNotFoundError.__doc__) blas_info = get_info('blas') if blas_info: libodr_files.append('d_lpk.f') blas_libs.extend(blas_info['libraries']) else: warnings.warn(BlasNotFoundError.__doc__) libodr_files.append('d_lpkbls.f') else: libodr_files.append('d_lpk.f') blas_libs.extend(atlas_info['libraries']) libodr = [os.path.join(local_path, 'odrpack', x) for x in libodr_files] config.add_library('odrpack', sources=libodr) sources = ['__odrpack.c'] config.add_extension('__odrpack', sources=sources, libraries=['odrpack']+blas_libs, include_dirs=[local_path], library_dirs=atlas_info['library_dirs'], ) return config |
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 = func(data1,self.rowind,self.indptr,-data2,other.rowind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N) |
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 = func(data1,self.rowind,self.indptr,-data2,other.rowind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N) |
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]+'cscadd') c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,other.rowind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N) |
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]+'cscadd') c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,other.rowind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N) |
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 = ext.depends[0] assert os.path.basename(target)=='clapack.pyf.src' return target |
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_array() |
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 fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) if (fa < fb): # Switch so fa > fb dum = xa; xa = xb; xb = dum dum = fa; fa = fb; fb = dum xc = xb + _gold*(xb-xa) fc = apply(func, (xc,)+args) funcalls = 3 iter = 0 while (fc < fb): tmp1 = (xb - xa)*(fb-fc) tmp2 = (xb - xc)*(fb-fa) val = tmp2-tmp1 if abs(val) < _verysmall_num: denom = 2.0*_verysmall_num else: denom = 2.0*val w = xb - ((xb-xc)*tmp2-(xb-xa)*tmp1)/denom wlim = xb + grow_limit*(xc-xb) if iter > 1000: raise RuntimeError, "Too many iterations." if (w-xc)*(xb-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xa = xb; xb=w; fa=fb; fb=fw return xa, xb, xc, fa, fb, fc, funcalls elif (fw > fb): xc = w; fc=fw return xa, xb, xc, fa, fb, fc, funcalls w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(wlim-xc) >= 0.0: w = wlim fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(xc-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xb=xc; xc=w; w=xc+_gold*(xc-xb) fb=fc; fc=fw; fw=apply(func, (w,)+args) funcalls += 1 else: w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 xa=xb; xb=xc; xc=w fa=fb; fb=fc; fc=fw return xa, xb, xc, fa, fb, fc, funcalls |
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 fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) if (fa < fb): # Switch so fa > fb dum = xa; xa = xb; xb = dum dum = fa; fa = fb; fb = dum xc = xb + _gold*(xb-xa) fc = apply(func, (xc,)+args) funcalls = 3 iter = 0 while (fc < fb): tmp1 = (xb - xa)*(fb-fc) tmp2 = (xb - xc)*(fb-fa) val = tmp2-tmp1 if abs(val) < _verysmall_num: denom = 2.0*_verysmall_num else: denom = 2.0*val w = xb - ((xb-xc)*tmp2-(xb-xa)*tmp1)/denom wlim = xb + grow_limit*(xc-xb) if iter > 1000: raise RuntimeError, "Too many iterations." if (w-xc)*(xb-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xa = xb; xb=w; fa=fb; fb=fw return xa, xb, xc, fa, fb, fc, funcalls elif (fw > fb): xc = w; fc=fw return xa, xb, xc, fa, fb, fc, funcalls w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(wlim-xc) >= 0.0: w = wlim fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(xc-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xb=xc; xc=w; w=xc+_gold*(xc-xb) fb=fc; fc=fw; fw=apply(func, (w,)+args) funcalls += 1 else: w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 xa=xb; xb=xc; xc=w fa=fb; fb=fc; fc=fw return xa, xb, xc, fa, fb, fc, funcalls |
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.shape[otheraxis]): thiscolor = _colors[_corder[k % len(_corder)]] sliceobj[otheraxis] = k gist.plg(y[sliceobj],x,type='solid',color=thiscolor,marks=0) append_global_linetype(_rcolors[thiscolor]+'-') |
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(Numy): ystart = (ph-tm) - (nY+1)*Yspace + bs for nX in range(Numx): xstart = lm + nX*Xspace + ls systems.append({}) systems[-1]['viewport'] = [xstart,xstart+Xspace-(ls+rs),ystart,ystart+Yspace-(ts+bs)] _current_style='/tmp/subplot%s.gs' % win fid = open(_current_style,'w') fid.write(write_style.style2string(systems)) fid.close() gist.winkill(win) gist.window(win,style=_current_style,width=int(8.5*dpi),height=int(11*dpi),dpi=dpi) |
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_palette() plwf.plwf(z,y,x,shade=shade,edges=edges,ecolor=edge_color,scale=zscale) [xmin,xmax,ymin,ymax] = pl3d.draw3(1) gist.limits(xmin,xmax,ymin,ymax) pl3d.gnomon(gnomon) |
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 here. Use cubic interpolation and then if the # result is within delta * dalpha or outside of the interval bounded by a_lo or a_hi # then use quadratic interpolation, if the result is still too close, then use bisection dalpha = a_hi-a_lo; if dalpha < 0: a,b = a_hi,a_lo else: a,b = a_lo, a_hi # minimizer of cubic interpolant # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi) # if the result is too close to the end points (or out of the interval) # then use quadratic interpolation with phi_lo, derphi_lo and phi_hi # if the result is stil too close to the end points (or out of the interval) # then use bisection if (i > 0): cchk = delta1*dalpha a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, a_rec, phi_rec) if (i==0) or (a_j is None) or (a_j > b-cchk) or (a_j < a+cchk): qchk = delta2*dalpha a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi) if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk): a_j = a_lo + 0.5*dalpha |
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 algorithm by Outputs: (alpha0, gc, fc) """ global fc, gc fc = 0 gc = 0 def phi(alpha): global fc fc += 1 return f(xk+alpha*pk,*args) if isinstance(myfprime,type(())): 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) else: fprime = myfprime def phiprime(alpha): global gc gc += 1 return Num.dot(fprime(xk+alpha*pk,*args),pk) alpha0 = 0 phi0 = old_fval derphi0 = Num.dot(gfk,pk) alpha1 = pymin(1.0,1.01*2*(phi0-old_old_fval)/derphi0) phi_a1 = phi(alpha1) #derphi_a1 = phiprime(alpha1) evaluated below phi_a0 = phi0 derphi_a0 = derphi0 i = 1 maxiter = 10 while 1: # bracketing phase if (phi_a1 > phi0 + c1*alpha1*derphi0) or \ ((phi_a1 >= phi_a0) and (i > 1)): alpha_star, fval_star = zoom(alpha0, alpha1, phi_a0, phi_a1, derphi_a0, phi, phiprime, phi0, derphi0, c1, c2) break derphi_a1 = phiprime(alpha1) if (abs(derphi_a1) <= -c2*derphi0): alpha_star = alpha1 fval_star = phi_a1 break if (derphi_a1 >= 0): alpha_star, fval_star = zoom(alpha1, alpha0, phi_a1, phi_a0, derphi_a1, phi, phiprime, phi0, derphi0, c1, c2) break alpha2 = 2 * alpha1 # increase by factor of two on each iteration i = i + 1 alpha0 = alpha1 alpha1 = alpha2 phi_a0 = phi_a1 phi_a1 = phi(alpha1) derphi_a0 = derphi_a1 # stopping test if lower function not found if (i > maxiter): alpha_star = alpha1 fval_star = phi_a1 break return alpha_star, fc, gc, fval_star, old_fval |
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 (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, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 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 old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 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 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
|
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 (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, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 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 old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 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 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
|
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 (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, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 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 old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 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 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
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 (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, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 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 old_fval = f(x0,*args) old_old_fval = old_fval + 5000 func_calls += 1 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 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 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
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 and Ribiere See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 120-122. 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, func_calls, grad_calls, warnflag}, {allvecs}) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 -- if retall then this vector of the iterates is returned 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 True """ 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 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 = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk old_fval = f(xk,*args) old_old_fval = old_fval + 5000 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 yk = gfkp1 - gfk beta_k = pymax(0,Num.dot(yk,gfkp1)/deltak) pk = -gfkp1 + beta_k * pk gfk = gfkp1 k = k + 1 if disp or full_output: fval = apply(f,(xk,)+args) 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
|
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 and Ribiere See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 120-122. 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, func_calls, grad_calls, warnflag}, {allvecs}) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 -- if retall then this vector of the iterates is returned 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 True """ 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 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 = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk old_fval = f(xk,*args) old_old_fval = old_fval + 5000 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 yk = gfkp1 - gfk beta_k = pymax(0,Num.dot(yk,gfkp1)/deltak) pk = -gfkp1 + beta_k * pk gfk = gfkp1 k = k + 1 if disp or full_output: fval = apply(f,(xk,)+args) 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
|
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 and Ribiere See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 120-122. 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, func_calls, grad_calls, warnflag}, {allvecs}) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 -- if retall then this vector of the iterates is returned 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 True """ 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 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 = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk old_fval = f(xk,*args) old_old_fval = old_fval + 5000 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 yk = gfkp1 - gfk beta_k = pymax(0,Num.dot(yk,gfkp1)/deltak) pk = -gfkp1 + beta_k * pk gfk = gfkp1 k = k + 1 if disp or full_output: fval = apply(f,(xk,)+args) 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
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 and Ribiere See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 120-122. 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, func_calls, grad_calls, warnflag}, {allvecs}) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 -- if retall then this vector of the iterates is returned 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 True """ 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 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 = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk old_fval = f(xk,*args) old_old_fval = old_fval + 5000 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 yk = gfkp1 - gfk beta_k = pymax(0,Num.dot(yk,gfkp1)/deltak) pk = -gfkp1 + beta_k * pk gfk = gfkp1 k = k + 1 if disp or full_output: fval = apply(f,(xk,)+args) 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
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 and Ribiere See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 120-122. 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, func_calls, grad_calls, warnflag}, {allvecs}) xopt -- the minimizer of f. fopt -- the value of f(xopt). 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 -- if retall then this vector of the iterates is returned 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 True """ 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 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 = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk old_fval = f(xk,*args) old_old_fval = old_fval + 5000 while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 yk = gfkp1 - gfk beta_k = pymax(0,Num.dot(yk,gfkp1)/deltak) pk = -gfkp1 + beta_k * pk gfk = gfkp1 k = k + 1 if disp or full_output: fval = apply(f,(xk,)+args) 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, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
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 not given, finite-differences on fprime are used to compute it. See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 140. 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: fprime(x, *args) fhess_p -- a function to compute the Hessian of f times an arbitrary vector: fhess_p (x, p, *args) fhess -- a function to compute the Hessian matrix of f. args -- extra arguments for f, fprime, fhess_p, and fhess (the same set of extra arguments is supplied to all of these functions). epsilon -- if fhess is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, fcalls, gcalls, hcalls, warnflag},{allvecs}) xopt -- the minimizer of f fopt -- the value of the function at xopt: fopt = f(xopt) fcalls -- the number of function calls. gcalls -- the number of gradient calls. hcalls -- the number of hessian calls. warnflag -- algorithm warnings: 1 : 'Maximum number of iterations exceeded.' allvecs -- a list of all tried iterates Additional Inputs: avextol -- Convergence is assumed when the average relative error in the minimizer falls below this amount. maxiter -- Maximum number of iterations to allow. full_output -- If non-zero return the optional outputs. disp -- If non-zero print convergence message. retall -- return a list of results at each iteration if True Remarks: Only one of fhess_p or fhess need be given. If fhess is provided, then fhess_p will be ignored. If neither fhess nor fhess_p is provided, then the hessian product will be approximated using finite differences on fprime. """ x0 = asarray(x0) fcalls = 0 gcalls = 0 hcalls = 0 if maxiter is None: maxiter = len(x0)*200 xtol = len(x0)*avextol update = [2*xtol] xk = x0 if retall: allvecs = [xk] k = 0 old_fval = f(x0,*args) fcalls += 1 while (Num.add.reduce(abs(update)) > xtol) and (k < maxiter): # Compute a search direction pk by applying the CG method to # del2 f(xk) p = - grad f(xk) starting from 0. b = -apply(fprime,(xk,)+args) gcalls = gcalls + 1 maggrad = Num.add.reduce(abs(b)) eta = min([0.5,Num.sqrt(maggrad)]) termcond = eta * maggrad xsupi = 0 ri = -b psupi = -ri i = 0 dri0 = Num.dot(ri,ri) if fhess is not None: # you want to compute hessian once. A = apply(fhess,(xk,)+args) hcalls = hcalls + 1 while Num.add.reduce(abs(ri)) > termcond: if fhess is None: if fhess_p is None: Ap = apply(approx_fhess_p,(xk,psupi,fprime,epsilon)+args) gcalls = gcalls + 2 else: Ap = apply(fhess_p,(xk,psupi)+args) hcalls = hcalls + 1 else: Ap = Num.dot(A,psupi) # check curvature curv = Num.dot(psupi,Ap) if (curv <= 0): if (i > 0): break else: xsupi = xsupi + dri0/curv * psupi break alphai = dri0 / curv xsupi = xsupi + alphai * psupi ri = ri + alphai * Ap dri1 = Num.dot(ri,ri) betai = dri1 / dri0 psupi = -ri + betai * psupi i = i + 1 dri0 = dri1 # update Num.dot(ri,ri) for next time. pk = xsupi # search direction is solution to system. gfk = -b # gradient at xk alphak, fc, gc, old_fval = line_search_BFGS(f,xk,pk,gfk,old_fval,args) fcalls = fcalls + fc gcalls = gcalls + gc update = alphak * pk xk = xk + update if retall: allvecs.append(xk) k = k + 1 if disp or full_output: fval = old_fval if 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" % fcalls print " Gradient evaluations: %d" % gcalls print " Hessian evaluations: %d" % hcalls else: warnflag = 0 if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % fcalls print " Gradient evaluations: %d" % gcalls print " Hessian evaluations: %d" % hcalls if full_output: retlist = xk, fval, fcalls, gcalls, hcalls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
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 not given, finite-differences on fprime are used to compute it. See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 140. 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: fprime(x, *args) fhess_p -- a function to compute the Hessian of f times an arbitrary vector: fhess_p (x, p, *args) fhess -- a function to compute the Hessian matrix of f. args -- extra arguments for f, fprime, fhess_p, and fhess (the same set of extra arguments is supplied to all of these functions). epsilon -- if fhess is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, fcalls, gcalls, hcalls, warnflag},{allvecs}) xopt -- the minimizer of f fopt -- the value of the function at xopt: fopt = f(xopt) fcalls -- the number of function calls. gcalls -- the number of gradient calls. hcalls -- the number of hessian calls. warnflag -- algorithm warnings: 1 : 'Maximum number of iterations exceeded.' allvecs -- a list of all tried iterates Additional Inputs: avextol -- Convergence is assumed when the average relative error in the minimizer falls below this amount. maxiter -- Maximum number of iterations to allow. full_output -- If non-zero return the optional outputs. disp -- If non-zero print convergence message. retall -- return a list of results at each iteration if True Remarks: Only one of fhess_p or fhess need be given. If fhess is provided, then fhess_p will be ignored. If neither fhess nor fhess_p is provided, then the hessian product will be approximated using finite differences on fprime. """ x0 = asarray(x0) fcalls = 0 gcalls = 0 hcalls = 0 if maxiter is None: maxiter = len(x0)*200 xtol = len(x0)*avextol update = [2*xtol] xk = x0 if retall: allvecs = [xk] k = 0 old_fval = f(x0,*args) fcalls += 1 while (Num.add.reduce(abs(update)) > xtol) and (k < maxiter): # Compute a search direction pk by applying the CG method to # del2 f(xk) p = - grad f(xk) starting from 0. b = -apply(fprime,(xk,)+args) gcalls = gcalls + 1 maggrad = Num.add.reduce(abs(b)) eta = min([0.5,Num.sqrt(maggrad)]) termcond = eta * maggrad xsupi = 0 ri = -b psupi = -ri i = 0 dri0 = Num.dot(ri,ri) if fhess is not None: # you want to compute hessian once. A = apply(fhess,(xk,)+args) hcalls = hcalls + 1 while Num.add.reduce(abs(ri)) > termcond: if fhess is None: if fhess_p is None: Ap = apply(approx_fhess_p,(xk,psupi,fprime,epsilon)+args) gcalls = gcalls + 2 else: Ap = apply(fhess_p,(xk,psupi)+args) hcalls = hcalls + 1 else: Ap = Num.dot(A,psupi) # check curvature curv = Num.dot(psupi,Ap) if (curv <= 0): if (i > 0): break else: xsupi = xsupi + dri0/curv * psupi break alphai = dri0 / curv xsupi = xsupi + alphai * psupi ri = ri + alphai * Ap dri1 = Num.dot(ri,ri) betai = dri1 / dri0 psupi = -ri + betai * psupi i = i + 1 dri0 = dri1 # update Num.dot(ri,ri) for next time. pk = xsupi # search direction is solution to system. gfk = -b # gradient at xk alphak, fc, gc, old_fval = line_search_BFGS(f,xk,pk,gfk,old_fval,args) fcalls = fcalls + fc gcalls = gcalls + gc update = alphak * pk xk = xk + update if retall: allvecs.append(xk) k = k + 1 if disp or full_output: fval = old_fval if 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" % fcalls print " Gradient evaluations: %d" % gcalls print " Hessian evaluations: %d" % hcalls else: warnflag = 0 if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % fcalls print " Gradient evaluations: %d" % gcalls print " Hessian evaluations: %d" % hcalls if full_output: retlist = xk, fval, fcalls, gcalls, hcalls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist |
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): myargs = (p0,)+args fval = func(*myargs) fpval = fprime(*myargs) if fpval == 0: print "Warning: zero-derivative encountered." return p0 p = p0 - func(*myargs)/fprime(*myargs) if abs(p-p0) < tol: return p p0 = p else: # Secant method p0 = x0 p1 = x0*(1+1e-4) q0 = apply(func,(p0,)+args) q1 = apply(func,(p1,)+args) for iter in range(maxiter): try: p = p1 - q1*(p1-p0)/(q1-q0) except ZeroDivisionError: if p1 != p0: print "Tolerance of %g reached" % (p1-p0) return (p1+p0)/2.0 if abs(p-p0) < tol: return p p0 = p1 q0 = q1 p1 = p q1 = apply(func,(p1,)+args) raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) |
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,11]]) for p in 'cz': f = getattr(fblas,p+'gemm',None) if f is None: continue assert_array_almost_equal(f(3j,[3-4j],[-4]),[-48-36j]) assert_array_almost_equal(f(3j,[3-4j],[-4],3,[5j]),[-48-21j]) 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,11]]) |
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,11]]) for p in 'cz': f = getattr(fblas,p+'gemm',None) if f is None: continue assert_array_almost_equal(f(3j,[3-4j],[-4]),[-48-36j]) assert_array_almost_equal(f(3j,[3-4j],[-4],3,[5j]),[-48-21j]) 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,11]]) |
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=tempDate) elif freq == 'M': return Date(freq, year=tempDate.year, month=tempDate.month) elif freq == 'Q': return Date(freq, yaer=tempDate.year, quarter=monthToQuarter(tempDate.month)) elif freq == 'A': return Date(freq, year=tempDate.year) |
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 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 |
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 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 |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 or method to be minimized. x0 -- the initial guess. args -- extra arguments for func. Outputs: (xopt, {fopt, iter, funcalls, warnflag}) xopt -- minimizer of function fopt -- value of function at minimum: fopt = func(xopt) iter -- number of iterations funcalls -- number of function calls warnflag -- Integer warning flag: 1 : 'Maximum number of function evaluations.' 2 : 'Maximum number of iterations.' allvecs -- a list of solutions at each iteration Additional Inputs: xtol -- acceptable relative error in xopt for convergence. ftol -- acceptable relative error in func(xopt) for convergence. maxiter -- the maximum number of iterations to perform. maxfun -- the maximum number of function evaluations. full_output -- non-zero if fval and warnflag outputs are desired. disp -- non-zero to print convergence messages. retall -- non-zero to return list of solutions at each iteration """ x0 = asfarray(x0) N = len(x0) rank = len(x0.shape) if not -1 < rank < 2: raise ValueError, "Initial guess must be a scalar or rank-1 sequence." if maxiter is None: maxiter = N * 200 if maxfun is None: maxfun = N * 200 rho = 1; chi = 2; psi = 0.5; sigma = 0.5; one2np1 = range(1,N+1) if rank == 0: sim = Num.zeros((N+1,),x0.typecode()) else: sim = Num.zeros((N+1,N),x0.typecode()) fsim = Num.zeros((N+1,),'d') sim[0] = x0 if retall: allvecs = [sim[0]] fsim[0] = apply(func,(x0,)+args) nonzdelt = 0.05 zdelt = 0.00025 for k in range(0,N): y = Num.array(x0,copy=1) if y[k] != 0: y[k] = (1+nonzdelt)*y[k] else: y[k] = zdelt sim[k+1] = y f = apply(func,(y,)+args) fsim[k+1] = f ind = Num.argsort(fsim) fsim = Num.take(fsim,ind) # sort so sim[0,:] has the lowest function value sim = Num.take(sim,ind,0) iterations = 1 funcalls = N+1 while (funcalls < maxfun and iterations < maxiter): if (max(Num.ravel(abs(sim[1:]-sim[0]))) <= xtol \ and max(abs(fsim[0]-fsim[1:])) <= ftol): break xbar = Num.add.reduce(sim[:-1],0) / N xr = (1+rho)*xbar - rho*sim[-1] fxr = apply(func,(xr,)+args) funcalls = funcalls + 1 doshrink = 0 if fxr < fsim[0]: xe = (1+rho*chi)*xbar - rho*chi*sim[-1] fxe = apply(func,(xe,)+args) funcalls = funcalls + 1 if fxe < fxr: sim[-1] = xe fsim[-1] = fxe else: sim[-1] = xr fsim[-1] = fxr else: # fsim[0] <= fxr if fxr < fsim[-2]: sim[-1] = xr fsim[-1] = fxr else: # fxr >= fsim[-2] # Perform contraction if fxr < fsim[-1]: xc = (1+psi*rho)*xbar - psi*rho*sim[-1] fxc = apply(func,(xc,)+args) funcalls = funcalls + 1 if fxc <= fxr: sim[-1] = xc fsim[-1] = fxc else: doshrink=1 else: # Perform an inside contraction xcc = (1-psi)*xbar + psi*sim[-1] fxcc = apply(func,(xcc,)+args) funcalls = funcalls + 1 if fxcc < fsim[-1]: sim[-1] = xcc fsim[-1] = fxcc else: doshrink = 1 if doshrink: for j in one2np1: sim[j] = sim[0] + sigma*(sim[j] - sim[0]) fsim[j] = apply(func,(sim[j],)+args) funcalls = funcalls + N ind = Num.argsort(fsim) sim = Num.take(sim,ind,0) fsim = Num.take(fsim,ind) iterations = iterations + 1 if retall: allvecs.append(sim[0]) x = sim[0] fval = min(fsim) warnflag = 0 if funcalls >= maxfun: warnflag = 1 if disp: print "Warning: Maximum number of function evaluations has "\ "been exceeded." elif iterations >= maxiter: warnflag = 2 if disp: print "Warning: Maximum number of iterations has been exceeded" else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % iterations print " Function evaluations: %d" % funcalls if full_output: retlist = x, fval, iterations, funcalls, warnflag if retall: retlist += (allvecs,) else: retlist = x if retall: retlist = (x, allvecs) return retlist |
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 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. gtol -- gradient norm must be less than gtol before succesful termination norm -- order of norm (Inf is max, -Inf is min) 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: 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) 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 gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ linesearch.line_search(f,myfprime,xk,pk,gfk, old_fval,old_old_fval,args=args) if alpha_k is None: # line search failed try different one. func_calls = func_calls + fc grad_calls = grad_calls + gc 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 gfk = gfkp1 k = k + 1 gnorm = vecnorm(gfk,ord=norm) if (gnorm <= gtol): break try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break #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,:] 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 |
|
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 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. gtol -- gradient norm must be less than gtol before succesful termination norm -- order of norm (Inf is max, -Inf is min) 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: 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) 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 gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ linesearch.line_search(f,myfprime,xk,pk,gfk, old_fval,old_old_fval,args=args) if alpha_k is None: # line search failed try different one. func_calls = func_calls + fc grad_calls = grad_calls + gc 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 gfk = gfkp1 k = k + 1 gnorm = vecnorm(gfk,ord=norm) if (gnorm <= gtol): break try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break #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,:] 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 |
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 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. gtol -- gradient norm must be less than gtol before succesful termination norm -- order of norm (Inf is max, -Inf is min) 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: 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) 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 gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ linesearch.line_search(f,myfprime,xk,pk,gfk, old_fval,old_old_fval,args=args) if alpha_k is None: # line search failed try different one. func_calls = func_calls + fc grad_calls = grad_calls + gc 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 gfk = gfkp1 k = k + 1 gnorm = vecnorm(gfk,ord=norm) if (gnorm <= gtol): break try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break #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,:] 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 |
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 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. gtol -- gradient norm must be less than gtol before succesful termination norm -- order of norm (Inf is max, -Inf is min) 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: 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) 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 gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ linesearch.line_search(f,myfprime,xk,pk,gfk, old_fval,old_old_fval,args=args) if alpha_k is None: # line search failed try different one. func_calls = func_calls + fc grad_calls = grad_calls + gc 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 gfk = gfkp1 k = k + 1 gnorm = vecnorm(gfk,ord=norm) if (gnorm <= gtol): break try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: warnflag = 2 break #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,:] 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 |