rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return csc_matrix(data, (colind, col_ptr))
return csc_matrix(data, (rowind, col_ptr))
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [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] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
mask = (a < threshmin)
mask |= (a < threshmin)
def threshold(a, threshmin=None, threshmax=None, newval=0): """Clip array to a given value.
aux = numpy.take( ar, perm 0,axis=0)
aux = numpy.take( ar, perm, axis=0)
def unique1d( ar1, retIndx = False ): """Unique elements of 1D array. When retIndx is True, return also the indices indx such that ar1[indx] is the resulting array of unique elements.""" ar = numpy.array( ar1 ).ravel() if retIndx: perm = numpy.argsort( ar ) aux = numpy.take( ar, perm 0,axis=0) flag = ediff1d( aux, 1 ) != 0 return numpy.compress( flag, perm ,axis=-1), numpy.compress( flag, aux ,axis=-1) else: aux = numpy.sort( ar ) return numpy.compress( ediff1d( aux, 1 ) != 0, aux ,axis=-1)
def ppcc_max(x, dist='tukeylambda'):
def ppcc_max(x, brack=(0.0,1.0), dist='tukeylambda'):
def ppcc_max(x, dist='tukeylambda'): """Returns the shape parameter that maximizes the probability plot correlation coefficient for the given data to a one-parameter family of distributions. See also ppcc_plot """ try: ppf_func = eval('distributions.%sppf'%dist) except AttributError: raise dist, "is not a valid distribution with a ppf." res = inspect.getargspec(ppf_func) if not ('loc' == res[0][-2] and 'scale' == res[0][-1] and \ 0.0==res[-1][-2] and 1.0==res[-1][-1]): raise ValueError, "Function has does not have default location", \ "and scale parameters\n that are 0.0 and 1.0 respectively." if (1 < len(res[0])-len(res[-1])-1) or \ (1 > len(res[0])-3): raise ValueError, "Must be a one-parameter family." N = len(x) Ui = zeros(N)*1.0 Ui[-1] = 0.5**(1.0/N) Ui[0] = 1-Ui[-1] i = arange(2,N) Ui[1:-1] = (i-0.3175)/(N+0.365) osr = sort(x) def tempfunc(shape, mi, yvals, func): xvals = func(mi, shape) slope, intercept, r, prob, sterrest = stats.linregress(xvals, yvals) return 1-r return optimize.brent(tempfunc, args=(Ui, osr, ppf_func))
return optimize.brent(tempfunc, args=(Ui, osr, ppf_func))
return optimize.brent(tempfunc, brack=brack, args=(Ui, osr, ppf_func))
def tempfunc(shape, mi, yvals, func): xvals = func(mi, shape) slope, intercept, r, prob, sterrest = stats.linregress(xvals, yvals) return 1-r
""" Later have log(0) raise warning, not error
""" log(0) should print warning, but succeed.
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
assert(0)
except: assert(0) def check_log_neg(self): """ log(-1) should print warning, but still raises error. """ try: val = logn(3,-1)
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
pass def check_log_neg(self): """ Later have log(-1) raise warning, not error """ try: val = logn(3,-1) assert(0) except ValueError:
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
val = logn(3,0) assert(0) except OverflowError: pass
val = log2(0) except: assert(0)
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
val = logn(3,-1) assert(0) except ValueError:
val = log2(-1) assert(0) except OverflowError:
def check_log_neg(self): """ Later have log(-1) raise warning, not error """ try: val = logn(3,-1) assert(0) except ValueError: pass
ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr
if csc: index0 = mat.rowind else: index0 = mat.colind ftype, lastel, data, index1 = mat.ftype, mat.nnz, mat.data, mat.indptr
def spsolve(A, b, permc_spec=2): if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'): raise ValueError, "sparse matrix must be able to return CSC format--"\ "A.tocsc()--or CSR format--A.tocsr()" if not hasattr(A, 'shape'): raise ValueError, "sparse matrix must be able to return shape" \ " (rows, cols) = A.shape" M, N = A.shape if (M != N): raise ValueError, "matrix must be square" if isUmfpack and useUmfpack: mat = _toCS_umfpack( A ) if mat.dtype.char not in 'dD': raise ValueError, "convert matrix data to double, please, using"\ " .astype(), or set linsolve.useUmfpack = False" family = {'d' : 'di', 'D' : 'zi'} umf = umfpack.UmfpackContext( family[mat.dtype.char] ) return umf.linsolve( umfpack.UMFPACK_A, mat, b, autoTranspose = True ) else: mat, csc = _toCS_superLU( A ) ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr gssv = eval('_superlu.' + ftype + 'gssv') print "data-ftype: %s compared to data %s" % (ftype, data.dtype.char) print "Calling _superlu.%sgssv" % ftype return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0]
res = csc + other return res
return csc + other
def __add__(self, other): csc = self.tocsc() res = csc + other return res
res = csc - other return res
return csc - other
def __sub__(self, other): csc = self.tocsc() res = csc - other return res
res = csc.__rsub__(other) return res
return csc.__rsub__(other)
def __rsub__(self, other): # other - self csc = self.tocsc() res = csc.__rsub__(other) return res
res = csc * other return res
return csc * other
def __mul__(self, other): csc = self.tocsc() res = csc * other return res
res = csc.__rmul__(other) return res
return csc.__rmul__(other)
def __rmul__(self, other): csc = self.tocsc() res = csc.__rmul__(other) return res
res = -csc return res
return -csc
def __neg__(self): csc = self.tocsc() res = -csc return res
res = csc.transpose() return res
return csc.transpose()
def transpose(self): csc = self.tocsc() res = csc.transpose() return res
res = csc.matrixmultiply(other) return res
return csc.matrixmultiply(other)
def matrixmultiply(self, other): """ A generic interface for matrix-matrix or matrix-vector multiplication. """ csc = self.tocsc() res = csc.matrixmultiply(other) return res
res = csc.matmat(other) return res
return csc.matmat(other)
def matmat(self, other): csc = self.tocsc() res = csc.matmat(other) return res
res = csc.matvec(vec) return res
return csc.matvec(vec)
def matvec(self, vec): csc = self.tocsc() res = csc.matvec(vec) return res
res = csc.rmatvec(vec, conj=conj) return res
return csc.rmatvec(vec, conj=conj)
def rmatvec(self, vec, conj=1): csc = self.tocsc() res = csc.rmatvec(vec, conj=conj) return res
ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
if isscalar(other): raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') elif isspmatrix(other): ocs = other.tocsc() if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar, ocs._dtypechar)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
def __add__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
ocs = csc_matrix(other)
ocs = other.tocsc()
def __rmul__(self, other): # other * self if isspmatrix(other): ocs = csc_matrix(other) return ocs.matmat(self) elif isscalar(other): new = self.copy() new.data = other * new.data new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: return transpose(self.rmatvec(transpose(other),conj=0))
new.data = -new.data
new.data *= -1
def __neg__(self): new = self.copy() new.data = -new.data return new
ocs = csc_matrix(other) 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]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind,self.indptr,-data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
if isscalar(other): raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') elif isspmatrix(other): ocs = other.tocsc() 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]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind,self.indptr,-data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
def __sub__(self, other): ocs = csc_matrix(other) 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]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind,self.indptr,-data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
ocs = csc_matrix(other) 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]+'cscadd') c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
if isscalar(other): raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') elif isspmatrix(other): ocs = other.tocsc() 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]+'cscadd') c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
def __rsub__(self, other): # implement other - self ocs = csc_matrix(other) 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]+'cscadd') c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
ocs = csc_matrix(other)
ocs = other.tocsc()
def __pow__(self, other): """ Element-by-element power (unless other is a scalar, in which case return the matrix power.) """ if isscalar(other): new = self.copy() new.data = new.data ** other new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,ocs._dtypechar)] nnz1, nnz2 = self.nnz, ocs.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscmul') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
try: m,n = other.shape except AttributeError:
if isscalar(other):
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
other_csr = other.tocsr() if (other_csr.shape != self.shape):
ocs = other.tocsr() if (ocs.shape != self.shape):
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] data1, data2 = _convert_data(self.data, other.data, dtypechar)
dtypechar = _coerce_rules[(self._dtypechar, ocs._dtypechar)] data1, data2 = _convert_data(self.data, ocs.data, dtypechar)
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
ocs = csr_matrix(other)
ocs = other.tocsc()
def __rmul__(self, other): # other * self if isspmatrix(other): ocs = csr_matrix(other) return occ.matmat(self) elif isscalar(other): new = self.copy() new.data = other * new.data new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: return transpose(self.rmatvec(transpose(other),conj=0))
ocs = csr_matrix(other)
if isscalar(other): raise NotImplementedError('subtracting a scalar from a sparse matrix is not yet supported') 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]+'cscadd') c,colc,ptrc,ierr = func(data1,self.colind,self.indptr,-data2,other.colind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csr_matrix.Construct(c,(colc,ptrc),M=M,N=N) def __rsub__(self, other): ocs = other.tocsr()
def __sub__(self, other): ocs = csr_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] data1, data2 = _convert_data(self.data, other.data, dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,colc,ptrc,ierr = func(data1,self.colind,self.indptr,-data2,other.colind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csr_matrix.Construct(c,(colc,ptrc),M=M,N=N)
dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] data1, data2 = _convert_data(self.data, other.data, dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,colc,ptrc,ierr = func(data1,self.colind,self.indptr,-data2,other.colind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csr_matrix.Construct(c,(colc,ptrc),M=M,N=N) def __rsub__(self, other): ocs = csr_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] data1, data2 = _convert_data(self.data, other.data, dtypechar)
dtypechar = _coerce_rules[(self._dtypechar, ocs._dtypechar)] data1, data2 = _convert_data(self.data, ocs.data, dtypechar)
def __sub__(self, other): ocs = csr_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] data1, data2 = _convert_data(self.data, other.data, dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,colc,ptrc,ierr = func(data1,self.colind,self.indptr,-data2,other.colind,other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csr_matrix.Construct(c,(colc,ptrc),M=M,N=N)
ocs = csr_matrix(other)
ocs = other.tocsr()
def __pow__(self, other): """ Element-by-element power (unless other is a scalar, in which case return the matrix power.) """ if isscalar(other): new = self.copy() new.data = new.data ** other new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: ocs = csr_matrix(other) 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.Construct(c,(colc,ptrc),M=M,N=N)
if isinstance(other, dok_matrix):
if isscalar(other): raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') elif isinstance(other, dok_matrix):
def __add__(self, other): if isinstance(other, dok_matrix): res = dok_matrix() res.update(self) res.shape = self.shape res.nnz = self.nnz for key in other.keys(): res[key] += other[key] else: csc = self.tocsc() res = csc + other return res
if isinstance(other, dok_matrix):
if isscalar(other): raise NotImplementedError('subtracting a scalar from a sparse matrix is not yet supported') elif isinstance(other, dok_matrix):
def __sub__(self, other): if isinstance(other, dok_matrix): res = dok_matrix() res.update(self) res.shape = self.shape res.nnz = self.nnz for key in other.keys(): res[key] -= other[key] else: csc = self.tocsc() res = csc - other return res
if isinstance(other, spmatrix):
if isspmatrix(other):
def __mul__(self, other): if isinstance(other, spmatrix): return self.matmat(other) other = asarray(other) if rank(other) > 0: return self.matvec(other) res = dok_matrix() for key in self.keys(): res[key] = other * self[key] return res
def bayes_mvs(data,alpha=0.95): """Return bayesian confidence intervals for the mean, var, and std.
def bayes_mvs(data,alpha=0.90): """Return Bayesian confidence intervals for the mean, var, and std.
def bayes_mvs(data,alpha=0.95): """Return bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta # q1 = (1-alpha)/2.0 q2 = (1+alpha)/2.0 a = (n-1)/2.0 fac = n*C/2.0 va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) # return (ma,mb),(va,vb),(sqrt(va),sqrt(vb))
alpha gives the probability that the returned interval contains the true parameter.
alpha gives the probability that the returned interval contains the true parameter. Uses peak of conditional pdf as starting center.
def bayes_mvs(data,alpha=0.95): """Return bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta # q1 = (1-alpha)/2.0 q2 = (1+alpha)/2.0 a = (n-1)/2.0 fac = n*C/2.0 va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) # return (ma,mb),(va,vb),(sqrt(va),sqrt(vb))
q1 = (1-alpha)/2.0 q2 = (1+alpha)/2.0 a = (n-1)/2.0
def bayes_mvs(data,alpha=0.95): """Return bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta # q1 = (1-alpha)/2.0 q2 = (1+alpha)/2.0 a = (n-1)/2.0 fac = n*C/2.0 va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) # return (ma,mb),(va,vb),(sqrt(va),sqrt(vb))
va = fac*distributions.invgamma.ppf(q1,a)
peak = 2/(n+1.) a = (n-1)/2.0 F_peak = distributions.invgamma.cdf(peak,a) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): q2 = alpha va = 0.0 else: va = fac*distributions.invgamma.ppf(q1,a)
def bayes_mvs(data,alpha=0.95): """Return bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta # q1 = (1-alpha)/2.0 q2 = (1+alpha)/2.0 a = (n-1)/2.0 fac = n*C/2.0 va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) # return (ma,mb),(va,vb),(sqrt(va),sqrt(vb))
return (ma,mb),(va,vb),(sqrt(va),sqrt(vb))
fac = sqrt(fac) peak = sqrt(2./n) F_peak = distributions.gengamma.cdf(peak,a,-2) q1 = F_peak - alpha/2.0 q2 = F_peak + alpha/2.0 if (q1 < 0): q2 = alpha sta = 0.0 else: sta = fac*distributions.gengamma.ppf(q1,a,-2) stb = fac*distributions.gengamma.ppf(q2,a,-2) return (ma,mb),(va,vb),(sta,stb)
def bayes_mvs(data,alpha=0.95): """Return bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. """ x = ravel(data) n = len(x) assert(n > 1) n = float(n) xbar = sb.add.reduce(x)/n C = sb.add.reduce(x*x)/n - xbar*xbar # fac = sqrt(C/(n-1)) tval = distributions.t.ppf((1+alpha)/2.0,n-1) delta = fac*tval ma = xbar - delta mb = xbar + delta # q1 = (1-alpha)/2.0 q2 = (1+alpha)/2.0 a = (n-1)/2.0 fac = n*C/2.0 va = fac*distributions.invgamma.ppf(q1,a) vb = fac*distributions.invgamma.ppf(q2,a) # return (ma,mb),(va,vb),(sqrt(va),sqrt(vb))
return special.bdtr(k,n,pr)
sv = errp(0) vals = special.bdtr(k,n,pr) sv = errp(sv) return where(k>=0,vals,0.0)
def binomcdf(k, n, pr=0.5): return special.bdtr(k,n,pr)
return special.bdtrc(k,n,pr)
sv = errp(0) vals = special.bdtrc(k,n,pr) sv = errp(sv) return where(k>=0,vals,1.0)
def binomsf(k, n, pr=0.5): return special.bdtrc(k,n,pr)
cond2 = (pr >= 1) || (pr <=0)
cond2 = (pr >= 1) | (pr <=0)
def nbinompdf(k, n, pr=0.5): k = arr(k) cond2 = (pr >= 1) || (pr <=0) cond1 = arr((k > n) & (k == floor(k))) sv =errp(0) temp = special.nbdtr(k,n,pr) temp2 = special.nbdtr(k-1,n,pr) sv = errp(sv) return select([cond2,cond1,k==n], [scipy.nan,temp-temp2,temp],0.0)
k, K = 0, len(stream._buffer)
k, K = stream.linelist[0], len(stream._buffer)
def getcolumns(stream, columns, separator): comment = stream.comment lenc = stream.lencomment k, K = 0, len(stream._buffer) while k < K: firstline = stream._buffer[k] if firstline != '' and firstline[:lenc] != comment: break k = k + 1 if k == K: raise ValueError, "No data found in file." firstline = stream._buffer[k] N = len(columns) collist = [None]*N colsize = [None]*N for k in range(N): collist[k] = build_numberlist(columns[k]) val = process_line(firstline, separator, collist, [Numeric.Float]*N, 0) for k in range(N): colsize[k] = len(val[k]) return colsize, collist
raise ValueError, "No data found in file."
raise ValueError, "First line to read not within %d lines of top." % K
def getcolumns(stream, columns, separator): comment = stream.comment lenc = stream.lencomment k, K = 0, len(stream._buffer) while k < K: firstline = stream._buffer[k] if firstline != '' and firstline[:lenc] != comment: break k = k + 1 if k == K: raise ValueError, "No data found in file." firstline = stream._buffer[k] N = len(columns) collist = [None]*N colsize = [None]*N for k in range(N): collist[k] = build_numberlist(columns[k]) val = process_line(firstline, separator, collist, [Numeric.Float]*N, 0) for k in range(N): colsize[k] = len(val[k]) return colsize, collist
assert_array_almost_equal(row*M, row*M.todense())
def check_rmatvec(self): M = self.spmatrix(matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]])) assert_array_almost_equal([1,2,3,4]*M, dot([1,2,3,4], M.toarray())) row = matrix([[1,2,3,4]]) # This doesn't work since row*M computes incorrectly when row is 2d. # NumPy needs special hooks for this. # assert_array_almost_equal(row*M, row*M.todense())
assert_array_almost_equal((a*bsp).todense(), a*b)
def check_matmat(self): a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) b = matrix([[0,1],[1,0],[0,2]],'d') asp = self.spmatrix(a) bsp = self.spmatrix(b) assert_array_almost_equal((asp*bsp).todense(), a*b) assert_array_almost_equal((asp*b).todense(), a*b) # The following test fails, since the dense matrix a takes control # of the multiplication, calling numpy.dot(), which fouls up # our sparse matrix. NumPy needs special hooks for this. # assert_array_almost_equal((a*bsp).todense(), a*b)
assert_array_almost_equal((a*csp).todense(), a*c)
def check_matmat(self): a = matrix([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) a2 = array([[3,0,0],[0,1,0],[2,0,3.0],[2,3,0]]) b = matrix([[0,1],[1,0],[0,2]],'d') asp = self.spmatrix(a) bsp = self.spmatrix(b) assert_array_almost_equal((asp*bsp).todense(), a*b) assert_array_almost_equal((asp*b).todense(), a*b) # The following test fails, since the dense matrix a takes control # of the multiplication, calling numpy.dot(), which fouls up # our sparse matrix. NumPy needs special hooks for this. # assert_array_almost_equal((a*bsp).todense(), a*b)
z = self.dot(x) + self.dot(y) - 2*self.dot(x, y)
z = self.dot(x, x) + self.dot(y, y) - 2*self.dot(x, y)
def __call__(self, x, y): z = self.dot(x) + self.dot(y) - 2*self.dot(x, y) return N.exp(-self.gamma*z)
def blackman(M):
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = grid[1:(M+1)/2+1] if M % 2 == 0: w = (2*n-1.0)/M w = r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w def blackman(M,sym=1):
def blackman(M): """The M-point Blackman window. """ n = arange(0,M) return 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1))
return 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) def bartlett(M):
w = 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w def bartlett(M,sym=1):
def blackman(M): """The M-point Blackman window. """ n = arange(0,M) return 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1))
return where(less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) def hanning(M):
w = where(less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) if not sym and not odd: w = w[:-1] return w def hanning(M,sym=1):
def bartlett(M): """The M-point Bartlett window. """ n = arange(0,M) return where(less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1))
return 0.5-0.5*cos(2.0*pi*n/(M-1)) def hamming(M):
w = 0.5-0.5*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w def hamming(M,sym=1):
def hanning(M): """The M-point Hanning window. """ n = arange(0,M) return 0.5-0.5*cos(2.0*pi*n/(M-1))
n = arange(0,M) return 0.54-0.46*cos(2.0*pi*n/(M-1)) def kaiser(M,beta):
if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.54-0.46*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w def kaiser(M,beta,sym=1):
def hamming(M): """The M-point Hamming window. """ n = arange(0,M) return 0.54-0.46*cos(2.0*pi*n/(M-1))
return special.i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/special.i0(beta) def gaussian(M,std):
w = special.i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/special.i0(beta) if not sym and not odd: w = w[:-1] return w def gaussian(M,std,sym=1):
def kaiser(M,beta): """Returns a Kaiser window of length M with shape parameter beta. """ n = arange(0,M) alpha = (M-1)/2.0 return special.i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/special.i0(beta)
return exp(-n**2 / sig2) def general_gaussian(M,p,sig):
w = exp(-n**2 / sig2) if not sym and not odd: w = w[:-1] return w def general_gaussian(M,p,sig,sym=1):
def gaussian(M,std): """Returns a Gaussian window of length M with standard-deviation std. """ n = arange(0,M)-(M-1.0)/2.0 sig2 = 2*std*std return exp(-n**2 / sig2)
return exp(-0.5*(n/sig)**(2*p))
w = exp(-0.5*(n/sig)**(2*p)) if not sym and not odd: w = w[:-1] return w
def general_gaussian(M,p,sig): """Returns a window with a generalized Gaussian shape. exp(-0.5*(x/sig)**(2*p)) half power point is at (2*log(2)))**(1/(2*p))*sig """ n = arange(0,M)-(M-1.0)/2.0 return exp(-0.5*(n/sig)**(2*p))
a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1]
a(s) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1]
def invres(r,p,k,tol=1e-3,rtype='avg'): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval, unique_roots """ extra = k p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = r1array(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while Numeric.allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a
b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1]
b(s) b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1]
def residue(b,a,tol=1e-3,rtype='avg'): """Compute partial-fraction expansion of b(s) / a(s). If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: invres, poly, polyval, unique_roots """ b,a = map(asarray,(b,a)) k,b = polydiv(b,a) p = roots(a) r = p*0.0 pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]]*mult[n]) p = asarray(p) # Compute the residue from the general formula indx = 0 for n in range(len(pout)): bn = b.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]]*mult[l]) an = r1array(poly(pn)) # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is # multiplicity of pole at po[n] sig = mult[n] for m in range(sig,0,-1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn,1),an) term2 = polymul(bn,polyder(an,1)) bn = polysub(term1,term2) an = polymul(an,an) r[indx+m-1] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += sig return r, p, k
a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1]
a(s) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1]
def residue(b,a,tol=1e-3,rtype='avg'): """Compute partial-fraction expansion of b(s) / a(s). If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: invres, poly, polyval, unique_roots """ b,a = map(asarray,(b,a)) k,b = polydiv(b,a) p = roots(a) r = p*0.0 pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]]*mult[n]) p = asarray(p) # Compute the residue from the general formula indx = 0 for n in range(len(pout)): bn = b.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]]*mult[l]) an = r1array(poly(pn)) # bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is # multiplicity of pole at po[n] sig = mult[n] for m in range(sig,0,-1): if sig > m: # compute next derivative of bn(s) / an(s) term1 = polymul(polyder(bn,1),an) term2 = polymul(bn,polyder(an,1)) bn = polysub(term1,term2) an = polymul(an,an) r[indx+m-1] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += sig return r, p, k
def residuez(b,a,tol=1e-3): pass def _get_window(window,Nx):
def residuez(b,a,tol=1e-3,rtype='avg'): """Compute partial-fraction expansion of b(z) / a(z). If M = len(b) and N = len(a) b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See also: invresz, poly, polyval, unique_roots """ b,a = map(asarray,(b,a)) gain = a[0] brev, arev = b[::-1],a[::-1] krev,brev = polydiv(brev,arev) k,b = krev[::-1],brev[::-1] p = roots(a) r = p*0.0 pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for n in range(len(pout)): p.extend([pout[n]]*mult[n]) p = asarray(p) indx = 0 for n in range(len(pout)): bn = brev.copy() pn = [] for l in range(len(pout)): if l != n: pn.extend([pout[l]]*mult[l]) an = r1array(poly(pn))[::-1] sig = mult[n] for m in range(sig,0,-1): if sig > m: term1 = polymul(polyder(bn,1),an) term2 = polymul(bn,polyder(an,1)) bn = polysub(term1,term2) an = polymul(an,an) r[indx+m-1] = polyval(bn,1.0/pout[n]) / polyval(an,1.0/pout[n]) \ / factorial(sig-m) / (-pout[n])**(sig-m) indx += sig return r/gain, p, k def invresz(r,p,k,tol=1e-3,rtype='avg'): """Compute b(z) and a(z) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See also: residuez, poly, polyval, unique_roots """ extra = Numeric.asarray(k) p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = r1array(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 brev = asarray(b)[::-1] for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) brev = polyadd(brev,(r[indx]*poly(t2))[::-1]) indx += 1 b = real_if_close(brev[::-1]) return b, a def get_window(window,Nx,fftbins=1): """Return a window of length Nx and type window. If fftbins is 1, create a "periodic" window ready to use with ifftshift and be multiplied by the result of an fft (SEE ALSO fftfreq). Window types: boxcar, triang, blackman, hamming, hanning, bartlett, kaiser (needs beta), gaussian (needs std), general_gaussian (needs power, width). If the window requires no parameters, then it can be a string. If the window requires parameters, the window argument should be a tuple with the first argument the string name of the window, and the next arguments the needed parameters. If window is a floating point number, it is interpreted as the beta parameter of the kaiser window. """ sym = not fftbins
def residuez(b,a,tol=1e-3): pass
params = (Nx,)+args
params = (Nx,)+args + (sym,)
def _get_window(window,Nx): try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian else: raise ValueError, "Unknown window type." params = (Nx,)+args else: winfunc = kaiser params = (Nx,beta) return winfunc(*params)
params = (Nx,beta)
params = (Nx,beta,sym)
def _get_window(window,Nx): try: beta = float(window) except (TypeError, ValueError): args = () if isinstance(window, types.TupleType): winstr = window[0] if len(window) > 1: args = window[1:] elif isinstance(window, types.StringType): if window in ['kaiser', 'ksr', 'gaussian', 'gauss', 'gss', 'general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: raise ValueError, "That window needs a parameter -- pass a tuple" else: winstr = window if winstr in ['blackman', 'black', 'blk']: winfunc = blackman elif winstr in ['hamming', 'hamm', 'ham']: winfunc = hamming elif winstr in ['bartlett', 'bart', 'brt']: winfunc = bartlett elif winstr in ['hanning', 'hann', 'han']: winfunc = hanning elif winstr in ['kaiser', 'ksr']: winfunc = kaiser elif winstr in ['gaussian', 'gauss', 'gss']: winfunc = gaussian elif winstr in ['general gaussian', 'general_gaussian', 'general gauss', 'general_gauss', 'ggs']: winfunc = general_gaussian else: raise ValueError, "Unknown window type." params = (Nx,)+args else: winfunc = kaiser params = (Nx,beta) return winfunc(*params)
def resample(x,num,axis=0,window=None):
def resample(x,num,t=None,axis=0,window=None):
def resample(x,num,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for non, band-limited signals. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) """ x = asarray(x) from scipy import fft,ifft X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = _get_window(window,Nx) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.typecode() not in ['F','D']: return y.real else: return y
non, band-limited signals.
sampled signals you didn't intend to be interpreted as band-limited.
def resample(x,num,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for non, band-limited signals. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) """ x = asarray(x) from scipy import fft,ifft X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = _get_window(window,Nx) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.typecode() not in ['F','D']: return y.real else: return y
from scipy import fft,ifft
def resample(x,num,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for non, band-limited signals. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) """ x = asarray(x) from scipy import fft,ifft X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = _get_window(window,Nx) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.typecode() not in ['F','D']: return y.real else: return y
W = _get_window(window,Nx)
W = ifftshift(get_window(window,Nx)) newshape = ones(len(x.shape)) newshape[axis] = len(W) W.shape = newshape
def resample(x,num,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for non, band-limited signals. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) """ x = asarray(x) from scipy import fft,ifft X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = _get_window(window,Nx) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.typecode() not in ['F','D']: return y.real else: return y
return y.real
y = y.real if t is None: return y
def resample(x,num,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for non, band-limited signals. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) """ x = asarray(x) from scipy import fft,ifft X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = _get_window(window,Nx) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.typecode() not in ['F','D']: return y.real else: return y
return y
new_t = arange(0,num)*(t[1]-t[0])* Nx / float(num) + t[0] return y, new_t
def resample(x,num,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for non, band-limited signals. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) """ x = asarray(x) from scipy import fft,ifft X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = _get_window(window,Nx) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.typecode() not in ['F','D']: return y.real else: return y
class truncnorm_gen(norm_gen):
class truncnorm_gen(rv_continuous):
def _entropy(self, b): eB = exp(b) return log(eB-1)+(1+eB*(b-1.0))/(1.0-eB)
self.nb = norm_gen._cdf(self,b) self.na = norm_gen._cdf(self,a)
self.nb = norm._cdf(b) self.na = norm._cdf(a)
def _argcheck(self, a, b): self.a = a self.b = b self.nb = norm_gen._cdf(self,b) self.na = norm_gen._cdf(self,a) return (a != b)
return norm_gen._pdf(self, x) / (self.nb - self.na)
return norm._pdf(x) / (self.nb - self.na)
def _pdf(self, x, a, b): return norm_gen._pdf(self, x) / (self.nb - self.na)
return (norm_gen._cdf(self, x) - self.na) / (self.nb - self.na)
return (norm._cdf(x) - self.na) / (self.nb - self.na)
def _cdf(self, x, a, b): return (norm_gen._cdf(self, x) - self.na) / (self.nb - self.na)
return norm_gen._ppf(self, q*self.nb + self.na*(1.0-q))
return norm._ppf(q*self.nb + self.na*(1.0-q))
def _ppf(self, q, a, b): return norm_gen._ppf(self, q*self.nb + self.na*(1.0-q))
pA, pB = norm_gen._pdf(self, a), norm_gen._pdf(self, b)
pA, pB = norm._pdf(a), norm._pdf(b)
def _stats(self, a, b): nA, nB = self.na, self.nb d = nB - nA pA, pB = norm_gen._pdf(self, a), norm_gen._pdf(self, b) mu = (pB - pA) / d mu2 = 1 + (a*pA - b*pB) / d - mu*mu return mu, mu2, None, None
Truncated Normal distribution
Truncated Normal distribution. The standard form of this distribution is a standard normal truncated to the range [a,b] --- notice that a and b are defined over the domain of the standard normal.
def _stats(self, a, b): nA, nB = self.na, self.nb d = nB - nA pA, pB = norm_gen._pdf(self, a), norm_gen._pdf(self, b) mu = (pB - pA) / d mu2 = 1 + (a*pA - b*pB) / d - mu*mu return mu, mu2, None, None
nbd = NA.zeros((n,), NA.Int)
nbd = NA.zeros((n,), NA.Int32)
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
iwa = NA.zeros((3*n,), NA.Int)
iwa = NA.zeros((3*n,), NA.Int32)
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
lsave = NA.zeros((4,), NA.Int) isave = NA.zeros((44,), NA.Int)
lsave = NA.zeros((4,), NA.Int32) isave = NA.zeros((44,), NA.Int32)
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
v v v v v v v ^ ^ ^ ^ ^ ^ ^
def complex(a, b): c = zeros(a.shape, dtype=complex_) c.real = a c.imag = b return c
idx = numpy.where(m.mask == False) if len(idx) != 0 and len(idx[0]) != 0: idx = idx[0][relpos]
if m.mask is ma.nomask: return 0
def __unmasked(m, get_val, relpos): idx = numpy.where(m.mask == False) if len(idx) != 0 and len(idx[0]) != 0: idx = idx[0][relpos] else: idx = None if get_val: if idx is None: return ma.masked else: return m[idx] else: return idx
idx = None if get_val: if idx is None: return ma.masked else: return m[idx] else: return idx
idx = numpy.where(m.mask == False) if len(idx) != 0 and len(idx[0]) != 0: idx = idx[0][relpos] else: idx = None if get_val: if idx is None: return ma.masked else: return m[idx] else: return idx
def __unmasked(m, get_val, relpos): idx = numpy.where(m.mask == False) if len(idx) != 0 and len(idx[0]) != 0: idx = idx[0][relpos] else: idx = None if get_val: if idx is None: return ma.masked else: return m[idx] else: return idx
return 0.0
shape = list(a.shape) del shape[axis] if shape: return np.zeros(shape, dtype=float) else: return np.float64(0.0)
def moment(a, moment=1, axis=0): """Calculates the nth moment about the mean for a sample. Generally used to calculate coefficients of skewness and kurtosis. Parameters ---------- a : array moment : int axis : int or None Returns ------- The appropriate moment along the given axis or over all values if axis is None. """ a, axis = _chk_asarray(a, axis) if moment == 1: # By definition the first moment about the mean is 0. return 0.0 else: mn = np.expand_dims(np.mean(a,axis),axis) s = np.power((a-mn), moment) return np.mean(s,axis)
wxPython_thread = ppimport_attr(ppimport('gui_thread'),wxPython_thread)
wxPython_thread = ppimport_attr(ppimport('gui_thread'),'wxPython_thread')
def _import_packages(): """ Import packages in scipy directory that implement info_<packagename>.py. See DEVELOPERS.txt for more info. """ from glob import glob import os frame = sys._getframe(1) for info_file in glob(os.path.join(__path__[0],'*','info_*.py')): package_name = os.path.basename(os.path.dirname(info_file)) if package_name != os.path.splitext(os.path.basename(info_file))[0][5:]: print ' !! Mismatch of package name %r and %s' \ % (package_name, info_file) continue sys.path.insert(0,os.path.dirname(info_file)) # TODO: catch exceptions here: exec 'import info_%s as info_module' % (package_name) del sys.path[0] if getattr(info_module,'ignore',0): continue global_symbols = getattr(info_module,'global_symbols',[]) if getattr(info_module,'postpone_import',1): code = '%s = ppimport(%r)' % (package_name,package_name) for name in global_symbols: code += '\n%s = ppimport_attr(%s,%r)' % (name,package_name,name) else: code = 'import %s' % (package_name) # XXX: Should we check the existence of package.test? Warn? code += '\n%s.test = ScipyTest(%s).test' % (package_name,package_name) if global_symbols: code += '\nfrom '+package_name+' import '+','.join(global_symbols) # XXX: Should we catch exceptions here?? exec (code, frame.f_globals,frame.f_locals) _level_docs(info_module) # XXX: Ugly hack to fix package name: code = '_level_docs()[-1] = (%s.__name__,_level_docs()[-1][1])' \ % (package_name) exec (code, frame.f_globals,frame.f_locals)
if self.iter >= GeneralizedLinearModel.niter:
if self.iter >= Model.niter:
def cont(self, results, tol=1.0e-05): """ Continue iterating, or has convergence been obtained? """ if self.iter >= GeneralizedLinearModel.niter: return False
self.mu = lband self.ml = uband
self.mu = uband self.ml = lband
def __init__(self, method = 'adams', with_jacobian = 0, rtol=1e-6,atol=1e-12, lband=None,uband=None, order = 12, nsteps = 500, max_step = 0.0, # corresponds to infinite min_step = 0.0, first_step = 0.0, # determined by solver ):
print "x = ", x print "f = ", f
def calcfc(x, con): f = func(x, *args) k = 0 print "x = ", x print "f = ", f for constraints in cons: con[k] = constraints(x, *consargs) k += 1 print "con = ", con return f
print "con = ", con
def calcfc(x, con): f = func(x, *args) k = 0 print "x = ", x print "f = ", f for constraints in cons: con[k] = constraints(x, *consargs) k += 1 print "con = ", con return f
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None)
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None):
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None) if badvalue is None: badvalue = nan self.badvalue = badvalue self.name = name self.a = a self.b = b if a is None: self.a = -scipy.inf if b is None: self.b = scipy.inf self.xa = xa self.xb = xb self.xtol = xtol self._size = 1 self.m = 0.0 self.moment_type = momtype self.vecfunc = new.instancemethod(sgf(self._ppf_single_call), self, rv_continuous) self.expandarr = 1 if momtype == 0: self.generic_moment = new.instancemethod(sgf(self._mom0_sc), self, rv_continuous) else: self.generic_moment = new.instancemethod(sgf(self._mom1_sc), self, rv_continuous) cdf_signature = inspect.getargspec(self._cdf.im_func) numargs1 = len(cdf_signature[0]) - 2 pdf_signature = inspect.getargspec(self._pdf.im_func) numargs2 = len(pdf_signature[0]) - 2 self.numargs = max(numargs1, numargs2)
alpha = alpha_gen(a=0.0,name='alpha',d1='this',d2='is',d3='a test')
alpha = alpha_gen(a=0.0,name='alpha')
def _stats(self): return [scipy.inf]*2 + [scipy.nan]*2
result = result + cast[imag.typecode()](1j) * imag
try: result = result + _unit_imag[imag.typecode()] * imag except KeyError: result = result + 1j*imag
def _parse_mimatrix(fid,bytes): dclass, cmplx, nzmax =_parse_array_flags(fid) dims = _get_element(fid)[0] name = ''.join(asarray(_get_element(fid)[0]).astype('c')) tupdims = tuple(dims[::-1]) if dclass in mxArrays: result, unused =_get_element(fid) if type == mxCHAR_CLASS: result = ''.join(asarray(result).astype('c')) else: if cmplx: imag, unused =_get_element(fid) result = result + cast[imag.typecode()](1j) * imag result = squeeze(transpose(reshape(result,tupdims))) elif dclass == mxCELL_CLASS: length = product(dims) result = zeros(length, PyObject) for i in range(length): sa, unused = _get_element(fid) result[i]= sa result = squeeze(transpose(reshape(result,tupdims))) if rank(result)==0: result = result.toscalar() elif dclass == mxSTRUCT_CLASS: length = product(dims) result = zeros(length, PyObject) namelength = _get_element(fid)[0] # get field names names = _get_element(fid)[0] splitnames = [names[i:i+namelength] for i in \ xrange(0,len(names),namelength)] fieldnames = [''.join(asarray(x).astype('c')).strip('\x00') for x in splitnames] for i in range(length): result[i] = mat_struct() for element in fieldnames: val,unused = _get_element(fid) result[i].__dict__[element] = val result = squeeze(transpose(reshape(result,tupdims))) if rank(result)==0: result = result.toscalar() # object is like a structure with but with a class name elif dclass == mxOBJECT_CLASS: class_name = ''.join(asarray(_get_element(fid)[0]).astype('c')) length = product(dims) result = zeros(length, PyObject) namelength = _get_element(fid)[0] # get field names names = _get_element(fid)[0] splitnames = [names[i:i+namelength] for i in \ xrange(0,len(names),namelength)] fieldnames = [''.join(asarray(x).astype('c')).strip('\x00') for x in splitnames] for i in range(length): result[i] = mat_obj() result[i]._classname = class_name for element in fieldnames: val,unused = _get_element(fid) result[i].__dict__[element] = val result = squeeze(transpose(reshape(result,tupdims))) if rank(result)==0: result = result.toscalar() elif dclass == mxSPARSE_CLASS: rowind, unused = _get_element(fid) colind, unused = _get_element(fid) res, unused = _get_element(fid) if cmplx: imag, unused = _get_element(fid) res = res + cast[imag.typecode()](1j)*imag if have_sparse: spmat = scipy.sparse.csc_matrix(res, (rowind[:len(res)], colind), M=dims[0],N=dims[1]) result = spmat else: result = (dims, rowind, colind, res) return result, name
res = res + cast[imag.typecode()](1j)*imag
try: res = res + _unit_imag[imag.typecode()] * imag except KeyError: res = res + 1j*imag
def _parse_mimatrix(fid,bytes): dclass, cmplx, nzmax =_parse_array_flags(fid) dims = _get_element(fid)[0] name = ''.join(asarray(_get_element(fid)[0]).astype('c')) tupdims = tuple(dims[::-1]) if dclass in mxArrays: result, unused =_get_element(fid) if type == mxCHAR_CLASS: result = ''.join(asarray(result).astype('c')) else: if cmplx: imag, unused =_get_element(fid) result = result + cast[imag.typecode()](1j) * imag result = squeeze(transpose(reshape(result,tupdims))) elif dclass == mxCELL_CLASS: length = product(dims) result = zeros(length, PyObject) for i in range(length): sa, unused = _get_element(fid) result[i]= sa result = squeeze(transpose(reshape(result,tupdims))) if rank(result)==0: result = result.toscalar() elif dclass == mxSTRUCT_CLASS: length = product(dims) result = zeros(length, PyObject) namelength = _get_element(fid)[0] # get field names names = _get_element(fid)[0] splitnames = [names[i:i+namelength] for i in \ xrange(0,len(names),namelength)] fieldnames = [''.join(asarray(x).astype('c')).strip('\x00') for x in splitnames] for i in range(length): result[i] = mat_struct() for element in fieldnames: val,unused = _get_element(fid) result[i].__dict__[element] = val result = squeeze(transpose(reshape(result,tupdims))) if rank(result)==0: result = result.toscalar() # object is like a structure with but with a class name elif dclass == mxOBJECT_CLASS: class_name = ''.join(asarray(_get_element(fid)[0]).astype('c')) length = product(dims) result = zeros(length, PyObject) namelength = _get_element(fid)[0] # get field names names = _get_element(fid)[0] splitnames = [names[i:i+namelength] for i in \ xrange(0,len(names),namelength)] fieldnames = [''.join(asarray(x).astype('c')).strip('\x00') for x in splitnames] for i in range(length): result[i] = mat_obj() result[i]._classname = class_name for element in fieldnames: val,unused = _get_element(fid) result[i].__dict__[element] = val result = squeeze(transpose(reshape(result,tupdims))) if rank(result)==0: result = result.toscalar() elif dclass == mxSPARSE_CLASS: rowind, unused = _get_element(fid) colind, unused = _get_element(fid) res, unused = _get_element(fid) if cmplx: imag, unused = _get_element(fid) res = res + cast[imag.typecode()](1j)*imag if have_sparse: spmat = scipy.sparse.csc_matrix(res, (rowind[:len(res)], colind), M=dims[0],N=dims[1]) result = spmat else: result = (dims, rowind, colind, res) return result, name
xplt_path = os.path.join(local_path,'xplt')
xplt_path = os.path.join(dot_join(parent_package,'xplt'))
def configuration(parent_package=''): """ gist only works with an X-windows server This will install *.gs and *.gp files to '%spython%s/site-packages/scipy/xplt' % (sys.prefix,sys.version[:3]) """ x11 = x11_info().get_info() if not x11: return config = default_config_dict('xplt',parent_package) local_path = get_path(__name__) sources = ['gistCmodule.c'] sources = [os.path.join(local_path,x) for x in sources] ext_arg = {'name':dot_join(parent_package,'xplt.gistC'), 'sources':sources} dict_append(ext_arg,**x11) dict_append(ext_arg,libraries=['m']) ext = Extension (**ext_arg) config['ext_modules'].append(ext) from glob import glob gist = glob(os.path.join(local_path,'gist','*.c')) # libraries are C static libraries config['libraries'].append(('gist',{'sources':gist, 'macros':[('STDC_HEADERS',1)]})) file_ext = ['*.gs','*.gp', '*.ps', '*.help'] xplt_files = [glob(os.path.join(local_path,x)) for x in file_ext] xplt_files = reduce(lambda x,y:x+y,xplt_files,[]) xplt_path = os.path.join(local_path,'xplt') config['data_files'].extend( [(xplt_path,xplt_files)]) return config
from scipy import real_if_close def invres(r,p,k,tol=1e-3):
from scipy import real_if_close, r1array def invres(r,p,k,tol=1e-3,rtype='avg'):
def unique_roots(p,tol=1e-3,rtype='min'): """Determine the unique roots and their multiplicities in two lists Inputs: p -- The list of roots tol --- The tolerance for two roots to be considered equal. rtype --- How to determine the returned root from the close ones: 'max': pick the maximum 'min': pick the minimum 'avg': average roots Outputs: (pout, mult) pout -- The list of sorted roots mult -- The multiplicity of each root """ if rtype in ['max','maximum']: comproot = scipy.max elif rtype in ['min','minimum']: comproot = scipy.min elif rtype in ['avg','mean']: comproot = scipy.mean p = asarray(p)*1.0 tol = abs(tol) p, indx = cmplx_sort(p) pout = [] mult = [] indx = -1 curp = p[0] + 5*tol sameroots = [] for k in range(len(p)): tr = p[k] if abs(tr-curp) < tol: sameroots.append(tr) curp = comproot(sameroots) pout[indx] = curp mult[indx] += 1 else: pout.append(tr) curp = tr sameroots = [tr] indx += 1 mult.append(1) return array(pout), array(mult)
See also: residue, poly, polyval
See also: residue, poly, polyval, unique_roots
def invres(r,p,k,tol=1e-3): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval """ extra = k p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype='avg') p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = poly(p) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while Numeric.allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a
pout, mult = unique_roots(p,tol=tol,rtype='avg')
pout, mult = unique_roots(p,tol=tol,rtype=rtype)
def invres(r,p,k,tol=1e-3): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval """ extra = k p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype='avg') p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = poly(p) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while Numeric.allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a
a = poly(p)
a = r1array(poly(p))
def invres(r,p,k,tol=1e-3): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval """ extra = k p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype='avg') p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = poly(p) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while Numeric.allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a