bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def __init__(self,*args,**kwords): """Initialize the LTI system using either: (numerator, denominator) (zeros, poles, gain) (A, B, C, D) -- state-space. """ N = len(args) if N == 2: # Numerator denominator transfer function input self.__dict__['num'], self.__dict__['den'] = normalize(*args) self.__dict__['zeros'], self.__dict__['poles'], \ self.__dict__['gain'] = tf2zpk(*args) self.__dict__['A'], self.__dict__['B'], \ self.__dict__['C'], \ self.__dict__['D'] = tf2ss(*args) self.inputs = 1 if len(self.num.shape) > 1: self.outputs = self.num.shape[0] else: self.outputs = 1 elif N == 3: # Zero-pole-gain form self.__dict__['zeros'], self.__dict__['poles'], \ self.__dict__['gain'] = args self.__dict__['num'], self.__dict__['den'] = zpk2tf(*args) self.__dict__['A'], self.__dict__['B'], \ self.__dict__['C'], \ self.__dict__['D'] = zpk2ss(*args) self.inputs = 1 if len(self.zeros.shape) > 1: self.outputs = self.zeros.shape[0] else: self.outputs = 1 elif N == 4: # State-space form self.__dict__['A'], self.__dict__['B'], \ self.__dict__['C'], \ self.__dict__['D'] = abcd_normalize(*args) self.__dict__['zeros'], self.__dict__['poles'], \ self.__dict__['gain'] = ss2zpk(*args) self.__dict__['num'], self.__dict__['den'] = ss2tf(*args) self.inputs = B.shape[-1] self.outputs = C.shape[0] else: raise ValueError, "Needs 2, 3, or 4 arguments."
def __init__(self,*args,**kwords): """Initialize the LTI system using either: (numerator, denominator) (zeros, poles, gain) (A, B, C, D) -- state-space. """ N = len(args) if N == 2: # Numerator denominator transfer function input self.__dict__['num'], self.__dict__['den'] = normalize(*args) self.__dict__['zeros'], self.__dict__['poles'], \ self.__dict__['gain'] = tf2zpk(*args) self.__dict__['A'], self.__dict__['B'], \ self.__dict__['C'], \ self.__dict__['D'] = tf2ss(*args) self.inputs = 1 if len(self.num.shape) > 1: self.outputs = self.num.shape[0] else: self.outputs = 1 elif N == 3: # Zero-pole-gain form self.__dict__['zeros'], self.__dict__['poles'], \ self.__dict__['gain'] = args self.__dict__['num'], self.__dict__['den'] = zpk2tf(*args) self.__dict__['A'], self.__dict__['B'], \ self.__dict__['C'], \ self.__dict__['D'] = zpk2ss(*args) self.inputs = 1 if len(self.zeros.shape) > 1: self.outputs = self.zeros.shape[0] else: self.outputs = 1 elif N == 4: # State-space form self.__dict__['A'], self.__dict__['B'], \ self.__dict__['C'], \ self.__dict__['D'] = abcd_normalize(*args) self.__dict__['zeros'], self.__dict__['poles'], \ self.__dict__['gain'] = ss2zpk(*args) self.__dict__['num'], self.__dict__['den'] = ss2tf(*args) self.inputs = self.B.shape[-1] self.outputs = self.C.shape[0] else: raise ValueError, "Needs 2, 3, or 4 arguments."
1,000
def _pmf(self, k, lambda_): fact = (1-exp(-lamba_)) return fact*exp(-lambda_(k))
def _pmf(self, k, lambda_): fact = (1-exp(-lambda_)) return fact*exp(-lambda_(k))
1,001
def check_stdX(self): y = scipy.stats.stdev(X) assert_almost_equal(y,2.738612788)
def check_stdX(self): y = scipy.stats.std(X) assert_almost_equal(y,2.738612788)
1,002
def check_stdZERO(self): y = scipy.stats.stdev(ZERO) assert_almost_equal(y,0.0)
def check_stdZERO(self): y = scipy.stats.std(ZERO) assert_almost_equal(y,0.0)
1,003
def check_stdBIG(self): y = scipy.stats.stdev(BIG) assert_almost_equal(y,2.738612788)
def check_stdBIG(self): y = scipy.stats.std(BIG) assert_almost_equal(y,2.738612788)
1,004
def check_stdLITTLE(self): y = scipy.stats.stdev(LITTLE) assert_approx_equal(y,2.738612788e-8)
def check_stdLITTLE(self): y = scipy.stats.std(LITTLE) assert_approx_equal(y,2.738612788e-8)
1,005
def check_stdHUGE(self): y = scipy.stats.stdev(HUGE) assert_approx_equal(y,2.738612788e12)
def check_stdHUGE(self): y = scipy.stats.std(HUGE) assert_approx_equal(y,2.738612788e12)
1,006
def check_stdTINY(self): y = scipy.stats.stdev(TINY) assert_almost_equal(y,0.0)
def check_stdTINY(self): y = scipy.stats.std(TINY) assert_almost_equal(y,0.0)
1,007
def check_stdROUND(self): y = scipy.stats.stdev(ROUND) assert_approx_equal(y,2.738612788)
def check_stdROUND(self): y = scipy.stats.std(ROUND) assert_approx_equal(y,2.738612788)
1,008
def rmdir(dir,depth=0): import os path = os.path.abspath(dir) all_files = os.listdir(path) indent = ' ' * depth for i in all_files: if not i == 'CVS': print indent, i if os.path.isdir(os.path.join(path,i)): rmdir(os.path.join(path,i),depth+1) else: cmd = 'cd ' + path + ';rm -r ' + i + ';cvs rm ' + i + ';cd ..' print cmd os.system(cmd)
def rmdir(dir,depth=0): import os path = os.path.abspath(dir) all_files = os.listdir(path) indent = ' ' * depth for i in all_files: if not i == 'CVS': print indent, i if os.path.isdir(os.path.join(path,i)): rmdir(os.path.join(path,i),depth+1) else: cmd = 'cd ' + path + ';rm -r ' + i + ';cvs rm ' + i + ';cd ..' print cmd os.system(cmd)
1,009
def check_euler(self): eu0 = euler(0) eu1 = euler(1) eu2 = euler(2) # just checking segfaults assert_almost_equal(eu0[0],1,8) assert_almost_equal(eu2[2],-1,8) eu24 = euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145,2404879675441, 370371188237525,69348874393137901, 15514534163557086905] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) err = nan_to_num((eu24-correct)/correct) errmax = max(err) assert_almost_equal(errmax, 0.0, 14)
def check_euler(self): eu0 = euler(0) eu1 = euler(1) eu2 = euler(2) # just checking segfaults assert_almost_equal(eu0[0],1,8) assert_almost_equal(eu2[2],-1,8) eu24 = euler(24) mathworld = [1,1,5,61,1385,50521,2702765,199360981, 19391512145l,2404879675441l, 370371188237525l,69348874393137901l, 15514534163557086905l] correct = zeros((25,),'d') for k in range(0,13): if (k % 2): correct[2*k] = -float(mathworld[k]) else: correct[2*k] = float(mathworld[k]) err = nan_to_num((eu24-correct)/correct) errmax = max(err) assert_almost_equal(errmax, 0.0, 14)
1,010
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=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, longname=None, shapes=None, extradoc=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 = sgf(self._ppf_single_call) self.vecentropy = sgf(self._entropy) 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,011
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=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, longname=None, shapes=None, extradoc=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 = sgf(self._mom0_sc) 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,012
def __init__(self, momtype=1, a=None, b=None, xa=-10.0, xb=10.0, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=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, longname=None, shapes=None, extradoc=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 = sgf(self._mom1_sc) 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,013
def _ppf_tosolve(self, x, q, *args): return apply(self.cdf, (x, )+args) - q
def _ppf_tosolve(self, x, q, *args): return apply(self.cdf, (x, )+args) - q
1,014
def _ppf_single_call(self, q, *args): return scipy.optimize.brentq(self._ppf_tosolve, self.xa, self.xb, args=(q,)+args, xtol=self.xtol)
def _ppf_single_call(self, q, *args): return scipy.optimize.brentq(self._ppf_tosolve, self.xa, self.xb, args=(q,)+args, xtol=self.xtol)
1,015
def _ppf(self,q): return special.kolmogi(1.0-q)
def _ppf(self,q): return special.kolmogi(1.0-q)
1,016
def _stats(self, c, moments='mv'): k = log(1.0+c) mu = (c-k)/(c*k) mu2 = ((c+2.0)*k-2.0*c)/(2*c*k*k) g1 = None g2 = None if 's' in moments: g1 = sqrt(2)*(12*c*c-9*c*k*(c+2)+2*k*k*(c*(c+3)+3)) g1 /= sqrt(c*(c*(k-2)+2*k))*(3*c*(k-2)+6*k) if 'k' in moments: g2 = c**3*(k-3)*(k*(3*k-16)+24)+12*k*c*c*(k-4)*(k-3) \ + 6*c*k*k*(3*k-14) + 12*k**3 g2 /= 3*c*(c*(k-2)+2*k)**2 return mu, mu2, g1, g2
defdef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) _stats(self,def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) c,def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) moments='mv'):def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) kdef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) =def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) log(1.0+c)def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) mudef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) =def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) (c-k)/(c*k)def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) mu2def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) =def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) ((c+2.0)*k-2.0*c)/(2*c*k*k)def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g1def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) =def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) Nonedef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g2def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) =def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) Nonedef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) ifdef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) 's'def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) indef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) moments:def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g1def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) =def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) sqrt(2)*(12*c*c-9*c*k*(c+2)+2*k*k*(c*(c+3)+3))def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g1def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) /=def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) sqrt(c*(c*(k-2)+2*k))*(3*c*(k-2)+6*k)def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) ifdef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) 'k'def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) indef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) moments:def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g2def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) =def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) c**3*(k-3)*(k*(3*k-16)+24)+12*k*c*c*(k-4)*(k-3)def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) \def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) +def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) 6*c*k*k*(3*k-14)def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) +def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) 12*k**3def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g2def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) /=def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) 3*c*(c*(k-2)+2*k)**2def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) returndef _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) mu,def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) mu2,def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g1,def _entropy(self, c): k = log(1+c) return k/2.0 - log(c/k) g2
1,017
def _stats(self, x, c): return burr_gen._stats(self, x, c, 1.0)
def _stats(self, x, c): return burr_gen._stats(self, x, c, 1.0)
1,018
def _isf(self, q, dfn, dfd): return special.fdtri(dfn, dfd, q)
def _isf(self, q, dfn, dfd): return special.fdtri(dfn, dfd, q)
1,019
def _ppf(self, q, dfn, dfd): return self._isf(1.0-q, dfn, dfd)
def _ppf(self, q, dfn, dfd): return self._isf(1.0-q, dfn, dfd)
1,020
def _argcheck(self, c): c = arr(c) self.b = where(c < 0, 1.0/abs(c), scipy.inf) self.a = where(c > 0, 0.0, -scipy.inf) return where(c==0, 0, 1)
def _argcheck(self, c): c = arr(c) self.b = where(c < 0, 1.0/abs(c), scipy.inf) return where(c==0, 0, 1)
1,021
def _munp(self, n, c): k = arange(0,n+1) val = (-1.0/c)**n * sum(scipy.comb(n,k)*(-1)**k / (1.0-c*k)) return where(c*n < 1, val, scipy.inf)
def _munp(self, n, c): k = arange(0,n+1) val = (-1.0/c)**n * sum(scipy.comb(n,k)*(-1)**k / (1.0-c*k)) return where(c*n < 1, val, scipy.inf)
1,022
def _ppf(self, q, c): return pow(-log(q),arr(-1.0/c))
def _ppf(self, q, c): return pow(-log(q),arr(-1.0/c))
1,023
def _stats(self): return 0, pi*pi/3.0, 0, 6.0/5.0
def _stats(self): return 0, pi*pi/3.0, 0, 6.0/5.0
1,024
def _stats(self, x): return 0, 0.25, 0, -1.0
def _stats(self): return 0, 0.25, 0, -1.0
1,025
def _stats(self, lam): return 0, None, 0, None
def _stats(self, lam): return 0, None, 0, None
1,026
def _cdf(self, x, c): output = 0.0*x val = (1.0+c)/(1.0-c) xp = extract( x<pi,x) xn = extract( x>=pi,x) if (any(xn)): xn = 2*pi - xn yn = tan(xn/2.0) on = 1.0-1.0/pi*arctan(val*yn) insert(output, x>=pi, on) if (any(xp)): yp = tan(xp/2.0) op = 1.0/pi*arctan(val*yp) insert(output, x<pi, op) return output
def _cdf(self, x, c): output = 0.0*x val = (1.0+c)/(1.0-c) c1 = x<pi c2 = 1-c1 xp = extract( c1,x) valp = extract(c1,val) xn = extract( c2,x) valn = extract(c2,val) if (any(xn)): xn = 2*pi - xn yn = tan(xn/2.0) on = 1.0-1.0/pi*arctan(val*yn) insert(output, x>=pi, on) if (any(xp)): yp = tan(xp/2.0) op = 1.0/pi*arctan(val*yp) insert(output, x<pi, op) return output
1,027
def _cdf(self, x, c): output = 0.0*x val = (1.0+c)/(1.0-c) xp = extract( x<pi,x) xn = extract( x>=pi,x) if (any(xn)): xn = 2*pi - xn yn = tan(xn/2.0) on = 1.0-1.0/pi*arctan(val*yn) insert(output, x>=pi, on) if (any(xp)): yp = tan(xp/2.0) op = 1.0/pi*arctan(val*yp) insert(output, x<pi, op) return output
def _cdf(self, x, c): output = 0.0*x val = (1.0+c)/(1.0-c) xp = extract( x<pi,x) xn = extract( x>=pi,x) if (any(xn)): xn = 2*pi - xn yn = tan(xn/2.0) on = 1.0-1.0/pi*arctan(valn*yn) insert(output, c2, on) if (any(xp)): yp = tan(xp/2.0) op = 1.0/pi*arctan(val*yp) insert(output, x<pi, op) return output
1,028
def _cdf(self, x, c): output = 0.0*x val = (1.0+c)/(1.0-c) xp = extract( x<pi,x) xn = extract( x>=pi,x) if (any(xn)): xn = 2*pi - xn yn = tan(xn/2.0) on = 1.0-1.0/pi*arctan(val*yn) insert(output, x>=pi, on) if (any(xp)): yp = tan(xp/2.0) op = 1.0/pi*arctan(val*yp) insert(output, x<pi, op) return output
def _cdf(self, x, c): output = 0.0*x val = (1.0+c)/(1.0-c) xp = extract( x<pi,x) xn = extract( x>=pi,x) if (any(xn)): xn = 2*pi - xn yn = tan(xn/2.0) on = 1.0-1.0/pi*arctan(val*yn) insert(output, x>=pi, on) if (any(xp)): yp = tan(xp/2.0) op = 1.0/pi*arctan(val*yp) insert(output, x<pi, op) return output
1,029
def __call__(self, *args, **kwds): raise ValueError return self.freeze(*args,**kwds)
def __call__(self, *args, **kwds): return self.freeze(*args,**kwds)
1,030
def _stats(self, n, pr): q = 1.0-pr mu = n * pr var = n * pr * q g1 = (q-pr) / sqrt(n*pr*q) g2 = (1.0-6*pr*q)/(n*pr*q) return mu, var, g1, g2
def _stats(self, n, pr): q = 1.0-pr mu = n * pr var = n * pr * q g1 = (q-pr) / sqrt(n*pr*q) g2 = (1.0-6*pr*q)/(n*pr*q) return mu, var, g1, g2
1,031
def _stats(self, pr): return binom_gen._stats(self, 1, pr)
def _stats(self, pr): return binom_gen._stats(self, 1, pr)
1,032
def _argcheck(self, n, pr): self.a = n return (n >= 0) & (pr >= 0) & (pr <= 1)
def _argcheck(self, n, pr): return (n >= 0) & (pr >= 0) & (pr <= 1)
1,033
def _stats(self, mu): var = mu g1 = 1.0/arr(sqrt(mu)) g2 = 1.0 / arr(mu) return mu, var, g1, g2
def _stats(self, mu): var = mu g1 = 1.0/arr(sqrt(mu)) g2 = 1.0 / arr(mu) return mu, var, g1, g2
1,034
def _stats(self, a): ea = exp(-a) e2a = exp(-2*a) e3a = exp(-3*a) e4a = exp(-4*a) mu2 = 2* (e2a + ea) / (1-ea)**3.0 mu4 = 2* (e4a + 11*e3a + 11*e2a + ea) / (1-ea)**5.0 return 0.0, mu2, 0.0, mu4 / mu2**2.0 - 3
def _stats(self, a): ea = exp(-a) e2a = exp(-2*a) e3a = exp(-3*a) e4a = exp(-4*a) mu2 = 2* (e2a + ea) / (1-ea)**3.0 mu4 = 2* (e4a + 11*e3a + 11*e2a + ea) / (1-ea)**5.0 return 0.0, mu2, 0.0, mu4 / mu2**2.0 - 3
1,035
def detrend(data, axis=-1, type='linear', bp=0): """Remove linear trend along axis from data. If type is 'constant' then remove mean only. If bp is given, then it is a sequence of points at which to break a piecewise-linear fit to the data. """ if type not in ['linear','l','constant','c']: raise ValueError, "Trend type must be linear or constant" data = asarray(data) if type in ['constant','c']: ret = data - expand_dims(mean(data,axis),axis) return ret else: dshape = data.shape N = dshape[axis] bp = sort(unique(r_[0,bp,N])) if any(bp > N): raise ValueError, "Breakpoints must be less than length of data along given axis." Nreg = len(bp) - 1 # Restructure data so that axis is along first dimension and # all other dimensions are collapsed into second dimension rnk = len(dshape) if axis < 0: axis = axis + rnk newdims = r_[axis,0:axis,axis+1:rnk] newdata = reshape(transpose(data,tuple(newdims)),(N,prod(dshape)/N)) newdata = newdata.copy() # make sure we have a copy # Find leastsq fit and remove it for each piece for m in range(Nreg): Npts = bp[m+1] - bp[m] A = ones((Npts,2),'d') A[:,0] = arange(1,Npts+1)*1.0/Npts sl = slice(bp[m],bp[m+1]) coef,resids,rank,s = linalg.lstsq(A,newdata[sl]) newdata[sl] = newdata[sl] - dot(A,coef) # Put data back in original shape. tdshape = take(dshape,newdims) ret = reshape(newdata,tdshape) vals = range(1,rnk) olddims = vals[:axis] + [0] + vals[axis:] ret = transpose(ret,tuple(olddims)) return ret
def detrend(data, axis=-1, type='linear', bp=0): """Remove linear trend along axis from data. If type is 'constant' then remove mean only. If bp is given, then it is a sequence of points at which to break a piecewise-linear fit to the data. """ if type not in ['linear','l','constant','c']: raise ValueError, "Trend type must be linear or constant" data = asarray(data) if type in ['constant','c']: ret = data - expand_dims(mean(data,axis),axis) return ret else: dshape = data.shape N = dshape[axis] bp = sort(unique(r_[0,bp,N])) if any(bp > N): raise ValueError, "Breakpoints must be less than length of data along given axis." Nreg = len(bp) - 1 # Restructure data so that axis is along first dimension and # all other dimensions are collapsed into second dimension rnk = len(dshape) if axis < 0: axis = axis + rnk newdims = r_[axis,0:axis,axis+1:rnk] newdata = reshape(transpose(data,tuple(newdims)),(N,prod(dshape)/N)) newdata = newdata.copy() # make sure we have a copy # Find leastsq fit and remove it for each piece for m in range(Nreg): Npts = bp[m+1] - bp[m] A = ones((Npts,2),dtype) A[:,0] = cast[dtype](arange(1,Npts+1)*1.0/Npts) sl = slice(bp[m],bp[m+1]) coef,resids,rank,s = linalg.lstsq(A,newdata[sl]) newdata[sl] = newdata[sl] - dot(A,coef) # Put data back in original shape. tdshape = take(dshape,newdims) ret = reshape(newdata,tdshape) vals = range(1,rnk) olddims = vals[:axis] + [0] + vals[axis:] ret = transpose(ret,tuple(olddims)) return ret
1,036
def spsolve(A, b, permc_spec=2): if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'): raise ValueError, "sparse matrix must be able to return CSC format--"\ "A.tocsc()--or CSR format--A.tocsr()" if not hasattr(A, 'shape'): raise ValueError, "sparse matrix must be able to return shape" \ " (rows, cols) = A.shape" M, N = A.shape if (M != N): raise ValueError, "matrix must be square" if isUmfpack and useUmfpack: mat = _toCS_umfpack( A ) if mat.dtype.char not in 'dD': raise ValueError, "convert matrix data to double, please, using"\ " .astype(), or set sparse.useUmfpack = False" family = {'d' : 'di', 'D' : 'zi'} umf = umfpack.UmfpackContext( family[mat.dtype.char] ) return umf.linsolve( umfpack.UMFPACK_A, mat, b, autoTranspose = True ) else: mat, csc = _toCS_superLU( A ) ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr gssv = eval('_superlu.' + ftype + 'gssv') print "data-ftype: %s compared to data %s" % (ftype, data.dtype.char) print "Calling _superlu.%sgssv" % ftype return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0]
def spsolve(A, b, permc_spec=2): if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'): raise ValueError, "sparse matrix must be able to return CSC format--"\ "A.tocsc()--or CSR format--A.tocsr()" if not hasattr(A, 'shape'): raise ValueError, "sparse matrix must be able to return shape" \ " (rows, cols) = A.shape" M, N = A.shape if (M != N): raise ValueError, "matrix must be square" if isUmfpack and useUmfpack: mat = _toCS_umfpack( A ) if mat.dtype.char not in 'dD': raise ValueError, "convert matrix data to double, please, using"\ " .astype(), or set linsolve.useUmfpack = False" family = {'d' : 'di', 'D' : 'zi'} umf = umfpack.UmfpackContext( family[mat.dtype.char] ) return umf.linsolve( umfpack.UMFPACK_A, mat, b, autoTranspose = True ) else: mat, csc = _toCS_superLU( A ) ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr gssv = eval('_superlu.' + ftype + 'gssv') print "data-ftype: %s compared to data %s" % (ftype, data.dtype.char) print "Calling _superlu.%sgssv" % ftype return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0]
1,037
def _stats(self): return 0.5, 1.0/12, 0, -1.2
def _stats(self): return 0.5, 1.0/12, 0, -1.2
1,038
def configuration(parent_package='', parent_path=None): local_path = get_path(__name__) config = Configuration('delaunay', parent_package, parent_path) config.add_extension("_delaunay", sources=["_delaunay.cpp", "VoronoiDiagramGenerator.cpp", "delaunay_utils.cpp", "natneighbors.cpp"], include_dirs=[local_path], ) return config
def configuration(parent_package='', top_path=None): config = Configuration('delaunay', parent_package, top_path) config.add_extension("_delaunay", sources=["_delaunay.cpp", "VoronoiDiagramGenerator.cpp", "delaunay_utils.cpp", "natneighbors.cpp"], include_dirs=[local_path], ) return config
1,039
def configuration(parent_package='', parent_path=None): local_path = get_path(__name__) config = Configuration('delaunay', parent_package, parent_path) config.add_extension("_delaunay", sources=["_delaunay.cpp", "VoronoiDiagramGenerator.cpp", "delaunay_utils.cpp", "natneighbors.cpp"], include_dirs=[local_path], ) return config
def configuration(parent_package='', parent_path=None): local_path = get_path(__name__) config = Configuration('delaunay', parent_package, parent_path) config.add_extension("_delaunay", sources=["_delaunay.cpp", "VoronoiDiagramGenerator.cpp", "delaunay_utils.cpp", "natneighbors.cpp"], include_dirs=['.'], ) return config
1,040
def tri(N, M=None, k=0, typecode=None): """ returns a N-by-M matrix where all the diagonals starting from lower left corner up to the k-th are all ones. """ if M is None: M = N if type(M) == type('d'): typecode = M M = N m = greater_equal(subtract.outer(arange(N), arange(M)),-k) if typecode is None: return m else: return m.astype(typecode)
def tri(N, M=None, k=0, typecode=None): """ returns a N-by-M matrix where all the diagonals starting from lower left corner up to the k-th are all ones. """ if M is None: M = N if type(M) == type('d'): typecode = M M = N m = greater_equal(subtract.outer(arange(N), arange(M)),-k) if typecode is None: return m else: return m.astype(typecode)
1,041
def tril(m, k=0): """ returns the elements on and below the k-th diagonal of m. k=0 is the main diagonal, k > 0 is above and k < 0 is below the main diagonal. """ svsp = m.spacesaver() m = asarray(m,savespace=1) out = tri(m.shape[0], m.shape[1], k=k, typecode=m.typecode())*m out.savespace(svsp) return out
def tril(m, k=0): """ returns the elements on and below the k-th diagonal of m. k=0 is the main diagonal, k > 0 is above and k < 0 is below the main diagonal. """ svsp = getattr(m,'spacesaver',lambda:0)() m = asarray(m,savespace=1) out = tri(m.shape[0], m.shape[1], k=k, typecode=m.typecode())*m out.savespace(svsp) return out
1,042
def triu(m, k=0): """ returns the elements on and above the k-th diagonal of m. k=0 is the main diagonal, k > 0 is above and k < 0 is below the main diagonal. """ svsp = m.spacesaver() m = asarray(m,savespace=1) out = (1-tri(m.shape[0], m.shape[1], k-1, m.typecode()))*m out.savespace(svsp) return out
def triu(m, k=0): """ returns the elements on and above the k-th diagonal of m. k=0 is the main diagonal, k > 0 is above and k < 0 is below the main diagonal. """ svsp = getattr(m,'spacesaver',lambda:0)() m = asarray(m,savespace=1) out = (1-tri(m.shape[0], m.shape[1], k-1, m.typecode()))*m out.savespace(svsp) return out
1,043
def fixed_quad(func,a,b,args=(),n=5): """Compute a definite integral using fixed-order Gaussian quadrature. Description: Integrate func from a to b using Gaussian quadrature of order n. Inputs: func -- a Python function or method to integrate. a -- lower limit of integration b -- upper limit of integration args -- extra arguments to pass to function. n -- order of quadrature integration. Outputs: (val, None) val -- Gaussian quadrature approximation to the integral. """ [x,w] = p_roots(n) ainf, binf = map(scipy.isinf,(a,b)) if ainf or binf: raise ValueError, "Gaussian quadrature is only available for finite limits." y = (b-a)*(x+1)/2.0 + a return (b-a)/2.0*sum(w*func(y,*args)), None
def fixed_quad(func,a,b,args=(),n=5): """Compute a definite integral using fixed-order Gaussian quadrature. Description: Integrate func from a to b using Gaussian quadrature of order n. Inputs: func -- a Python function or method to integrate (must accept vector inputs) a -- lower limit of integration b -- upper limit of integration args -- extra arguments to pass to function. n -- order of quadrature integration. Outputs: (val, None) val -- Gaussian quadrature approximation to the integral. """ [x,w] = p_roots(n) ainf, binf = map(scipy.isinf,(a,b)) if ainf or binf: raise ValueError, "Gaussian quadrature is only available for finite limits." y = (b-a)*(x+1)/2.0 + a return (b-a)/2.0*sum(w*func(y,*args)), None
1,044
def quadrature(func,a,b,args=(),tol=1.49e-8,maxiter=50): """Compute a definite integral using fixed-tolerance Gaussian quadrature. Description: Integrate func from a to b using Gaussian quadrature with absolute tolerance tol. Inputs: func -- a Python function or method to integrate. a -- lower limit of integration. b -- upper limit of integration. args -- extra arguments to pass to function. tol -- iteration stops when error between last two iterates is less than tolerance. maxiter -- maximum number of iterations. Outputs: (val, err) val -- Gaussian quadrature approximation (within tolerance) to integral. err -- Difference between last two estimates of the integral. """ err = 100.0 val = err n = 1 while (err > tol) and (n < maxiter): newval = fixed_quad(func,a,b,args,n)[0] err = abs(newval-val) val = newval n = n + 1 if (n==maxiter): print "maxiter (%d) exceeded. Latest difference = %e" % (n,err) else: print "Took %d points." % n return val, err
def quadrature(func,a,b,args=(),tol=1.49e-8,maxiter=50): """Compute a definite integral using fixed-tolerance Gaussian quadrature. Description: Integrate func from a to b using Gaussian quadrature with absolute tolerance tol. Inputs: func -- a Python function or method to integrate. a -- lower limit of integration. b -- upper limit of integration. args -- extra arguments to pass to function. tol -- iteration stops when error between last two iterates is less than tolerance. maxiter -- maximum number of iterations. Outputs: (val, err) val -- Gaussian quadrature approximation (within tolerance) to integral. err -- Difference between last two estimates of the integral. """ err = 100.0 val = err n = 1 while (err > tol) and (n < maxiter): newval = fixed_quad(vec_func,a,b,(func,)+args,n)[0] err = abs(newval-val) val = newval n = n + 1 if (n==maxiter): print "maxiter (%d) exceeded. Latest difference = %e" % (n,err) else: print "Took %d points." % n return val, err
1,045
def configuration(parent_package='',parent_path=None): from scipy_distutils.core import Extension from scipy_distutils.misc_util import fortran_library_item, dot_join,\ SourceGenerator, get_path, default_config_dict, get_build_temp from scipy_distutils.system_info import get_info,dict_append,\ AtlasNotFoundError,LapackNotFoundError,BlasNotFoundError,\ LapackSrcNotFoundError,BlasSrcNotFoundError,NotFoundError package = 'linalg' from interface_gen import generate_interface config = default_config_dict(package,parent_package) local_path = get_path(__name__,parent_path) def local_join(*paths): return os.path.join(*((local_path,)+paths)) abs_local_path = os.path.abspath(local_path) no_atlas = 0 lapack_opt = get_info('lapack_opt') if not lapack_opt: raise NotFoundError,'no lapack/blas resources found' atlas_version = ([v[3:-3] for k,v in lapack_opt.get('define_macros',[]) \ if k=='ATLAS_INFO']+[None])[0] if atlas_version: print 'ATLAS version',atlas_version target_dir = '' skip_names = {'clapack':[],'flapack':[],'cblas':[],'fblas':[]} if skip_single_routines: target_dir = 'dbl' skip_names['clapack'].extend(\ 'sgesv cgesv sgetrf cgetrf sgetrs cgetrs sgetri cgetri'\ ' sposv cposv spotrf cpotrf spotrs cpotrs spotri cpotri'\ ' slauum clauum strtri ctrtri'.split()) skip_names['flapack'].extend(skip_names['clapack']) skip_names['flapack'].extend(\ 'sgesdd cgesdd sgelss cgelss sgeqrf cgeqrf sgeev cgeev'\ ' sgegv cgegv ssyev cheev slaswp claswp sgees cgees' ' sggev cggev'.split()) skip_names['cblas'].extend('saxpy caxpy'.split()) skip_names['fblas'].extend(skip_names['cblas']) skip_names['fblas'].extend(\ 'srotg crotg srotmg srot csrot srotm sswap cswap sscal cscal'\ ' csscal scopy ccopy sdot cdotu cdotc snrm2 scnrm2 sasum scasum'\ ' isamax icamax sgemv cgemv chemv ssymv strmv ctrmv'\ ' sgemm cgemm'.split()) if using_lapack_blas: target_dir = join(target_dir,'blas') skip_names['fblas'].extend(\ 'drotmg srotmg drotm srotm'.split()) if atlas_version=='3.2.1_pre3.3.6': target_dir = join(target_dir,'atlas321') skip_names['clapack'].extend(\ 'sgetri dgetri cgetri zgetri spotri dpotri cpotri zpotri'\ ' slauum dlauum clauum zlauum strtri dtrtri ctrtri ztrtri'.split()) elif atlas_version>'3.4.0' and atlas_version<='3.5.12': skip_names['clapack'].extend('cpotrf zpotrf'.split()) def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target # fblas: ext_args = {'name': dot_join(parent_package,package,'fblas'), 'sources': [generate_pyf, local_join('src','fblaswrap.f')], 'depends': map(local_join,['generic_fblas.pyf', 'generic_fblas1.pyf', 'generic_fblas2.pyf', 'generic_fblas3.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # cblas: ext_args = {'name': dot_join(parent_package,package,'cblas'), 'sources': [generate_pyf], 'depends': map(local_join,['generic_cblas.pyf', 'generic_cblas1.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # flapack: ext_args = {'name': dot_join(parent_package,package,'flapack'), 'sources': [generate_pyf], 'depends': map(local_join,['generic_flapack.pyf', 'flapack_user_routines.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # clapack: ext_args = {'name': dot_join(parent_package,package,'clapack'), 'sources': [generate_pyf], 'depends': map(local_join,['generic_clapack.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # _flinalg: ext_args = {'name':dot_join(parent_package,package,'_flinalg'), 'sources':[local_join('src','det.f'), local_join('src','lu.f')] } dict_append(ext_args,**lapack_opt) config['ext_modules'].append(Extension(**ext_args)) # calc_lwork: ext_args = {'name':dot_join(parent_package,package,'calc_lwork'), 'sources':[local_join('src','calc_lwork.f')], } dict_append(ext_args,**lapack_opt) config['ext_modules'].append(Extension(**ext_args)) # atlas_version: ext_args = {'name':dot_join(parent_package,package,'atlas_version'), 'sources':[os.path.join(local_path,'atlas_version.c')]} dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) return config
def configuration(parent_package='',parent_path=None): from scipy_distutils.core import Extension from scipy_distutils.misc_util import dot_join, get_path, default_config_dict from scipy_distutils.system_info import get_info, dict_append, NotFoundError package = 'linalg' from interface_gen import generate_interface config = default_config_dict(package,parent_package) local_path = get_path(__name__,parent_path) def local_join(*paths): return os.path.join(*((local_path,)+paths)) abs_local_path = os.path.abspath(local_path) no_atlas = 0 lapack_opt = get_info('lapack_opt') if not lapack_opt: raise NotFoundError,'no lapack/blas resources found' atlas_version = ([v[3:-3] for k,v in lapack_opt.get('define_macros',[]) \ if k=='ATLAS_INFO']+[None])[0] if atlas_version: print 'ATLAS version',atlas_version target_dir = '' skip_names = {'clapack':[],'flapack':[],'cblas':[],'fblas':[]} if skip_single_routines: target_dir = 'dbl' skip_names['clapack'].extend(\ 'sgesv cgesv sgetrf cgetrf sgetrs cgetrs sgetri cgetri'\ ' sposv cposv spotrf cpotrf spotrs cpotrs spotri cpotri'\ ' slauum clauum strtri ctrtri'.split()) skip_names['flapack'].extend(skip_names['clapack']) skip_names['flapack'].extend(\ 'sgesdd cgesdd sgelss cgelss sgeqrf cgeqrf sgeev cgeev'\ ' sgegv cgegv ssyev cheev slaswp claswp sgees cgees' ' sggev cggev'.split()) skip_names['cblas'].extend('saxpy caxpy'.split()) skip_names['fblas'].extend(skip_names['cblas']) skip_names['fblas'].extend(\ 'srotg crotg srotmg srot csrot srotm sswap cswap sscal cscal'\ ' csscal scopy ccopy sdot cdotu cdotc snrm2 scnrm2 sasum scasum'\ ' isamax icamax sgemv cgemv chemv ssymv strmv ctrmv'\ ' sgemm cgemm'.split()) if using_lapack_blas: target_dir = join(target_dir,'blas') skip_names['fblas'].extend(\ 'drotmg srotmg drotm srotm'.split()) if atlas_version=='3.2.1_pre3.3.6': target_dir = join(target_dir,'atlas321') skip_names['clapack'].extend(\ 'sgetri dgetri cgetri zgetri spotri dpotri cpotri zpotri'\ ' slauum dlauum clauum zlauum strtri dtrtri ctrtri ztrtri'.split()) elif atlas_version>'3.4.0' and atlas_version<='3.5.12': skip_names['clapack'].extend('cpotrf zpotrf'.split()) def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target # fblas: ext_args = {'name': dot_join(parent_package,package,'fblas'), 'sources': [generate_pyf, local_join('src','fblaswrap.f')], 'depends': map(local_join,['generic_fblas.pyf', 'generic_fblas1.pyf', 'generic_fblas2.pyf', 'generic_fblas3.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # cblas: ext_args = {'name': dot_join(parent_package,package,'cblas'), 'sources': [generate_pyf], 'depends': map(local_join,['generic_cblas.pyf', 'generic_cblas1.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # flapack: ext_args = {'name': dot_join(parent_package,package,'flapack'), 'sources': [generate_pyf], 'depends': map(local_join,['generic_flapack.pyf', 'flapack_user_routines.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # clapack: ext_args = {'name': dot_join(parent_package,package,'clapack'), 'sources': [generate_pyf], 'depends': map(local_join,['generic_clapack.pyf']) } dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) # _flinalg: ext_args = {'name':dot_join(parent_package,package,'_flinalg'), 'sources':[local_join('src','det.f'), local_join('src','lu.f')] } dict_append(ext_args,**lapack_opt) config['ext_modules'].append(Extension(**ext_args)) # calc_lwork: ext_args = {'name':dot_join(parent_package,package,'calc_lwork'), 'sources':[local_join('src','calc_lwork.f')], } dict_append(ext_args,**lapack_opt) config['ext_modules'].append(Extension(**ext_args)) # atlas_version: ext_args = {'name':dot_join(parent_package,package,'atlas_version'), 'sources':[os.path.join(local_path,'atlas_version.c')]} dict_append(ext_args,**lapack_opt) ext = Extension(**ext_args) config['ext_modules'].append(ext) return config
1,046
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
1,047
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
1,048
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
1,049
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
def generate_pyf(extension, build_dir): name = extension.name.split('.')[-1] target = join(build_dir,target_dir,name+'.pyf') if name[0]=='c' and atlas_version is None and newer(__file__,target): f = open(target,'w') f.write('python module '+name+'\n') f.write('usercode void empty_module(void) {}\n') f.write('interface\n') f.write('subroutine empty_module()\n') f.write('intent(c) empty_module\n') f.write('end subroutine empty_module\n') f.write('end interface\nend python module'+name+'\n') f.close() return target if newer_group(extension.depends,target): generate_interface(name, extension.depends[0], target, skip_names[name]) return target
1,050
def getsize_type(mtype): if mtype in ['b','uchar','byte','unsigned char','integer*1', 'int8']: mtype = 'b' elif mtype in ['c', 'char','char*1']: mtype = 'c' elif mtype in ['1','schar', 'signed char']: mtype = '1' elif mtype in ['s','short','int16','integer*2']: mtype = 's' elif mtype in ['i','int']: mtype = 'i' elif mtype in ['l','long','int32','integer*4']: mtype = 'l' elif mtype in ['f','float','float32','real*4']: mtype = 'f' elif mtype in ['d','double','float64','real*8']: mtype = 'd' elif mtype in ['F','complex float','complex*8','complex64']: mtype = 'F' elif mtype in ['D','complex*16','complex128','complex','complex double']: mtype = 'D' else: raise TypeError, 'Bad datatype -- ' + mtype argout = (array(0,mtype).itemsize(),mtype) return argout
def getsize_type(mtype): if mtype in ['b','uchar','byte','unsigned char','integer*1', 'int8']: mtype = 'b' elif mtype in ['c', 'char','char*1']: mtype = 'c' elif mtype in ['1','schar', 'signed char']: mtype = '1' elif mtype in ['s','short','int16','integer*2']: mtype = 's' elif mtype in ['i','int']: mtype = 'i' elif mtype in ['l','long','int32','integer*4']: mtype = 'l' elif mtype in ['f','float','float32','real*4', 'real']: mtype = 'f' elif mtype in ['d','double','float64','real*8']: mtype = 'd' elif mtype in ['F','complex float','complex*8','complex64']: mtype = 'F' elif mtype in ['D','complex*16','complex128','complex','complex double']: mtype = 'D' else: raise TypeError, 'Bad datatype -- ' + mtype argout = (array(0,mtype).itemsize(),mtype) return argout
1,051
def getsize_type(mtype): if mtype in ['b','uchar','byte','unsigned char','integer*1', 'int8']: mtype = 'b' elif mtype in ['c', 'char','char*1']: mtype = 'c' elif mtype in ['1','schar', 'signed char']: mtype = '1' elif mtype in ['s','short','int16','integer*2']: mtype = 's' elif mtype in ['i','int']: mtype = 'i' elif mtype in ['l','long','int32','integer*4']: mtype = 'l' elif mtype in ['f','float','float32','real*4']: mtype = 'f' elif mtype in ['d','double','float64','real*8']: mtype = 'd' elif mtype in ['F','complex float','complex*8','complex64']: mtype = 'F' elif mtype in ['D','complex*16','complex128','complex','complex double']: mtype = 'D' else: raise TypeError, 'Bad datatype -- ' + mtype argout = (array(0,mtype).itemsize(),mtype) return argout
def getsize_type(mtype): if mtype in ['b','uchar','byte','unsigned char','integer*1', 'int8']: mtype = 'b' elif mtype in ['c', 'char','char*1']: mtype = 'c' elif mtype in ['1','schar', 'signed char']: mtype = '1' elif mtype in ['s','short','int16','integer*2']: mtype = 's' elif mtype in ['i','int']: mtype = 'i' elif mtype in ['l','long','int32','integer*4']: mtype = 'l' elif mtype in ['f','float','float32','real*4']: mtype = 'f' elif mtype in ['d','double','float64','real*8', 'double precision']: mtype = 'd' elif mtype in ['F','complex float','complex*8','complex64']: mtype = 'F' elif mtype in ['D','complex*16','complex128','complex','complex double']: mtype = 'D' else: raise TypeError, 'Bad datatype -- ' + mtype argout = (array(0,mtype).itemsize(),mtype) return argout
1,052
def fort_write(self,fmt,*args): """Write a Fortran binary record.
def fort_write(self,fmt,*args): """Write a Fortran binary record.
1,053
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) 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
def _parse_mimatrix(fid,bytes): dclass, cmplx, nzmax =_parse_array_flags(fid) dims = _get_element(fid)[0] name = asarray(_get_element(fid)[0]).tostring() 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 = asarray(_get_element(fid)[0]).tostring() 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,054
def getnzmax(self): try: nzmax = self.nzmax except AttributeError: try: nzmax = self.nnz except AtrributeError: nzmax = 0 return nzmax
def getnzmax(self): try: nzmax = self.nzmax except AttributeError: try: nzmax = self.nnz except AttributeError: nzmax = 0 return nzmax
1,055
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csc') if isinstance(s,spmatrix): if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape tcode = s.typecode func = getattr(sparsetools,tcode+'transp') self.data, self.rowind, self.indptr = \ func(s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.rowind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array M, N = s.shape s = asarray(s) if s.typecode() not in 'fdFD': s = s*1.0 typecode = s.typecode() func = getattr(sparsetools,_transtabl[typecode]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,),typecode) rowa = zeros((nnz,),'i') ptra = zeros((N+1,),'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz)
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csc') if isinstance(s,spmatrix): if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools,s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.rowind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array M, N = s.shape s = asarray(s) if s.typecode() not in 'fdFD': s = s*1.0 typecode = s.typecode() func = getattr(sparsetools,_transtabl[typecode]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,),typecode) rowa = zeros((nnz,),'i') ptra = zeros((N+1,),'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz)
1,056
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csc') if isinstance(s,spmatrix): if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape tcode = s.typecode func = getattr(sparsetools,tcode+'transp') self.data, self.rowind, self.indptr = \ func(s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.rowind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array M, N = s.shape s = asarray(s) if s.typecode() not in 'fdFD': s = s*1.0 typecode = s.typecode() func = getattr(sparsetools,_transtabl[typecode]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,),typecode) rowa = zeros((nnz,),'i') ptra = zeros((N+1,),'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz)
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csc') if isinstance(s,spmatrix): if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape tcode = s.typecode func = getattr(sparsetools,tcode+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.rowind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array M, N = s.shape s = asarray(s) if s.typecode() not in 'fdFD': s = s*1.0 typecode = s.typecode() func = getattr(sparsetools,_transtabl[typecode]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,),typecode) rowa = zeros((nnz,),'i') ptra = zeros((N+1,),'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz)
1,057
def __add__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self.typecode,other.typecode)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], other.data[:nnz2], typecode) func = getattr(sparsetools,_transtabl[typecode]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,other.rowind[:nnz2],other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N)
def __add__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self.typecode,other.typecode)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], typecode) func = getattr(sparsetools,_transtabl[typecode]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,other.rowind[:nnz2],other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N)
1,058
def __add__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self.typecode,other.typecode)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], other.data[:nnz2], typecode) func = getattr(sparsetools,_transtabl[typecode]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,other.rowind[:nnz2],other.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N)
def __add__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." typecode = _coerce_rules[(self.typecode,other.typecode)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], other.data[:nnz2], typecode) func = getattr(sparsetools,_transtabl[typecode]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix(c,(rowc,ptrc),M=M,N=N)
1,059
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csr') if isinstance(s,spmatrix): if isinstance(s, csr_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.colind = s.colind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.colind = s.colind self.indptr = s.indptr elif isinstance(s, csc_matrix): self.shape = s.shape tcode = s.typecode func = getattr(sparsetools,tcode+'transp') self.data, self.colind, self.indptr = \ func(s.data, s.rowind, s.indptr) else: try: temp = s.tocsr() except AttributeError: temp = csr_matrix(s.tocsc()) self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.colind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array ocsc = csc_matrix(transpose(s)) self.shape = ocsc.shape[1], ocsc.shape[0] self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data elif isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s),2)): ijnew = ij.copy() ijnew[:,0] = ij[:,1] ijnew[:,1] = ij[:,0] temp = coo_matrix(s,ijnew,M=M,N=N,nzmax=nzmax, typecode=typecode) temp = temp.tocsc() self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(ij, types.TupleType) and (len(ij)==2): self.data = asarray(s) self.colind = ij[0] self.indptr = ij[1] if N is None: N = max(self.colind) if M is None: M = len(self.indptr) - 1 self.shape = (M,N) else: raise ValueError, "Unrecognized form for csr_matrix constructor." else: raise ValueError, "Unrecognized form for csr_matrix constructor."
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csr') if isinstance(s,spmatrix): if isinstance(s, csr_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.colind = s.colind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.colind = s.colind self.indptr = s.indptr elif isinstance(s, csc_matrix): self.shape = s.shape func = getattr(sparsetools,s.ftype+'transp') self.data, self.colind, self.indptr = \ func(s.data, s.rowind, s.indptr) else: try: temp = s.tocsr() except AttributeError: temp = csr_matrix(s.tocsc()) self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.colind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array ocsc = csc_matrix(transpose(s)) self.shape = ocsc.shape[1], ocsc.shape[0] self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data elif isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s),2)): ijnew = ij.copy() ijnew[:,0] = ij[:,1] ijnew[:,1] = ij[:,0] temp = coo_matrix(s,ijnew,M=M,N=N,nzmax=nzmax, typecode=typecode) temp = temp.tocsc() self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(ij, types.TupleType) and (len(ij)==2): self.data = asarray(s) self.colind = ij[0] self.indptr = ij[1] if N is None: N = max(self.colind) if M is None: M = len(self.indptr) - 1 self.shape = (M,N) else: raise ValueError, "Unrecognized form for csr_matrix constructor." else: raise ValueError, "Unrecognized form for csr_matrix constructor."
1,060
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csr') if isinstance(s,spmatrix): if isinstance(s, csr_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.colind = s.colind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.colind = s.colind self.indptr = s.indptr elif isinstance(s, csc_matrix): self.shape = s.shape tcode = s.typecode func = getattr(sparsetools,tcode+'transp') self.data, self.colind, self.indptr = \ func(s.data, s.rowind, s.indptr) else: try: temp = s.tocsr() except AttributeError: temp = csr_matrix(s.tocsc()) self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.colind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array ocsc = csc_matrix(transpose(s)) self.shape = ocsc.shape[1], ocsc.shape[0] self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data elif isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s),2)): ijnew = ij.copy() ijnew[:,0] = ij[:,1] ijnew[:,1] = ij[:,0] temp = coo_matrix(s,ijnew,M=M,N=N,nzmax=nzmax, typecode=typecode) temp = temp.tocsc() self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(ij, types.TupleType) and (len(ij)==2): self.data = asarray(s) self.colind = ij[0] self.indptr = ij[1] if N is None: N = max(self.colind) if M is None: M = len(self.indptr) - 1 self.shape = (M,N) else: raise ValueError, "Unrecognized form for csr_matrix constructor." else: raise ValueError, "Unrecognized form for csr_matrix constructor."
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csr') if isinstance(s,spmatrix): if isinstance(s, csr_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.colind = s.colind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.colind = s.colind self.indptr = s.indptr elif isinstance(s, csc_matrix): self.shape = s.shape tcode = s.typecode func = getattr(sparsetools,tcode+'transp') self.data, self.colind, self.indptr = \ func(s.shape[1], s.data, s.rowind, s.indptr) else: try: temp = s.tocsr() except AttributeError: temp = csr_matrix(s.tocsc()) self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.colind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array ocsc = csc_matrix(transpose(s)) self.shape = ocsc.shape[1], ocsc.shape[0] self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data elif isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s),2)): ijnew = ij.copy() ijnew[:,0] = ij[:,1] ijnew[:,1] = ij[:,0] temp = coo_matrix(s,ijnew,M=M,N=N,nzmax=nzmax, typecode=typecode) temp = temp.tocsc() self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr self.shape = temp.shape elif isinstance(ij, types.TupleType) and (len(ij)==2): self.data = asarray(s) self.colind = ij[0] self.indptr = ij[1] if N is None: N = max(self.colind) if M is None: M = len(self.indptr) - 1 self.shape = (M,N) else: raise ValueError, "Unrecognized form for csr_matrix constructor." else: raise ValueError, "Unrecognized form for csr_matrix constructor."
1,061
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.colind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nzmax < nnz): raise ValueError, "Nzmax must not be less than nnz." if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (self.indptr[-1] > len(self.colind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.colind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != nzmax): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nzmax < nnz): raise ValueError, "Nzmax must not be less than nnz." if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (self.indptr[-1] > len(self.colind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.colind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
1,062
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.colind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nzmax < nnz): raise ValueError, "Nzmax must not be less than nnz." if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (self.indptr[-1] > len(self.colind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.colind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.colind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (self.indptr[-1] > len(self.colind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.colind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
1,063
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.colind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nzmax < nnz): raise ValueError, "Nzmax must not be less than nnz." if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (self.indptr[-1] > len(self.colind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.colind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.colind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nzmax < nnz): raise ValueError, "Nzmax must not be less than nnz." if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (nnz > nzmax): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.colind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
1,064
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.colind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nzmax < nnz): raise ValueError, "Nzmax must not be less than nnz." if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (self.indptr[-1] > len(self.colind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.colind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.colind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, colind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.colind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != M+1): raise ValueError, "Index pointer should be of length #rows + 1" if (nzmax < nnz): raise ValueError, "Nzmax must not be less than nnz." if (nnz>0) and (max(self.colind[:nnz]) >= M): raise ValueError, "Column-values must be < N." if (self.indptr[-1] > len(self.colind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.typecode = self.data.typecode() if self.typecode not in 'fdFD': self.typecode = 'd' self.data = self.data.astype('d') self.ftype = _transtabl[self.typecode]
1,065
def transp(self, copy=0): M,N = self.shape new = csr_matrix(N,M,nzmax=0,typecode=self.typecode) if copy: new.data = self.data.copy() new.colind = self.rowind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.colind = self.rowind new.indptr = self.indptr new._check() return new
def transp(self, copy=0): M,N = self.shape new = csc_matrix(N,M,nzmax=0,typecode=self.typecode) if copy: new.data = self.data.copy() new.colind = self.rowind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.colind = self.rowind new.indptr = self.indptr new._check() return new
1,066
def transp(self, copy=0): M,N = self.shape new = csr_matrix(N,M,nzmax=0,typecode=self.typecode) if copy: new.data = self.data.copy() new.colind = self.rowind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.colind = self.rowind new.indptr = self.indptr new._check() return new
def transp(self, copy=0): M,N = self.shape new = csr_matrix(N,M,nzmax=0,typecode=self.typecode) if copy: new.data = self.data.copy() new.rowind = self.colind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.colind = self.rowind new.indptr = self.indptr new._check() return new
1,067
def transp(self, copy=0): M,N = self.shape new = csr_matrix(N,M,nzmax=0,typecode=self.typecode) if copy: new.data = self.data.copy() new.colind = self.rowind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.colind = self.rowind new.indptr = self.indptr new._check() return new
def transp(self, copy=0): M,N = self.shape new = csr_matrix(N,M,nzmax=0,typecode=self.typecode) if copy: new.data = self.data.copy() new.colind = self.rowind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.rowind = self.colind new.indptr = self.indptr new._check() return new
1,068
def _parse_header(fid, dict): correct_endian = (ord('M')<<8) + ord('I') # if this number is read no BS fid.seek(126) # skip to endian detector endian_test = fid.read(1,'int16') if (endian_test == correct_endian): openstr = 'n' else: # must byteswap if LittleEndian: openstr = 'b' else: openstr = 'l' fid.setformat(openstr) # change byte-order if necessary fid.rewind() dict['__header__'] = fid.fid.read(124).strip(' \t\n\000') vers = fid.read(1,'int16') dict['__version__'] = '%d.%d' % (vers >> 8, vers & 255) fid.seek(2,1) # move to start of data return
def _parse_header(fid, dict): correct_endian = (ord('M')<<8) + ord('I') # if this number is read no BS fid.seek(126) # skip to endian detector endian_test = fid.read(1,'int16') if (endian_test == correct_endian): openstr = 'n' else: # must byteswap if LittleEndian: openstr = 'b' else: openstr = 'l' fid.setformat(openstr) # change byte-order if necessary fid.rewind() dict['__header__'] = fid.raw_read(124).strip(' \t\n\000') vers = fid.read(1,'int16') dict['__version__'] = '%d.%d' % (vers >> 8, vers & 255) fid.seek(2,1) # move to start of data return
1,069
def _get_element(fid): test = fid.fid.read(1) if len(test) == 0: # nothing left raise EOFError else: fid.rewind(1) # get the data tag raw_tag = fid.read(1,'u') # check for compressed numbytes = raw_tag >> 16 if numbytes > 0: # compressed format if numbytes > 4: raise IOError, "Problem with MAT file: " \ "too many bytes in compressed format." dtype = raw_tag & 65535 el = fid.read(numbytes,miDataTypes[dtype][2],c_is_b=1) fid.seek(4-numbytes,1) # skip padding return el, None # otherwise parse tag dtype = raw_tag numbytes = fid.read(1,'u') if dtype != miMATRIX: # basic data type try: outarr = fid.read(numbytes,miDataTypes[dtype][2],c_is_b=1) except KeyError: raise ValueError, "Unknown data type" mod8 = numbytes%8 if mod8: # skip past padding skip = 8-mod8 fid.seek(skip,1) return outarr, None # handle miMatrix type el, name = _parse_mimatrix(fid,numbytes) return el, name
def _get_element(fid): test = fid.raw_read(1) if len(test) == 0: # nothing left raise EOFError else: fid.rewind(1) # get the data tag raw_tag = fid.read(1,'u') # check for compressed numbytes = raw_tag >> 16 if numbytes > 0: # compressed format if numbytes > 4: raise IOError, "Problem with MAT file: " \ "too many bytes in compressed format." dtype = raw_tag & 65535 el = fid.read(numbytes,miDataTypes[dtype][2],c_is_b=1) fid.seek(4-numbytes,1) # skip padding return el, None # otherwise parse tag dtype = raw_tag numbytes = fid.read(1,'u') if dtype != miMATRIX: # basic data type try: outarr = fid.read(numbytes,miDataTypes[dtype][2],c_is_b=1) except KeyError: raise ValueError, "Unknown data type" mod8 = numbytes%8 if mod8: # skip past padding skip = 8-mod8 fid.seek(skip,1) return outarr, None # handle miMatrix type el, name = _parse_mimatrix(fid,numbytes) return el, name
1,070
def valarray(shape,value=nan,typecode=None): """Return an array of all value. """ out = reshape(repeat([value],product(shape)),shape) if typecode is None: return out else: return out.astype(typecode)
def valarray(shape,value=nan,typecode=None): """Return an array of all value. """ out = reshape(repeat([value],product(shape)),shape) if typecode is not None: out = out.astype(typecode) if not isinstance(out, ndarray): out = asarray(out) return out
1,071
def validate_active(): global _active if _active is None: figure() try: if not _active.window_is_alive(): _active = None figure() except: pass
def validate_active(): global _active if _active is None: figure() try: if not _active.proxy_object_alive: _active = None figure() except: pass
1,072
def bilinear(b,a,fs=1.0): """Return a digital filter from an analog filter using the bilinear transform. The bilinear transform substitutes (z-1) / (z+1) for s """ a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = Num.Float M = max([N,D]) Np = M Dp = M bprime = Num.zeros(Np+1,artype) aprime = Num.zeros(Dp+1,artype) for j in range(Np+1): val = 0.0 for i in range(N+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*b[N-i]*pow(2*fs,i)*(-1)**k bprime[j] = val for j in range(Dp+1): val = 0.0 for i in range(D+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*a[D-i]*pow(2*fs,i)*(-1)**k aprime[j] = val return normalize(bprime, aprime)
def bilinear(b,a,fs=1.0): """Return a digital filter from an analog filter using the bilinear transform. The bilinear transform substitutes (z-1) / (z+1) for s """ fs =float(fs) a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = Num.Float M = max([N,D]) Np = M Dp = M bprime = Num.zeros(Np+1,artype) aprime = Num.zeros(Dp+1,artype) for j in range(Np+1): val = 0.0 for i in range(N+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*b[N-i]*pow(2*fs,i)*(-1)**k bprime[j] = val for j in range(Dp+1): val = 0.0 for i in range(D+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*a[D-i]*pow(2*fs,i)*(-1)**k aprime[j] = val return normalize(bprime, aprime)
1,073
def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=0, ftype='butter', output='ba'): """IIR digital and analog filter design given order and critical points. Description: Design an Nth order lowpass digital or analog filter and return the filter coefficients in (B,A) (numerator, denominator) or (Z,P,K) form. Inputs: N -- the order of the filter. Wn -- a scalar or length-2 sequence giving the critical frequencies. rp, rs -- For chebyshev and elliptic filters provides the maximum ripple in the passband and the minimum attenuation in the stop band. btype -- the type of filter (lowpass, highpass, bandpass, or bandstop). analog -- non-zero to return an analog filter, otherwise a digital filter is returned. ftype -- the type of IIR filter (Butterworth, Cauer (Elliptic), Bessel, Chebyshev1, Chebyshev2) output -- 'ba' for (b,a) output, 'zpk' for (z,p,k) output. SEE ALSO butterord, cheb1ord, cheb2ord, ellipord """ ftype, btype, output = map(string.lower, (ftype, btype, output)) Wn = Num.asarray(Wn) try: btype = band_dict[btype] except KeyError: raise ValueError, "%s is an invalid bandtype for filter." % btype try: typefunc = filter_dict[ftype][0] except KeyError: raise ValueError, "%s is not a valid basic iir filter." % ftype if output not in ['ba', 'zpk']: raise ValueError, "%s is not a valid output form." % output #pre-warp frequencies for digital filter design if not analog: fs = 2 warped = 2*fs*tan(pi*Wn/fs) else: warped = Wn # convert to low-pass prototype if btype in ['lowpass', 'highpass']: wo = warped else: bw = warped[1] - warped[0] wo = sqrt(warped[0]*warped[1]) # Get analog lowpass prototype if typefunc in [buttap, besselap]: z, p, k = typefunc(N) elif typefunc == cheb1ap: if rp is None: raise ValueError, "passband ripple (rp) must be provided to design a Chebyshev I filter." z, p, k = typefunc(N, rp) elif typefunc == cheb2ap: if rs is None: raise ValueError, "stopband atteunatuion (rs) must be provided to design an Chebyshev II filter." z, p, k = typefunc(N, rs) else: # Elliptic filters if rs is None or rp is None: raise ValueErrro, "Both rp and rs must be provided to design an elliptic filter." z, p, k = typefunc(N, rp, rs) b, a = zpk2tf(z,p,k) # transform to lowpass, bandpass, highpass, or bandstop if btype == 'lowpass': b, a = lp2lp(b,a,wo=wo) elif btype == 'highpass': b, a = lp2hp(b,a,wo=wo) elif btype == 'bandpass': b, a = lp2bp(b,a,wo=wo,bw=bw) else: # 'bandstop' b, a = lp2bs(b,a,wo=wo,bw=bw) # Find discrete equivalent if necessary if not analog: b, a = bilinear(b, a, fs=fs) # Transform to proper out type (pole-zero, state-space, numer-denom) if output == 'zpk': return tf2zpk(b,a) else: return b,a
def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=0, ftype='butter', output='ba'): """IIR digital and analog filter design given order and critical points. Description: Design an Nth order lowpass digital or analog filter and return the filter coefficients in (B,A) (numerator, denominator) or (Z,P,K) form. Inputs: N -- the order of the filter. Wn -- a scalar or length-2 sequence giving the critical frequencies. rp, rs -- For chebyshev and elliptic filters provides the maximum ripple in the passband and the minimum attenuation in the stop band. btype -- the type of filter (lowpass, highpass, bandpass, or bandstop). analog -- non-zero to return an analog filter, otherwise a digital filter is returned. ftype -- the type of IIR filter (Butterworth, Cauer (Elliptic), Bessel, Chebyshev1, Chebyshev2) output -- 'ba' for (b,a) output, 'zpk' for (z,p,k) output. SEE ALSO butterord, cheb1ord, cheb2ord, ellipord """ ftype, btype, output = map(string.lower, (ftype, btype, output)) Wn = Num.asarray(Wn) try: btype = band_dict[btype] except KeyError: raise ValueError, "%s is an invalid bandtype for filter." % btype try: typefunc = filter_dict[ftype][0] except KeyError: raise ValueError, "%s is not a valid basic iir filter." % ftype if output not in ['ba', 'zpk']: raise ValueError, "%s is not a valid output form." % output #pre-warp frequencies for digital filter design if not analog: fs = 2.0 warped = 2*fs*tan(pi*Wn/fs) else: warped = Wn # convert to low-pass prototype if btype in ['lowpass', 'highpass']: wo = warped else: bw = warped[1] - warped[0] wo = sqrt(warped[0]*warped[1]) # Get analog lowpass prototype if typefunc in [buttap, besselap]: z, p, k = typefunc(N) elif typefunc == cheb1ap: if rp is None: raise ValueError, "passband ripple (rp) must be provided to design a Chebyshev I filter." z, p, k = typefunc(N, rp) elif typefunc == cheb2ap: if rs is None: raise ValueError, "stopband atteunatuion (rs) must be provided to design an Chebyshev II filter." z, p, k = typefunc(N, rs) else: # Elliptic filters if rs is None or rp is None: raise ValueErrro, "Both rp and rs must be provided to design an elliptic filter." z, p, k = typefunc(N, rp, rs) b, a = zpk2tf(z,p,k) # transform to lowpass, bandpass, highpass, or bandstop if btype == 'lowpass': b, a = lp2lp(b,a,wo=wo) elif btype == 'highpass': b, a = lp2hp(b,a,wo=wo) elif btype == 'bandpass': b, a = lp2bp(b,a,wo=wo,bw=bw) else: # 'bandstop' b, a = lp2bs(b,a,wo=wo,bw=bw) # Find discrete equivalent if necessary if not analog: b, a = bilinear(b, a, fs=fs) # Transform to proper out type (pole-zero, state-space, numer-denom) if output == 'zpk': return tf2zpk(b,a) else: return b,a
1,074
def __setitem__(self, index, x): try: assert len(index) == 2 except (AssertionError, TypeError): raise IndexError, "invalid index" i, j = index if isinstance(i, int): if not (i>=0 and i<self.shape[0]): raise IndexError, "lil_matrix index out of range" else: if isinstance(i, slice): seq = xrange(i.start or 0, i.stop or self.shape[1], i.step or 1) elif operator.isSequenceType(i): seq = i else: raise IndexError, "invalid index" try: if not len(x) == len(seq): raise ValueError, "number of elements in source must be" \ " same as number of elements in destimation" except TypeError: # Either x or seq is not a sequence. Note that a sparse matrix # is also not a sequence under this definition. # Currently we don't support setting to/from non-sequence types. # This could be enhanced, though, to allow a scalar source, # and/or a sparse vector. raise TypeError, "unsupported type for lil_matrix.__setitem__" else: # Sequence: call __setitem__ recursively, once for each row for i in xrange(len(seq)): self[seq[i], index[1]] = x[i] return
def __setitem__(self, index, x): try: assert len(index) == 2 except (AssertionError, TypeError): raise IndexError, "invalid index" i, j = index if isinstance(i, int): if not (i>=0 and i<self.shape[0]): raise IndexError, "lil_matrix index out of range" else: if isinstance(i, slice): seq = xrange(i.start or 0, i.stop or self.shape[1], i.step or 1) elif operator.isSequenceType(i): seq = i else: raise IndexError, "invalid index" try: if not len(x) == len(seq): raise ValueError, "number of elements in source must be" \ " same as number of elements in destimation" except TypeError: # Either x or seq is not a sequence. Note that a sparse matrix # is also not a sequence under this definition. # Currently we don't support setting to/from non-sequence types. # This could be enhanced, though, to allow a scalar source, # and/or a sparse vector. raise TypeError, "unsupported type for lil_matrix.__setitem__" else: # Sequence: call __setitem__ recursively, once for each row for i in xrange(len(seq)): self[seq[i], index[1]] = x[i] return
1,075
def tmax(a,upperlimit,axis=0,inclusive=True): """Returns the maximum value of a, along axis, including only values greater than (or equal to, if inclusive is True) upperlimit. If the limit is set to None, a limit larger than the max value in the array is used. """ a, axis = asarray(a, axis) if inclusive: upperfcn = less else: upperfcn = less_equal if upperlimit is None: upperlimit = maximum.reduce(ravel(a))+1 smallest = minimum.reduce(ravel(a)) ta = where(upperfcn(a,upperlimit),a,smallest) return maximum.reduce(ta,axis)
def tmax(a,upperlimit,axis=0,inclusive=True): """Returns the maximum value of a, along axis, including only values greater than (or equal to, if inclusive is True) upperlimit. If the limit is set to None, a limit larger than the max value in the array is used. """ a, axis = _chk_asarray(a, axis) if inclusive: upperfcn = less else: upperfcn = less_equal if upperlimit is None: upperlimit = maximum.reduce(ravel(a))+1 smallest = minimum.reduce(ravel(a)) ta = where(upperfcn(a,upperlimit),a,smallest) return maximum.reduce(ta,axis)
1,076
def check_basic(self): a1 = [1,-4,4] a2 = [4,-16,16] a3 = [1,5,6] assert_array_almost_equal(roots(a1),[2,2],11) assert_array_almost_equal(roots(a2),[2,2],11) assert_array_almost_equal(sort(roots(a3)),sort([-3,-2]),11)
def check_basic(self): a1 = [1,-4,4] a2 = [4,-16,16] a3 = [1,5,6] assert_array_almost_equal(roots(a1),[2,2],11) assert_array_almost_equal(roots(a2),[2,2],11) assert_array_almost_equal(sort(roots(a3)),sort([-3,-2]),11)
1,077
def check_inverse(self): a = rand(5) assert_array_almost_equal(sort(roots(poly(a))),sort(a),11)
def check_inverse(self): a = rand(5) assert_array_almost_equal(sort(roots(poly(a))),sort(a),11)
1,078
def check_nd(self): x = sort(20*rand(10,20,30)) y = x**2 + 2*x + 1 dx = x[:,1:,:] - x[:,:-1,:] val = add.reduce(dx*(y[:,1:,:] + y[:,:-1,:])/2.0,1) assert_array_equal(trapz(y,x,1),val)
def check_nd(self): x = sort(20*rand(10,20,30)) y = x**2 + 2*x + 1 dx = x[:,1:,:] - x[:,:-1,:] val = add.reduce(dx*(y[:,1:,:] + y[:,:-1,:])/2.0,1) assert_array_equal(trapz(y,x,1),val)
1,079
def blackman(M): """blackman(M) returns 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,080
def bartlett(M): """bartlett(M) returns 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,081
def hanning(M): """hanning(M) returns 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,082
def hamming(M): """hamming(M) returns 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,083
def kaiser(M,beta): """kaiser(M, beta) returns a Kaiser window of length M with shape parameter beta. It depends on the cephes module for the modified bessel function i0. """ 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,084
def configuration(parent_package=''): package = 'linalg' from interface_gen import generate_interface config = default_config_dict(package,parent_package) local_path = get_path(__name__) atlas_info = get_info('atlas') #atlas_info = {} # uncomment if ATLAS is available but want to use # Fortran LAPACK/BLAS; useful for testing f_libs = [] blas_info,lapack_info = {},{} if not atlas_info: warnings.warn(AtlasNotFoundError.__doc__) blas_info = get_info('blas') #blas_info = {} # test building BLAS from sources. if not blas_info: warnings.warn(BlasNotFoundError.__doc__) blas_src_info = get_info('blas_src') if not blas_src_info: raise BlasSrcNotFoundError,BlasSrcNotFoundError.__doc__ dict_append(blas_info,libraries=['blas_src']) f_libs.append(fortran_library_item(\ 'blas_src',blas_src_info['sources'], )) lapack_info = get_info('lapack') #lapack_info = {} # test building LAPACK from sources. if not lapack_info: warnings.warn(LapackNotFoundError.__doc__) lapack_src_info = get_info('lapack_src') if not lapack_src_info: raise LapackSrcNotFoundError,LapackSrcNotFoundError.__doc__ dict_append(lapack_info,libraries=['lapack_src']) f_libs.append(fortran_library_item(\ 'lapack_src',lapack_src_info['sources'], )) mod_sources = {} if atlas_info or blas_info: mod_sources['fblas'] = ['generic_fblas.pyf', 'generic_fblas1.pyf', 'generic_fblas2.pyf', 'generic_fblas3.pyf', os.path.join('src','fblaswrap.f'), ] if atlas_info or lapack_info: mod_sources['flapack'] = ['generic_flapack.pyf'] if atlas_info: mod_sources['cblas'] = ['generic_cblas.pyf', 'generic_cblas1.pyf'] mod_sources['clapack'] = ['generic_clapack.pyf'] else: dict_append(atlas_info,**lapack_info) dict_append(atlas_info,**blas_info) skip_names = {'clapack':[],'flapack':[],'cblas':[],'fblas':[]} if skip_single_routines: skip_names['clapack'].extend(\ 'sgesv cgesv sgetrf cgetrf sgetrs cgetrs sgetri cgetri'\ ' sposv cposv spotrf cpotrf spotrs cpotrs spotri cpotri'\ ' slauum clauum strtri ctrtri'.split()) skip_names['flapack'].extend(skip_names['clapack']) skip_names['flapack'].extend(\ 'sgesdd cgesdd sgelss cgelss sgeqrf cgeqrf sgeev cgeev'\ ' sgegv cgegv ssyev cheev slaswp claswp sgees cgees' ' sggev cggev'.split()) skip_names['cblas'].extend('saxpy caxpy'.split()) skip_names['fblas'].extend(skip_names['cblas']) skip_names['fblas'].extend(\ 'srotg crotg srotmg srot csrot srotm sswap cswap sscal cscal'\ 'csscal scopy ccopy sdot cdotu cdotc snrm2 scnrm2 sasum scasum'\ 'samax camax sgemv cgemv chemv ssymv strmv ctrmv sgemm cgemm'.split()) if atlas_version_pre_3_3: skip_names['clapack'].extend(\ 'sgetri dgetri cgetri zgetri spotri dpotri cpotri zpotri'\ ' slauum dlauum clauum zlauum strtri dtrtri ctrtri ztrtri'.split()) 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, skip_names.get(mod_name,[])) sources = filter(lambda s:s[-4:]!='.pyf',sources) ext_args = {'name':dot_join(parent_package,package,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,package,'_flinalg'), 'sources':flinalg} dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) ext_args = {'name':dot_join(parent_package,package,'calc_lwork'), 'sources':[os.path.join(local_path,'src','calc_lwork.f')], } dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) config['fortran_libraries'].extend(f_libs) return config
def configuration(parent_package=''): package = 'linalg' from interface_gen import generate_interface config = default_config_dict(package,parent_package) local_path = get_path(__name__) atlas_info = get_info('atlas') #atlas_info = {} # uncomment if ATLAS is available but want to use # Fortran LAPACK/BLAS; useful for testing f_libs = [] blas_info,lapack_info = {},{} if not atlas_info: warnings.warn(AtlasNotFoundError.__doc__) blas_info = get_info('blas') #blas_info = {} # test building BLAS from sources. if not blas_info: warnings.warn(BlasNotFoundError.__doc__) blas_src_info = get_info('blas_src') if not blas_src_info: raise BlasSrcNotFoundError,BlasSrcNotFoundError.__doc__ dict_append(blas_info,libraries=['blas_src']) f_libs.append(fortran_library_item(\ 'blas_src',blas_src_info['sources'], )) lapack_info = get_info('lapack') #lapack_info = {} # test building LAPACK from sources. if not lapack_info: warnings.warn(LapackNotFoundError.__doc__) lapack_src_info = get_info('lapack_src') if not lapack_src_info: raise LapackSrcNotFoundError,LapackSrcNotFoundError.__doc__ dict_append(lapack_info,libraries=['lapack_src']) f_libs.append(fortran_library_item(\ 'lapack_src',lapack_src_info['sources'], )) mod_sources = {} if atlas_info or blas_info: mod_sources['fblas'] = ['generic_fblas.pyf', 'generic_fblas1.pyf', 'generic_fblas2.pyf', 'generic_fblas3.pyf', os.path.join('src','fblaswrap.f'), ] if atlas_info or lapack_info: mod_sources['flapack'] = ['generic_flapack.pyf'] if atlas_info: mod_sources['cblas'] = ['generic_cblas.pyf', 'generic_cblas1.pyf'] mod_sources['clapack'] = ['generic_clapack.pyf'] else: dict_append(atlas_info,**lapack_info) dict_append(atlas_info,**blas_info) skip_names = {'clapack':[],'flapack':[],'cblas':[],'fblas':[]} if skip_single_routines: skip_names['clapack'].extend(\ 'sgesv cgesv sgetrf cgetrf sgetrs cgetrs sgetri cgetri'\ ' sposv cposv spotrf cpotrf spotrs cpotrs spotri cpotri'\ ' slauum clauum strtri ctrtri'.split()) skip_names['flapack'].extend(skip_names['clapack']) skip_names['flapack'].extend(\ 'sgesdd cgesdd sgelss cgelss sgeqrf cgeqrf sgeev cgeev'\ ' sgegv cgegv ssyev cheev slaswp claswp sgees cgees' ' sggev cggev'.split()) skip_names['cblas'].extend('saxpy caxpy'.split()) skip_names['fblas'].extend(skip_names['cblas']) skip_names['fblas'].extend(\ 'srotg crotg srotmg srot csrot srotm sswap cswap sscal cscal'\ ' csscal scopy ccopy sdot cdotu cdotc snrm2 scnrm2 sasum scasum'\ ' isamax icamax sgemv cgemv chemv ssymv strmv ctrmv'\ ' sgemm cgemm'.split()) if atlas_version_pre_3_3: skip_names['clapack'].extend(\ 'sgetri dgetri cgetri zgetri spotri dpotri cpotri zpotri'\ ' slauum dlauum clauum zlauum strtri dtrtri ctrtri ztrtri'.split()) 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, skip_names.get(mod_name,[])) sources = filter(lambda s:s[-4:]!='.pyf',sources) ext_args = {'name':dot_join(parent_package,package,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,package,'_flinalg'), 'sources':flinalg} dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) ext_args = {'name':dot_join(parent_package,package,'calc_lwork'), 'sources':[os.path.join(local_path,'src','calc_lwork.f')], } dict_append(ext_args,**atlas_info) config['ext_modules'].append(Extension(**ext_args)) config['fortran_libraries'].extend(f_libs) return config
1,085
def mmwrite(target,a,comment='',field=None,precision=None): """ Writes the sparse or dense matrix A to a Matrix Market formatted file. Inputs: target - Matrix Market filename (extension .mtx) or open file object a - sparse or full matrix comment - comments to be prepended to the Matrix Market file field - 'real' | 'complex' | 'pattern' | 'integer' precision - Number of digits to display for real or complex values. """ close_it = 0 if type(target) is type(''): if target[-4:] != '.mtx': target = target + '.mtx' target = open(target,'w') close_it = 1 if type(a) in [ListType,ArrayType,TupleType] or hasattr(a,'__array__'): rep = 'array' a = asarray(a) if len(a.shape) != 2: raise ValueError, 'expected matrix' rows,cols = a.shape entires = rows*cols typecode = a.typecode() if field is not None: if field=='integer': a = a.astype('i') elif field=='real': if typecode not in 'fd': a = a.astype('d') elif field=='complex': if typecode not in 'FD': a = a.astype('D') elif field=='pattern': pass else: raise ValueError,'unknown field '+field typecode = a.typecode() else: rep = 'coordinate' from scipy.sparse import spmatrix if not isinstance(a,spmatrix): raise ValueError,'unknown matrix type ' + `type(a)` rows,cols = a.shape entries = a.getnnz() typecode = a.gettypecode() if precision is None: if typecode in 'fF': precision = 8 else: precision = 16 if field is None: if typecode in 'li': field = 'integer' elif typecode in 'df': field = 'real' elif typecode in 'DF': field = 'complex' else: raise TypeError,'unexpected typecode '+typecode if rep == 'array': symm = _get_symmetry(a) else: symm = 'general' target.write('%%%%MatrixMarket matrix %s %s %s\n' % (rep,field,symm)) for line in comment.split('\n'): target.write('%%%s\n' % (line)) if field in ['real','integer']: if field=='real': format = '%%.%ie\n' % precision else: format = '%i\n' elif field=='complex': format = '%%.%ie %%.%ie\n' % (precision,precision) if rep == 'array': target.write('%i %i\n' % (rows,cols)) if field in ['real','integer']: if symm=='general': for j in range(cols): for i in range(rows): target.write(format % a[i,j]) else: for j in range(cols): for i in range(j,rows): target.write(format % a[i,j]) elif field=='complex': if symm=='general': for j in range(cols): for i in range(rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) else: for j in range(cols): for i in range(j,rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) elif field=='pattern': raise ValueError,'Pattern type inconsisted with dense matrix' else: raise TypeError,'Unknown matrix type '+`field` else: format = '%i %i ' + format target.write('%i %i %i\n' % (rows,cols,entires)) assert symm=='general',`symm` if field in ['real','integer']: for i in range(entries): target.write(format % (a.rowcol(i)+(a.getdata(i),))) elif field=='complex': for i in range(entries): value = a.getdata(i) target.write(format % ((a.rowcol(i))+(real(value),imag(value)))) elif field=='pattern': raise NotImplementedError,`field` else: raise TypeError,'Unknown matrix type '+`field` if close_it: target.close() else: target.flush() return
def mmwrite(target,a,comment='',field=None,precision=None): """ Writes the sparse or dense matrix A to a Matrix Market formatted file. Inputs: target - Matrix Market filename (extension .mtx) or open file object a - sparse or full matrix comment - comments to be prepended to the Matrix Market file field - 'real' | 'complex' | 'pattern' | 'integer' precision - Number of digits to display for real or complex values. """ close_it = 0 if type(target) is type(''): if target[-4:] != '.mtx': target = target + '.mtx' target = open(target,'w') close_it = 1 if type(a) in [ListType,ArrayType,TupleType] or hasattr(a,'__array__'): rep = 'array' a = asarray(a) if len(a.shape) != 2: raise ValueError, 'expected matrix' rows,cols = a.shape entries = rows*cols typecode = a.typecode() if field is not None: if field=='integer': a = a.astype('i') elif field=='real': if typecode not in 'fd': a = a.astype('d') elif field=='complex': if typecode not in 'FD': a = a.astype('D') elif field=='pattern': pass else: raise ValueError,'unknown field '+field typecode = a.typecode() else: rep = 'coordinate' from scipy.sparse import spmatrix if not isinstance(a,spmatrix): raise ValueError,'unknown matrix type ' + `type(a)` rows,cols = a.shape entries = a.getnnz() typecode = a.gettypecode() if precision is None: if typecode in 'fF': precision = 8 else: precision = 16 if field is None: if typecode in 'li': field = 'integer' elif typecode in 'df': field = 'real' elif typecode in 'DF': field = 'complex' else: raise TypeError,'unexpected typecode '+typecode if rep == 'array': symm = _get_symmetry(a) else: symm = 'general' target.write('%%%%MatrixMarket matrix %s %s %s\n' % (rep,field,symm)) for line in comment.split('\n'): target.write('%%%s\n' % (line)) if field in ['real','integer']: if field=='real': format = '%%.%ie\n' % precision else: format = '%i\n' elif field=='complex': format = '%%.%ie %%.%ie\n' % (precision,precision) if rep == 'array': target.write('%i %i\n' % (rows,cols)) if field in ['real','integer']: if symm=='general': for j in range(cols): for i in range(rows): target.write(format % a[i,j]) else: for j in range(cols): for i in range(j,rows): target.write(format % a[i,j]) elif field=='complex': if symm=='general': for j in range(cols): for i in range(rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) else: for j in range(cols): for i in range(j,rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) elif field=='pattern': raise ValueError,'Pattern type inconsisted with dense matrix' else: raise TypeError,'Unknown matrix type '+`field` else: format = '%i %i ' + format target.write('%i %i %i\n' % (rows,cols,entires)) assert symm=='general',`symm` if field in ['real','integer']: for i in range(entries): target.write(format % (a.rowcol(i)+(a.getdata(i),))) elif field=='complex': for i in range(entries): value = a.getdata(i) target.write(format % ((a.rowcol(i))+(real(value),imag(value)))) elif field=='pattern': raise NotImplementedError,`field` else: raise TypeError,'Unknown matrix type '+`field` if close_it: target.close() else: target.flush() return
1,086
def mmwrite(target,a,comment='',field=None,precision=None): """ Writes the sparse or dense matrix A to a Matrix Market formatted file. Inputs: target - Matrix Market filename (extension .mtx) or open file object a - sparse or full matrix comment - comments to be prepended to the Matrix Market file field - 'real' | 'complex' | 'pattern' | 'integer' precision - Number of digits to display for real or complex values. """ close_it = 0 if type(target) is type(''): if target[-4:] != '.mtx': target = target + '.mtx' target = open(target,'w') close_it = 1 if type(a) in [ListType,ArrayType,TupleType] or hasattr(a,'__array__'): rep = 'array' a = asarray(a) if len(a.shape) != 2: raise ValueError, 'expected matrix' rows,cols = a.shape entires = rows*cols typecode = a.typecode() if field is not None: if field=='integer': a = a.astype('i') elif field=='real': if typecode not in 'fd': a = a.astype('d') elif field=='complex': if typecode not in 'FD': a = a.astype('D') elif field=='pattern': pass else: raise ValueError,'unknown field '+field typecode = a.typecode() else: rep = 'coordinate' from scipy.sparse import spmatrix if not isinstance(a,spmatrix): raise ValueError,'unknown matrix type ' + `type(a)` rows,cols = a.shape entries = a.getnnz() typecode = a.gettypecode() if precision is None: if typecode in 'fF': precision = 8 else: precision = 16 if field is None: if typecode in 'li': field = 'integer' elif typecode in 'df': field = 'real' elif typecode in 'DF': field = 'complex' else: raise TypeError,'unexpected typecode '+typecode if rep == 'array': symm = _get_symmetry(a) else: symm = 'general' target.write('%%%%MatrixMarket matrix %s %s %s\n' % (rep,field,symm)) for line in comment.split('\n'): target.write('%%%s\n' % (line)) if field in ['real','integer']: if field=='real': format = '%%.%ie\n' % precision else: format = '%i\n' elif field=='complex': format = '%%.%ie %%.%ie\n' % (precision,precision) if rep == 'array': target.write('%i %i\n' % (rows,cols)) if field in ['real','integer']: if symm=='general': for j in range(cols): for i in range(rows): target.write(format % a[i,j]) else: for j in range(cols): for i in range(j,rows): target.write(format % a[i,j]) elif field=='complex': if symm=='general': for j in range(cols): for i in range(rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) else: for j in range(cols): for i in range(j,rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) elif field=='pattern': raise ValueError,'Pattern type inconsisted with dense matrix' else: raise TypeError,'Unknown matrix type '+`field` else: format = '%i %i ' + format target.write('%i %i %i\n' % (rows,cols,entires)) assert symm=='general',`symm` if field in ['real','integer']: for i in range(entries): target.write(format % (a.rowcol(i)+(a.getdata(i),))) elif field=='complex': for i in range(entries): value = a.getdata(i) target.write(format % ((a.rowcol(i))+(real(value),imag(value)))) elif field=='pattern': raise NotImplementedError,`field` else: raise TypeError,'Unknown matrix type '+`field` if close_it: target.close() else: target.flush() return
def mmwrite(target,a,comment='',field=None,precision=None): """ Writes the sparse or dense matrix A to a Matrix Market formatted file. Inputs: target - Matrix Market filename (extension .mtx) or open file object a - sparse or full matrix comment - comments to be prepended to the Matrix Market file field - 'real' | 'complex' | 'pattern' | 'integer' precision - Number of digits to display for real or complex values. """ close_it = 0 if type(target) is type(''): if target[-4:] != '.mtx': target = target + '.mtx' target = open(target,'w') close_it = 1 if type(a) in [ListType,ArrayType,TupleType] or hasattr(a,'__array__'): rep = 'array' a = asarray(a) if len(a.shape) != 2: raise ValueError, 'expected matrix' rows,cols = a.shape entires = rows*cols typecode = a.typecode() if field is not None: if field=='integer': a = a.astype('i') elif field=='real': if typecode not in 'fd': a = a.astype('d') elif field=='complex': if typecode not in 'FD': a = a.astype('D') elif field=='pattern': pass else: raise ValueError,'unknown field '+field typecode = a.typecode() else: rep = 'coordinate' from scipy.sparse import spmatrix if not isinstance(a,spmatrix): raise ValueError,'unknown matrix type ' + `type(a)` rows,cols = a.shape entries = a.getnnz() typecode = a.gettypecode() if precision is None: if typecode in 'fF': precision = 8 else: precision = 16 if field is None: if typecode in 'li': field = 'integer' elif typecode in 'df': field = 'real' elif typecode in 'DF': field = 'complex' else: raise TypeError,'unexpected typecode '+typecode if rep == 'array': symm = _get_symmetry(a) else: symm = 'general' target.write('%%%%MatrixMarket matrix %s %s %s\n' % (rep,field,symm)) for line in comment.split('\n'): target.write('%%%s\n' % (line)) if field in ['real','integer']: if field=='real': format = '%%.%ie\n' % precision else: format = '%i\n' elif field=='complex': format = '%%.%ie %%.%ie\n' % (precision,precision) if rep == 'array': target.write('%i %i\n' % (rows,cols)) if field in ['real','integer']: if symm=='general': for j in range(cols): for i in range(rows): target.write(format % a[i,j]) else: for j in range(cols): for i in range(j,rows): target.write(format % a[i,j]) elif field=='complex': if symm=='general': for j in range(cols): for i in range(rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) else: for j in range(cols): for i in range(j,rows): aij = a[i,j] target.write(format % (real(aij),imag(aij))) elif field=='pattern': raise ValueError,'Pattern type inconsisted with dense matrix' else: raise TypeError,'Unknown matrix type '+`field` else: format = '%i %i ' + format target.write('%i %i %i\n' % (rows,cols,entries)) assert symm=='general',`symm` if field in ['real','integer']: for i in range(entries): target.write(format % (a.rowcol(i)+(a.getdata(i),))) elif field=='complex': for i in range(entries): value = a.getdata(i) target.write(format % ((a.rowcol(i))+(real(value),imag(value)))) elif field=='pattern': raise NotImplementedError,`field` else: raise TypeError,'Unknown matrix type '+`field` if close_it: target.close() else: target.flush() return
1,087
def resize1d(arr, newlen): old = len(arr) new = zeros((newlen,), arr.dtype.char) new[:old] = arr return new
def resize1d(arr, newlen): old = len(arr) new = zeros((newlen,), arr.dtype) new[:old] = arr return new
1,088
def __repr__(self): format = self.getformat() return "<%dx%d sparse matrix of type '%s'\n\twith %d stored "\ "elements (space for %d)\n\tin %s format>" % \ (self.shape + (self.dtype.char, self.getnnz(), self.nzmax, \ _formats[format][1]))
def __repr__(self): format = self.getformat() return "<%dx%d sparse matrix of type '%s'\n\twith %d stored "\ "elements (space for %d)\n\tin %s format>" % \ (self.shape + (self.dtype.type, self.getnnz(), self.nzmax, \ _formats[format][1]))
1,089
def _real(self): csc = self.tocsc() csc.data = real(csc.data) csc.dtype.char = csc.data.dtype.char csc.ftype = _transtabl[csc.dtype.char] return csc
def _real(self): csc = self.tocsc() csc.data = real(csc.data) csc.dtype = csc.data.dtype csc.ftype = _transtabl[csc.dtype.char] return csc
1,090
def _imag(self): csc = self.tocsc() csc.data = imag(csc.data) csc.dtype.char = csc.data.dtype.char csc.ftype = _transtabl[csc.dtype.char] return csc
def _imag(self): csc = self.tocsc() csc.data = imag(csc.data) csc.dtype = csc.data.dtype csc.ftype = _transtabl[csc.dtype.char] return csc
1,091
def _check(self): M, N = self.shape nnz = self.indptr[-1] nzmax = len(self.rowind)
def _check(self): M, N = self.shape nnz = self.indptr[-1] nzmax = len(self.rowind)
1,092
def _check(self): M, N = self.shape nnz = self.indptr[-1] nzmax = len(self.rowind)
def _check(self): M, N = self.shape nnz = self.indptr[-1] nzmax = len(self.rowind)
1,093
def __mul__(self, other): """ Scalar, vector, or matrix multiplication """ if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data *= other new.dtype.char = new.data.dtype.char new.ftype = _transtabl[new.dtype.char] return new else: return self.dot(other) #else: # return TypeError, "unknown type for sparse matrix multiplication"
def __mul__(self, other): """ Scalar, vector, or matrix multiplication """ if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data *= other new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: return self.dot(other) #else: # return TypeError, "unknown type for sparse matrix multiplication"
1,094
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = other * new.data new.dtype.char = new.data.dtype.char new.ftype = _transtabl[new.dtype.char] return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = other * new.data new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
1,095
def __pow__(self, other): """ Element-by-element power (unless other is a scalar, in which case return the matrix power.) """ if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = new.data ** other new.dtype.char = new.data.dtype.char new.ftype = _transtabl[new.dtype.char] return new else: ocs = other.tocsc() if (ocs.shape != self.shape): raise ValueError, "inconsistent shapes" dtypechar = _coerce_rules[(self.dtype.char, ocs.dtype.char)] nnz1, nnz2 = self.nnz, ocs.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools, _transtabl[dtypechar]+'cscmul') c, rowc, ptrc, ierr = func(data1, self.rowind[:nnz1], self.indptr, data2, ocs.rowind[:nnz2], ocs.indptr) if ierr: raise ValueError, "ran out of space (but shouldn't have happened)" M, N = self.shape return csc_matrix((c, rowc, ptrc), dims=(M, N))
def __pow__(self, other): """ Element-by-element power (unless other is a scalar, in which case return the matrix power.) """ if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = new.data ** other new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: ocs = other.tocsc() if (ocs.shape != self.shape): raise ValueError, "inconsistent shapes" dtypechar = _coerce_rules[(self.dtype.char, ocs.dtype.char)] nnz1, nnz2 = self.nnz, ocs.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools, _transtabl[dtypechar]+'cscmul') c, rowc, ptrc, ierr = func(data1, self.rowind[:nnz1], self.indptr, data2, ocs.rowind[:nnz2], ocs.indptr) if ierr: raise ValueError, "ran out of space (but shouldn't have happened)" M, N = self.shape return csc_matrix((c, rowc, ptrc), dims=(M, N))
1,096
def transpose(self, copy=False): M, N = self.shape new = csr_matrix((N, M), nzmax=self.nzmax, dtype=self.dtype.char) if copy: new.data = self.data.copy() new.colind = self.rowind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.colind = self.rowind new.indptr = self.indptr new._check() return new
def transpose(self, copy=False): M, N = self.shape new = csr_matrix((N, M), nzmax=self.nzmax, dtype=self.dtype) if copy: new.data = self.data.copy() new.colind = self.rowind.copy() new.indptr = self.indptr.copy() else: new.data = self.data new.colind = self.rowind new.indptr = self.indptr new._check() return new
1,097
def conj(self, copy=False): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtype.char) if copy: new.data = self.data.conj().copy() new.rowind = self.rowind.conj().copy() new.indptr = self.indptr.conj().copy() else: new.data = self.data.conj() new.rowind = self.rowind.conj() new.indptr = self.indptr.conj() new._check() return new
def conj(self, copy=False): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtype) if copy: new.data = self.data.conj().copy() new.rowind = self.rowind.conj().copy() new.indptr = self.indptr.conj().copy() else: new.data = self.data.conj() new.rowind = self.rowind.conj() new.indptr = self.indptr.conj() new._check() return new
1,098
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtype.char) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtype) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
1,099