rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
with a dense matrix d
with a dense array or matrix d
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtype) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False):
def __init__(self, arg1, dims=None, nzmax=100, dtype='d', copy=False):
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...
s = asarray(arg1)
s = arg1
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...
ijnew = ij.copy() ijnew[:, 0] = ij[:, 1] ijnew[:, 1] = ij[:, 0] temp = coo_matrix(s, ijnew, dims=dims, nzmax=nzmax, dtype=dtype).tocsr() self.shape = temp.shape self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr except:
except (AssertionError, TypeError, ValueError, AttributeError):
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...
raise NotImplementedError, 'adding a scalar to a sparse matrix ' \
raise NotImplementedError, 'adding a scalar to a CSR matrix ' \
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): # Now we would add this scalar to every element. raise NotImplementedError, 'adding a scalar to a sparse matrix ' \ 'is not yet supported' elif isspmatrix(other): ocs = other.tocsr() if (ocs.shape ...
other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
try: tr = other.transpose() except AttributeError: tr = asarray(other).transpose() return self.transpose().dot(tr).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = other * new.data # allows type conversion new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: other = asarray(other) return self.transpose().dot(other...
if (rank(other) != 1) or (len(other) != self.shape[1]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'csrmux') y = func(self.data, self.colind, self.indptr, other) return y
if isdense(other): func = getattr(sparsetools, self.ftype+'csrmux') y = func(self.data, self.colind, self.indptr, other) return y else: raise TypeError, "need a dense vector"
def matvec(self, other): if (rank(other) != 1) or (len(other) != self.shape[1]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'csrmux') y = func(self.data, self.colind, self.indptr, other) return y
if (rank(other) != 1) or (len(other) != self.shape[0]): raise ValueError, "dimension mismatch"
def rmatvec(self, other, conjugate=True): if (rank(other) != 1) or (len(other) != self.shape[0]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'cscmux') if conjugate: cd = conj(self.data) else: cd = self.data y = func(cd, self.colind, self.indptr, other, self.shape[1]) return y
raise KeyError, "index out of bounds"
raise IndexError, "index out of bounds"
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise KeyError, "index out of bounds" if (row >= M): self.indptr = resiz...
raise KeyError, "key out of bounds"
raise IndexError, "index out of bounds"
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise KeyError, "index out of bounds" if (row >= M): self.indptr = resiz...
""" A dictionary of keys based matrix. This is relatively efficient for constructing sparse matrices for conversion to other sparse matrix types. It does type checking on input by default. To disable this type checking and speed up element accesses slightly, set self._validate to False.
""" A dictionary of keys based matrix. This is an efficient structure for constructing sparse matrices for conversion to other sparse matrix types.
# def csc_cmp(x, y):
def __init__(self, A=None):
def __init__(self, A=None, dtype='d'):
def __init__(self, A=None): """ Create a new dictionary-of-keys sparse matrix. An optional argument A is accepted, which initializes the dok_matrix with it. This can be a tuple of dimensions (m, n) or a (dense) array to copy. """ dict.__init__(self) spmatrix.__init__(self) self.shape = (0, 0) # If _validate is True, e...
A = asarray(A)
def __init__(self, A=None): """ Create a new dictionary-of-keys sparse matrix. An optional argument A is accepted, which initializes the dok_matrix with it. This can be a tuple of dimensions (m, n) or a (dense) array to copy. """ dict.__init__(self) spmatrix.__init__(self) self.shape = (0, 0) # If _validate is True, e...
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self....
new.shape = self.shape for key in other.keys():
for key in other:
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self....
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self...
for key in other.keys():
for key in other:
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self...
else:
elif isdense(other):
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self...
new = dok_matrix() for key in self.keys():
new = dok_matrix(self.shape, dtype=self.dtype) for key in self:
def __neg__(self): new = dok_matrix() for key in self.keys(): new[key] = -self[key] return new
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
def __mul__(self, other): # self * other if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = val * other #new.dtype.char = self.dtype.char return new else: return self.dot(other)
for (key, val) in self.items():
for (key, val) in self.iteritems():
def __mul__(self, other): # self * other if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = val * other #new.dtype.char = self.dtype.char return new else: return self.dot(other)
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose...
for (key, val) in self.items():
for (key, val) in self.iteritems():
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose...
other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
try: tr = other.transpose() except AttributeError: tr = asarray(other).transpose() return self.transpose().dot(tr).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose...
newshape = (self.shape[1], self.shape[0]) new = dok_matrix(newshape) for key in self.keys(): new[key[1], key[0]] = self[key]
m, n = self.shape new = dok_matrix((n, m), dtype=self.dtype) for key, value in self.iteritems(): new[key[1], key[0]] = value
def transpose(self): """ Return the transpose """ newshape = (self.shape[1], self.shape[0]) new = dok_matrix(newshape) for key in self.keys(): new[key[1], key[0]] = self[key] return new
new = dok_matrix() for key in self.keys(): new[key[1], key[0]] = conj(self[key])
m, n = self.shape new = dok_matrix((n, m), dtype=self.dtype) for key, value in self.iteritems(): new[key[1], key[0]] = conj(value)
def conjtransp(self): """ Return the conjugate transpose """ new = dok_matrix() for key in self.keys(): new[key[1], key[0]] = conj(self[key]) return new
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
def copy(self): new = dok_matrix() new.update(self) new.shape = self.shape return new
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newk...
for key in self.keys():
for key in self:
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newk...
for key in self.keys():
for key in self:
def split(self, cols_or_rows, columns=1): # similar to take but returns two array, the extracted # columns plus the resulting array # assumes cols_or_rows is sorted base = dok_matrix() ext = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: for key in self.keys(): num = searchsorted(cols_or_rows,...
for key in self.keys():
for key in self:
def matvec(self, other): other = asarray(other) if other.shape[0] != self.shape[1]: raise ValueError, "dimensions do not match" new = [0]*self.shape[0] for key in self.keys(): new[int(key[0])] += self[key] * other[int(key[1]), ...] return array(new)
if other.shape[-1] != self.shape[0]: raise ValueError, "dimensions do not match" new = [0]*self.shape[1] for key in self.keys(): new[int(key[1])] += other[..., int(key[0])] * conj(self[key]) return array(new)
if other.shape[-1] != self.shape[0]: raise ValueError, "dimensions do not match" new = [0]*self.shape[1] for key in self: new[int(key[1])] += other[..., int(key[0])] * conj(self[key]) return array(new)
def rmatvec(self, other, conjugate=True): other = asarray(other)
data = [0]*nzmax colind = [0]*nzmax
data = zeros(nzmax, dtype=self.dtype) colind = zeros(nzmax, dtype=self.dtype)
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this...
row_ptr = [nnz]*(self.shape[0]+1)
row_ptr = empty(self.shape[0]+1, dtype=int) row_ptr[:] = nnz
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this...
row_ptr[current_row+1:ikey0+1] = [k]*N
row_ptr[current_row+1:ikey0+1] = k
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this...
keys = [(k[1], k[0]) for k in self.keys()]
keys = [(k[1], k[0]) for k in self]
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
data = [0]*nzmax rowind = [0]*nzmax
data = zeros(nzmax, dtype=self.dtype) rowind = zeros(nzmax, dtype=self.dtype)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
col_ptr = [nnz]*(self.shape[1]+1)
col_ptr = empty(self.shape[1]+1) col_ptr[:] = nnz
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
col_ptr[current_col+1:ikey1+1] = [k]*N
col_ptr[current_col+1:ikey1+1] = k
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
data = array(data) rowind = array(rowind) col_ptr = array(col_ptr)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
for key in self.keys():
for key in self:
def todense(self, dtype=None): if dtype is None: dtype = 'd' new = zeros(self.shape, dtype=dtype) for key in self.keys(): ikey0 = int(key[0]) ikey1 = int(key[1]) new[ikey0, ikey1] = self[key] if amax(ravel(abs(new.imag))) == 0: new = new.real return new
"""Return a sparse matrix in CSR format given its diagonals.
"""Return a sparse matrix in CSC format given its diagonals.
def spdiags(diags, offsets, M, N): """Return a sparse matrix in CSR format given its diagonals. B = spdiags(diags, offsets, M, N) Inputs: diags -- rows contain diagonal values offsets -- diagonals to set (0 is main) M, N -- sparse matrix returned is M X N """ diags = array(transpose(diags), copy=True) if diags.d...
diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsr')
diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsc')
def spdiags(diags, offsets, M, N): """Return a sparse matrix in CSR format given its diagonals. B = spdiags(diags, offsets, M, N) Inputs: diags -- rows contain diagonal values offsets -- diagonals to set (0 is main) M, N -- sparse matrix returned is M X N """ diags = array(transpose(diags), copy=True) if diags.d...
return 1.0/(1+exp(-1.0/b*norm.ppf(q)-a))
return 1.0/(1+exp(-1.0/b*(norm.ppf(q)-a)))
def _ppf(self, q, a, b): return 1.0/(1+exp(-1.0/b*norm.ppf(q)-a))
yout -- impulse response of system.
yout -- impulse response of system (except possible singularities at 0).
def impulse(system, X0=None, T=None, N=None): """Impulse response of continuous-time system. Inputs: system -- an instance of the LTI class or a tuple with 2, 3, or 4 elements representing (num, den), (zero, pole, gain), or (A, B, C, D) representation of the system. X0 -- (optional, default = 0) inital state-vector. ...
buffer=raw_tag[4:])
buffer=raw_tag[4:4+byte_count])
def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = ndarray(shape=(), dtype=self.dtypes['tag_full'], buffer = raw_tag) mdtype = tag['mdtype'] byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype &...
return self.current_getter().get_array()
return self.current_getter(byte_count).get_array()
def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = ndarray(shape=(), dtype=self.dtypes['tag_full'], buffer = raw_tag) mdtype = tag['mdtype'] byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype &...
elif not byte_count: getter = Mat5EmptyMatrixGetter(self)
def matrix_getter_factory(self): ''' Returns reader for next matrix at top level ''' tag = self.read_dtype(self.dtypes['tag_full']) mdtype = tag['mdtype'] byte_count = tag['byte_count'] next_pos = self.mat_stream.tell() + byte_count if mdtype == miCOMPRESSED: getter = Mat5ZArrayReader(self, byte_count).matrix_getter_fa...
getter = self.current_getter()
getter = self.current_getter(byte_count)
def matrix_getter_factory(self): ''' Returns reader for next matrix at top level ''' tag = self.read_dtype(self.dtypes['tag_full']) mdtype = tag['mdtype'] byte_count = tag['byte_count'] next_pos = self.mat_stream.tell() + byte_count if mdtype == miCOMPRESSED: getter = Mat5ZArrayReader(self, byte_count).matrix_getter_fa...
def current_getter(self):
def current_getter(self, byte_count):
def current_getter(self): ''' Return matrix getter for current stream position
derphi_a1 = phiprime(alpha1)
def phiprime(alpha): global gc gc += 1 return Num.dot(fprime(xk+alpha*pk,*args),pk)
allvecs -- a list of all iterates
allvecs -- a list of all iterates (only returned if retall==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 (...
config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage('io')
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpac...
config.add_subpackage('linsolve') config.add_subpackage('maxentropy')
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpac...
config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse')
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpac...
config.add_subpackage('ndimage') config.add_subpackage('weave')
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpac...
modname = __name__[__name__.rfind('.')-1:] + '.expressions'
modname = __name__[:__name__.rfind('.')] + '.expressions'
def makeExpressions(context): """Make private copy of the expressions module with a custom get_context(). An attempt was made to make this threadsafe, but I can't guarantee it's bulletproof. """ import sys, imp modname = __name__[__name__.rfind('.')-1:] + '.expressions' # get our own, private copy of expressions imp.a...
wx_class.init2 = wx_class.__init__ wx_class.__init__ = plain_class__init__
if not hasattr(wx_class, 'init2'): wx_class.init2 = wx_class.__init__ wx_class.__init__ = plain_class__init__
def register(wx_class): """ Create a gui_thread compatible version of wx_class Test whether a proxy is necessary. If so, generate and return the proxy class. if not, just return the wx_class unaltered. """ if running_in_second_thread: #print 'proxy generated' return proxify(wx_class) else: wx_class.init2 = wx_class....
from gui_thread_guts import proxy_event, print_exception, smart_return
from gui_thread_guts import proxy_event, smart_return
body = """def %(method)s(self,*args,**kw): \"\"\"%(documentation)s\"\"\" %(pre_test)s from gui_thread_guts import proxy_event, print_exception, smart_return %(import_statement)s #import statement finished = threading.Event() # remove proxies if present args = dereference_arglist(args) %(arguments)s #arguments evt = pro...
print_exception(finished.exception_info) raise finished.exception_info['type'],finished.exception_info['value']
raise finished.exception_info[0],finished.exception_info[1]
body = """def %(method)s(self,*args,**kw): \"\"\"%(documentation)s\"\"\" %(pre_test)s from gui_thread_guts import proxy_event, print_exception, smart_return %(import_statement)s #import statement finished = threading.Event() # remove proxies if present args = dereference_arglist(args) %(arguments)s #arguments evt = pro...
def Numeric_random(size): import random from Numeric import zeros, Float64 results = zeros(size,Float64) f = results.flat for i in range(len(f)): f[i] = random.random() return results
def Numeric_random(size): import random from Numeric import zeros, Float64 results = zeros(size,Float64) f = results.flat for i in range(len(f)): f[i] = random.random() return results
def fmin_bfgs(f, x0, fprime=None, args=(), maxgtol=1e-5, epsilon=_epsilon,
def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-4, norm=Inf, epsilon=_epsilon,
def fmin_bfgs(f, x0, fprime=None, args=(), maxgtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno ...
maxgtol -- maximum allowable gradient magnitude for stopping
gtol -- gradient norm must be less than gtol before succesful termination norm -- order of norm (Inf is max, -Inf is min)
def fmin_bfgs(f, x0, fprime=None, args=(), maxgtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno ...
gtol = maxgtol
def fmin_bfgs(f, x0, fprime=None, args=(), maxgtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno ...
while (Num.maximum.reduce(abs(gfk)) > gtol) and (k < maxiter):
gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter):
def fmin_bfgs(f, x0, fprime=None, args=(), maxgtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno ...
gfk = gfkp1
def fmin_bfgs(f, x0, fprime=None, args=(), maxgtol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function using the BFGS algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the quasi-Newton method of Broyden, Fletcher, Goldfarb, and Shanno ...
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon,
def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-4, norm=Inf, epsilon=_epsilon,
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, 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 Pola...
avegtol -- minimum average value of gradient for stopping
gtol -- stop when norm of gradient is less than gtol norm -- order of vector norm to use
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, 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 Pola...
avegtol -- the minimum occurs when fprime(xopt)==0. This specifies how close to zero the average magnitude of fprime(xopt) needs to be.
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, 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 Pola...
gtol = N*avegtol
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, 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 Pola...
while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter):
gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter):
def fmin_cg(f, x0, fprime=None, args=(), avegtol=1e-5, epsilon=_epsilon, 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 Pola...
This can be instantiated in two ways:
This can be instantiated in several ways:
def copy(self): csc = self.tocsc() return csc.copy()
??
standard CSC representation
def copy(self): csc = self.tocsc() return csc.copy()
self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr)
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)
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...
This can be instantiated in four ways: 1. csr_matrix(s)
This can be instantiated in several ways: - csr_matrix(d) with a dense matrix d - csr_matrix(s)
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtypechar) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
2. csr_matrix((M, N), [nzmax, dtype])
- csr_matrix((M, N), [nzmax, dtype])
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtypechar) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
3. csr_matrix(data, ij, [(M, N), nzmax])
- csr_matrix((data, ij), [(M, N), nzmax])
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtypechar) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
4. csr_matrix(data, (row, ptr), [(M, N)]) ??
- csr_matrix((data, row, ptr), [(M, N)]) standard CSR representation
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtypechar) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
def __init__(self, arg1, arg2=None, arg3=None, nzmax=100, dtype='d', copy=False):
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False):
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtypechar) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
if isspmatrix(arg1):
if isdense(arg1): 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]) elif isspmatrix(arg1):
def __init__(self, arg1, arg2=None, arg3=None, nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isspmatrix(arg1): s = arg1 if isinstance(s, csr_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.colind = s.colind.copy() self.indptr = s.indptr.copy() else...
assert len(arg1) == 2 and type(arg1[0]) == int and type(arg1[1]) == int except AssertionError: raise TypeError, "matrix dimensions must be a tuple of two integers" (M, N) = arg1 self.data = zeros((nzmax,), dtype) self.colind = zeros((nzmax,), 'i') self.indptr = zeros((M+1,), 'i') self.shape = (M, N) elif isinstance(arg...
(M, N) = arg1 M = int(M) N = int(N) self.data = zeros((nzmax,), dtype) self.colind = zeros((nzmax,), int) self.indptr = zeros((M+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) ijnew = ij.copy() ijnew[...
def __init__(self, arg1, arg2=None, arg3=None, nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isspmatrix(arg1): s = arg1 if isinstance(s, csr_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.colind = s.colind.copy() self.indptr = s.indptr.copy() else...
M, N = arg3 except TypeError: raise TypeError, "argument 3 must be a pair (M, N) of dimensions" else: M = N = None if N is None: try: N = int(amax(self.colind)) + 1 except ValueError: N = 0 if M is None: M = len(self.indptr) - 1 if M == -1: M = 0 self.shape = (M, N) else: raise ValueError, "unrecognized form for csr_m...
(s, colind, indptr) = arg1 if copy: self.data = array(s) self.colind = array(colind) self.indptr = array(indptr) else: self.data = asarray(s) self.colind = asarray(colind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csr_matrix constructor"
def __init__(self, arg1, arg2=None, arg3=None, nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isspmatrix(arg1): s = arg1 if isinstance(s, csr_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.colind = s.colind.copy() self.indptr = s.indptr.copy() else...
return csr_matrix(c, (colc, ptrc), (M, N))
return csr_matrix((c, colc, ptrc), dims=(M, N))
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): # Now we would add this scalar to every element. raise NotImplementedError, 'adding a scalar to a sparse matrix ' \ 'is not yet supported' elif isspmatrix(other): ocs = other.tocsr() if (ocs.shape ...
return csr_matrix(c, (colc, ptrc), (M, N))
return csr_matrix((c, colc, ptrc), dims=(M, N))
def __pow__(self, other): """ Element-by-element power (unless other is a scalar, in which case return the matrix power.) """ if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = new.data ** other new.dtypechar = new.data.dtypechar new.ftype = _transtabl[new.dtypechar] return new elif...
return csr_matrix(c, (rowc, ptrc), (M, N))
return csr_matrix((c, rowc, ptrc), dims=(M, N))
def matmat(self, other): if isspmatrix(other): M, K1 = self.shape K2, N = other.shape a, rowa, ptra = self.data, self.colind, self.indptr if (K1 != K2): raise ValueError, "shape mismatch error" if isinstance(other, csc_matrix): other._check() dtypechar = _coerce_rules[(self.dtypechar, other.dtypechar)] ftype = _transta...
return csr_matrix(data, (colind, row_ptr))
return csr_matrix((data, colind, row_ptr), nzmax=nzmax)
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = self.nnz assert nnz == len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax row_ptr = [0]*(self.shape[0]+1) current_row = 0 k = 0 for key in keys: ikey0 = int(key[0]) ike...
return csc_matrix((data, rowind, col_ptr))
return csc_matrix((data, rowind, col_ptr), nzmax=nzmax)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ keys = self.keys() # Sort based on columns keys.sort(csc_cmp) nnz = self.nnz assert nnz == len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax rowind = [0]*nzmax col_ptr = [0]*(self.shape[1]+1) current_col = 0 k = 0 for k...
return csr_matrix(a, (cola, ptra), self.shape)
return csr_matrix((a, cola, ptra), dims=self.shape)
def tocsr(self): func = getattr(sparsetools, self.ftype+"cootocsc") data, row, col = self._normalize(rowfirst=True) a, cola, ptra, ierr = func(self.shape[0], data, col, row) if ierr: raise RuntimeError, "error in conversion" return csr_matrix(a, (cola, ptra), self.shape)
config.add_subpackage('cluster')
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage(...
row_ptr[-1] = nnz+1
row_ptr[-1] = nnz
def getCSR(self): # Return Compressed Sparse Row format arrays for this matrix keys = self.keys() keys.sort() nnz = len(keys) data = [None]*nnz colind = [None]*nnz row_ptr = [None]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: current_row = ik...
col_ptr[-1] = nnz+1
col_ptr[-1] = nnz
def getCSC(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz rowind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: curren...
def sparse_linear_solve(A,b):
def sparse_linear_solve(A,b,permc_spec=0):
def sparse_linear_solve(A,b): if not hasattr(A, 'getCSR') and not hasattr(A, 'getCSC'): raise ValueError, "Sparse matrix must be able to return CSC format--"\ "A.getCSC()--or CSR format--A.getCSR()" if not hasattr(A,'shape'): raise ValueError, "Sparse matrix must be able to return shape (rows,cols) = A.shape" if hasatt...
return gssv(M,N,lastel,data,index0,index1,b,csc)
return gssv(M,N,lastel,data,index0,index1,b,csc,permc_spec)
def sparse_linear_solve(A,b): if not hasattr(A, 'getCSR') and not hasattr(A, 'getCSC'): raise ValueError, "Sparse matrix must be able to return CSC format--"\ "A.getCSC()--or CSR format--A.getCSR()" if not hasattr(A,'shape'): raise ValueError, "Sparse matrix must be able to return shape (rows,cols) = A.shape" if hasatt...
def str_array(arr, precision=5,col_sep=' ',row_sep="\n"):
def str_array(arr, precision=5,col_sep=' ',row_sep="\n",ss=0):
def str_array(arr, precision=5,col_sep=' ',row_sep="\n"): thestr = [] arr = asarray(arr) N,M = arr.shape thistype = arr.typecode() nofloat = (thistype in '1silbwu') or (thistype in 'Oc') cmplx = thistype in 'FD' fmtstr = "%%.%de" % precision for n in xrange(N): theline = [] for m in xrange(M): val = arr[n,m] if nofloat...
if nofloat:
if ss and abs(val) < cmpnum: val = 0*val if nofloat or val==0:
def str_array(arr, precision=5,col_sep=' ',row_sep="\n"): thestr = [] arr = asarray(arr) N,M = arr.shape thistype = arr.typecode() nofloat = (thistype in '1silbwu') or (thistype in 'Oc') cmplx = thistype in 'FD' fmtstr = "%%.%de" % precision for n in xrange(N): theline = [] for m in xrange(M): val = arr[n,m] if nofloat...
istr = eval('fmtstr % ival') if (ival >= 0):
if (ival >= 0): istr = eval('fmtstr % ival')
def str_array(arr, precision=5,col_sep=' ',row_sep="\n"): thestr = [] arr = asarray(arr) N,M = arr.shape thistype = arr.typecode() nofloat = (thistype in '1silbwu') or (thistype in 'Oc') cmplx = thistype in 'FD' fmtstr = "%%.%de" % precision for n in xrange(N): theline = [] for m in xrange(M): val = arr[n,m] if nofloat...
precision=5, keep_open=0):
precision=5, suppress_small=0, keep_open=0):
def write_array(fileobject, arr, separator=" ", linesep='\n', precision=5, keep_open=0): """Write a rank-2 or less array to file represented by fileobject. Inputs: fileobject -- An open file object or a string to a valid filename. arr -- The array to write. separator -- separator to write between elements of the arra...
col_sep=separator, row_sep=linesep)
col_sep=separator, row_sep=linesep, ss = suppress_small)
def write_array(fileobject, arr, separator=" ", linesep='\n', precision=5, keep_open=0): """Write a rank-2 or less array to file represented by fileobject. Inputs: fileobject -- An open file object or a string to a valid filename. arr -- The array to write. separator -- separator to write between elements of the arra...
class test_trapz(unittest.TestCase): def check_basic(self): pass class test_diff(unittest.TestCase): pass class test_corrcoef(unittest.TestCase): pass class test_cov(unittest.TestCase): pass class test_squeeze(unittest.TestCase): pass class test_sinc(unittest.TestCase): pass class test_angle(unittest.TestCase): ...
def check_basic(self): ba = [1,2,10,11,6,5,4] ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]] for ctype in ['1','b','s','i','l','f','d','F','D']: a = array(ba,ctype) a2 = array(ba2,ctype) if ctype in ['1', 'b']: self.failUnlessRaises(ArithmeticError, cumprod, a) self.failUnlessRaises(ArithmeticError, cumprod, a2, 1) self.failUn...
argout = (array(0,mtype).itemsize,mtype) return argout
newarr = array(0,mtype) return newarr.itemsize, newarr.dtype.char
def getsize_type(mtype): if mtype in ['B','uchar','byte','unsigned char','integer*1', 'int8']: mtype = 'B' elif mtype in ['h','schar', 'signed char']: mtype = 'B' elif mtype in ['h','short','int16','integer*2']: mtype = 'h' elif mtype in ['H','ushort','uint16','unsigned short']: mtype = 'H' elif mtype in ['i','int']: m...