bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
def wiener(im,mysize=None,noise=None): """Perform a Wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
1,200
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a Wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
1,201
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,ones(mysize),1) / product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
1,202
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,ones(mysize),1) / product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
1,203
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(ravel(lVar)) res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res) return out
1,204
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = size(a)-1 M = size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
1,205
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
1,206
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
1,207
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
1,208
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= Numeric.sum(a[m+1:]*y[:N-m]) return zi
def lfiltic(b,a,y,x=None): """Given a linear filter (b,a) and initial conditions on the output y and the input x, return the inital conditions on the state vector zi which is used by lfilter to generate the output given the input. If M=len(b)-1 and N=len(a)-1. Then, the initial conditions are given in the vectors x and y as x = {x[-1],x[-2],...,x[-M]} y = {y[-1],y[-2],...,y[-N]} If x is not given, its inital conditions are assumed zero. If either vector is too short, then zeros are added to achieve the proper length. The output vector zi contains zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]} where K=max(M,N). """ N = Numeric.size(a)-1 M = Numeric.size(b)-1 K = max(M,N) y = asarray(y) zi = zeros(K,y.dtype.char) if x is None: x = zeros(M,y.dtype.char) else: x = asarray(x) L = Numeric.size(x) if L < M: x = r_[x,zeros(M-L)] L = Numeric.size(y) if L < N: y = r_[y,zeros(N-L)] for m in range(M): zi[m] = Numeric.sum(b[m+1:]*x[:M-m]) for m in range(N): zi[m] -= sum(a[m+1:]*y[:N-m]) return zi
1,209
def boxcar(M,sym=1): """The M-point boxcar window. """ return Numeric.ones(M,Numeric.Float)
def boxcar(M,sym=1): """The M-point boxcar window. """ return ones(M, float)
1,210
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = numpy.r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = numpy.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = numpy.r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = numpy.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
1,211
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = numpy.r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = numpy.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = numpy.r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = numpy.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
1,212
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = numpy.r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = numpy.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = numpy.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
1,213
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = numpy.r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = numpy.r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
def triang(M,sym=1): """The M-point triangular window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(1,int((M+1)/2)+1) if M % 2 == 0: w = (2*n-1.0)/M w = numpy.r_[w, w[::-1]] else: w = 2*n/(M+1.0) w = r_[w, w[-2::-1]] if not sym and not odd: w = w[:-1] return w
1,214
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = Numeric.arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = numpy.r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = Numeric.arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = numpy.r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
1,215
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = Numeric.arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = numpy.r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = Numeric.arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = numpy.r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
1,216
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = Numeric.arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = numpy.r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = numpy.r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
1,217
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = Numeric.arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = numpy.r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
def parzen(M,sym=1): """The M-point Parzen window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = Numeric.arange(-(M-1)/2.0,(M-1)/2.0+0.5,1.0) na = extract(n < -(M-1)/4.0, n) nb = extract(abs(n) <= (M-1)/4.0, n) wa = 2*(1-abs(na)/(M/2.0))**3.0 wb = 1-6*(abs(nb)/(M/2.0))**2.0 + 6*(abs(nb)/(M/2.0))**3.0 w = r_[wa,wb,wa[::-1]] if not sym and not odd: w = w[:-1] return w
1,218
def bohman(M,sym=1): """The M-point Bohman window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 fac = abs(linspace(-1,1,M)[1:-1]) w = (1 - fac)* cos(pi*fac) + 1.0/pi*sin(pi*fac) w = numpy.r_[0,w,0] if not sym and not odd: w = w[:-1] return w
def bohman(M,sym=1): """The M-point Bohman window """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 fac = abs(linspace(-1,1,M)[1:-1]) w = (1 - fac)* cos(pi*fac) + 1.0/pi*sin(pi*fac) w = numpy.r_[0,w,0] if not sym and not odd: w = w[:-1] return w
1,219
def bohman(M,sym=1): """The M-point Bohman window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 fac = abs(linspace(-1,1,M)[1:-1]) w = (1 - fac)* cos(pi*fac) + 1.0/pi*sin(pi*fac) w = numpy.r_[0,w,0] if not sym and not odd: w = w[:-1] return w
def bohman(M,sym=1): """The M-point Bohman window """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 fac = abs(linspace(-1,1,M)[1:-1]) w = (1 - fac)* cos(pi*fac) + 1.0/pi*sin(pi*fac) w = numpy.r_[0,w,0] if not sym and not odd: w = w[:-1] return w
1,220
def bohman(M,sym=1): """The M-point Bohman window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 fac = abs(linspace(-1,1,M)[1:-1]) w = (1 - fac)* cos(pi*fac) + 1.0/pi*sin(pi*fac) w = numpy.r_[0,w,0] if not sym and not odd: w = w[:-1] return w
def bohman(M,sym=1): """The M-point Bohman window """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 fac = abs(linspace(-1,1,M)[1:-1]) w = (1 - fac)* cos(pi*fac) + 1.0/pi*sin(pi*fac) w = r_[0,w,0] if not sym and not odd: w = w[:-1] return w
1,221
def blackman(M,sym=1): """The M-point Blackman window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def blackman(M,sym=1): """The M-point Blackman window. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,222
def blackman(M,sym=1): """The M-point Blackman window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def blackman(M,sym=1): """The M-point Blackman window. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,223
def nuttall(M,sym=1): """A minimum 4-term Blackman-Harris window according to Nuttall. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.3635819, 0.4891775, 0.1365995, 0.0106411] n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
def nuttall(M,sym=1): """A minimum 4-term Blackman-Harris window according to Nuttall. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.3635819, 0.4891775, 0.1365995, 0.0106411] n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
1,224
def nuttall(M,sym=1): """A minimum 4-term Blackman-Harris window according to Nuttall. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.3635819, 0.4891775, 0.1365995, 0.0106411] n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
def nuttall(M,sym=1): """A minimum 4-term Blackman-Harris window according to Nuttall. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.3635819, 0.4891775, 0.1365995, 0.0106411] n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
1,225
def blackmanharris(M,sym=1): """The M-point minimum 4-term Blackman-Harris window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.35875, 0.48829, 0.14128, 0.01168]; n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
def blackmanharris(M,sym=1): """The M-point minimum 4-term Blackman-Harris window. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.35875, 0.48829, 0.14128, 0.01168]; n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
1,226
def blackmanharris(M,sym=1): """The M-point minimum 4-term Blackman-Harris window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.35875, 0.48829, 0.14128, 0.01168]; n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
def blackmanharris(M,sym=1): """The M-point minimum 4-term Blackman-Harris window. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 a = [0.35875, 0.48829, 0.14128, 0.01168]; n = arange(0,M) fac = n*2*pi/(M-1.0) w = a[0] - a[1]*cos(fac) + a[2]*cos(2*fac) - a[3]*cos(3*fac) if not sym and not odd: w = w[:-1] return w
1,227
def bartlett(M,sym=1): """The M-point Bartlett window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = where(Numeric.less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def bartlett(M,sym=1): """The M-point Bartlett window. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = where(Numeric.less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,228
def bartlett(M,sym=1): """The M-point Bartlett window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = where(Numeric.less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def bartlett(M,sym=1): """The M-point Bartlett window. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = where(Numeric.less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,229
def bartlett(M,sym=1): """The M-point Bartlett window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = where(Numeric.less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def bartlett(M,sym=1): """The M-point Bartlett window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = where(less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,230
def hanning(M,sym=1): """The M-point Hanning window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.5-0.5*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def hanning(M,sym=1): """The M-point Hanning window. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.5-0.5*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,231
def hanning(M,sym=1): """The M-point Hanning window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.5-0.5*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def hanning(M,sym=1): """The M-point Hanning window. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.5-0.5*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,232
def barthann(M,sym=1): """Return the M-point modified Bartlett-Hann window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) fac = abs(n/(M-1.0)-0.5) w = 0.62 - 0.48*fac + 0.38*cos(2*pi*fac) if not sym and not odd: w = w[:-1] return w
def barthann(M,sym=1): """Return the M-point modified Bartlett-Hann window. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) fac = abs(n/(M-1.0)-0.5) w = 0.62 - 0.48*fac + 0.38*cos(2*pi*fac) if not sym and not odd: w = w[:-1] return w
1,233
def barthann(M,sym=1): """Return the M-point modified Bartlett-Hann window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) fac = abs(n/(M-1.0)-0.5) w = 0.62 - 0.48*fac + 0.38*cos(2*pi*fac) if not sym and not odd: w = w[:-1] return w
def barthann(M,sym=1): """Return the M-point modified Bartlett-Hann window. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) fac = abs(n/(M-1.0)-0.5) w = 0.62 - 0.48*fac + 0.38*cos(2*pi*fac) if not sym and not odd: w = w[:-1] return w
1,234
def hamming(M,sym=1): """The M-point Hamming window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.54-0.46*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def hamming(M,sym=1): """The M-point Hamming window. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.54-0.46*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,235
def hamming(M,sym=1): """The M-point Hamming window. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.54-0.46*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
def hamming(M,sym=1): """The M-point Hamming window. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) w = 0.54-0.46*cos(2.0*pi*n/(M-1)) if not sym and not odd: w = w[:-1] return w
1,236
def kaiser(M,beta,sym=1): """Returns a Kaiser window of length M with shape parameter beta. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) alpha = (M-1)/2.0 w = special.i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/special.i0(beta) if not sym and not odd: w = w[:-1] return w
def kaiser(M,beta,sym=1): """Returns a Kaiser window of length M with shape parameter beta. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) alpha = (M-1)/2.0 w = special.i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/special.i0(beta) if not sym and not odd: w = w[:-1] return w
1,237
def kaiser(M,beta,sym=1): """Returns a Kaiser window of length M with shape parameter beta. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) alpha = (M-1)/2.0 w = special.i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/special.i0(beta) if not sym and not odd: w = w[:-1] return w
def kaiser(M,beta,sym=1): """Returns a Kaiser window of length M with shape parameter beta. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M) alpha = (M-1)/2.0 w = special.i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/special.i0(beta) if not sym and not odd: w = w[:-1] return w
1,238
def gaussian(M,std,sym=1): """Returns a Gaussian window of length M with standard-deviation std. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(0,M)-(M-1.0)/2.0 sig2 = 2*std*std w = exp(-n**2 / sig2) if not sym and not odd: w = w[:-1] return w
def gaussian(M,std,sym=1): """Returns a Gaussian window of length M with standard-deviation std. """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(0,M)-(M-1.0)/2.0 sig2 = 2*std*std w = exp(-n**2 / sig2) if not sym and not odd: w = w[:-1] return w
1,239
def gaussian(M,std,sym=1): """Returns a Gaussian window of length M with standard-deviation std. """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(0,M)-(M-1.0)/2.0 sig2 = 2*std*std w = exp(-n**2 / sig2) if not sym and not odd: w = w[:-1] return w
def gaussian(M,std,sym=1): """Returns a Gaussian window of length M with standard-deviation std. """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M + 1 n = arange(0,M)-(M-1.0)/2.0 sig2 = 2*std*std w = exp(-n**2 / sig2) if not sym and not odd: w = w[:-1] return w
1,240
def general_gaussian(M,p,sig,sym=1): """Returns a window with a generalized Gaussian shape. exp(-0.5*(x/sig)**(2*p)) half power point is at (2*log(2)))**(1/(2*p))*sig """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M)-(M-1.0)/2.0 w = exp(-0.5*(n/sig)**(2*p)) if not sym and not odd: w = w[:-1] return w
def general_gaussian(M,p,sig,sym=1): """Returns a window with a generalized Gaussian shape. exp(-0.5*(x/sig)**(2*p)) half power point is at (2*log(2)))**(1/(2*p))*sig """ if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M)-(M-1.0)/2.0 w = exp(-0.5*(n/sig)**(2*p)) if not sym and not odd: w = w[:-1] return w
1,241
def general_gaussian(M,p,sig,sym=1): """Returns a window with a generalized Gaussian shape. exp(-0.5*(x/sig)**(2*p)) half power point is at (2*log(2)))**(1/(2*p))*sig """ if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M)-(M-1.0)/2.0 w = exp(-0.5*(n/sig)**(2*p)) if not sym and not odd: w = w[:-1] return w
def general_gaussian(M,p,sig,sym=1): """Returns a window with a generalized Gaussian shape. exp(-0.5*(x/sig)**(2*p)) half power point is at (2*log(2)))**(1/(2*p))*sig """ if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 n = arange(0,M)-(M-1.0)/2.0 w = exp(-0.5*(n/sig)**(2*p)) if not sym and not odd: w = w[:-1] return w
1,242
def slepian(M,width,sym=1): if (M*width > 27.38): raise ValueError, "Cannot reliably obtain slepian sequences for"\ " M*width > 27.38." if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 twoF = width/2.0 alpha = (M-1)/2.0 m = arange(0,M)-alpha n = m[:,NewAxis] k = m[NewAxis,:] AF = twoF*special.sinc(twoF*(n-k)) [lam,vec] = linalg.eig(AF) ind = argmax(abs(lam)) w = abs(vec[:,ind]) w = w / max(w) if not sym and not odd: w = w[:-1] return w
def slepian(M,width,sym=1): if (M*width > 27.38): raise ValueError, "Cannot reliably obtain slepian sequences for"\ " M*width > 27.38." if M < 1: return array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 twoF = width/2.0 alpha = (M-1)/2.0 m = arange(0,M)-alpha n = m[:,NewAxis] k = m[NewAxis,:] AF = twoF*special.sinc(twoF*(n-k)) [lam,vec] = linalg.eig(AF) ind = argmax(abs(lam)) w = abs(vec[:,ind]) w = w / max(w) if not sym and not odd: w = w[:-1] return w
1,243
def slepian(M,width,sym=1): if (M*width > 27.38): raise ValueError, "Cannot reliably obtain slepian sequences for"\ " M*width > 27.38." if M < 1: return Numeric.array([]) if M == 1: return Numeric.ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 twoF = width/2.0 alpha = (M-1)/2.0 m = arange(0,M)-alpha n = m[:,NewAxis] k = m[NewAxis,:] AF = twoF*special.sinc(twoF*(n-k)) [lam,vec] = linalg.eig(AF) ind = argmax(abs(lam)) w = abs(vec[:,ind]) w = w / max(w) if not sym and not odd: w = w[:-1] return w
def slepian(M,width,sym=1): if (M*width > 27.38): raise ValueError, "Cannot reliably obtain slepian sequences for"\ " M*width > 27.38." if M < 1: return Numeric.array([]) if M == 1: return ones(1,'d') odd = M % 2 if not sym and not odd: M = M+1 twoF = width/2.0 alpha = (M-1)/2.0 m = arange(0,M)-alpha n = m[:,NewAxis] k = m[NewAxis,:] AF = twoF*special.sinc(twoF*(n-k)) [lam,vec] = linalg.eig(AF) ind = argmax(abs(lam)) w = abs(vec[:,ind]) w = w / max(w) if not sym and not odd: w = w[:-1] return w
1,244
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) Xf = fft(x,N,axis=0) h = Numeric.zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:,Numeric.NewAxis] x = ifft(Xf*h) return x
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) Xf = fft(x,N,axis=0) h = Numeric.zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:,Numeric.NewAxis] x = ifft(Xf*h) return x
1,245
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) Xf = fft(x,N,axis=0) h = Numeric.zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:,Numeric.NewAxis] x = ifft(Xf*h) return x
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = real(x) Xf = fft(x,N,axis=0) h = Numeric.zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:,Numeric.NewAxis] x = ifft(Xf*h) return x
1,246
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) Xf = fft(x,N,axis=0) h = Numeric.zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:,Numeric.NewAxis] x = ifft(Xf*h) return x
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) Xf = fft(x,N,axis=0) h = zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:,Numeric.NewAxis] x = ifft(Xf*h) return x
1,247
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) Xf = fft(x,N,axis=0) h = Numeric.zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:,Numeric.NewAxis] x = ifft(Xf*h) return x
def hilbert(x, N=None): """Return the hilbert transform of x of length N. """ x = asarray(x) if N is None: N = len(x) if N <=0: raise ValueError, "N must be positive." if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) Xf = fft(x,N,axis=0) h = Numeric.zeros(N) if N % 2 == 0: h[0] = h[N/2] = 1 h[1:N/2] = 2 else: h[0] = 1 h[1:(N+1)/2] = 2 if len(x.shape) > 1: h = h[:, NewAxis] x = ifft(Xf*h) return x
1,248
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = Numeric.zeros(N[0],'d') h2 = Numeric.zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:,Numeric.NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = Numeric.zeros(N[0],'d') h2 = Numeric.zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:,Numeric.NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
1,249
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = Numeric.zeros(N[0],'d') h2 = Numeric.zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:,Numeric.NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = Numeric.zeros(N[0],'d') h2 = Numeric.zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:,Numeric.NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
1,250
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = Numeric.zeros(N[0],'d') h2 = Numeric.zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:,Numeric.NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = zeros(N[0],'d') h2 = zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:,Numeric.NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
1,251
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = Numeric.zeros(N[0],'d') h2 = Numeric.zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:,Numeric.NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
def hilbert2(x,N=None): """Return the '2-D' hilbert transform of x of length N. """ x = asarray(x) x = asarray(x) if N is None: N = x.shape if len(N) < 2: if N <=0: raise ValueError, "N must be positive." N = (N,N) if numpy.iscomplexobj(x): print "Warning: imaginary part of x ignored." x = numpy.real(x) print N Xf = fft2(x,N,axes=(0,1)) h1 = Numeric.zeros(N[0],'d') h2 = Numeric.zeros(N[1],'d') for p in range(2): h = eval("h%d"%(p+1)) N1 = N[p] if N1 % 2 == 0: h[0] = h[N1/2] = 1 h[1:N1/2] = 2 else: h[0] = 1 h[1:(N1+1)/2] = 2 exec("h%d = h" % (p+1), globals(), locals()) h = h1[:,NewAxis] * h2[NewAxis,:] k = len(x.shape) while k > 2: h = h[:, NewAxis] k -= 1 x = ifft2(Xf*h,axes=(0,1)) return x
1,252
def cmplx_sort(p): "sort roots based on magnitude." p = asarray(p) if numpy.iscomplexobj(p): indx = Numeric.argsort(abs(p)) else: indx = Numeric.argsort(p) return Numeric.take(p,indx), indx
def cmplx_sort(p): "sort roots based on magnitude." p = asarray(p) if iscomplexobj(p): indx = argsort(abs(p)) else: indx = Numeric.argsort(p) return Numeric.take(p,indx), indx
1,253
def cmplx_sort(p): "sort roots based on magnitude." p = asarray(p) if numpy.iscomplexobj(p): indx = Numeric.argsort(abs(p)) else: indx = Numeric.argsort(p) return Numeric.take(p,indx), indx
def cmplx_sort(p): "sort roots based on magnitude." p = asarray(p) if numpy.iscomplexobj(p): indx = Numeric.argsort(abs(p)) else: indx = argsort(p) return take(p,indx), indx
1,254
def unique_roots(p,tol=1e-3,rtype='min'): """Determine the unique roots and their multiplicities in two lists Inputs: p -- The list of roots tol --- The tolerance for two roots to be considered equal. rtype --- How to determine the returned root from the close ones: 'max': pick the maximum 'min': pick the minimum 'avg': average roots Outputs: (pout, mult) pout -- The list of sorted roots mult -- The multiplicity of each root """ if rtype in ['max','maximum']: comproot = numpy.maximum elif rtype in ['min','minimum']: comproot = numpy.minimum elif rtype in ['avg','mean']: comproot = numpy.mean p = asarray(p)*1.0 tol = abs(tol) p, indx = cmplx_sort(p) pout = [] mult = [] indx = -1 curp = p[0] + 5*tol sameroots = [] for k in range(len(p)): tr = p[k] if abs(tr-curp) < tol: sameroots.append(tr) curp = comproot(sameroots) pout[indx] = curp mult[indx] += 1 else: pout.append(tr) curp = tr sameroots = [tr] indx += 1 mult.append(1) return array(pout), array(mult)
def unique_roots(p,tol=1e-3,rtype='min'): """Determine the unique roots and their multiplicities in two lists Inputs: p -- The list of roots tol --- The tolerance for two roots to be considered equal. rtype --- How to determine the returned root from the close ones: 'max': pick the maximum 'min': pick the minimum 'avg': average roots Outputs: (pout, mult) pout -- The list of sorted roots mult -- The multiplicity of each root """ if rtype in ['max','maximum']: comproot = numpy.maximum elif rtype in ['min','minimum']: comproot = numpy.minimum elif rtype in ['avg','mean']: comproot = numpy.mean p = asarray(p)*1.0 tol = abs(tol) p, indx = cmplx_sort(p) pout = [] mult = [] indx = -1 curp = p[0] + 5*tol sameroots = [] for k in range(len(p)): tr = p[k] if abs(tr-curp) < tol: sameroots.append(tr) curp = comproot(sameroots) pout[indx] = curp mult[indx] += 1 else: pout.append(tr) curp = tr sameroots = [tr] indx += 1 mult.append(1) return array(pout), array(mult)
1,255
def invres(r,p,k,tol=1e-3,rtype='avg'): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval, unique_roots """ extra = k p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while Numeric.allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a
def invres(r,p,k,tol=1e-3,rtype='avg'): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval, unique_roots """ extra = k p, indx = cmplx_sort(p) r = take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while Numeric.allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a
1,256
def invres(r,p,k,tol=1e-3,rtype='avg'): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval, unique_roots """ extra = k p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while Numeric.allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a
def invres(r,p,k,tol=1e-3,rtype='avg'): """Compute b(s) and a(s) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1] H(s) = ------ = ---------------------------------------------- a(s) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1] r[0] r[1] r[-1] = -------- + -------- + ... + --------- + k(s) (s-p[0]) (s-p[1]) (s-p[-1]) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------- + ----------- + ... + ----------- (s-p[i]) (s-p[i])**2 (s-p[i])**n See also: residue, poly, polyval, unique_roots """ extra = k p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 for k in range(len(pout)): temp = [] for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) b = polyadd(b,r[indx]*poly(t2)) indx += 1 b = real_if_close(b) while allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1): b = b[1:] return b, a
1,257
def invresz(r,p,k,tol=1e-3,rtype='avg'): """Compute b(z) and a(z) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See also: residuez, poly, polyval, unique_roots """ extra = asarray(k) p, indx = cmplx_sort(p) r = Numeric.take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 brev = asarray(b)[::-1] for k in range(len(pout)): temp = [] # Construct polynomial which does not include any of this root for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) brev = polyadd(brev,(r[indx]*poly(t2))[::-1]) indx += 1 b = real_if_close(brev[::-1]) return b, a
def invresz(r,p,k,tol=1e-3,rtype='avg'): """Compute b(z) and a(z) from partial fraction expansion: r,p,k If M = len(b) and N = len(a) b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1) H(z) = ------ = ---------------------------------------------- a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1) r[0] r[-1] = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ... (1-p[0]z**(-1)) (1-p[-1]z**(-1)) If there are any repeated roots (closer than tol), then the partial fraction expansion has terms like r[i] r[i+1] r[i+n-1] -------------- + ------------------ + ... + ------------------ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n See also: residuez, poly, polyval, unique_roots """ extra = asarray(k) p, indx = cmplx_sort(p) r = take(r,indx) pout, mult = unique_roots(p,tol=tol,rtype=rtype) p = [] for k in range(len(pout)): p.extend([pout[k]]*mult[k]) a = atleast_1d(poly(p)) if len(extra) > 0: b = polymul(extra,a) else: b = [0] indx = 0 brev = asarray(b)[::-1] for k in range(len(pout)): temp = [] # Construct polynomial which does not include any of this root for l in range(len(pout)): if l != k: temp.extend([pout[l]]*mult[l]) for m in range(mult[k]): t2 = temp[:] t2.extend([pout[k]]*(mult[k]-m-1)) brev = polyadd(brev,(r[indx]*poly(t2))[::-1]) indx += 1 b = real_if_close(brev[::-1]) return b, a
1,258
def resample(x,num,t=None,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. The resampled signal starts at the same value of x but is sampled with a spacing of len(x) / num * (spacing of x). Because a Fourier method is used, the signal is assumed periodic. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for sampled signals you didn't intend to be interpreted as band-limited. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) The first sample of the returned vector is the same as the first sample of the input vector, the spacing between samples is changed from dx to dx * len(x) / num If t is not None, then it represents the old sample positions, and the new sample positions will be returned as well as the new samples. """ x = asarray(x) X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = ifftshift(get_window(window,Nx)) newshape = ones(len(x.shape)) newshape[axis] = len(W) W=W.reshape(newshape) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.dtype.char not in ['F','D']: y = y.real if t is None: return y else: new_t = arange(0,num)*(t[1]-t[0])* Nx / float(num) + t[0] return y, new_t
def resample(x,num,t=None,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. The resampled signal starts at the same value of x but is sampled with a spacing of len(x) / num * (spacing of x). Because a Fourier method is used, the signal is assumed periodic. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for sampled signals you didn't intend to be interpreted as band-limited. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) The first sample of the returned vector is the same as the first sample of the input vector, the spacing between samples is changed from dx to dx * len(x) / num If t is not None, then it represents the old sample positions, and the new sample positions will be returned as well as the new samples. """ x = asarray(x) X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = ifftshift(get_window(window,Nx)) newshape = ones(len(x.shape)) newshape[axis] = len(W) W=W.reshape(newshape) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(numpy.minimum(num,Nx)) Y = zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.dtype.char not in ['F','D']: y = y.real if t is None: return y else: new_t = arange(0,num)*(t[1]-t[0])* Nx / float(num) + t[0] return y, new_t
1,259
def resample(x,num,t=None,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. The resampled signal starts at the same value of x but is sampled with a spacing of len(x) / num * (spacing of x). Because a Fourier method is used, the signal is assumed periodic. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for sampled signals you didn't intend to be interpreted as band-limited. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) The first sample of the returned vector is the same as the first sample of the input vector, the spacing between samples is changed from dx to dx * len(x) / num If t is not None, then it represents the old sample positions, and the new sample positions will be returned as well as the new samples. """ x = asarray(x) X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = ifftshift(get_window(window,Nx)) newshape = ones(len(x.shape)) newshape[axis] = len(W) W=W.reshape(newshape) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.dtype.char not in ['F','D']: y = y.real if t is None: return y else: new_t = arange(0,num)*(t[1]-t[0])* Nx / float(num) + t[0] return y, new_t
def resample(x,num,t=None,axis=0,window=None): """Resample to num samples using Fourier method along the given axis. The resampled signal starts at the same value of x but is sampled with a spacing of len(x) / num * (spacing of x). Because a Fourier method is used, the signal is assumed periodic. Window controls a Fourier-domain window that tapers the Fourier spectrum before zero-padding to aleviate ringing in the resampled values for sampled signals you didn't intend to be interpreted as band-limited. If window is a string then use the named window. If window is a float, then it represents a value of beta for a kaiser window. If window is a tuple, then the first component is a string representing the window, and the next arguments are parameters for that window. Possible windows are: 'blackman' ('black', 'blk') 'hamming' ('hamm', 'ham') 'bartlett' ('bart', 'brt') 'hanning' ('hann', 'han') 'kaiser' ('ksr') # requires parameter (beta) 'gaussian' ('gauss', 'gss') # requires parameter (std.) 'general gauss' ('general', 'ggs') # requires two parameters (power, width) The first sample of the returned vector is the same as the first sample of the input vector, the spacing between samples is changed from dx to dx * len(x) / num If t is not None, then it represents the old sample positions, and the new sample positions will be returned as well as the new samples. """ x = asarray(x) X = fft(x,axis=axis) Nx = x.shape[axis] if window is not None: W = ifftshift(get_window(window,Nx)) newshape = ones(len(x.shape)) newshape[axis] = len(W) W=W.reshape(newshape) X = X*W sl = [slice(None)]*len(x.shape) newshape = list(x.shape) newshape[axis] = num N = int(Numeric.minimum(num,Nx)) Y = Numeric.zeros(newshape,'D') sl[axis] = slice(0,(N+1)/2) Y[sl] = X[sl] sl[axis] = slice(-(N-1)/2,None) Y[sl] = X[sl] y = ifft(Y,axis=axis)*(float(num)/float(Nx)) if x.dtype.char not in ['F','D']: y = y.real if t is None: return y else: new_t = arange(0,num)*(t[1]-t[0])* Nx / float(num) + t[0] return y, new_t
1,260
def toimage(arr,high=255,low=0,cmin=None,cmax=None,pal=None, mode=None,channel_axis=None): """Takes a Numeric array and returns a PIL image. The mode of the PIL image depends on the array shape, the pal keyword, and the mode keyword. For 2-D arrays, if pal is a valid (N,3) byte-array giving the RGB values (from 0 to 255) then mode='P', otherwise mode='L', unless mode is given as 'F' or 'I' in which case a float and/or integer array is made For 3-D arrays, the channel_axis argument tells which dimension of the array holds the channel data. For 3-D arrays if one of the dimensions is 3, the mode is 'RGB' by default or 'YCbCr' if selected. if the The Numeric array must be either 2 dimensional or 3 dimensional. """ data = Numeric.asarray(arr) shape = list(data.shape) valid = len(shape)==2 or ((len(shape)==3) and \ ((3 in shape) or (4 in shape))) assert valid, "Not a suitable array shape for any mode." if len(shape) == 2: shape = (shape[1],shape[0]) # columns show up first if mode in [None, 'L', 'P']: bytedata = bytescale(data,high=high,low=low,cmin=cmin,cmax=cmax) image = Image.fromstring('L',shape,bytedata.tostring()) if pal is not None: image.putpalette(asarray(pal,typecode=_UInt8).tostring()) # Becomes a mode='P' automagically. elif mode == 'P': # default gray-scale pal = arange(0,256,1,typecode='b')[:,NewAxis] * \ ones((3,),typecode='b')[NewAxis,:] image.putpalette(asarray(pal,typecode=_UInt8).tostring()) return image if mode == '1': # high input gives threshold for 1 bytedata = ((data > high)*255).astype('b') image = Image.fromstring('L',shape,bytedata.tostring()) image = image.convert(mode='1') return image if cmin is None: cmin = amin(ravel(data)) if cmax is None: cmax = amax(ravel(data)) data = (data*1.0 - cmin)*(high-low)/(cmax-cmin) + low if mode == 'F': image = Image.fromstring(mode,shape,data.astype('f').tostring()) elif mode == 'I': image = Image.fromstring(mode,shape,data.astype('i').tostring()) else: raise ValueError, _errstr return image # if here then 3-d array with a 3 or a 4 in the shape length. # Check for 3 in datacube shape --- 'RGB' or 'YCbCr' if channel_axis is None: if (3 in shape): ca = Numeric.nonzero(asarray(shape) == 3)[0] else: ca = Numeric.nonzero(asarray(shape) == 4) if len(ca): ca = ca[0] else: raise ValueError, "Could not find channel dimension." else: ca = channel_axis numch = shape[ca] if numch not in [3,4]: raise ValueError, "Channel axis dimension is not valid." bytedata = bytescale(data,high=high,low=low,cmin=cmin,cmax=cmax) if ca == 2: strdata = bytedata.tostring() shape = (shape[1],shape[0]) elif ca == 1: strdata = transpose(bytedata,(0,2,1)).tostring() shape = (shape[2],shape[0]) elif ca == 0: strdata = transpose(bytedata,(1,2,0)).tostring() shape = (shape[2],shape[1]) if mode is None: if numch == 3: mode = 'RGB' else: mode = 'RGBA' if mode not in ['RGB','RGBA','YCbCr','CMYK']: raise ValueError, _errstr if mode in ['RGB', 'YCbCr']: assert numch == 3, "Invalid array shape for mode." if mode in ['RGBA', 'CMYK']: assert numch == 4, "Invalid array shape for mode." # Here we know data and mode is coorect image = Image.fromstring(mode, shape, strdata) return image
def toimage(arr,high=255,low=0,cmin=None,cmax=None,pal=None, mode=None,channel_axis=None): """Takes a Numeric array and returns a PIL image. The mode of the PIL image depends on the array shape, the pal keyword, and the mode keyword. For 2-D arrays, if pal is a valid (N,3) byte-array giving the RGB values (from 0 to 255) then mode='P', otherwise mode='L', unless mode is given as 'F' or 'I' in which case a float and/or integer array is made For 3-D arrays, the channel_axis argument tells which dimension of the array holds the channel data. For 3-D arrays if one of the dimensions is 3, the mode is 'RGB' by default or 'YCbCr' if selected. if the The Numeric array must be either 2 dimensional or 3 dimensional. """ data = Numeric.asarray(arr) shape = list(data.shape) valid = len(shape)==2 or ((len(shape)==3) and \ ((3 in shape) or (4 in shape))) assert valid, "Not a suitable array shape for any mode." if len(shape) == 2: shape = (shape[1],shape[0]) # columns show up first if mode in [None, 'L', 'P']: bytedata = bytescale(data,high=high,low=low,cmin=cmin,cmax=cmax) image = Image.fromstring('L',shape,bytedata.tostring()) if pal is not None: image.putpalette(asarray(pal,typecode=_UInt8).tostring()) # Becomes a mode='P' automagically. elif mode == 'P': # default gray-scale pal = arange(0,256,1,typecode='b')[:,NewAxis] * \ ones((3,),typecode='b')[NewAxis,:] image.putpalette(asarray(pal,typecode=_UInt8).tostring()) return image if mode == '1': # high input gives threshold for 1 bytedata = ((data > high)*255).astype('b') image = Image.fromstring('L',shape,bytedata.tostring()) image = image.convert(mode='1') return image if cmin is None: cmin = amin(ravel(data)) if cmax is None: cmax = amax(ravel(data)) data = (data*1.0 - cmin)*(high-low)/(cmax-cmin) + low if mode == 'I': image = Image.fromstring(mode,shape,data.astype('i').tostring()) else: raise ValueError, _errstr return image # if here then 3-d array with a 3 or a 4 in the shape length. # Check for 3 in datacube shape --- 'RGB' or 'YCbCr' if channel_axis is None: if (3 in shape): ca = Numeric.nonzero(asarray(shape) == 3)[0] else: ca = Numeric.nonzero(asarray(shape) == 4) if len(ca): ca = ca[0] else: raise ValueError, "Could not find channel dimension." else: ca = channel_axis numch = shape[ca] if numch not in [3,4]: raise ValueError, "Channel axis dimension is not valid." bytedata = bytescale(data,high=high,low=low,cmin=cmin,cmax=cmax) if ca == 2: strdata = bytedata.tostring() shape = (shape[1],shape[0]) elif ca == 1: strdata = transpose(bytedata,(0,2,1)).tostring() shape = (shape[2],shape[0]) elif ca == 0: strdata = transpose(bytedata,(1,2,0)).tostring() shape = (shape[2],shape[1]) if mode is None: if numch == 3: mode = 'RGB' else: mode = 'RGBA' if mode not in ['RGB','RGBA','YCbCr','CMYK']: raise ValueError, _errstr if mode in ['RGB', 'YCbCr']: assert numch == 3, "Invalid array shape for mode." if mode in ['RGBA', 'CMYK']: assert numch == 4, "Invalid array shape for mode." # Here we know data and mode is coorect image = Image.fromstring(mode, shape, strdata) return image
1,261
def __mul__(self, other): if isinstance(other, dok_matrix): return self.matmat(other) other = asarray(other) if rank(other) > 0: return self.matvec(other) res = dok_matrix() for key in self.keys(): res[key] = other * self[key] return res
def __mul__(self, other): if isinstance(other, spmatrix): return self.matmat(other) other = asarray(other) if rank(other) > 0: return self.matvec(other) res = dok_matrix() for key in self.keys(): res[key] = other * self[key] return res
1,262
def tocsr(self): # Return Compressed Sparse Row format arrays for this matrix keys = self.keys() keys.sort() nnz = len(keys) data = [0]*nnz colind = [0]*nnz row_ptr = [0]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: current_row = ikey0 row_ptr[ikey0] = k data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix(data,(colind, row_ptr))
def tocsr(self): # Return Compressed Sparse Row format arrays for this matrix keys = self.keys() keys.sort() nnz = len(keys) data = [0]*nnz colind = [0]*nnz row_ptr = [0]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey1-current_col row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix(data,(colind, row_ptr))
1,263
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [0]*nnz rowind = [0]*nnz col_ptr = [0]*(self.shape[1]+1) current_col = 0 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
1,264
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
1,265
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] rowind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
1,266
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) rowind = array(rowind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
1,267
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
def tocsc(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) return csc_matrix(data, (colind, col_ptr))
1,268
def threshold(a, threshmin=None, threshmax=None, newval=0): """Clip array to a given value.
def threshold(a, threshmin=None, threshmax=None, newval=0): """Clip array to a given value.
1,269
def unique1d( ar1, retIndx = False ): """Unique elements of 1D array. When retIndx is True, return also the indices indx such that ar1[indx] is the resulting array of unique elements.""" ar = numpy.array( ar1 ).ravel() if retIndx: perm = numpy.argsort( ar ) aux = numpy.take( ar, perm 0,axis=0) flag = ediff1d( aux, 1 ) != 0 return numpy.compress( flag, perm ,axis=-1), numpy.compress( flag, aux ,axis=-1) else: aux = numpy.sort( ar ) return numpy.compress( ediff1d( aux, 1 ) != 0, aux ,axis=-1)
def unique1d( ar1, retIndx = False ): """Unique elements of 1D array. When retIndx is True, return also the indices indx such that ar1[indx] is the resulting array of unique elements.""" ar = numpy.array( ar1 ).ravel() if retIndx: perm = numpy.argsort( ar ) aux = numpy.take( ar, perm, axis=0) flag = ediff1d( aux, 1 ) != 0 return numpy.compress( flag, perm ,axis=-1), numpy.compress( flag, aux ,axis=-1) else: aux = numpy.sort( ar ) return numpy.compress( ediff1d( aux, 1 ) != 0, aux ,axis=-1)
1,270
def ppcc_max(x, dist='tukeylambda'): """Returns the shape parameter that maximizes the probability plot correlation coefficient for the given data to a one-parameter family of distributions. See also ppcc_plot """ try: ppf_func = eval('distributions.%sppf'%dist) except AttributError: raise dist, "is not a valid distribution with a ppf." res = inspect.getargspec(ppf_func) if not ('loc' == res[0][-2] and 'scale' == res[0][-1] and \ 0.0==res[-1][-2] and 1.0==res[-1][-1]): raise ValueError, "Function has does not have default location", \ "and scale parameters\n that are 0.0 and 1.0 respectively." if (1 < len(res[0])-len(res[-1])-1) or \ (1 > len(res[0])-3): raise ValueError, "Must be a one-parameter family." N = len(x) Ui = zeros(N)*1.0 Ui[-1] = 0.5**(1.0/N) Ui[0] = 1-Ui[-1] i = arange(2,N) Ui[1:-1] = (i-0.3175)/(N+0.365) osr = sort(x) def tempfunc(shape, mi, yvals, func): xvals = func(mi, shape) slope, intercept, r, prob, sterrest = stats.linregress(xvals, yvals) return 1-r return optimize.brent(tempfunc, args=(Ui, osr, ppf_func))
def ppcc_max(x, brack=(0.0,1.0), dist='tukeylambda'): """Returns the shape parameter that maximizes the probability plot correlation coefficient for the given data to a one-parameter family of distributions. See also ppcc_plot """ try: ppf_func = eval('distributions.%sppf'%dist) except AttributError: raise dist, "is not a valid distribution with a ppf." res = inspect.getargspec(ppf_func) if not ('loc' == res[0][-2] and 'scale' == res[0][-1] and \ 0.0==res[-1][-2] and 1.0==res[-1][-1]): raise ValueError, "Function has does not have default location", \ "and scale parameters\n that are 0.0 and 1.0 respectively." if (1 < len(res[0])-len(res[-1])-1) or \ (1 > len(res[0])-3): raise ValueError, "Must be a one-parameter family." N = len(x) Ui = zeros(N)*1.0 Ui[-1] = 0.5**(1.0/N) Ui[0] = 1-Ui[-1] i = arange(2,N) Ui[1:-1] = (i-0.3175)/(N+0.365) osr = sort(x) def tempfunc(shape, mi, yvals, func): xvals = func(mi, shape) slope, intercept, r, prob, sterrest = stats.linregress(xvals, yvals) return 1-r return optimize.brent(tempfunc, args=(Ui, osr, ppf_func))
1,271
def tempfunc(shape, mi, yvals, func): xvals = func(mi, shape) slope, intercept, r, prob, sterrest = stats.linregress(xvals, yvals) return 1-r
def tempfunc(shape, mi, yvals, func): xvals = func(mi, shape) slope, intercept, r, prob, sterrest = stats.linregress(xvals, yvals) return 1-r
1,272
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
def check_log_0(self): """ log(0) should print warning, but succeed. """ try: val = logn(3,0) assert(0) except OverflowError: pass
1,273
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) except: assert(0) def check_log_neg(self): """ log(-1) should print warning, but still raises error. """ try: val = logn(3,-1) except OverflowError: pass
1,274
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
1,275
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
def check_log_0(self): """ log(0) should print warning, but succeed. """ try: val = logn(3,0) assert(0) except OverflowError: pass
1,276
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
def check_log_0(self): """ Later have log(0) raise warning, not error """ try: val = logn(3,0) assert(0) except OverflowError: pass
1,277
def check_log_neg(self): """ Later have log(-1) raise warning, not error """ try: val = logn(3,-1) assert(0) except ValueError: pass
def check_log_neg(self): """ Later have log(-1) raise warning, not error """ try: val = log2(-1) assert(0) except OverflowError: pass
1,278
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]
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 ) if csc: index0 = mat.rowind else: index0 = mat.colind ftype, lastel, data, index1 = mat.ftype, mat.nnz, mat.data, 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,279
def __add__(self, other): csc = self.tocsc() res = csc + other return res
def __add__(self, other): csc = self.tocsc() res = csc + other return res
1,280
def __sub__(self, other): csc = self.tocsc() res = csc - other return res
def __sub__(self, other): csc = self.tocsc() res = csc - other return res
1,281
def __rsub__(self, other): # other - self csc = self.tocsc() res = csc.__rsub__(other) return res
def __rsub__(self, other): # other - self csc = self.tocsc() res = csc.__rsub__(other) return res
1,282
def __mul__(self, other): csc = self.tocsc() res = csc * other return res
def __mul__(self, other): csc = self.tocsc() res = csc * other return res
1,283
def __rmul__(self, other): csc = self.tocsc() res = csc.__rmul__(other) return res
def __rmul__(self, other): csc = self.tocsc() return csc.__rmul__(other)
1,284
def __neg__(self): csc = self.tocsc() res = -csc return res
def __neg__(self): csc = self.tocsc() res = -csc return res
1,285
def transpose(self): csc = self.tocsc() res = csc.transpose() return res
def transpose(self): csc = self.tocsc() res = csc.transpose() return res
1,286
def matrixmultiply(self, other): """ A generic interface for matrix-matrix or matrix-vector multiplication. """ csc = self.tocsc() res = csc.matrixmultiply(other) return res
def matrixmultiply(self, other): """ A generic interface for matrix-matrix or matrix-vector multiplication. """ csc = self.tocsc() return csc.matrixmultiply(other)
1,287
def matmat(self, other): csc = self.tocsc() res = csc.matmat(other) return res
def matmat(self, other): csc = self.tocsc() res = csc.matmat(other) return res
1,288
def matvec(self, vec): csc = self.tocsc() res = csc.matvec(vec) return res
def matvec(self, vec): csc = self.tocsc() res = csc.matvec(vec) return res
1,289
def rmatvec(self, vec, conj=1): csc = self.tocsc() res = csc.rmatvec(vec, conj=conj) return res
def rmatvec(self, vec, conj=1): csc = self.tocsc() res = csc.rmatvec(vec, conj=conj) return res
1,290
def __add__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
def __add__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,other._dtypechar)] nnz1, nnz2 = self.nnz, other.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
1,291
def __rmul__(self, other): # other * self if isspmatrix(other): ocs = csc_matrix(other) return ocs.matmat(self) elif isscalar(other): new = self.copy() new.data = other * new.data new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: return transpose(self.rmatvec(transpose(other),conj=0))
def __rmul__(self, other): # other * self if isspmatrix(other): ocs = other.tocsc() return ocs.matmat(self) elif isscalar(other): new = self.copy() new.data = other * new.data new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: return transpose(self.rmatvec(transpose(other),conj=0))
1,292
def __neg__(self): new = self.copy() new.data = -new.data return new
def __neg__(self): new = self.copy() new.data *= -1 return new
1,293
def __sub__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,ocs._dtypechar)] data1, data2 = _convert_data(self.data, ocs.data, dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind,self.indptr,-data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
def __sub__(self, other): ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,ocs._dtypechar)] data1, data2 = _convert_data(self.data, ocs.data, dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(data1,self.rowind,self.indptr,-data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
1,294
def __rsub__(self, other): # implement other - self ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,ocs._dtypechar)] data1, data2 = _convert_data(self.data, ocs.data, dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
def __rsub__(self, other): # implement other - self if isscalar(other): raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') elif isspmatrix(other): ocs = other.tocsc() if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,ocs._dtypechar)] data1, data2 = _convert_data(self.data, ocs.data, dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscadd') c,rowc,ptrc,ierr = func(-data1,self.rowind,self.indptr,data2,ocs.rowind,ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
1,295
def __pow__(self, other): """ Element-by-element power (unless other is a scalar, in which case return the matrix power.) """ if isscalar(other): new = self.copy() new.data = new.data ** other new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: ocs = csc_matrix(other) if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,ocs._dtypechar)] nnz1, nnz2 = self.nnz, ocs.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscmul') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
def __pow__(self, other): """ Element-by-element power (unless other is a scalar, in which case return the matrix power.) """ if isscalar(other): new = self.copy() new.data = new.data ** other new._dtypechar = new.data.dtypechar new.ftype = _transtabl[new._dtypechar] return new else: ocs = other.tocsc() if (ocs.shape != self.shape): raise ValueError, "Inconsistent shapes." dtypechar = _coerce_rules[(self._dtypechar,ocs._dtypechar)] nnz1, nnz2 = self.nnz, ocs.nnz data1, data2 = _convert_data(self.data[:nnz1], ocs.data[:nnz2], dtypechar) func = getattr(sparsetools,_transtabl[dtypechar]+'cscmul') c,rowc,ptrc,ierr = func(data1,self.rowind[:nnz1],self.indptr,data2,ocs.rowind[:nnz2],ocs.indptr) if ierr: raise ValueError, "Ran out of space (but shouldn't have happened)." M, N = self.shape return csc_matrix.Construct(c,(rowc,ptrc),M=M,N=N)
1,296
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
1,297
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
1,298
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
def __add__(self, other): # First check if argument is a scalar try: m,n = other.shape except AttributeError: # Okay, assume it's scalar # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a sparse matrix is not yet supported') other_csr = other.tocsr() #ocs = csr_matrix(other) if (other_csr.shape != self.shape): raise ValueError, "inconsistent shapes."
1,299