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 = (ocsc.shape[1], ocsc.shape[0])
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 = (ocsc.shape[1], ocsc.shape[0])
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 = (ocsc.shape[1], ocsc.shape[0])
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 != self.shape): raise ValueError, "inconsistent shapes"
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.transpose()).transpose()
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 = resize1d(self.indptr, row+2) self.indptr[M+1:] = self.indptr[M] M = row+1 elif (row < 0): row = M - row if (col >= N): N = col+1 elif (col < 0): col = N - col self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.colind = resize1d(self.colind, nzmax + alloc) func(self.data, self.colind, self.indptr, col, row, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise KeyError, "key out of bounds" else: raise NotImplementedError
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 = resize1d(self.indptr, row+2) self.indptr[M+1:] = self.indptr[M] M = row+1 elif (row < 0): row = M - row if (col >= N): N = col+1 elif (col < 0): col = N - col self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.colind = resize1d(self.colind, nzmax + alloc) func(self.data, self.colind, self.indptr, col, row, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise KeyError, "key out of bounds" else: raise NotImplementedError
""" 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, ensure __setitem__ keys are integer tuples self._validate = True if A is not None: if type(A) == tuple: # Interpret as dimensions try: dims = A (M, N) = dims assert M == int(M) and M > 0 assert N == int(N) and N > 0 self.shape = (int(M), int(N)) return except (TypeError, ValueError, AssertionError): raise TypeError, "dimensions must be a 2-tuple of positive"\ " integers" if isspmatrix(A): # For sparse matrices, this is too inefficient; we need # something else. raise NotImplementedError, "initializing a dok_matrix with " \ "a sparse matrix is not yet supported" elif isdense(A): A = asarray(A) if rank(A) == 2: M, N = A.shape self.shape = (M, N) for i in range(M): for j in range(N): if A[i, j] != 0: self[i, j] = A[i, j] elif rank(A) == 1: M = A.shape[0] self.shape = (M, 1) for i in range(M): if A[i] != 0: self[i, 0] = A[i] else: raise TypeError, "array for initialization must have rank 2" else: raise TypeError, "argument should be a tuple of dimensions " \ "or a sparse or dense matrix"
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, ensure __setitem__ keys are integer tuples self._validate = True if A is not None: if type(A) == tuple: # Interpret as dimensions try: dims = A (M, N) = dims assert M == int(M) and M > 0 assert N == int(N) and N > 0 self.shape = (int(M), int(N)) return except (TypeError, ValueError, AssertionError): raise TypeError, "dimensions must be a 2-tuple of positive"\ " integers" if isspmatrix(A): # For sparse matrices, this is too inefficient; we need # something else. raise NotImplementedError, "initializing a dok_matrix with " \ "a sparse matrix is not yet supported" elif isdense(A): A = asarray(A) if rank(A) == 2: M, N = A.shape self.shape = (M, N) for i in range(M): for j in range(N): if A[i, j] != 0: self[i, j] = A[i, j] elif rank(A) == 1: M = A.shape[0] self.shape = (M, 1) for i in range(M): if A[i] != 0: self[i, 0] = A[i] else: raise TypeError, "array for initialization must have rank 2" else: raise TypeError, "argument should be a tuple of dimensions " \ "or a sparse or dense matrix"
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.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
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.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
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.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
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.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
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.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
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().dot(other.transpose()).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().dot(other.transpose()).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().dot(other.transpose()).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[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
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[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
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, key[1]) if cols_or_rows[num]==key[1]: newkey = (key[0], num) ext[newkey] = self[key] else: newkey = (key[0], key[1]-num) base[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if cols_or_rows[num]==key[0]: newkey = (num, key[1]) ext[newkey] = self[key] else: newkey = (key[0]-num, key[1]) base[newkey] = self[key] return base, ext
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 sufficient?? row_ptr = [nnz]*(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: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
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 sufficient?? row_ptr = [nnz]*(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: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
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 sufficient?? row_ptr = [nnz]*(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: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
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.dtype.char not in 'fdFD': diags = diags.astype('d') offsets = array(offsets, copy=False) mtype = diags.dtype.char assert(len(offsets) == diags.shape[1]) # set correct diagonal to csr conversion routine for this type diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsr') a, rowa, ptra, ierr = diagfunc(M, N, diags, offsets) if ierr: raise ValueError, "ran out of memory (shouldn't have happened)" return csc_matrix((a, rowa, ptra), dims=(M, N))
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.dtype.char not in 'fdFD': diags = diags.astype('d') offsets = array(offsets, copy=False) mtype = diags.dtype.char assert(len(offsets) == diags.shape[1]) # set correct diagonal to csr conversion routine for this type diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsr') a, rowa, ptra, ierr = diagfunc(M, N, diags, offsets) if ierr: raise ValueError, "ran out of memory (shouldn't have happened)" return csc_matrix((a, rowa, ptra), dims=(M, N))
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. T -- (optional) time points (autocomputed if not given). N -- (optional) number of time points to autocompute (100 if not given). Ouptuts: (T, yout) T -- output time points, yout -- impulse response of system. """ if isinstance(system, lti): sys = system else: sys = lti(*system) if X0 is None: B = sys.B else: B = sys.B + X0 if N is None: N = 100 if T is None: vals = linalg.eigvals(sys.A) tc = 1.0/min(abs(real(vals))) T = arange(0,5*tc,5*tc / float(N)) h = zeros(T.shape, sys.A.typecode()) for k in range(len(h)): eA = Mat(linalg.expm(sys.A*T[k])) B,C = map(Mat, (B,sys.C)) h[k] = squeeze(C*eA*B) return T, h
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 & 0xFFFF dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize return ndarray(shape=(el_count,), dtype=dt, buffer=raw_tag[4:]) byte_count = tag['byte_count'] if mdtype == miMATRIX: return self.current_getter().get_array() if mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: raise TypeError, 'Do not support encoding %d' % mdtype el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize el = ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) return el
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 & 0xFFFF dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize return ndarray(shape=(el_count,), dtype=dt, buffer=raw_tag[4:]) byte_count = tag['byte_count'] if mdtype == miMATRIX: return self.current_getter().get_array() if mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: raise TypeError, 'Do not support encoding %d' % mdtype el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize el = ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) return el
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_factory() elif not mdtype == miMATRIX: raise TypeError, \ 'Expecting miMATRIX type here, got %d' % mdtype elif not byte_count: # an empty miMATRIX can contain no bytes getter = Mat5EmptyMatrixGetter(self) else: getter = self.current_getter() getter.next_position = next_pos return getter
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_factory() elif not mdtype == miMATRIX: raise TypeError, \ 'Expecting miMATRIX type here, got %d' % mdtype elif not byte_count: # an empty miMATRIX can contain no bytes getter = Mat5EmptyMatrixGetter(self) else: getter = self.current_getter() getter.next_position = next_pos return getter
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 (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 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
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_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config
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_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config
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_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config
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_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config
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.acquire_lock() try: old = sys.modules.pop(modname) import expressions private = sys.modules.pop(modname) sys.modules[modname] = old finally: imp.release_lock() def get_context(): return context private.get_context = get_context return private
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.__init__ wx_class.__init__ = plain_class__init__ return 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 = proxy_event(%(call_method)s,arg_list,kw,finished) self.post(evt) finished.wait() if finished.exception_info: print_exception(finished.exception_info) raise finished.exception_info['type'],finished.exception_info['value'] %(results)s #results\n""" %locals()
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 = proxy_event(%(call_method)s,arg_list,kw,finished) self.post(evt) finished.wait() if finished.exception_info: print_exception(finished.exception_info) raise finished.exception_info['type'],finished.exception_info['value'] %(results)s #results\n""" %locals()
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 (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. maxgtol -- maximum allowable gradient magnitude for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: 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] gtol = maxgtol sk = [2*gtol] warnflag = 0 while (Num.maximum.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: #warnflag = 2 #break 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,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist
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 (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. maxgtol -- maximum allowable gradient magnitude for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: 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] gtol = maxgtol sk = [2*gtol] warnflag = 0 while (Num.maximum.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: #warnflag = 2 #break 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,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist
gtol = 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 (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. maxgtol -- maximum allowable gradient magnitude for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: 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] gtol = maxgtol sk = [2*gtol] warnflag = 0 while (Num.maximum.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: #warnflag = 2 #break 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,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist
while (Num.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 (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. maxgtol -- maximum allowable gradient magnitude for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: 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] gtol = maxgtol sk = [2*gtol] warnflag = 0 while (Num.maximum.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: #warnflag = 2 #break 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,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist
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 (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. maxgtol -- maximum allowable gradient magnitude for stopping epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag}, <allvecs>) xopt -- the minimizer of f. fopt -- the value of f(xopt). gopt -- the value of f'(xopt). (Should be near 0) Bopt -- the value of 1/f''(xopt). (inverse hessian matrix) func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- a list of all iterates (only returned if retall==1) Additional Inputs: 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] gtol = maxgtol sk = [2*gtol] warnflag = 0 while (Num.maximum.reduce(abs(gfk)) > gtol) and (k < maxiter): pk = -Num.dot(Hk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args) func_calls = func_calls + fc grad_calls = grad_calls + gc xkp1 = xk + alpha_k * pk if retall: allvecs.append(xkp1) sk = xkp1 - xk xk = xkp1 if gfkp1 is None: if app_fprime: gfkp1 = apply(approx_fprime,(xkp1,f,epsilon)+args) func_calls = func_calls + len(x0) + 1 else: gfkp1 = apply(fprime,(xkp1,)+args) grad_calls = grad_calls + 1 yk = gfkp1 - gfk k = k + 1 try: rhok = 1 / Num.dot(yk,sk) except ZeroDivisionError: #warnflag = 2 #break 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,:] gfk = gfkp1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls print " Gradient evaluations: %d" % grad_calls if full_output: retlist = xk, fval, gfk, Hk, func_calls, grad_calls, warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist
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 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 xk = x0 old_fval = f(xk,*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 if retall: allvecs = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 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 = 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
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 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 xk = x0 old_fval = f(xk,*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 if retall: allvecs = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 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 = 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
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 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 xk = x0 old_fval = f(xk,*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 if retall: allvecs = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 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 = 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
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 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 xk = x0 old_fval = f(xk,*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 if retall: allvecs = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 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 = 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
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 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 xk = x0 old_fval = f(xk,*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 if retall: allvecs = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk while (Num.add.reduce(abs(gfk)) > gtol) and (k < maxiter): deltak = Num.dot(gfk,gfk) alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk,old_fval,old_old_fval,args=args,c2=0.3) func_calls += fc grad_calls += gc xk = xk + alpha_k*pk if retall: allvecs.append(xk) 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 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 = 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
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, 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 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 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"
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: self.data = s.data self.colind = s.colind self.indptr = s.indptr elif isinstance(s, csc_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.colind, self.indptr = \ func(s.shape[1], s.data, s.rowind, s.indptr) else: try: temp = s.tocsr() except AttributeError: temp = csr_matrix(s.tocsc()) self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: 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(arg1, ArrayType) or type(arg1) == list: s = asarray(arg1) if (rank(s) == 2): # converting from a full array 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])
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(arg1, ArrayType) or type(arg1) == list: s = asarray(arg1) if (rank(s) == 2): 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 isinstance(arg2, ArrayType) and (rank(arg2) == 2) and (shape(arg2) == (len(s), 2)): ij = arg2 ijnew = ij.copy() ijnew[:, 0] = ij[:, 1] ijnew[:, 1] = ij[:, 0] temp = coo_matrix(s, ijnew, dims=(M, N), nzmax=nzmax, dtype=dtype) temp = temp.tocsr() self.shape = temp.shape self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr elif type(arg2) == tuple and len(arg2)==2: self.data = asarray(s) self.colind = arg2[0] self.indptr = arg2[1] if arg3 != None:
(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[:, 0] = ij[:, 1] ijnew[:, 1] = ij[:, 0] temp = coo_matrix(s, ijnew, dims=(M, N), nzmax=nzmax, dtype=dtype) temp = temp.tocsr() self.shape = temp.shape self.data = temp.data self.colind = temp.rowind self.indptr = temp.indptr except:
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: self.data = s.data self.colind = s.colind self.indptr = s.indptr elif isinstance(s, csc_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.colind, self.indptr = \ func(s.shape[1], s.data, s.rowind, s.indptr) else: try: temp = s.tocsr() except AttributeError: temp = csr_matrix(s.tocsc()) self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: 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(arg1, ArrayType) or type(arg1) == list: s = asarray(arg1) if (rank(s) == 2): # converting from a full array 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])
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_matrix constructor"
(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: self.data = s.data self.colind = s.colind self.indptr = s.indptr elif isinstance(s, csc_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.colind, self.indptr = \ func(s.shape[1], s.data, s.rowind, s.indptr) else: try: temp = s.tocsr() except AttributeError: temp = csr_matrix(s.tocsc()) self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: 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(arg1, ArrayType) or type(arg1) == list: s = asarray(arg1) if (rank(s) == 2): # converting from a full array 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])
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 != self.shape): raise ValueError, "inconsistent shapes"
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 isspmatrix(other): ocs = other.tocsr() if (ocs.shape != self.shape): raise ValueError, "inconsistent shapes" dtypechar = _coerce_rules[(self.dtypechar, ocs.dtypechar)] data1, data2 = _convert_data(self.data, ocs.data, dtypechar) func = getattr(sparsetools, _transtabl[dtypechar]+'cscmul') c, colc, ptrc, ierr = func(data1, self.colind, self.indptr, data2, ocs.colind, ocs.indptr) if ierr: raise ValueError, "ran out of space (but shouldn't have happened)" M, N = self.shape return csr_matrix(c, (colc, ptrc), (M, N)) else: raise TypeError, "unsupported type for sparse matrix power"
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 = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'csrmucsc') b = other.data colb = other.rowind ptrb = other.indptr out = 'csc' firstarg = () elif isinstance(other, csr_matrix): other._check() dtypechar = _coerce_rules[(self.dtypechar, other.dtypechar)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'cscmucsc') b, colb, ptrb = a, rowa, ptra a, rowa, ptra = other.data, other.colind, other.indptr out = 'csr' firstarg = (N,) else: other = other.tocsc() dtypechar = _coerce_rules[(self.dtypechar, other.dtypechar)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'csrmucsc') b = other.data colb = other.rowind ptrb = other.indptr out = 'csc' firstarg = () a, b = _convert_data(a, b, dtypechar) newshape = (M, N) if out == 'csr': ptrc = zeros((M+1,), 'i') else: ptrc = zeros((N+1,), 'i') nnzc = 2*max(ptra[-1], ptrb[-1]) c = zeros((nnzc,), dtypechar) rowc = zeros((nnzc,), 'i') ierr = irow = kcol = 0 while 1: args = firstarg+(a, rowa, ptra, b, colb, ptrb, c, rowc, ptrc, irow, kcol, ierr) c, rowc, ptrc, irow, kcol, ierr = func(*args) if (ierr==0): break # otherwise we were too small and must resize percent_to_go = 1- (1.0*kcol) / N newnnzc = int(ceil((1+percent_to_go)*nnzc)) c = resize1d(c, newnnzc) rowc = resize1d(rowc, newnnzc) nnzc = newnnzc
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]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix(data, (colind, row_ptr))
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 key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: N = ikey1-current_col col_ptr[current_col+1:ikey1+1] = [k]*N current_col = ikey1 data[k] = self[key] rowind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) rowind = array(rowind) col_ptr = array(col_ptr) return csc_matrix((data, rowind, col_ptr))
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('io') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('linsolve') config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config
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 = ikey0 row_ptr[ikey0] = k data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz+1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) ftype = data.typecode() if ftype not in ['d','D','f','F']: data = data*1.0 ftype = 'd' return ftype, nnz, data, colind, row_ptr
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: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] rowind[k] = ikey0 k += 1 col_ptr[-1] = nnz+1 data = array(data) rowind = array(rowind) col_ptr = array(col_ptr) ftype = data.typecode() if ftype not in ['d','D','f','F']: data = data*1.0 ftype = 'd' return ftype, nnz, data, rowind, col_ptr
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 hasattr(A, 'getCSC'): ftype, lastel, data, index0, index1 = A.getCSC() csc = 1 else: ftype, lastel, data, index0, index1 = A.getCSR() csc = 0 M,N = A.shape gssv = eval('_superlu.' + ftype + 'gssv') return gssv(M,N,lastel,data,index0,index1,b,csc)
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 hasattr(A, 'getCSC'): ftype, lastel, data, index0, index1 = A.getCSC() csc = 1 else: ftype, lastel, data, index0, index1 = A.getCSR() csc = 0 M,N = A.shape gssv = eval('_superlu.' + ftype + 'gssv') return gssv(M,N,lastel,data,index0,index1,b,csc)
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: thisval = str(val) elif cmplx: rval = real(val) ival = imag(val) thisval = eval('fmtstr % rval') istr = eval('fmtstr % ival') if (ival >= 0): thisval = '%s+j%s' % (thisval, istr) else: thisval = '%s-j%s' % (thisval, istr) else: thisval = eval('fmtstr % val') theline.append(thisval) strline = col_sep.join(theline) thestr.append(strline) return row_sep.join(thestr)
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: thisval = str(val) elif cmplx: rval = real(val) ival = imag(val) thisval = eval('fmtstr % rval') istr = eval('fmtstr % ival') if (ival >= 0): thisval = '%s+j%s' % (thisval, istr) else: thisval = '%s-j%s' % (thisval, istr) else: thisval = eval('fmtstr % val') theline.append(thisval) strline = col_sep.join(theline) thestr.append(strline) return row_sep.join(thestr)
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: thisval = str(val) elif cmplx: rval = real(val) ival = imag(val) thisval = eval('fmtstr % rval') istr = eval('fmtstr % ival') if (ival >= 0): thisval = '%s+j%s' % (thisval, istr) else: thisval = '%s-j%s' % (thisval, istr) else: thisval = eval('fmtstr % val') theline.append(thisval) strline = col_sep.join(theline) thestr.append(strline) return row_sep.join(thestr)
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 array. linesep -- separator to write between rows of array precision -- number of digits after the decimal place to write. keep_open = non-zero to return the open file, otherwise, the file is closed. Outputs: file -- The open file (if keep_open is non-zero) """ file = get_open_file(fileobject, mode='wa') rank = Numeric.rank(arr) if rank > 2: raise ValueError, "Can-only write up to 2-D arrays." if rank == 0: h = 1 arr = Numeric.reshape(arr, (1,1)) elif rank == 1: h = Numeric.shape(arr)[0] arr = Numeric.reshape(arr, (h,1)) else: h = Numeric.shape(arr)[0] arr = asarray(arr) for ch in separator: if ch in '0123456789-+FfeEgGjJIi.': raise ValueError, "Bad string for separator" astr = str_array(arr, precision=precision, col_sep=separator, row_sep=linesep) file.write(astr) if keep_open: return file else: file.close() return
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 array. linesep -- separator to write between rows of array precision -- number of digits after the decimal place to write. keep_open = non-zero to return the open file, otherwise, the file is closed. Outputs: file -- The open file (if keep_open is non-zero) """ file = get_open_file(fileobject, mode='wa') rank = Numeric.rank(arr) if rank > 2: raise ValueError, "Can-only write up to 2-D arrays." if rank == 0: h = 1 arr = Numeric.reshape(arr, (1,1)) elif rank == 1: h = Numeric.shape(arr)[0] arr = Numeric.reshape(arr, (h,1)) else: h = Numeric.shape(arr)[0] arr = asarray(arr) for ch in separator: if ch in '0123456789-+FfeEgGjJIi.': raise ValueError, "Bad string for separator" astr = str_array(arr, precision=precision, col_sep=separator, row_sep=linesep) file.write(astr) if keep_open: return file else: file.close() return
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): pass
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.failUnlessRaises(ArithmeticError, cumprod, a) else: assert_array_equal(cumprod(a), array([1, 2, 20, 220, 1320, 6600, 26400],ctype)) assert_array_equal(cumprod(a2), array([[ 1, 2, 3, 4], [ 5, 12, 21, 36], [50, 36, 84, 180]],ctype)) assert_array_equal(cumprod(a2,axis=1), array([[ 1, 2, 6, 24], [ 5, 30, 210, 1890], [10, 30, 120, 600]],ctype))
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']: mtype = 'i' elif mtype in ['i','uint','uint32','unsigned int']: mtype = 'I' elif mtype in ['l','long','int32','integer*4']: mtype = 'l' elif mtype in ['f','float','float32','real*4', 'real']: mtype = 'f' elif mtype in ['d','double','float64','real*8', 'double precision']: mtype = 'd' elif mtype in ['F','complex float','complex*8','complex64']: mtype = 'F' elif mtype in ['D','complex*16','complex128','complex','complex double']: mtype = 'D' else: mtype = obj2sctype(mtype) argout = (array(0,mtype).itemsize,mtype) return argout