bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
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))
def __rmul__(self, other): # other * self if isspmatrix(other): ocs = other.tocsc() 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))
1,300
def __neg__(self): new = self.copy() new.data = -new.data return new
def __neg__(self): new = self.copy() new.data *= -1 return new
1,301
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)
def __sub__(self, 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() 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)
1,302
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)
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)
1,303
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)
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 = 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.Construct(c,(colc,ptrc),M=M,N=N)
1,304
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)
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)
1,305
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)
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)
1,306
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
def __add__(self, other): if isscalar(other): raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') elif 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
1,307
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
def __sub__(self, other): if isscalar(other): raise NotImplementedError('subtracting a scalar from a sparse matrix is not yet supported') elif 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
1,308
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 __mul__(self, other): if isspmatrix(other): 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
1,309
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))
def bayes_mvs(data,alpha=0.90): """Return Bayesian confidence intervals for the mean, var, and std. Assumes 1-d data all has same mean and variance and uses Jeffrey's prior for variance and std. alpha gives the probability that the returned interval contains the true parameter. """ 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))
1,310
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))
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. Uses peak of conditional pdf as starting center. """ 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))
1,311
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))
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 # 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))
1,312
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))
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 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) vb = fac*distributions.invgamma.ppf(q2,a) # return (ma,mb),(va,vb),(sqrt(va),sqrt(vb))
1,313
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))
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) # 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)
1,314
def binomcdf(k, n, pr=0.5): return special.bdtr(k,n,pr)
def binomcdf(k, n, pr=0.5): sv = errp(0) vals = special.bdtr(k,n,pr) sv = errp(sv) return where(k>=0,vals,0.0)
1,315
def binomsf(k, n, pr=0.5): return special.bdtrc(k,n,pr)
def binomsf(k, n, pr=0.5): sv = errp(0) vals = special.bdtrc(k,n,pr) sv = errp(sv) return where(k>=0,vals,1.0)
1,316
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)
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)
1,317
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
def getcolumns(stream, columns, separator): comment = stream.comment lenc = stream.lencomment k, K = stream.linelist[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
1,318
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
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, "First line to read not within %d lines of top." % K 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
1,319
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())
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())
1,320
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)
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)
1,321
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)
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)
1,322
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)
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.assert_array_almost_equal((a*csp).todense(), a*c) NumPy needs special hooks for this. # assert_array_almost_equal((a*bsp).todense(), a*b)
1,323
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)
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)
1,324
def __call__(self, x, y): z = self.dot(x) + self.dot(y) - 2*self.dot(x, y) return N.exp(-self.gamma*z)
def __call__(self, x, y): z = self.dot(x, x) + self.dot(y, y) - 2*self.dot(x, y) return N.exp(-self.gamma*z)
1,325
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))
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): """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))
1,326
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))
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))
1,327
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))
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))
1,328
def hanning(M): """The M-point Hanning window. """ n = arange(0,M) return 0.5-0.5*cos(2.0*pi*n/(M-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))
1,329
def hamming(M): """The M-point Hamming window. """ n = arange(0,M) return 0.54-0.46*cos(2.0*pi*n/(M-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))
1,330
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)
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)
1,331
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)
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)
1,332
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))
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 w = exp(-0.5*(n/sig)**(2*p)) if not sym and not odd: w = w[:-1] return w
1,333
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
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) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-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
1,334
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 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] s**(M-1) + b[1] s**(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
1,335
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 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) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-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
1,336
def residuez(b,a,tol=1e-3): pass
def residuez(b,a,tol=1e-3): pass
1,337
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 _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)
1,338
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 _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 + (sym,) else: winfunc = kaiser params = (Nx,beta) return winfunc(*params)
1,339
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 _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,sym) return winfunc(*params)
1,340
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
def resample(x,num,t=None,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
1,341
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
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 sampled signals you didn't intend to be interpreted as band-limited. 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
1,342
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
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) 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
1,343
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
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 = ifftshift(get_window(window,Nx)) newshape = ones(len(x.shape)) newshape[axis] = len(W) W.shape = newshape 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
1,344
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
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']: y = y.real if t is None: return y else: return y
1,345
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
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: new_t = arange(0,num)*(t[1]-t[0])* Nx / float(num) + t[0] return y, new_t
1,346
def _entropy(self): return 0.64472988584940017414
def _entropy(self): return 0.64472988584940017414
1,347
def _entropy(self, b): eB = exp(b) return log(eB-1)+(1+eB*(b-1.0))/(1.0-eB)
def _entropy(self, b): eB = exp(b) return log(eB-1)+(1+eB*(b-1.0))/(1.0-eB)
1,348
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)
def _argcheck(self, a, b): self.a = a self.b = b self.nb = norm._cdf(b) self.na = norm._cdf(a) return (a != b)
1,349
def _pdf(self, x, a, b): return norm_gen._pdf(self, x) / (self.nb - self.na)
def _pdf(self, x, a, b): return norm_gen._pdf(self, x) / (self.nb - self.na)
1,350
def _cdf(self, x, a, b): return (norm_gen._cdf(self, 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)
1,351
def _ppf(self, q, a, b): return norm_gen._ppf(self, 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))
1,352
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
def _stats(self, a, b): nA, nB = self.na, self.nb d = nB - nA pA, pB = norm._pdf(a), norm._pdf(b) mu = (pB - pA) / d mu2 = 1 + (a*pA - b*pB) / d - mu*mu return mu, mu2, None, None
1,353
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
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
1,354
def integ(p): return log(pow(p,lam-1)+pow(1-p,lam-1))
definteg(p):returnlog(pow(p,lam-1)+pow(1-p,lam-1))
1,355
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
1,356
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
1,357
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
def func_and_grad(x): f = func(x, *args) g = fprime(x, *args) return f, g
1,358
def complex(a, b): c = zeros(a.shape, dtype=complex_) c.real = a c.imag = b return c
defv v v v v v v ^ ^ ^ ^ ^ ^ ^ complex(a,v v v v v v v ^ ^ ^ ^ ^ ^ ^ b):v v v v v v v ^ ^ ^ ^ ^ ^ ^ cv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ zeros(a.shape,v v v v v v v ^ ^ ^ ^ ^ ^ ^ dtype=complex_)v v v v v v v ^ ^ ^ ^ ^ ^ ^ c.realv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ av v v v v v v ^ ^ ^ ^ ^ ^ ^ c.imagv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ bv v v v v v v ^ ^ ^ ^ ^ ^ ^ returnv v v v v v v ^ ^ ^ ^ ^ ^ ^ c
1,359
def complex(a, b): c = zeros(a.shape, dtype=complex_) c.real = a c.imag = b return c
defv v v v v v v ^ ^ ^ ^ ^ ^ ^ complex(a,v v v v v v v ^ ^ ^ ^ ^ ^ ^ b):v v v v v v v ^ ^ ^ ^ ^ ^ ^ cv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ zeros(a.shape,v v v v v v v ^ ^ ^ ^ ^ ^ ^ dtype=complex_)v v v v v v v ^ ^ ^ ^ ^ ^ ^ c.realv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ av v v v v v v ^ ^ ^ ^ ^ ^ ^ c.imagv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ bv v v v v v v ^ ^ ^ ^ ^ ^ ^ returnv v v v v v v ^ ^ ^ ^ ^ ^ ^ c
1,360
def complex(a, b): c = zeros(a.shape, dtype=complex_) c.real = a c.imag = b return c
defv v v v v v v ^ ^ ^ ^ ^ ^ ^ complex(a,v v v v v v v ^ ^ ^ ^ ^ ^ ^ b):v v v v v v v ^ ^ ^ ^ ^ ^ ^ cv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ zeros(a.shape,v v v v v v v ^ ^ ^ ^ ^ ^ ^ dtype=complex_)v v v v v v v ^ ^ ^ ^ ^ ^ ^ c.realv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ av v v v v v v ^ ^ ^ ^ ^ ^ ^ c.imagv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ bv v v v v v v ^ ^ ^ ^ ^ ^ ^ returnv v v v v v v ^ ^ ^ ^ ^ ^ ^ c
1,361
def complex(a, b): c = zeros(a.shape, dtype=complex_) c.real = a c.imag = b return c
defv v v v v v v ^ ^ ^ ^ ^ ^ ^ complex(a,v v v v v v v ^ ^ ^ ^ ^ ^ ^ b):v v v v v v v ^ ^ ^ ^ ^ ^ ^ cv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ zeros(a.shape,v v v v v v v ^ ^ ^ ^ ^ ^ ^ dtype=complex_)v v v v v v v ^ ^ ^ ^ ^ ^ ^ c.realv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ av v v v v v v ^ ^ ^ ^ ^ ^ ^ c.imagv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ bv v v v v v v ^ ^ ^ ^ ^ ^ ^ returnv v v v v v v ^ ^ ^ ^ ^ ^ ^ c
1,362
def complex(a, b): c = zeros(a.shape, dtype=complex_) c.real = a c.imag = b return c
defv v v v v v v ^ ^ ^ ^ ^ ^ ^ complex(a,v v v v v v v ^ ^ ^ ^ ^ ^ ^ b):v v v v v v v ^ ^ ^ ^ ^ ^ ^ cv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ zeros(a.shape,v v v v v v v ^ ^ ^ ^ ^ ^ ^ dtype=complex_)v v v v v v v ^ ^ ^ ^ ^ ^ ^ c.realv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ av v v v v v v ^ ^ ^ ^ ^ ^ ^ c.imagv v v v v v v ^ ^ ^ ^ ^ ^ ^ =v v v v v v v ^ ^ ^ ^ ^ ^ ^ bv v v v v v v ^ ^ ^ ^ ^ ^ ^ returnv v v v v v v ^ ^ ^ ^ ^ ^ ^ c
1,363
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
def __unmasked(m, get_val, relpos): if m.mask is ma.nomask: return 0 else: idx = None if get_val: if idx is None: return ma.masked else: return m[idx] else: return idx
1,364
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
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
1,365
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)
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. shape = list(a.shape) del shape[axis] if shape: return np.zeros(shape, dtype=float) else: return np.float64(0.0) else: mn = np.expand_dims(np.mean(a,axis),axis) s = np.power((a-mn), moment) return np.mean(s,axis)
1,366
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)
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)
1,367
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)
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)
1,368
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)
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)
1,369
def cont(self, results, tol=1.0e-05): """ Continue iterating, or has convergence been obtained? """ if self.iter >= GeneralizedLinearModel.niter: return False
def cont(self, results, tol=1.0e-05): """ Continue iterating, or has convergence been obtained? """ if self.iter >= Model.niter: return False
1,370
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 ):
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 ):
1,371
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 calcfc(x, con): f = func(x, *args) k = 0 for constraints in cons: con[k] = constraints(x, *consargs) k += 1 print "con = ", con return f
1,372
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 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 return f
1,373
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)
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)
1,374
def _stats(self): return [scipy.inf]*2 + [scipy.nan]*2
def _stats(self): return [scipy.inf]*2 + [scipy.nan]*2
1,375
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
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) try: result = result + _unit_imag[imag.typecode()] * imag except KeyError: result = result + 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
1,376
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
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) try: res = res + _unit_imag[imag.typecode()] * imag except KeyError: res = res + 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
1,377
def sum_func(a, axis=-1): axis = encode_axis(axis) if isinstance(a, ConstantNode): return a if isinstance(a, (bool, int, float, complex)): a = ConstantNode(a) kind = a.astKind if kind == 'bool': kind = 'int' return FuncNode('sum', [a, axis], kind=kind)
def sum_func(a, axis=-1): axis = encode_axis(axis) if isinstance(a, ConstantNode): return a if isinstance(a, (bool, int, float, complex)): a = ConstantNode(a) kind = a.astKind if kind == 'bool': kind = 'int' return FuncNode('sum', [a, axis], kind=kind)
1,378
def prod_func(a, axis=-1): axis = encode_axis(axis) if isinstance(a, (bool, int, float, complex)): a = ConstantNode(a) if isinstance(a, ConstantNode): return a kind = a.astKind if kind == 'bool': kind = 'int' return FuncNode('prod', [a, axis], kind=kind)
def prod_func(a, axis=-1): axis = encode_axis(axis) if isinstance(a, (bool, int, float, complex)): a = ConstantNode(a) if isinstance(a, ConstantNode): return a kind = a.astKind if kind == 'bool': kind = 'int' return FuncNode('prod', [a, axis], kind=kind)
1,379
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
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(dot_join(parent_package,'xplt')) config['data_files'].extend( [(xplt_path,xplt_files)]) return config
1,380
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)
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)
1,381
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
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, unique_roots """ 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
1,382
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
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=rtype) 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
1,383
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
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 = 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
1,384
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
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 """ 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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
1,385
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
def residue(b,a,tol=1e-3): """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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
1,386
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
def residue(b,a,tol=1e-3): """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 """ 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
1,387
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
1,388
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
1,389
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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(dn)) bn = polysub(term1,term2) an = polymul(an,an) r[indx] = polyval(bn,pout[n]) / polyval(an,pout[n]) \ / factorial(sig-m) indx += 1 return r, p, k
def residue(b,a,tol=1e-3): """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 """ 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='avg') 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 = 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(dn)) 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
1,390
def draw_graph_area(self,dc=None): if not dc: dc = wx.wxClientDC(self) self.layout_data() # just to check how real time plot would go...
def draw_graph_area(self,dc=None): if not dc: dc = wx.wxClientDC(self) self.layout_data() # just to check how real time plot would go...
1,391
def configuration(parent_package=''): from interface_gen import generate_interface config = default_config_dict('linalg',parent_package) local_path = get_path(__name__) test_path = os.path.join(local_path,'tests') config['packages'].append(dot_join(parent_package,'linalg.tests')) config['package_dir']['linalg.tests'] = test_path atlas_info = get_info('atlas') if not atlas_info: raise AtlasNotFoundError,AtlasNotFoundError.__doc__ mod_sources = {'fblas':['generic_fblas.pyf', 'generic_fblas1.pyf', 'generic_fblas2.pyf', 'generic_fblas3.pyf', os.path.join('src','fblaswrap.f'), ], } #'cblas':['generic_cblas.pyf', # 'generic_cblas1.pyf'], #'flapack':['generic_flapack.pyf'], #'clapack':['generic_clapack.pyf']} for mod_name,sources in mod_sources.items(): sources = [os.path.join(local_path,s) for s in sources] mod_file = os.path.join(local_path,mod_name+'.pyf') if dep_util.newer_group(sources,mod_file): generate_interface(mod_name,sources[0],mod_file) sources = filter(lambda s:s[-4:]!='.pyf',sources) ext_args = {'name':dot_join(parent_package,'linalg',mod_name), 'sources':[mod_file]+sources} dict_append(ext_args,**atlas_info) ext = Extension(**ext_args) ext.need_fcompiler_opts = 1 config['ext_modules'].append(ext) flinalg = [] for f in ['det.f','lu.f', #'wrappers.c','inv.f', ]: flinalg.append(os.path.join(local_path,'src',f)) ext_args = {'name':dot_join(parent_package,'linalg','_flinalg'), 'sources':flinalg} dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) ext_args = {'name':dot_join(parent_package,'linalg','calc_lwork'), 'sources':[os.path.join(local_path,'src','calc_lwork.f')], } dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) return config
def configuration(parent_package=''): from interface_gen import generate_interface config = default_config_dict('linalg',parent_package) local_path = get_path(__name__) test_path = os.path.join(local_path,'tests') config['packages'].append(dot_join(parent_package,'linalg.tests')) config['package_dir']['linalg.tests'] = test_path atlas_info = get_info('atlas') if not atlas_info: raise AtlasNotFoundError,AtlasNotFoundError.__doc__ mod_sources = {'fblas':['generic_fblas.pyf', 'generic_fblas1.pyf', 'generic_fblas2.pyf', 'generic_fblas3.pyf', os.path.join('src','fblaswrap.f'), ], } #'cblas':['generic_cblas.pyf', # 'generic_cblas1.pyf'], #'flapack':['generic_flapack.pyf'], #'clapack':['generic_clapack.pyf']} for mod_name,sources in mod_sources.items(): sources = [os.path.join(local_path,s) for s in sources] mod_file = os.path.join(local_path,mod_name+'.pyf') if dep_util.newer_group(sources,mod_file): generate_interface(mod_name,sources[0],mod_file) sources = filter(lambda s:s[-4:]!='.pyf',sources) ext_args = {'name':dot_join(parent_package,'linalg',mod_name), 'sources':[mod_file]+sources} dict_append(ext_args,**atlas_info) ext = Extension(**ext_args) ext.need_fcompiler_opts = 1 config['ext_modules'].append(ext) flinalg = [] for f in ['det.f','lu.f', #'wrappers.c','inv.f', ]: flinalg.append(os.path.join(local_path,'src',f)) ext_args = {'name':dot_join(parent_package,'linalg','_flinalg'), 'sources':flinalg} dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) ext_args = {'name':dot_join(parent_package,'linalg','calc_lwork'), 'sources':[os.path.join(local_path,'src','calc_lwork.f')], } dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) return config
1,392
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) # Compute the residue from the general formula (for discrete-time) # the polynomial is in z**(-1) and the multiplication is by terms # like this (1-p[i] z**(-1))**mult[i]. After differentiation, # we must divide by (-p[i])**(m-k) as well as (m-k)! 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] # bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is # multiplicity of pole at po[n] and b(z) and a(z) are polynomials. 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,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 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) if krev == []: k = [] else: k = krev[::-1] b = 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) # Compute the residue from the general formula (for discrete-time) # the polynomial is in z**(-1) and the multiplication is by terms # like this (1-p[i] z**(-1))**mult[i]. After differentiation, # we must divide by (-p[i])**(m-k) as well as (m-k)! 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] # bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is # multiplicity of pole at po[n] and b(z) and a(z) are polynomials. 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,1.0/pout[n]) / polyval(an,1.0/pout[n]) \ / factorial(sig-m) / (-pout[n])**(sig-m) indx += sig return r/gain, p, k
1,393
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
1,394
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (C<=0) or ((i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
1,395
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
1,396
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
1,397
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
def zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): fc = gc = 0 maxiter = 10 i = 0 while 1: # interpolate to find a trial step length between a_lo and a_hi A = phi_lo; B = derphi_lo; dalpha = a_hi-a_lo; C = (phi_hi - phi_lo - dalpha*derphi_lo)/dalpha**2; if (c<=0) or (i%3)==2): # Use bisection a_j = a_lo + 0.5*dalpha; else: # Use min of quadratic a_j = a_lo - 0.5*B/C; phi_aj = phi(a_j) fc += 1 if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) gc += 1 if abs(derphi_aj) <= -c2*derphi0: a_star = a_j break if derphi_aj*(a_hi - a_lo) >= 0: a_hi = a_lo phi_hi = phi_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): a_star = a_j break return a_star, fc, gc
1,398
def phiprime(alpha): return Num.dot(fprime(xk+alpha*pk,*args),pk)
def phiprime(alpha): return Num.dot(fprime(xk+alpha*pk,*args),pk)
1,399