bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
---|---|---|
def bilinear(b,a,fs=1.0): a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = Float M = max([N,D]) Np = M Dp = M bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype) for j in range(Np+1): val = 0.0 for i in range(N+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*b[N-i]*pow(2*fs,i)*(-1)**k bprime[j] = val for j in range(Dp+1): val = 0.0 for i in range(D+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*a[D-i]*pow(2*fs,i)*(-1)**k aprime[j] = val return normalize(bprime, aprime) | def bilinear(b,a,fs=1.0): a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = Num.Float M = max([N,D]) Np = M Dp = M bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype) for j in range(Np+1): val = 0.0 for i in range(N+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*b[N-i]*pow(2*fs,i)*(-1)**k bprime[j] = val for j in range(Dp+1): val = 0.0 for i in range(D+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*a[D-i]*pow(2*fs,i)*(-1)**k aprime[j] = val return normalize(bprime, aprime) | 600 |
def bilinear(b,a,fs=1.0): a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = Float M = max([N,D]) Np = M Dp = M bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype) for j in range(Np+1): val = 0.0 for i in range(N+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*b[N-i]*pow(2*fs,i)*(-1)**k bprime[j] = val for j in range(Dp+1): val = 0.0 for i in range(D+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*a[D-i]*pow(2*fs,i)*(-1)**k aprime[j] = val return normalize(bprime, aprime) | def bilinear(b,a,fs=1.0): a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = Float M = max([N,D]) Np = M Dp = M bprime = Num.zeros(Np+1,artype) aprime = Num.zeros(Dp+1,artype) for j in range(Np+1): val = 0.0 for i in range(N+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*b[N-i]*pow(2*fs,i)*(-1)**k bprime[j] = val for j in range(Dp+1): val = 0.0 for i in range(D+1): for k in range(i+1): for l in range(M-i+1): if k+l == j: val += comb(i,k)*comb(M-i,l)*a[D-i]*pow(2*fs,i)*(-1)**k aprime[j] = val return normalize(bprime, aprime) | 601 |
def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=0, ftype='butter', output='ba'): """IIR digital and analog filter design given order and critical points. Description: Design an Nth order lowpass digital or analog filter and return the filter coefficients in (B,A) (numerator, denominator) or (Z,P,K) form. Inputs: N -- the order of the filter. Wn -- a scalar or length-2 sequence giving the critical frequencies. rp, rs -- For chebyshev and elliptic filters provides the maximum ripple in the passband and the minimum attenuation in the stop band. btype -- the type of filter (lowpass, highpass, bandpass, or bandstop). analog -- non-zero to return an analog filter, otherwise a digital filter is returned. ftype -- the type of IIR filter (Butterworth, Cauer (Elliptic), Bessel, Chebyshev1, Chebyshev2) output -- 'ba' for (B,A) output, 'zpk' for (Z,P,K) output. """ ftype, btype, output = map(string.lower, (ftype, btype, output)) Wn = asarray(Wn) try: btype = band_dict[btype] except KeyError: raise ValueError, "%s is an invalid bandtype for filter." % btype try: typefunc = filter_dict[ftype][0] except KeyError: raise ValueError, "%s is not a valid basic iir filter." % ftype if output not in ['ba', 'zpk']: raise ValueError, "%s is not a valid output form." % output #pre-warp frequencies for digital filter design if not analog: fs = 2 warped = 2*fs*tan(pi*Wn/fs) else: warped = Wn # convert to low-pass prototype if btype in ['lowpass', 'highpass']: wo = warped else: bw = warped[1] - warped[0] wo = sqrt(warped[0]*warped[1]) # Get analog lowpass prototype if typefunc in [buttap, besselap]: z, p, k = typefunc(N) elif typefunc == cheb1ap: if rp is None: raise ValueError, "passband ripple (rp) must be provided to design a Chebyshev I filter." z, p, k = typefunc(N, rp) elif typefunc == cheb2ap: if rs is None: raise ValueError, "stopband atteunatuion (rs) must be provided to design an Chebyshev II filter." z, p, k = typefunc(N, rs) else: # Elliptic filters if rs is None or rp is None: raise ValueErrro, "Both rp and rs must be provided to design an elliptic filter." z, p, k = typefunc(N, rp, rs) b, a = zpk2tf(z,p,k) # transform to lowpass, bandpass, highpass, or bandstop if btype == 'lowpass': b, a = lp2lp(b,a,wo=wo) elif btype == 'highpass': b, a = lp2hp(b,a,wo=wo) elif btype == 'bandpass': b, a = lp2bp(b,a,wo=wo,bw=bw) else: # 'bandstop' b, a = lp2bs(b,a,wo=wo,bw=bw) # Find discrete equivalent if necessary if not analog: b, a = bilinear(b, a, fs=fs) # Transform to proper out type (pole-zero, state-space, numer-denom) if output == 'zpk': return tf2zpk(b,a) else: return b,a | def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=0, ftype='butter', output='ba'): """IIR digital and analog filter design given order and critical points. Description: Design an Nth order lowpass digital or analog filter and return the filter coefficients in (B,A) (numerator, denominator) or (Z,P,K) form. Inputs: N -- the order of the filter. Wn -- a scalar or length-2 sequence giving the critical frequencies. rp, rs -- For chebyshev and elliptic filters provides the maximum ripple in the passband and the minimum attenuation in the stop band. btype -- the type of filter (lowpass, highpass, bandpass, or bandstop). analog -- non-zero to return an analog filter, otherwise a digital filter is returned. ftype -- the type of IIR filter (Butterworth, Cauer (Elliptic), Bessel, Chebyshev1, Chebyshev2) output -- 'ba' for (B,A) output, 'zpk' for (Z,P,K) output. """ ftype, btype, output = map(string.lower, (ftype, btype, output)) Wn = Num.asarray(Wn) try: btype = band_dict[btype] except KeyError: raise ValueError, "%s is an invalid bandtype for filter." % btype try: typefunc = filter_dict[ftype][0] except KeyError: raise ValueError, "%s is not a valid basic iir filter." % ftype if output not in ['ba', 'zpk']: raise ValueError, "%s is not a valid output form." % output #pre-warp frequencies for digital filter design if not analog: fs = 2 warped = 2*fs*tan(pi*Wn/fs) else: warped = Wn # convert to low-pass prototype if btype in ['lowpass', 'highpass']: wo = warped else: bw = warped[1] - warped[0] wo = sqrt(warped[0]*warped[1]) # Get analog lowpass prototype if typefunc in [buttap, besselap]: z, p, k = typefunc(N) elif typefunc == cheb1ap: if rp is None: raise ValueError, "passband ripple (rp) must be provided to design a Chebyshev I filter." z, p, k = typefunc(N, rp) elif typefunc == cheb2ap: if rs is None: raise ValueError, "stopband atteunatuion (rs) must be provided to design an Chebyshev II filter." z, p, k = typefunc(N, rs) else: # Elliptic filters if rs is None or rp is None: raise ValueErrro, "Both rp and rs must be provided to design an elliptic filter." z, p, k = typefunc(N, rp, rs) b, a = zpk2tf(z,p,k) # transform to lowpass, bandpass, highpass, or bandstop if btype == 'lowpass': b, a = lp2lp(b,a,wo=wo) elif btype == 'highpass': b, a = lp2hp(b,a,wo=wo) elif btype == 'bandpass': b, a = lp2bp(b,a,wo=wo,bw=bw) else: # 'bandstop' b, a = lp2bs(b,a,wo=wo,bw=bw) # Find discrete equivalent if necessary if not analog: b, a = bilinear(b, a, fs=fs) # Transform to proper out type (pole-zero, state-space, numer-denom) if output == 'zpk': return tf2zpk(b,a) else: return b,a | 602 |
def buttord(wp, ws, gpass, gstop, analog=0): """Butterworth filter order selection. Description: Return the order of the lowest order digital Butterworth filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: wp = 0.2, ws = 0.3 Highpass: wp = 0.3, ws = 0.2 Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Butterworth filter which meets specs. Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). Should be used with scipy.signal.butter to give filter results. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) filter_type +=1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies if not analog: passb = tan(wp*pi/2.0) stopb = tan(ws*pi/2.0) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'butter'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'butter'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil( log10((GSTOP-1.0)/(GPASS-1.0)) / (2*log10(nat)))) # Find the butterworth natural frequency W0 (or the "3dB" frequency") # to give exactly gstop at nat. W0 will be between 1 and nat try: W0 = nat / ( ( 10**(0.1*abs(gstop))-1)**(1.0/(2.0*ord))) except ZeroDivisionError: W0 = nat print "Warning, order is zero...check input parametegstop." # now convert this frequency back from lowpass prototype # to the original analog filter if filter_type == 1: # low WN = W0*passb elif filter_type == 2: # high WN = passb / W0 elif filter_type == 3: # stop WN = zeros(2,Numeric.Float) WN[0] = ((passb[1] - passb[0]) + sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN[1] = ((passb[1] - passb[0]) - sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN = Num.sort(abs(WN)) elif filter_type == 4: # pass W0 = array([-W0, W0],Numeric.Float) WN = -W0 * (passb[1]-passb[0]) / 2.0 + sqrt(W0**2 / 4.0 * \ (passb[1]-passb[0])**2 + \ passb[0]*passb[1]) WN = Num.sort(abs(WN)) else: raise ValueError, "Bad type." if not analog: wn = (2.0/pi)*arctan(WN) else: wn = WN if len(wn) == 1: wn = wn[0] return ord, wn | def buttord(wp, ws, gpass, gstop, analog=0): """Butterworth filter order selection. Description: Return the order of the lowest order digital Butterworth filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: wp = 0.2, ws = 0.3 Highpass: wp = 0.3, ws = 0.2 Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Butterworth filter which meets specs. Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). Should be used with scipy.signal.butter to give filter results. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) filter_type +=1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies if not analog: passb = tan(wp*pi/2.0) stopb = tan(ws*pi/2.0) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'butter'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'butter'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil( log10((GSTOP-1.0)/(GPASS-1.0)) / (2*log10(nat)))) # Find the butterworth natural frequency W0 (or the "3dB" frequency") # to give exactly gstop at nat. W0 will be between 1 and nat try: W0 = nat / ( ( 10**(0.1*abs(gstop))-1)**(1.0/(2.0*ord))) except ZeroDivisionError: W0 = nat print "Warning, order is zero...check input parametegstop." # now convert this frequency back from lowpass prototype # to the original analog filter if filter_type == 1: # low WN = W0*passb elif filter_type == 2: # high WN = passb / W0 elif filter_type == 3: # stop WN = Num.zeros(2,Numeric.Float) WN[0] = ((passb[1] - passb[0]) + sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN[1] = ((passb[1] - passb[0]) - sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN = Num.sort(abs(WN)) elif filter_type == 4: # pass W0 = array([-W0, W0],Numeric.Float) WN = -W0 * (passb[1]-passb[0]) / 2.0 + sqrt(W0**2 / 4.0 * \ (passb[1]-passb[0])**2 + \ passb[0]*passb[1]) WN = Num.sort(abs(WN)) else: raise ValueError, "Bad type." if not analog: wn = (2.0/pi)*arctan(WN) else: wn = WN if len(wn) == 1: wn = wn[0] return ord, wn | 603 |
def buttord(wp, ws, gpass, gstop, analog=0): """Butterworth filter order selection. Description: Return the order of the lowest order digital Butterworth filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: wp = 0.2, ws = 0.3 Highpass: wp = 0.3, ws = 0.2 Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Butterworth filter which meets specs. Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). Should be used with scipy.signal.butter to give filter results. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) filter_type +=1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies if not analog: passb = tan(wp*pi/2.0) stopb = tan(ws*pi/2.0) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'butter'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'butter'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil( log10((GSTOP-1.0)/(GPASS-1.0)) / (2*log10(nat)))) # Find the butterworth natural frequency W0 (or the "3dB" frequency") # to give exactly gstop at nat. W0 will be between 1 and nat try: W0 = nat / ( ( 10**(0.1*abs(gstop))-1)**(1.0/(2.0*ord))) except ZeroDivisionError: W0 = nat print "Warning, order is zero...check input parametegstop." # now convert this frequency back from lowpass prototype # to the original analog filter if filter_type == 1: # low WN = W0*passb elif filter_type == 2: # high WN = passb / W0 elif filter_type == 3: # stop WN = zeros(2,Numeric.Float) WN[0] = ((passb[1] - passb[0]) + sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN[1] = ((passb[1] - passb[0]) - sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN = Num.sort(abs(WN)) elif filter_type == 4: # pass W0 = array([-W0, W0],Numeric.Float) WN = -W0 * (passb[1]-passb[0]) / 2.0 + sqrt(W0**2 / 4.0 * \ (passb[1]-passb[0])**2 + \ passb[0]*passb[1]) WN = Num.sort(abs(WN)) else: raise ValueError, "Bad type." if not analog: wn = (2.0/pi)*arctan(WN) else: wn = WN if len(wn) == 1: wn = wn[0] return ord, wn | def buttord(wp, ws, gpass, gstop, analog=0): """Butterworth filter order selection. Description: Return the order of the lowest order digital Butterworth filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: wp = 0.2, ws = 0.3 Highpass: wp = 0.3, ws = 0.2 Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Butterworth filter which meets specs. Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). Should be used with scipy.signal.butter to give filter results. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) filter_type +=1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies if not analog: passb = tan(wp*pi/2.0) stopb = tan(ws*pi/2.0) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'butter'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'butter'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil( log10((GSTOP-1.0)/(GPASS-1.0)) / (2*log10(nat)))) # Find the butterworth natural frequency W0 (or the "3dB" frequency") # to give exactly gstop at nat. W0 will be between 1 and nat try: W0 = nat / ( ( 10**(0.1*abs(gstop))-1)**(1.0/(2.0*ord))) except ZeroDivisionError: W0 = nat print "Warning, order is zero...check input parametegstop." # now convert this frequency back from lowpass prototype # to the original analog filter if filter_type == 1: # low WN = W0*passb elif filter_type == 2: # high WN = passb / W0 elif filter_type == 3: # stop WN = zeros(2,Numeric.Float) WN[0] = ((passb[1] - passb[0]) + sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN[1] = ((passb[1] - passb[0]) - sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN = Num.sort(abs(WN)) elif filter_type == 4: # pass W0 = Num.array([-W0, W0],Numeric.Float) WN = -W0 * (passb[1]-passb[0]) / 2.0 + sqrt(W0**2 / 4.0 * \ (passb[1]-passb[0])**2 + \ passb[0]*passb[1]) WN = Num.sort(abs(WN)) else: raise ValueError, "Bad type." if not analog: wn = (2.0/pi)*arctan(WN) else: wn = WN if len(wn) == 1: wn = wn[0] return ord, wn | 604 |
def cheb2ord(wp, ws, gpass, gstop, analog=0): """Chebyshev type II filter order selection. Description: Return the order of the lowest order digital Chebyshev Type II filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: Wp = 0.2, Ws = 0.3 Highpass: Wp = 0.3, Ws = 0.2 Bandpass: Wp = [0.2, 0.5], Ws = [0.1, 0.6] Bandstop: Wp = [0.1, 0.6], Ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Chebyshev type II filter that meets specs. Wn -- The Chebyshev natural frequency for use with scipy.signal.cheby2 to give the filter. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) if wp[0] < ws[0]: filter_type += 1 else: filter_type += 2 # Pre-wagpass frequencies if not analog: passb = tan(pi*wp/2) stopb = tan(pi*ws/2) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil(arccosh(sqrt((GSTOP-1.0) / (GPASS-1.0))) / arccosh(nat))) # Find frequency where analog response is -gpass dB. # Then convert back from low-pass prototype to the original filter. new_freq = cosh(1.0/ord * arccosh(sqrt((GSTOP-1.0)/(GPASS-1.0)))) new_freq = 1.0 / new_freq if filter_type == 1: nat = passb / new_freq elif filter_type == 2: nat = passb * new_freq elif filter_type == 3: nat = zeros(2,Num.Float) nat[0] = new_freq / 2.0 * (passb[0]-passb[1]) + \ sqrt(new_freq**2 * (passb[1]-passb[0])**2 / 4.0 + \ passb[1] * passb[0]) nat[1] = passb[1] * passb[0] / nat[0] elif filter_type == 4: nat = zeros(2,Num.Float) nat[0] = 1.0/(2.0*new_freq) * (passb[0] - passb[1]) + \ sqrt((passb[1]-passb[0])**2 / (4.0*new_freq**2) + \ passb[1] * passb[0]) nat[1] = passb[0] * passb[1] / nat[0] if not analog: wn = (2.0/pi)*arctan(nat) else: wn = nat if len(wn) == 1: wn = wn[0] return ord, wn | def cheb2ord(wp, ws, gpass, gstop, analog=0): """Chebyshev type II filter order selection. Description: Return the order of the lowest order digital Chebyshev Type II filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: Wp = 0.2, Ws = 0.3 Highpass: Wp = 0.3, Ws = 0.2 Bandpass: Wp = [0.2, 0.5], Ws = [0.1, 0.6] Bandstop: Wp = [0.1, 0.6], Ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Chebyshev type II filter that meets specs. Wn -- The Chebyshev natural frequency for use with scipy.signal.cheby2 to give the filter. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) if wp[0] < ws[0]: filter_type += 1 else: filter_type += 2 # Pre-wagpass frequencies if not analog: passb = tan(pi*wp/2) stopb = tan(pi*ws/2) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil(arccosh(sqrt((GSTOP-1.0) / (GPASS-1.0))) / arccosh(nat))) # Find frequency where analog response is -gpass dB. # Then convert back from low-pass prototype to the original filter. new_freq = cosh(1.0/ord * arccosh(sqrt((GSTOP-1.0)/(GPASS-1.0)))) new_freq = 1.0 / new_freq if filter_type == 1: nat = passb / new_freq elif filter_type == 2: nat = passb * new_freq elif filter_type == 3: nat = Num.zeros(2,Num.Float) nat[0] = new_freq / 2.0 * (passb[0]-passb[1]) + \ sqrt(new_freq**2 * (passb[1]-passb[0])**2 / 4.0 + \ passb[1] * passb[0]) nat[1] = passb[1] * passb[0] / nat[0] elif filter_type == 4: nat = Num.zeros(2,Num.Float) nat[0] = 1.0/(2.0*new_freq) * (passb[0] - passb[1]) + \ sqrt((passb[1]-passb[0])**2 / (4.0*new_freq**2) + \ passb[1] * passb[0]) nat[1] = passb[0] * passb[1] / nat[0] if not analog: wn = (2.0/pi)*arctan(nat) else: wn = nat if len(wn) == 1: wn = wn[0] return ord, wn | 605 |
def cheb2ord(wp, ws, gpass, gstop, analog=0): """Chebyshev type II filter order selection. Description: Return the order of the lowest order digital Chebyshev Type II filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: Wp = 0.2, Ws = 0.3 Highpass: Wp = 0.3, Ws = 0.2 Bandpass: Wp = [0.2, 0.5], Ws = [0.1, 0.6] Bandstop: Wp = [0.1, 0.6], Ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Chebyshev type II filter that meets specs. Wn -- The Chebyshev natural frequency for use with scipy.signal.cheby2 to give the filter. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) if wp[0] < ws[0]: filter_type += 1 else: filter_type += 2 # Pre-wagpass frequencies if not analog: passb = tan(pi*wp/2) stopb = tan(pi*ws/2) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil(arccosh(sqrt((GSTOP-1.0) / (GPASS-1.0))) / arccosh(nat))) # Find frequency where analog response is -gpass dB. # Then convert back from low-pass prototype to the original filter. new_freq = cosh(1.0/ord * arccosh(sqrt((GSTOP-1.0)/(GPASS-1.0)))) new_freq = 1.0 / new_freq if filter_type == 1: nat = passb / new_freq elif filter_type == 2: nat = passb * new_freq elif filter_type == 3: nat = zeros(2,Num.Float) nat[0] = new_freq / 2.0 * (passb[0]-passb[1]) + \ sqrt(new_freq**2 * (passb[1]-passb[0])**2 / 4.0 + \ passb[1] * passb[0]) nat[1] = passb[1] * passb[0] / nat[0] elif filter_type == 4: nat = zeros(2,Num.Float) nat[0] = 1.0/(2.0*new_freq) * (passb[0] - passb[1]) + \ sqrt((passb[1]-passb[0])**2 / (4.0*new_freq**2) + \ passb[1] * passb[0]) nat[1] = passb[0] * passb[1] / nat[0] if not analog: wn = (2.0/pi)*arctan(nat) else: wn = nat if len(wn) == 1: wn = wn[0] return ord, wn | def cheb2ord(wp, ws, gpass, gstop, analog=0): """Chebyshev type II filter order selection. Description: Return the order of the lowest order digital Chebyshev Type II filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: Wp = 0.2, Ws = 0.3 Highpass: Wp = 0.3, Ws = 0.2 Bandpass: Wp = [0.2, 0.5], Ws = [0.1, 0.6] Bandstop: Wp = [0.1, 0.6], Ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Chebyshev type II filter that meets specs. Wn -- The Chebyshev natural frequency for use with scipy.signal.cheby2 to give the filter. """ wp = r1array(wp) ws = r1array(ws) filter_type = 2*(len(wp)-1) if wp[0] < ws[0]: filter_type += 1 else: filter_type += 2 # Pre-wagpass frequencies if not analog: passb = tan(pi*wp/2) stopb = tan(pi*ws/2) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'cheby'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil(arccosh(sqrt((GSTOP-1.0) / (GPASS-1.0))) / arccosh(nat))) # Find frequency where analog response is -gpass dB. # Then convert back from low-pass prototype to the original filter. new_freq = cosh(1.0/ord * arccosh(sqrt((GSTOP-1.0)/(GPASS-1.0)))) new_freq = 1.0 / new_freq if filter_type == 1: nat = passb / new_freq elif filter_type == 2: nat = passb * new_freq elif filter_type == 3: nat = Num.zeros(2,Num.Float) nat[0] = new_freq / 2.0 * (passb[0]-passb[1]) + \ sqrt(new_freq**2 * (passb[1]-passb[0])**2 / 4.0 + \ passb[1] * passb[0]) nat[1] = passb[1] * passb[0] / nat[0] elif filter_type == 4: nat = Num.zeros(2,Num.Float) nat[0] = 1.0/(2.0*new_freq) * (passb[0] - passb[1]) + \ sqrt((passb[1]-passb[0])**2 / (4.0*new_freq**2) + \ passb[1] * passb[0]) nat[1] = passb[0] * passb[1] / nat[0] if not analog: wn = (2.0/pi)*arctan(nat) else: wn = nat if len(wn) == 1: wn = wn[0] return ord, wn | 606 |
def cheb2ap(N,rs): """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass analog filter prototype with rs decibels of ripple in the stopband. """ de = 1.0/sqrt(10**(0.1*rs)-1) mu = arcsinh(1.0/de)/N if N % 2: m = N - 1 n = Num.concatenate((arange(1,N-1,2),arange(N+2,2*N,2))) else: m = N n = arange(1,2*N,2) z = conjugate(1j / cos(n*pi/(2.0*N))) p = exp(1j*(pi*arange(1,2*N,2)/(2.0*N) + pi/2.0)) p = sinh(mu) * p.real + 1j*cosh(mu)*p.imag p = 1.0 / p k = (MLab.prod(-p)/MLab.prod(-z)).real return z, p, k | def cheb2ap(N,rs): """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass analog filter prototype with rs decibels of ripple in the stopband. """ de = 1.0/sqrt(10**(0.1*rs)-1) mu = arcsinh(1.0/de)/N if N % 2: m = N - 1 n = Num.concatenate((Num.arange(1,N-1,2),Num.arange(N+2,2*N,2))) else: m = N n = arange(1,2*N,2) z = conjugate(1j / cos(n*pi/(2.0*N))) p = exp(1j*(pi*arange(1,2*N,2)/(2.0*N) + pi/2.0)) p = sinh(mu) * p.real + 1j*cosh(mu)*p.imag p = 1.0 / p k = (MLab.prod(-p)/MLab.prod(-z)).real return z, p, k | 607 |
def cheb2ap(N,rs): """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass analog filter prototype with rs decibels of ripple in the stopband. """ de = 1.0/sqrt(10**(0.1*rs)-1) mu = arcsinh(1.0/de)/N if N % 2: m = N - 1 n = Num.concatenate((arange(1,N-1,2),arange(N+2,2*N,2))) else: m = N n = arange(1,2*N,2) z = conjugate(1j / cos(n*pi/(2.0*N))) p = exp(1j*(pi*arange(1,2*N,2)/(2.0*N) + pi/2.0)) p = sinh(mu) * p.real + 1j*cosh(mu)*p.imag p = 1.0 / p k = (MLab.prod(-p)/MLab.prod(-z)).real return z, p, k | def cheb2ap(N,rs): """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass analog filter prototype with rs decibels of ripple in the stopband. """ de = 1.0/sqrt(10**(0.1*rs)-1) mu = arcsinh(1.0/de)/N if N % 2: m = N - 1 n = Num.concatenate((arange(1,N-1,2),arange(N+2,2*N,2))) else: m = N n = Num.arange(1,2*N,2) z = conjugate(1j / cos(n*pi/(2.0*N))) p = exp(1j*(pi*arange(1,2*N,2)/(2.0*N) + pi/2.0)) p = sinh(mu) * p.real + 1j*cosh(mu)*p.imag p = 1.0 / p k = (MLab.prod(-p)/MLab.prod(-z)).real return z, p, k | 608 |
def cheb2ap(N,rs): """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass analog filter prototype with rs decibels of ripple in the stopband. """ de = 1.0/sqrt(10**(0.1*rs)-1) mu = arcsinh(1.0/de)/N if N % 2: m = N - 1 n = Num.concatenate((arange(1,N-1,2),arange(N+2,2*N,2))) else: m = N n = arange(1,2*N,2) z = conjugate(1j / cos(n*pi/(2.0*N))) p = exp(1j*(pi*arange(1,2*N,2)/(2.0*N) + pi/2.0)) p = sinh(mu) * p.real + 1j*cosh(mu)*p.imag p = 1.0 / p k = (MLab.prod(-p)/MLab.prod(-z)).real return z, p, k | def cheb2ap(N,rs): """Return (z,p,k) zero, pole, gain for Nth order Chebyshev type II lowpass analog filter prototype with rs decibels of ripple in the stopband. """ de = 1.0/sqrt(10**(0.1*rs)-1) mu = arcsinh(1.0/de)/N if N % 2: m = N - 1 n = Num.concatenate((arange(1,N-1,2),arange(N+2,2*N,2))) else: m = N n = arange(1,2*N,2) z = conjugate(1j / cos(n*pi/(2.0*N))) p = exp(1j*(pi*Num.arange(1,2*N,2)/(2.0*N) + pi/2.0)) p = sinh(mu) * p.real + 1j*cosh(mu)*p.imag p = 1.0 / p k = (MLab.prod(-p)/MLab.prod(-z)).real return z, p, k | 609 |
def ellipap(N,rp,rs): """Return (z,p,k) zeros, poles, and gain of an Nth order normalized prototype elliptic analog lowpass filter with rp decibels of ripple in the passband and a stopband rs decibels down. Broken... """ if N == 1: p = -sqrt(1.0/(10**(0.1*rp)-1.0)) k = -p z = [] return z, p, k eps = Num.sqrt(10**(0.1*rp)-1) ck1 = eps / Num.sqrt(10**(0.1*rs)-1) ck1p = Num.sqrt(1-ck1*ck1) if ck1p == 1: raise ValueError, "Cannot design a filter with given rp and rs specifications." wp = 1 val = special.ellpk([1-ck1*ck1,1-ck1p*ck1p]) if abs(1-ck1p*ck1p) < EPSILON: krat = 0 else: krat = N*val[0] / val[1] m = optimize.fmin(kratio, 0.5, args=(krat,), maxfun=250, maxiter=250, disp=0) if m < 0 or m > 1: m = optimize.fminbound(kratio, 0, 1, args=(krat,), maxfun=250, maxiter=250, disp=0) capk = special.ellpk(1-m) ws = wp / sqrt(m) m1 = 1-m j = arange(1-N%2,N,2) jj = len(j) [s,c,d,phi] = special.ellpj(j*capk/N,m*ones(jj)) snew = Num.compress(abs(s) > EPSILON, s) z = 1.0 / (sqrt(m)*snew) z = 1j*z z = Num.concatenate((z,conjugate(z))) r = optimize.fmin(vratio, special.ellpk(1-m), args=(1/eps, ck1p*ck1p), maxfun=250, maxiter=250, disp=0) v0 = capk * r / (N*val[0]) [sv,cv,dv,phi] = special.ellpj(v0,1-m) p = -(c*d*sv*cv + 1j*s*dv) / (1-(d*sv)**2.0) if N % 2: newp = Num.compress(abs(p.imag) > EPSILON*Num.sqrt(MLab.sum(p*Num.conjugate(p)).real), p) p = Num.concatenate((p,conjugate(newp))) else: p = Num.concatenate((p,conjugate(p))) k = (MLab.prod(-p) / MLab.prod(-z)).real if N % 2 == 0: k = k / Num.sqrt((1+eps*eps)) return z, p, k | def ellipap(N,rp,rs): """Return (z,p,k) zeros, poles, and gain of an Nth order normalized prototype elliptic analog lowpass filter with rp decibels of ripple in the passband and a stopband rs decibels down. Broken... """ if N == 1: p = -sqrt(1.0/(10**(0.1*rp)-1.0)) k = -p z = [] return z, p, k eps = Num.sqrt(10**(0.1*rp)-1) ck1 = eps / Num.sqrt(10**(0.1*rs)-1) ck1p = Num.sqrt(1-ck1*ck1) if ck1p == 1: raise ValueError, "Cannot design a filter with given rp and rs specifications." wp = 1 val = special.ellpk([1-ck1*ck1,1-ck1p*ck1p]) if abs(1-ck1p*ck1p) < EPSILON: krat = 0 else: krat = N*val[0] / val[1] m = optimize.fmin(kratio, 0.5, args=(krat,), maxfun=250, maxiter=250, disp=0) if m < 0 or m > 1: m = optimize.fminbound(kratio, 0, 1, args=(krat,), maxfun=250, maxiter=250, disp=0) capk = special.ellpk(1-m) ws = wp / sqrt(m) m1 = 1-m j = Num.arange(1-N%2,N,2) jj = len(j) [s,c,d,phi] = special.ellpj(j*capk/N,m*ones(jj)) snew = Num.compress(abs(s) > EPSILON, s) z = 1.0 / (sqrt(m)*snew) z = 1j*z z = Num.concatenate((z,conjugate(z))) r = optimize.fmin(vratio, special.ellpk(1-m), args=(1/eps, ck1p*ck1p), maxfun=250, maxiter=250, disp=0) v0 = capk * r / (N*val[0]) [sv,cv,dv,phi] = special.ellpj(v0,1-m) p = -(c*d*sv*cv + 1j*s*dv) / (1-(d*sv)**2.0) if N % 2: newp = Num.compress(abs(p.imag) > EPSILON*Num.sqrt(MLab.sum(p*Num.conjugate(p)).real), p) p = Num.concatenate((p,conjugate(newp))) else: p = Num.concatenate((p,conjugate(p))) k = (MLab.prod(-p) / MLab.prod(-z)).real if N % 2 == 0: k = k / Num.sqrt((1+eps*eps)) return z, p, k | 610 |
def ellipap(N,rp,rs): """Return (z,p,k) zeros, poles, and gain of an Nth order normalized prototype elliptic analog lowpass filter with rp decibels of ripple in the passband and a stopband rs decibels down. Broken... """ if N == 1: p = -sqrt(1.0/(10**(0.1*rp)-1.0)) k = -p z = [] return z, p, k eps = Num.sqrt(10**(0.1*rp)-1) ck1 = eps / Num.sqrt(10**(0.1*rs)-1) ck1p = Num.sqrt(1-ck1*ck1) if ck1p == 1: raise ValueError, "Cannot design a filter with given rp and rs specifications." wp = 1 val = special.ellpk([1-ck1*ck1,1-ck1p*ck1p]) if abs(1-ck1p*ck1p) < EPSILON: krat = 0 else: krat = N*val[0] / val[1] m = optimize.fmin(kratio, 0.5, args=(krat,), maxfun=250, maxiter=250, disp=0) if m < 0 or m > 1: m = optimize.fminbound(kratio, 0, 1, args=(krat,), maxfun=250, maxiter=250, disp=0) capk = special.ellpk(1-m) ws = wp / sqrt(m) m1 = 1-m j = arange(1-N%2,N,2) jj = len(j) [s,c,d,phi] = special.ellpj(j*capk/N,m*ones(jj)) snew = Num.compress(abs(s) > EPSILON, s) z = 1.0 / (sqrt(m)*snew) z = 1j*z z = Num.concatenate((z,conjugate(z))) r = optimize.fmin(vratio, special.ellpk(1-m), args=(1/eps, ck1p*ck1p), maxfun=250, maxiter=250, disp=0) v0 = capk * r / (N*val[0]) [sv,cv,dv,phi] = special.ellpj(v0,1-m) p = -(c*d*sv*cv + 1j*s*dv) / (1-(d*sv)**2.0) if N % 2: newp = Num.compress(abs(p.imag) > EPSILON*Num.sqrt(MLab.sum(p*Num.conjugate(p)).real), p) p = Num.concatenate((p,conjugate(newp))) else: p = Num.concatenate((p,conjugate(p))) k = (MLab.prod(-p) / MLab.prod(-z)).real if N % 2 == 0: k = k / Num.sqrt((1+eps*eps)) return z, p, k | def ellipap(N,rp,rs): """Return (z,p,k) zeros, poles, and gain of an Nth order normalized prototype elliptic analog lowpass filter with rp decibels of ripple in the passband and a stopband rs decibels down. Broken... """ if N == 1: p = -sqrt(1.0/(10**(0.1*rp)-1.0)) k = -p z = [] return z, p, k eps = Num.sqrt(10**(0.1*rp)-1) ck1 = eps / Num.sqrt(10**(0.1*rs)-1) ck1p = Num.sqrt(1-ck1*ck1) if ck1p == 1: raise ValueError, "Cannot design a filter with given rp and rs specifications." wp = 1 val = special.ellpk([1-ck1*ck1,1-ck1p*ck1p]) if abs(1-ck1p*ck1p) < EPSILON: krat = 0 else: krat = N*val[0] / val[1] m = optimize.fmin(kratio, 0.5, args=(krat,), maxfun=250, maxiter=250, disp=0) if m < 0 or m > 1: m = optimize.fminbound(kratio, 0, 1, args=(krat,), maxfun=250, maxiter=250, disp=0) capk = special.ellpk(1-m) ws = wp / sqrt(m) m1 = 1-m j = arange(1-N%2,N,2) jj = len(j) [s,c,d,phi] = special.ellpj(j*capk/N,m*Num.ones(jj)) snew = Num.compress(abs(s) > EPSILON, s) z = 1.0 / (sqrt(m)*snew) z = 1j*z z = Num.concatenate((z,conjugate(z))) r = optimize.fmin(vratio, special.ellpk(1-m), args=(1/eps, ck1p*ck1p), maxfun=250, maxiter=250, disp=0) v0 = capk * r / (N*val[0]) [sv,cv,dv,phi] = special.ellpj(v0,1-m) p = -(c*d*sv*cv + 1j*s*dv) / (1-(d*sv)**2.0) if N % 2: newp = Num.compress(abs(p.imag) > EPSILON*Num.sqrt(MLab.sum(p*Num.conjugate(p)).real), p) p = Num.concatenate((p,conjugate(newp))) else: p = Num.concatenate((p,conjugate(p))) k = (MLab.prod(-p) / MLab.prod(-z)).real if N % 2 == 0: k = k / Num.sqrt((1+eps*eps)) return z, p, k | 611 |
def __init__(self, parent, id = -1, pos=wx.wxPyDefaultPosition, size=wx.wxPyDefaultSize,**attr): wx.wxWindow.__init__(self, parent, id, pos,size) wx.EVT_PAINT(self,self.OnPaint) property_object.__init__(self,attr) background = wx.wxNamedColour(self.background_color) self.SetBackgroundColour(background) #self.SetBackgroundColour(wx.wxLIGHT_GREY) #self.title = text_object('') #self.x_title = text_object('') #self.y_title = text_object('') self.title = text_window(self,'') self.x_title = text_window(self,'') self.y_title = text_window(self,'') self.all_titles = [self.title,self.x_title,self.y_title] #handy to have #self.x_axis = axis_object(graph_location='above',rotate=0) #self.y_axis = axis_object(graph_location='right',rotate=90) self.x_axis = axis_window(self,graph_location='above',rotate=0) self.y_axis = axis_window(self,graph_location='right',rotate=90) | def __init__(self, parent, id = -1, pos=wx.wxPyDefaultPosition, size=wx.wxPyDefaultSize,**attr): wx.wxWindow.__init__(self, parent, id, pos,size) wx.EVT_PAINT(self,self.OnPaint) property_object.__init__(self, attr) background = wx.wxNamedColour(self.background_color) self.SetBackgroundColour(background) #self.SetBackgroundColour(wx.wxLIGHT_GREY) #self.title = text_object('') #self.x_title = text_object('') #self.y_title = text_object('') self.title = text_window(self,'') self.x_title = text_window(self,'') self.y_title = text_window(self,'') self.all_titles = [self.title,self.x_title,self.y_title] #handy to have #self.x_axis = axis_object(graph_location='above',rotate=0) #self.y_axis = axis_object(graph_location='right',rotate=90) self.x_axis = axis_window(self,graph_location='above',rotate=0) self.y_axis = axis_window(self,graph_location='right',rotate=90) | 612 |
def __init__(self, parent, id = -1, pos=wx.wxPyDefaultPosition, size=wx.wxPyDefaultSize,**attr): wx.wxWindow.__init__(self, parent, id, pos,size) wx.EVT_PAINT(self,self.OnPaint) property_object.__init__(self,attr) background = wx.wxNamedColour(self.background_color) self.SetBackgroundColour(background) #self.SetBackgroundColour(wx.wxLIGHT_GREY) #self.title = text_object('') #self.x_title = text_object('') #self.y_title = text_object('') self.title = text_window(self,'') self.x_title = text_window(self,'') self.y_title = text_window(self,'') self.all_titles = [self.title,self.x_title,self.y_title] #handy to have #self.x_axis = axis_object(graph_location='above',rotate=0) #self.y_axis = axis_object(graph_location='right',rotate=90) self.x_axis = axis_window(self,graph_location='above',rotate=0) self.y_axis = axis_window(self,graph_location='right',rotate=90) | def __init__(self, parent, id = -1, pos=wx.wxPyDefaultPosition, size=wx.wxPyDefaultSize,**attr): wx.wxWindow.__init__(self, parent, id, pos,size) wx.EVT_PAINT(self,self.OnPaint) property_object.__init__(self,attr) background = wx.wxNamedColour(self.background_color) self.SetBackgroundColour(background) #self.SetBackgroundColour(wx.wxLIGHT_GREY) #self.title = text_object('') #self.x_title = text_object('') #self.y_title = text_object('') self.title = text_window(self,'') self.x_title = text_window(self,'') self.y_title = text_window(self,'') self.all_titles = [self.title,self.x_title,self.y_title] #handy to have #self.x_axis = axis_object(graph_location='above',rotate=0) #self.y_axis = axis_object(graph_location='right',rotate=90) self.x_axis = axis_window(self,graph_location='above',rotate=0) self.y_axis = axis_window(self,graph_location='right',rotate=90) | 613 |
def layout_graph(self,graph_area,dc): self.axes = [] #data_x_bounds,data_y_bounds = [0,6.28], [-1.1,1000] #jeez this is unwieldy code... smalls = []; bigs =[] if len(self.line_list): p1,p2 = self.line_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(self.image_list): p1,p2 = self.image_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(smalls): min_point = minimum.reduce(smalls) max_point = maximum.reduce(bigs) else: min_point = array((-1.,-1),) max_point = array((1.,1)) data_x_bounds = array((min_point[0],max_point[0])) data_y_bounds = array((min_point[1],max_point[1])) self.x_axis.calculate_ticks(data_x_bounds) height = self.x_axis.max_label_height(dc) graph_area.trim_bottom(height) self.y_axis.calculate_ticks(data_y_bounds) width = self.y_axis.max_label_width(dc) graph_area.trim_left(width) if self.aspect_ratio == 'equal': x_scale = graph_area.width() / self.x_axis.range() y_scale = graph_area.height() / self.y_axis.range() #print 'scales:', x_scale,y_scale,self.x_axis.range(),self.y_axis.range() if x_scale > y_scale: new_width = y_scale * self.x_axis.range() remove = .5 * (graph_area.width() - new_width) graph_area.trim_left(remove) graph_area.trim_right(remove) else: new_height = x_scale * self.y_axis.range() remove = .5 * (graph_area.height() - new_height) graph_area.trim_top(remove) graph_area.trim_bottom(remove) #self.y2_axis = axis_object(graph_location='left',rotate=90) #self.y2_axis.label_location = 'plus' #self.y2_axis.calculate_ticks(y2bounds) #width = self.y2_axis.max_label_width(dc) #graph_area.trim_right(width) self.x_axis.layout(graph_area,dc) self.x_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.x_axis) self.y_axis.layout(graph_area,dc) self.y_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.y_axis) | def layout_graph(self,graph_area,dc): self.axes = [] #data_x_bounds,data_y_bounds = [0,6.28], [-1.1,1000] #jeez this is unwieldy code... smalls = []; bigs =[] if len(self.line_list): p1,p2 = self.line_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(self.image_list): p1,p2 = self.image_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(smalls): min_point = minimum.reduce(smalls) max_point = maximum.reduce(bigs) else: min_point = array((-1.,-1.),) max_point = array((1.,1.)) data_x_bounds = array((min_point[0],max_point[0])) data_y_bounds = array((min_point[1],max_point[1])) self.x_axis.calculate_ticks(data_x_bounds) height = self.x_axis.max_label_height(dc) graph_area.trim_bottom(height) self.y_axis.calculate_ticks(data_y_bounds) width = self.y_axis.max_label_width(dc) graph_area.trim_left(width) if self.aspect_ratio == 'equal': x_scale = graph_area.width() / self.x_axis.range() y_scale = graph_area.height() / self.y_axis.range() #print 'scales:', x_scale,y_scale,self.x_axis.range(),self.y_axis.range() if x_scale > y_scale: new_width = y_scale * self.x_axis.range() remove = .5 * (graph_area.width() - new_width) graph_area.trim_left(remove) graph_area.trim_right(remove) else: new_height = x_scale * self.y_axis.range() remove = .5 * (graph_area.height() - new_height) graph_area.trim_top(remove) graph_area.trim_bottom(remove) #self.y2_axis = axis_object(graph_location='left',rotate=90) #self.y2_axis.label_location = 'plus' #self.y2_axis.calculate_ticks(y2bounds) #width = self.y2_axis.max_label_width(dc) #graph_area.trim_right(width) self.x_axis.layout(graph_area,dc) self.x_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.x_axis) self.y_axis.layout(graph_area,dc) self.y_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.y_axis) | 614 |
def layout_graph(self,graph_area,dc): self.axes = [] #data_x_bounds,data_y_bounds = [0,6.28], [-1.1,1000] #jeez this is unwieldy code... smalls = []; bigs =[] if len(self.line_list): p1,p2 = self.line_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(self.image_list): p1,p2 = self.image_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(smalls): min_point = minimum.reduce(smalls) max_point = maximum.reduce(bigs) else: min_point = array((-1.,-1),) max_point = array((1.,1)) data_x_bounds = array((min_point[0],max_point[0])) data_y_bounds = array((min_point[1],max_point[1])) self.x_axis.calculate_ticks(data_x_bounds) height = self.x_axis.max_label_height(dc) graph_area.trim_bottom(height) self.y_axis.calculate_ticks(data_y_bounds) width = self.y_axis.max_label_width(dc) graph_area.trim_left(width) if self.aspect_ratio == 'equal': x_scale = graph_area.width() / self.x_axis.range() y_scale = graph_area.height() / self.y_axis.range() #print 'scales:', x_scale,y_scale,self.x_axis.range(),self.y_axis.range() if x_scale > y_scale: new_width = y_scale * self.x_axis.range() remove = .5 * (graph_area.width() - new_width) graph_area.trim_left(remove) graph_area.trim_right(remove) else: new_height = x_scale * self.y_axis.range() remove = .5 * (graph_area.height() - new_height) graph_area.trim_top(remove) graph_area.trim_bottom(remove) #self.y2_axis = axis_object(graph_location='left',rotate=90) #self.y2_axis.label_location = 'plus' #self.y2_axis.calculate_ticks(y2bounds) #width = self.y2_axis.max_label_width(dc) #graph_area.trim_right(width) self.x_axis.layout(graph_area,dc) self.x_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.x_axis) self.y_axis.layout(graph_area,dc) self.y_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.y_axis) | def layout_graph(self,graph_area,dc): self.axes = [] #data_x_bounds,data_y_bounds = [0,6.28], [-1.1,1000] #jeez this is unwieldy code... smalls = []; bigs =[] if len(self.line_list): p1,p2 = self.line_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(self.image_list): p1,p2 = self.image_list.bounding_box() smalls.append(p1);bigs.append(p2) if len(smalls): min_point = minimum.reduce(smalls) max_point = maximum.reduce(bigs) else: min_point = array((-1.,-1),) max_point = array((1.,1)) data_x_bounds = array((min_point[0],max_point[0])) data_y_bounds = array((min_point[1],max_point[1])) self.x_axis.calculate_ticks(data_x_bounds) height = self.x_axis.max_label_height(dc) graph_area.trim_bottom(height) self.y_axis.calculate_ticks(data_y_bounds) width = self.y_axis.max_label_width(dc) graph_area.trim_left(width) if self.aspect_ratio == 'equal': x_scale = float(graph_area.width()) / self.x_axis.range() y_scale = float(graph_area.height()) / self.y_axis.range() #print 'scales:', x_scale,y_scale,self.x_axis.range(),self.y_axis.range() if x_scale > y_scale: new_width = y_scale * self.x_axis.range() remove = .5 * (graph_area.width() - new_width) graph_area.trim_left(remove) graph_area.trim_right(remove) else: new_height = x_scale * self.y_axis.range() remove = .5 * (graph_area.height() - new_height) graph_area.trim_top(remove) graph_area.trim_bottom(remove) #self.y2_axis = axis_object(graph_location='left',rotate=90) #self.y2_axis.label_location = 'plus' #self.y2_axis.calculate_ticks(y2bounds) #width = self.y2_axis.max_label_width(dc) #graph_area.trim_right(width) self.x_axis.layout(graph_area,dc) self.x_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.x_axis) self.y_axis.layout(graph_area,dc) self.y_axis.move((graph_area.left(),graph_area.bottom())) self.axes.append(self.y_axis) | 615 |
def draw_graph_area(self,dc=None): if not dc: dc = wx.wxClientDC(self) self.layout_data() # just to check how real time plot would go... | def draw_graph_area(self,dc=None): if not dc: dc = wx.wxClientDC(self) self.layout_data() # just to check how real time plot would go... | 616 |
def draw(self,dc=None): #if not len(self.line_list) or len(self.image_list): # return # resize if necessary #print 'draw' | def draw(self,dc=None): #if not len(self.line_list) or len(self.image_list): # return # resize if necessary #print 'draw' | 617 |
def draw(self,dc=None): #if not len(self.line_list) or len(self.image_list): # return # resize if necessary #print 'draw' | def draw(self,dc=None): #if not len(self.line_list) or len(self.image_list): # return # resize if necessary #print 'draw' | 618 |
def OnPrintPage(self, page): dc = self.GetDC() | def OnPrintPage(self, page): dc = self.GetDC() | 619 |
def __init__(self, parent=wx.NULL, id = -1, title = '', pos=wx.wxPyDefaultPosition, size=default_size,visible=1): wx.wxFrame.__init__(self, parent, id, title,pos,size) | def __init__(self, parent=wx.NULL, id = -1, title = '', pos=wx.wxPyDefaultPosition, size=default_size,visible=1): wx.wxFrame.__init__(self, parent, id, title,pos,size) | 620 |
def evaluate(self, points): """Evaluate the estimated pdf on a set of points. | def evaluate(self, points): """Evaluate the estimated pdf on a set of points. | 621 |
def xlabel(self,t): cmd = 'set xlabel "' + t + '"' self._replot(cmd) | def xtitle(self,t): cmd = 'set xlabel "' + t + '"' self._replot(cmd) | 622 |
def ylabel(self,t): cmd = 'set ylabel "' + t + '"' self._replot(cmd) | def ytitle(self,t): cmd = 'set ylabel "' + t + '"' self._replot(cmd) | 623 |
def zlabel(self,t): cmd = 'set zlabel "' + t + '"' self._replot(cmd) | def ztitle(self,t): cmd = 'set zlabel "' + t + '"' self._replot(cmd) | 624 |
def _figure_rtics(self,minval,maxval,guess=20): xr = abs(maxval-minval) l10 = log10(xr) fl = floor(l10) xnorm = 10**(l10-fl) #you can change the value of 5 # to something if you want more tics... posns = guess / xnorm if (posns > 40): tics = 0.05 # eg 0, .05, .10, ... if (posns > 20): tics = 0.1 # eg 0, .1, .2, ... elif (posns > 10): tics = 0.2 #/* eg 0,0.2,0.4,... */ elif (posns > 4): tics = 0.5 #/* 0,0.5,1, */ elif (posns > 1): tics = 1 #/* 0,1,2,.... */ elif (posns > 0.5): tics = 2 #/* 0, 2, 4, 6 */ else: # getting desperate... the ceil is to make sure we # go over rather than under - eg plot [-10:10] x*x # gives a range of about 99.999 - tics=xnorm gives # tics at 0, 99.99 and 109.98 - BAD ! # This way, inaccuracy the other way will round # up (eg 0->100.0001 => tics at 0 and 101 # I think latter is better than former tics = ceil(xnorm); | def _figure_rtics(self,minval,maxval,guess=20): xr = abs(maxval-minval) l10 = log10(xr) fl = floor(l10) xnorm = 10**(l10-fl) #you can change the value of 5 # to something if you want more tics... posns = guess / xnorm if (posns > 40): tics = 0.05 # eg 0, .05, .10, ... if (posns > 20): tics = 0.1 # eg 0, .1, .2, ... elif (posns > 10): tics = 0.2 #/* eg 0,0.2,0.4,... */ elif (posns > 4): tics = 0.5 #/* 0,0.5,1, */ elif (posns > 1): tics = 1 #/* 0,1,2,.... */ elif (posns > 0.5): tics = 2 #/* 0, 2, 4, 6 */ else: # getting desperate... the ceil is to make sure we # go over rather than under - eg plot [-10:10] x*x # gives a range of about 99.999 - tics=xnorm gives # tics at 0, 99.99 and 109.98 - BAD ! # This way, inaccuracy the other way will round # up (eg 0->100.0001 => tics at 0 and 101 # I think latter is better than former tics = ceil(xnorm); | 625 |
def __init__(self, val): UserList.UserList.__init__(self, val) | def __init__(self, val): UserList.UserList.__init__(self, val) | 626 |
def __init__(self, val): UserDict.UserDict.__init__(self, val) | def __init__(self, val): UserDict.UserDict.__init__(self, val) | 627 |
def configuration(parent_package=''): """ gist only works with an X-windows server This will install *.gs and *.gp files to '%spython%s/site-packages/scipy/xplt' % (sys.prefix,sys.version[:3]) """ # Check for X11 libraries try: execfile('../saved_values.py') try: X11 = X11 except NameError: X11 = check_and_save() except IOError: X11 = check_and_save() if X11: config = default_config_dict() if parent_package: parent_package = parent_package + '.' local_path = get_path(__name__) config['packages'].append(parent_package+'xplt') from scipy_distutils.core import Extension sources = ['gistCmodule.c'] sources = [os.path.join(local_path,x) for x in sources] ext = Extension(parent_package+'xplt.gistC', sources, include_dirs = ['/usr/include/X11'], library_dirs = ['/usr/X11R6/lib'], libraries = ['X11','m']) config['ext_modules'].append(ext) from glob import glob gist = glob(os.path.join(local_path,'gist','*.c')) # libraries are C static libraries config['libraries'].append(('gist',{'sources':gist, 'macros':[('STDC_HEADERS',1)]})) file_ext = ['*.gs','*.gp', '*.ps', '*.help'] xplt_files = [glob(os.path.join(local_path,x)) for x in file_ext] xplt_files = reduce(lambda x,y:x+y,xplt_files,[]) xplt_path = os.path.join(local_path,'xplt') config['data_files'].extend( [(xplt_path,xplt_files)]) return config | def configuration(parent_package=''): """ gist only works with an X-windows server This will install *.gs and *.gp files to '%spython%s/site-packages/scipy/xplt' % (sys.prefix,sys.version[:3]) """ # Check for X11 libraries try: exec(open(save_file).read()) try: X11 = X11 except NameError: X11 = check_and_save() except IOError: X11 = check_and_save() if X11: config = default_config_dict() if parent_package: parent_package = parent_package + '.' local_path = get_path(__name__) config['packages'].append(parent_package+'xplt') from scipy_distutils.core import Extension sources = ['gistCmodule.c'] sources = [os.path.join(local_path,x) for x in sources] ext = Extension(parent_package+'xplt.gistC', sources, include_dirs = ['/usr/include/X11'], library_dirs = ['/usr/X11R6/lib'], libraries = ['X11','m']) config['ext_modules'].append(ext) from glob import glob gist = glob(os.path.join(local_path,'gist','*.c')) # libraries are C static libraries config['libraries'].append(('gist',{'sources':gist, 'macros':[('STDC_HEADERS',1)]})) file_ext = ['*.gs','*.gp', '*.ps', '*.help'] xplt_files = [glob(os.path.join(local_path,x)) for x in file_ext] xplt_files = reduce(lambda x,y:x+y,xplt_files,[]) xplt_path = os.path.join(local_path,'xplt') config['data_files'].extend( [(xplt_path,xplt_files)]) return config | 628 |
def __setattr__(self,key,val): | def __setattr__(self,key,val): | 629 |
def getCSR(self): # Return Compressed Sparse Row format arrays for this matrix keys = self.keys() keys.sort() nnz = len(keys) data = [None]*nnz colind = [None]*nnz row_ptr = [None]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: current_row = ikey0 row_ptr[ikey0] = k data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz data = array(data) colind = array(colind) row_ptr = array(row_ptr) ftype = data.typecode() if ftype not in ['d','D','f','F']: data = data*1.0 ftype = 'd' return ftype, nnz, data, colind, row_ptr | def getCSR(self): # Return Compressed Sparse Row format arrays for this matrix keys = self.keys() keys.sort() nnz = len(keys) data = [None]*nnz colind = [None]*nnz row_ptr = [None]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: current_row = ikey0 row_ptr[ikey0] = k data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz data = array(data) colind = array(colind) row_ptr = array(row_ptr) ftype = data.typecode() if ftype not in ['d','D','f','F']: data = data*1.0 ftype = 'd' return ftype, nnz, data, colind, row_ptr | 630 |
def getCSC(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz rowind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] rowind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) rowind = array(rowind) col_ptr = array(col_ptr) ftype = data.typecode() if ftype not in ['d','D','f','F']: data = data*1.0 ftype = 'd' return ftype, nnz, data, rowind, col_ptr | def getCSC(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz rowind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] rowind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) rowind = array(rowind) col_ptr = array(col_ptr) ftype = data.typecode() if ftype not in ['d','D','f','F']: data = data*1.0 ftype = 'd' return ftype, nnz, data, rowind, col_ptr | 631 |
def dense(self,typecode=None): if typecode is None: typecode = self.type if typecode is None: typecode = 'd' new = zeros(self.shape,typecode) for key in self.keys(): ikey0 = int(key[0]) ikey1 = int(key[1]) new[ikey0,ikey1] = self[key] return new | defdense(self,typecode=None):iftypecodeisNone:typecode=self.typeiftypecodeisNone:typecode='d'new=zeros(self.shape,typecode)forkeyinself.keys():ikey0=int(key[0])ikey1=int(key[1])new[ikey0,ikey1]=self[key]returnnew | 632 |
def __init__(self,s,i=None,j=None,M=None,N=None,nzmax=None, typecode=Float): if type(s) in [types.ListType, ArrayType]: s = array(s,copy=0,typecode=typecode) if s.typecode() not in 'fdFD': # only support these 4 types. s = s.astype('d') sz = len(s) i = array(i,typecode='l',copy=0) j = array(j,typecode='l',copy=0) if nzmax is None: nzmax = sz if M is None: M = max(i)+1 if N is None: N = max(j)+1 self.ptype = s.typecode() self.data = zeros((nzmax,),s.typecode()) self.ftype = _transtabl[self.ptype] self.index = [zeros((nzmax,)),zeros((M+1,))] convfunc = eval('_sparsekit.'+self.ftype+'coocsr') convfunc(array(M),array(nzmax),s,i+1,j+1,self.data,self.index[0],self.index[1]) self.lastel = len(s)-1 elif type(s) is types.IntType: M = int(s) N = int(i) if j is None: j = 0 nzmax = int(j) self.ptype = typecode self.ftype = _transtabl[self.ptype] self.data = zeros((nzmax,),typecode) self.index = [zeros((nzmax,)),zeros((M+1,))] self.lastel = 0 elif isspmatrix(s) and s.storage=='CSR': # make a copy for attr in dir(s): if attr not in ['data','index']: setattr(self,attr,getattr(s,attr)) self.data = array(s.data,copy=1) self.index = [array(s.index[0],copy=1),array(s.index[1],copy=1)] return else: raise TypeError, "Unsupported type %s" % type(s) | def __init__(self,s,i=None,j=None,M=None,N=None,nzmax=None, typecode=Float): if isinstance(s, dictmatrix): ftype, nnz, data, index0, index1 = s.getCSR() self.ftype = ftype self.ptype = _itranstabl[ftype] self.lastel = nnz-1 self.data = data self.index = [index0+1, index1+1] M, N = s.shape nzmax = nnz elif type(s) in [types.ListType, ArrayType]: s = array(s,copy=0,typecode=typecode) if s.typecode() not in 'fdFD': # only support these 4 types. s = s.astype('d') sz = len(s) i = array(i,typecode='l',copy=0) j = array(j,typecode='l',copy=0) if nzmax is None: nzmax = sz if M is None: M = max(i)+1 if N is None: N = max(j)+1 self.ptype = s.typecode() self.data = zeros((nzmax,),s.typecode()) self.ftype = _transtabl[self.ptype] self.index = [zeros((nzmax,)),zeros((M+1,))] convfunc = eval('_sparsekit.'+self.ftype+'coocsr') convfunc(array(M),array(nzmax),s,i+1,j+1,self.data,self.index[0],self.index[1]) self.lastel = len(s)-1 elif type(s) is types.IntType: M = int(s) N = int(i) if j is None: j = 0 nzmax = int(j) self.ptype = typecode self.ftype = _transtabl[self.ptype] self.data = zeros((nzmax,),typecode) self.index = [zeros((nzmax,)),zeros((M+1,))] self.lastel = 0 elif isspmatrix(s) and s.storage=='CSR': # make a copy for attr in dir(s): if attr not in ['data','index']: setattr(self,attr,getattr(s,attr)) self.data = array(s.data,copy=1) self.index = [array(s.index[0],copy=1),array(s.index[1],copy=1)] return else: raise TypeError, "Unsupported type %s" % type(s) | 633 |
def getCSR(self): return A.ftype, A.lastel+1, A.data, A.index[0]-1, A.index[1]-1 | def getCSR(self): return A.ftype, A.lastel+1, A.data, A.index[0]-1, A.index[1]-1 | 634 |
def getCSC(self): B = A.transp() return B.ftype, B.lastel+1, B.data, B.index[0]-1, B.index[1]-1 | def getCSC(self): B = self.transp() return B.ftype, B.lastel+1, B.data, B.index[0]-1, B.index[1]-1 | 635 |
def solve(A,b,permc_spec=2): if not hasattr(A, 'getCSR') and not hasattr(A, 'getCSC'): raise ValueError, "Sparse matrix must be able to return CSC format--"\ "A.getCSC()--or CSR format--A.getCSR()" if not hasattr(A,'shape'): raise ValueError, "Sparse matrix must be able to return shape (rows,cols) = A.shape" if hasattr(A, 'getCSC'): ftype, lastel, data, index0, index1 = A.getCSC() csc = 1 else: ftype, lastel, data, index0, index1 = A.getCSR() csc = 0 M,N = A.shape gssv = eval('_superlu.' + _transtabl[ftype] + 'gssv') return gssv(M,N,lastel,data,index0,index1,b,csc,permc_spec)[0] | def solve(A,b,permc_spec=2): if not hasattr(A, 'getCSR') and not hasattr(A, 'getCSC'): raise ValueError, "Sparse matrix must be able to return CSC format--"\ "A.getCSC()--or CSR format--A.getCSR()" if not hasattr(A,'shape'): raise ValueError, "Sparse matrix must be able to return shape (rows,cols) = A.shape" if hasattr(A, 'getCSC'): ftype, lastel, data, index0, index1 = A.getCSC() csc = 1 else: ftype, lastel, data, index0, index1 = A.getCSR() csc = 0 M,N = A.shape gssv = eval('_superlu.' + ftype + 'gssv') return gssv(M,N,lastel,data,index0,index1,b,csc,permc_spec)[0] | 636 |
def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + ftype + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | 637 |
def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | 638 |
def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | 639 |
def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | 640 |
def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | def lu_factor(A, permc_spec=2, diag_pivot_thresh=1.0, drop_tol=0.0, relax=1, panel_size=10): ftype, nnz, data, rowind, colptr = A.getCSC() M,N = A.shape gstrf = eval('_superlu.' + _transtabl[ftype] + 'gstrf') return gstrf(M,N,nnz,data,rowind,colptr,permc_spec, diag_pivot_thresh, drop_tol, relax, panel_size) | 641 |
def prune(self): """ Remove empty space after all non-zero elements. """ nnz = self.indptr[-1] if self.nzmax <= nnz: if self.nzmax < nnz: raise RunTimeError, "should never have nnz > nzmax" return self.nnz = nnz self.data = self.data[:nnz] self.rowind = self.rowind[:nnz] self.nzmax = nnz self._check() | def prune(self): """ Remove empty space after all non-zero elements. """ nnz = self.indptr[-1] if self.nzmax <= nnz: if self.nzmax < nnz: raise RuntimeError, "should never have nnz > nzmax" return self.nnz = nnz self.data = self.data[:nnz] self.rowind = self.rowind[:nnz] self.nzmax = nnz self._check() | 642 |
def prune(self): """ Eliminate non-zero entries, leaving space for at least newnzmax elements. """ nnz = self.indptr[-1] if self.nzmax <= nnz: if self.nzmax < nnz: raise RunTimeError, "should never have nnz > nzmax" return self.data = self.data[:nnz] self.colind = self.colind[:nnz] self.nzmax = nnz self._check() | def prune(self): """ Eliminate non-zero entries, leaving space for at least newnzmax elements. """ nnz = self.indptr[-1] if self.nzmax <= nnz: if self.nzmax < nnz: raise RuntimeError, "should never have nnz > nzmax" return self.data = self.data[:nnz] self.colind = self.colind[:nnz] self.nzmax = nnz self._check() | 643 |
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('special', parent_package, top_path) define_macros = [] | def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('special', parent_package, top_path) define_macros = [] | 644 |
def eig(a,b=None,left=0,right=1,overwrite_a=0,overwrite_b=0): """ Solve ordinary and generalized eigenvalue problem of a square matrix. Inputs: a -- An N x N matrix. b -- An N x N matrix [default is identity(N)]. left -- Return left eigenvectors [disabled]. right -- Return right eigenvectors [enabled]. Outputs: w -- eigenvalues [left==right==0]. w,vr -- w and right eigenvectors [left==0,right=1]. w,vl -- w and left eigenvectors [left==1,right==0]. w,vl,vr -- [left==right==1]. Definitions: a * vr[:,i] = w[i] * b * vr[:,i] a^H * vl[:,i] = conjugate(w[i]) * b^H * vl[:,i] where a^H denotes transpose(conjugate(a)). """ a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' overwrite_a = overwrite_a or (_datanotshared(a1,a)) if b is not None: b = asarray_chkfinite(b) return _geneig(a1,b,left,right,overwrite_a,overwrite_b) geev, = get_lapack_funcs(('geev',),(a1,)) compute_vl,compute_vr=left,right if geev.module_name[:7] == 'flapack': lwork = calc_lwork.geev(geev.prefix,a1.shape[0], compute_vl,compute_vr)[1] if geev.prefix in 'cz': w,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi else: # 'clapack' if geev.prefix in 'cz': w,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi if info<0: raise ValueError,\ 'illegal value in %-th argument of internal geev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" only_real = numpy.logical_and.reduce(numpy.equal(w.imag,0.0)) if not (geev.prefix in 'cz' or only_real): t = w.dtype.char if left: vl = _make_complex_eigvecs(w, vl, t) if right: vr = _make_complex_eigvecs(w, vr, t) if not (left or right): return w if left: if right: return w, vl, vr return w, vl return w, vr | def eig(a,b=None, left=False, right=True, overwrite_a=False, overwrite_b=False): """ Solve ordinary and generalized eigenvalue problem of a square matrix. Inputs: a -- An N x N matrix. b -- An N x N matrix [default is identity(N)]. left -- Return left eigenvectors [disabled]. right -- Return right eigenvectors [enabled]. Outputs: w -- eigenvalues [left==right==0]. w,vr -- w and right eigenvectors [left==0,right=1]. w,vl -- w and left eigenvectors [left==1,right==0]. w,vl,vr -- [left==right==1]. Definitions: a * vr[:,i] = w[i] * b * vr[:,i] a^H * vl[:,i] = conjugate(w[i]) * b^H * vl[:,i] where a^H denotes transpose(conjugate(a)). """ a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' overwrite_a = overwrite_a or (_datanotshared(a1,a)) if b is not None: b = asarray_chkfinite(b) return _geneig(a1,b,left,right,overwrite_a,overwrite_b) geev, = get_lapack_funcs(('geev',),(a1,)) compute_vl,compute_vr=left,right if geev.module_name[:7] == 'flapack': lwork = calc_lwork.geev(geev.prefix,a1.shape[0], compute_vl,compute_vr)[1] if geev.prefix in 'cz': w,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi else: # 'clapack' if geev.prefix in 'cz': w,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi if info<0: raise ValueError,\ 'illegal value in %-th argument of internal geev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" only_real = numpy.logical_and.reduce(numpy.equal(w.imag,0.0)) if not (geev.prefix in 'cz' or only_real): t = w.dtype.char if left: vl = _make_complex_eigvecs(w, vl, t) if right: vr = _make_complex_eigvecs(w, vr, t) if not (left or right): return w if left: if right: return w, vl, vr return w, vl return w, vr | 645 |
def eig(a,b=None,left=0,right=1,overwrite_a=0,overwrite_b=0): """ Solve ordinary and generalized eigenvalue problem of a square matrix. Inputs: a -- An N x N matrix. b -- An N x N matrix [default is identity(N)]. left -- Return left eigenvectors [disabled]. right -- Return right eigenvectors [enabled]. Outputs: w -- eigenvalues [left==right==0]. w,vr -- w and right eigenvectors [left==0,right=1]. w,vl -- w and left eigenvectors [left==1,right==0]. w,vl,vr -- [left==right==1]. Definitions: a * vr[:,i] = w[i] * b * vr[:,i] a^H * vl[:,i] = conjugate(w[i]) * b^H * vl[:,i] where a^H denotes transpose(conjugate(a)). """ a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' overwrite_a = overwrite_a or (_datanotshared(a1,a)) if b is not None: b = asarray_chkfinite(b) return _geneig(a1,b,left,right,overwrite_a,overwrite_b) geev, = get_lapack_funcs(('geev',),(a1,)) compute_vl,compute_vr=left,right if geev.module_name[:7] == 'flapack': lwork = calc_lwork.geev(geev.prefix,a1.shape[0], compute_vl,compute_vr)[1] if geev.prefix in 'cz': w,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi else: # 'clapack' if geev.prefix in 'cz': w,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi if info<0: raise ValueError,\ 'illegal value in %-th argument of internal geev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" only_real = numpy.logical_and.reduce(numpy.equal(w.imag,0.0)) if not (geev.prefix in 'cz' or only_real): t = w.dtype.char if left: vl = _make_complex_eigvecs(w, vl, t) if right: vr = _make_complex_eigvecs(w, vr, t) if not (left or right): return w if left: if right: return w, vl, vr return w, vl return w, vr | def eig(a,b=None,left=0,right=1,overwrite_a=0,overwrite_b=0): """ Solve ordinary and generalized eigenvalue problem of a square matrix. Inputs: a -- An N x N matrix. b -- An N x N matrix [default is identity(N)]. left -- Return left eigenvectors [disabled]. right -- Return right eigenvectors [enabled]. Outputs: w -- eigenvalues [left==right==False]. w,vr -- w and right eigenvectors [left==False,right=True]. w,vl -- w and left eigenvectors [left==True,right==False]. w,vl,vr -- [left==right==True]. Definitions: a * vr[:,i] = w[i] * b * vr[:,i] a^H * vl[:,i] = conjugate(w[i]) * b^H * vl[:,i] where a^H denotes transpose(conjugate(a)). """ a1 = asarray_chkfinite(a) if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' overwrite_a = overwrite_a or (_datanotshared(a1,a)) if b is not None: b = asarray_chkfinite(b) return _geneig(a1,b,left,right,overwrite_a,overwrite_b) geev, = get_lapack_funcs(('geev',),(a1,)) compute_vl,compute_vr=left,right if geev.module_name[:7] == 'flapack': lwork = calc_lwork.geev(geev.prefix,a1.shape[0], compute_vl,compute_vr)[1] if geev.prefix in 'cz': w,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1,lwork = lwork, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi else: # 'clapack' if geev.prefix in 'cz': w,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) else: wr,wi,vl,vr,info = geev(a1, compute_vl=compute_vl, compute_vr=compute_vr, overwrite_a=overwrite_a) t = {'f':'F','d':'D'}[wr.dtype.char] w = wr+_I*wi if info<0: raise ValueError,\ 'illegal value in %-th argument of internal geev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" only_real = numpy.logical_and.reduce(numpy.equal(w.imag,0.0)) if not (geev.prefix in 'cz' or only_real): t = w.dtype.char if left: vl = _make_complex_eigvecs(w, vl, t) if right: vr = _make_complex_eigvecs(w, vr, t) if not (left or right): return w if left: if right: return w, vl, vr return w, vl return w, vr | 646 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a, lower=True, eigvals_only=False, overwrite_a=False): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 647 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [True: UPLO='L' (default) / False: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 648 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: For eigvals_only == False (the default), w,v -- w: eigenvalues, v: eigenvectors For eigvals_only == True, w -- eigenvalues Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 649 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 650 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 651 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 652 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 653 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 654 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 655 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 656 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 657 |
def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | def eigh(a,lower=1,eigvals_only=0,overwrite_a=0): """ Solve real symmetric or complex hermitian eigenvalue problem. Inputs: a -- A hermitian N x N matrix. lower -- values in a are read from lower triangle [1: UPLO='L' (default) / 0: UPLO='U'] eigvals_only -- don't compute eigenvectors. overwrite_a -- content of a may be destroyed Outputs: w,v -- w: eigenvalues, v: eigenvectors [for eigvals_only == False] w -- eigenvalues [for eigvals_only == True (default)]. Definitions: a * v[:,i] = w[i] * vr[:,i] v.H * v = identity """ if eigvals_only or overwrite_a: a1 = asarray_chkfinite(a) overwrite_a = overwrite_a or (_datanotshared(a1,a)) else: a1 = array(a) if (a1.dtype.char in typecodes['AllFloat']) and not isfinite(a1).all(): raise ValueError, "array must not contain infs or NaNs" overwrite_a = 1 if len(a1.shape) != 2 or a1.shape[0] != a1.shape[1]: raise ValueError, 'expected square matrix' if a1.dtype.char in 'FD': heev, = get_lapack_funcs(('heev',),(a1,)) if heev.module_name[:7] == 'flapack': lwork = calc_lwork.heev(heev.prefix,a1.shape[0],lower) w,v,info = heev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = heev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal heev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" else: # a1.dtype.char in 'fd': syev, = get_lapack_funcs(('syev',),(a1,)) if syev.module_name[:7] == 'flapack': lwork = calc_lwork.syev(syev.prefix,a1.shape[0],lower) w,v,info = syev(a1,lwork = lwork, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) else: # 'clapack' w,v,info = syev(a1, compute_v = not eigvals_only, lower = lower, overwrite_a = overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal syev'%(-info) if info>0: raise LinAlgError,"eig algorithm did not converge" if eigvals_only: return w return w, v | 658 |
def matview(A,cmax=None,cmin=None,palette=None,color='black'): """Plot an image of a matrix. """ A = Numeric.asarray(A) if A.typecode() in ['D','F']: print "Warning: complex array given, plotting magnitude." A = Numeric.abs(A) M,N = A.shape A = A[::-1,:] if cmax is None: cmax = max(ravel(A)) if cmin is None: cmin = min(ravel(A)) cmax = float(cmax) cmin = float(cmin) byteimage = gist.bytscl(A,cmin=cmin,cmax=cmax) change_palette(palette) gist.window(style='nobox.gs') _current_style='nobox.gs' gist.pli(byteimage) old_vals = gist.limits(square=1) vals = gist.limits(square=1) vp = gist.viewport() axv,bxv,ayv,byv = vp axs,bxs,ays,bys = vals[:4] # bottom left corner column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = -axs*(bxv-axv)/(bxs-axs) + axv gist.plt('1',posx,posy-0.005,justify='LT',color=color) # bottom left corner row gist.plt(str(M),posx-0.005,posy,justify='RB',color=color) # top left corner row posy = (M-ays)*(byv-ayv)/(bys-ays) + ayv gist.plt('1',posx-0.005,posy,justify='RT',color=color) # bottom right column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = (N-axs)*(bxv-axv)/(bxs-axs) + axv gist.plt(str(N),posx,posy-0.005,justify='RT',color=color) | def matview(A,cmax=None,cmin=None,palette=None,color='black'): """Plot an image of a matrix. """ A = Numeric.asarray(A) if A.typecode() in ['D','F']: print "Warning: complex array given, plotting magnitude." A = abs(A) M,N = A.shape A = A[::-1,:] if cmax is None: cmax = max(ravel(A)) if cmin is None: cmin = min(ravel(A)) cmax = float(cmax) cmin = float(cmin) byteimage = gist.bytscl(A,cmin=cmin,cmax=cmax) change_palette(palette) gist.window(style='nobox.gs') _current_style='nobox.gs' gist.pli(byteimage) old_vals = gist.limits(square=1) vals = gist.limits(square=1) vp = gist.viewport() axv,bxv,ayv,byv = vp axs,bxs,ays,bys = vals[:4] # bottom left corner column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = -axs*(bxv-axv)/(bxs-axs) + axv gist.plt('1',posx,posy-0.005,justify='LT',color=color) # bottom left corner row gist.plt(str(M),posx-0.005,posy,justify='RB',color=color) # top left corner row posy = (M-ays)*(byv-ayv)/(bys-ays) + ayv gist.plt('1',posx-0.005,posy,justify='RT',color=color) # bottom right column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = (N-axs)*(bxv-axv)/(bxs-axs) + axv gist.plt(str(N),posx,posy-0.005,justify='RT',color=color) | 659 |
def compare_times(setup, expr): print "Expression:", expr numpy_timer = timeit.Timer(expr, setup) numpy_time = numpy_timer.timeit(number=iterations) print 'numpy:', numpy_time / iterations weave_timer = timeit.Timer('blitz("result=%s")' % expr, setup) weave_time = weave_timer.timeit(number=iterations) print "Weave:", weave_time/iterations print "Speed-up of weave over numpy:", numpy_time/weave_time numexpr_timer = timeit.Timer('evaluate("%s")' % expr, setup) numexpr_time = numexpr_timer.timeit(number=iterations) print "numexpr:", numexpr_time/iterations print "Speed-up of numexpr over numpy:", numpy_time/numexpr_time | def compare_times(setup, expr): print "Expression:", expr numpy_timer = timeit.Timer(expr, setup) numpy_time = numpy_timer.timeit(number=iterations) print 'numpy:', numpy_time / iterations try: weave_timer = timeit.Timer('blitz("result=%s")' % expr, setup) weave_time = weave_timer.timeit(number=iterations) print "Weave:", weave_time/iterations print "Speed-up of weave over numpy:", numpy_time/weave_time except: print "Skipping weave timing" numexpr_timer = timeit.Timer('evaluate("%s")' % expr, setup) numexpr_time = numexpr_timer.timeit(number=iterations) print "numexpr:", numexpr_time/iterations print "Speed-up of numexpr over numpy:", numpy_time/numexpr_time | 660 |
def compare_times(setup, expr): print "Expression:", expr numpy_timer = timeit.Timer(expr, setup) numpy_time = numpy_timer.timeit(number=iterations) print 'numpy:', numpy_time / iterations weave_timer = timeit.Timer('blitz("result=%s")' % expr, setup) weave_time = weave_timer.timeit(number=iterations) print "Weave:", weave_time/iterations print "Speed-up of weave over numpy:", numpy_time/weave_time numexpr_timer = timeit.Timer('evaluate("%s")' % expr, setup) numexpr_time = numexpr_timer.timeit(number=iterations) print "numexpr:", numexpr_time/iterations print "Speed-up of numexpr over numpy:", numpy_time/numexpr_time | def compare_times(setup, expr): print "Expression:", expr numpy_timer = timeit.Timer(expr, setup) numpy_time = numpy_timer.timeit(number=iterations) print 'numpy:', numpy_time / iterations weave_timer = timeit.Timer('blitz("result=%s")' % expr, setup) weave_time = weave_timer.timeit(number=iterations) print "Weave:", weave_time/iterations print "Speed-up of weave over numpy:", numpy_time/weave_time numexpr_timer = timeit.Timer('evaluate("%s")' % expr, setup) numexpr_time = numexpr_timer.timeit(number=iterations) print "numexpr:", numexpr_time/iterations print "Speed-up of numexpr over numpy:", numpy_time/numexpr_time | 661 |
def compare_times(setup, expr): print "Expression:", expr numpy_timer = timeit.Timer(expr, setup) numpy_time = numpy_timer.timeit(number=iterations) print 'numpy:', numpy_time / iterations weave_timer = timeit.Timer('blitz("result=%s")' % expr, setup) weave_time = weave_timer.timeit(number=iterations) print "Weave:", weave_time/iterations print "Speed-up of weave over numpy:", numpy_time/weave_time numexpr_timer = timeit.Timer('evaluate("%s")' % expr, setup) numexpr_time = numexpr_timer.timeit(number=iterations) print "numexpr:", numexpr_time/iterations print "Speed-up of numexpr over numpy:", numpy_time/numexpr_time | def compare_times(setup, expr): print "Expression:", expr numpy_timer = timeit.Timer(expr, setup) numpy_time = numpy_timer.timeit(number=iterations) print 'numpy:', numpy_time / iterations weave_timer = timeit.Timer('blitz("result=%s")' % expr, setup) weave_time = weave_timer.timeit(number=iterations) print "Weave:", weave_time/iterations print "Speed-up of weave over numpy:", numpy_time/weave_time numexpr_timer = timeit.Timer('evaluate("%s")' % expr, setup) numexpr_time = numexpr_timer.timeit(number=iterations) print "numexpr:", numexpr_time/iterations print "Speed-up of numexpr over numpy:", numpy_time/numexpr_time | 662 |
def check(expr): try: if not alltrue(eval(expr) == evaluate(expr)): print ">>> %s: FAILED" % expr print " GOT :", evaluate(expr)[:3], "..." print " EXPECTED :", eval(expr)[:3], "..." return False else: print " %s" % expr#, evaluate(expr)[:3], "..." return True except StandardError, err: print ">>> %s: ERROR(%s)" % (expr, err) return False | def check(expr): try: npval = eval(expr) neval = evaluate(expr) if not (shape(npval) == shape(neval) and alltrue(ravel(npval) == ravel(neval))): print ">>> %s: FAILED" % expr print " GOT :", evaluate(expr)[:3], "..." print " EXPECTED :", eval(expr)[:3], "..." return False else: print " %s" % expr#, evaluate(expr)[:3], "..." return True except StandardError, err: print ">>> %s: ERROR(%s)" % (expr, err) return False | 663 |
def check(expr): try: if not alltrue(eval(expr) == evaluate(expr)): print ">>> %s: FAILED" % expr print " GOT :", evaluate(expr)[:3], "..." print " EXPECTED :", eval(expr)[:3], "..." return False else: print " %s" % expr#, evaluate(expr)[:3], "..." return True except StandardError, err: print ">>> %s: ERROR(%s)" % (expr, err) return False | def check(expr): try: if not alltrue(eval(expr) == evaluate(expr)): print ">>> %s: FAILED" % expr print " GOT :", neval[:3], "..." print " EXPECTED :", npval[:3], "..." return False else: print " %s" % expr#, evaluate(expr)[:3], "..." return True except StandardError, err: print ">>> %s: ERROR(%s)" % (expr, err) return False | 664 |
def fixed_point(func, x0, args=(), tol=1e-10, maxiter=50): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < tol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | def fixed_point(func, x0, args=(), xtol=1e-10, maxiter=500): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < tol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | 665 |
def fixed_point(func, x0, args=(), tol=1e-10, maxiter=50): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < tol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | def fixed_point(func, x0, args=(), tol=1e-10, maxiter=50): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Warning: Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < tol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | 666 |
def fixed_point(func, x0, args=(), tol=1e-10, maxiter=50): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < tol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | def fixed_point(func, x0, args=(), tol=1e-10, maxiter=50): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < xtol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | 667 |
def fixed_point(func, x0, args=(), tol=1e-10, maxiter=50): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < tol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | def fixed_point(func, x0, args=(), tol=1e-10, maxiter=50): """Given a function of one variable and a starting point, find a fixed-point of the function: i.e. where func(x)=x. """ p0 = x0 for iter in range(maxiter): p1 = apply(func,(p0,)+args) p2 = apply(func,(p1,)+args) try: p = p0 - (p1 - p0)*(p1-p0) / (p2-2.0*p1+p0) except ZeroDivisionError: print "Difference in estimates is %g" % (abs(p2-p1)) return p2 if abs(p-p0) < tol: return p p0 = p raise RuntimeError, "Failed to converge after %d iterations, value is %f" % (maxiter,p) | 668 |
def draw(self,dc=None): #if not len(self.line_list) or len(self.image_list): # return # resize if necessary #print 'draw' t1 = time.clock();self.reset_size(dc);t2 = time.clock() #print 'resize:',t2 - t1 if not dc: dc = wx.wxClientDC(self) | def draw(self,dc=None): #if not len(self.line_list) or len(self.image_list): # return # resize if necessary #print 'draw' t1 = time.clock();self.reset_size(dc);t2 = time.clock() #print 'resize:',t2 - t1 if not dc: dc = wx.wxClientDC(self) | 669 |
def update(self): self.client_size = (0,0) # forces the layout self.Refresh() | def update(self,event=None): self.client_size = (0,0) # forces the layout self.Refresh() | 670 |
def func_and_grad(x): x = asarray(x) f = func(x, *args) g = fprime(x, *args) return f, list(g) | def func_and_grad(x): x = asarray(x) f = func(x, *args) g = fprime(x, *args) return f, list(g) | 671 |
def figure(which_one = None): global _figure; global _active if which_one == None: title ='Figure %d' % len(_figure) _figure.append(plot_class(title=title)) _active = _figure[-1] else: if (type(which_one) == type(1)) or (type(which_one) == type(1.)): try: _active = _figure[int(which_one)] except IndexError: msg = "There are currently only %d active figures" % len(_figure) raise IndexError, msg #try: _figure.index(which_one) #except ValueError: _figure.append(which_one) #_active = which_one return current() | def figure(which_one = None): global _figure; global _active if which_one == None: title ='Figure %d' % len(_figure) _figure.append(plot_class(title=title)) _active = _figure[-1] else: if (type(which_one) == type(1)) or (type(which_one) == type(1.)): try: _active = _figure[int(which_one)] except IndexError: msg = "There are currently only %d active figures" % len(_figure) raise IndexError, msg #try: _figure.index(which_one) #except ValueError: _figure.append(which_one) #_active = which_one return current() | 672 |
def test_smallest_same_kind(self): R = self.recaster value = 1 # smallest same kind # Define expected type output from same kind downcast of value required_types = {'complex': N.complex128, 'float': N.float64, 'int': N.int32, 'uint': None} for kind, req_type in required_types.items(): if req_type is not None: rdtsz = N.dtype(req_type).itemsize for T in N.sctypes[kind]: tdtsz = N.dtype(T).itemsize ok_T = T in R.sctype_list expect_none = ((req_type is None) or ((tdtsz < rdtsz) and not ok_T)) A = N.array(value, T) C = R.smallest_same_kind(A) if expect_none: assert C is None, 'Expecting None for %s' % T else: assert C is not None, 'Got unexpected None from %s' % T assert C.dtype.type == req_type, \ 'Expected %s type, got %s type' % \ (C.dtype.type, req_type) | def test_smallest_same_kind(self): R = self.recaster value = 1 # smallest same kind # Define expected type output from same kind downcast of value required_types = {'complex': N.complex128, 'float': N.float64, 'int': N.int32, 'uint': None} for kind, req_type in required_types.items(): if req_type is not None: rdtsz = N.dtype(req_type).itemsize for T in N.sctypes[kind]: tdtsz = N.dtype(T).itemsize ok_T = T in R.sctype_list expect_none = ((req_type is None) or ((tdtsz <= rdtsz) and not ok_T)) A = N.array(value, T) C = R.smallest_same_kind(A) if expect_none: assert C is None, 'Expecting None for %s' % T else: assert C is not None, 'Got unexpected None from %s' % T assert C.dtype.type == req_type, \ 'Expected %s type, got %s type' % \ (C.dtype.type, req_type) | 673 |
def binompdf(k, n, pr=0.5): k = arr(k) assert (0<pr<1) cond = arr((k > 0) & (k == floor(k))) return where(cond, special.bdtr(k,n,pr)-special.bdtr(k-1,n,pr), 0.0) | def binompdf(k, n, pr=0.5): k = arr(k) assert (0<pr<1) cond = arr((k > 0) & (k == floor(k))) sv =errp(0) temp = special.bdtr(k,n,pr) temp2 = special.bdtr(k-1,n,pr) sv = errp(sv) return select([cond,k==0], [temp-temp2,temp],0.0) | 674 |
def buttord(wp, ws, gpass, gstop, analog=0): """Butterworth filter order selection. Description: Return the order of the lowest order digital Butterworth filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: wp = 0.2, ws = 0.3 Highpass: wp = 0.3, ws = 0.2 Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Butterworth filter which meets specs. Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). Should be used with scipy.signal.butter to give filter results. """ wp = asarray_1d(wp) ws = asarray_1d(ws) filter_type = 2*(len(wp)-1) filter_type +=1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies if not analog: passb = tan(wp*pi/2.0) stopb = tan(ws*pi/2.0) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'butter'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'butter'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil( log10((GSTOP-1.0)/(GPASS-1.0)) / (2*log10(nat)))) # Find the butterworth natural frequency W0 (or the "3dB" frequency") # to give exactly gstop at nat. W0 will be between 1 and nat try: W0 = nat / ( ( 10**(0.1*abs(gstop))-1)**(1.0/(2.0*or))) except ZeroDivisionError: W0 = nat print "Warning, order is zero...check input parametegstop." # now convert this frequency back from lowpass prototype # to the original analog filter if filter_type == 1: # low WN = W0*passb elif filter_type == 2: # high WN = passb / W0 elif filter_type == 3: # stop WN = zeros(2,Numeric.Float) WN[0] = ((passb[1] - passb[0]) + sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN[1] = ((passb[1] - passb[0]) - sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN = Num.sort(abs(WN)) elif filter_type == 4: # pass W0 = array([-W0, W0],Numeric.Float) WN = -W0 * (passb[1]-passb[0]) / 2.0 + sqrt(W0**2 / 4.0 * \ (passb[1]-passb[0])**2 + \ passb[0]*passb[1]) WN = Num.sort(abs(WN)) else: raise ValueError, "Bad type." if not analog: wn = (2.0/pi)*arctan(WN) else: wn = WN return ord, wn | def buttord(wp, ws, gpass, gstop, analog=0): """Butterworth filter order selection. Description: Return the order of the lowest order digital Butterworth filter that loses no more than gpass dB in the passband and has at least gstop dB attenuation in the stopband. Inputs: wp, ws -- Passb and stopb edge frequencies, normalized from 0 to 1 (1 corresponds to pi radians / sample). For example: Lowpass: wp = 0.2, ws = 0.3 Highpass: wp = 0.3, ws = 0.2 Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] gpass -- The maximum loss in the passband (dB). gstop -- The minimum attenuation in the stopband (dB). analog -- Non-zero to design an analog filter (in this case wp and ws are in radians / second). Outputs: (ord, Wn) ord -- The lowest order for a Butterworth filter which meets specs. Wn -- The Butterworth natural frequency (i.e. the "3dB frequency"). Should be used with scipy.signal.butter to give filter results. """ wp = asarray_1d(wp) ws = asarray_1d(ws) filter_type = 2*(len(wp)-1) filter_type +=1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies if not analog: passb = tan(wp*pi/2.0) stopb = tan(ws*pi/2.0) else: passb = wp stopb = ws if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = scipy.optimize.fminbound(band_stop_obj, passb[0], stopb[0]-1e-12, args=(0,passb,stopb,gpass,gstop,'butter'), disp=0) passb[0] = wp0 wp1 = scipy.optimize.fminbound(band_stop_obj, stopb[1]+1e-12, passb[1], args=(1,passb,stopb,gpass,gstop,'butter'), disp=0) passb[1] = wp1 nat = (stopb * (passb[0]-passb[1])) / (stopb**2 - passb[0]*passb[1]) elif filter_type == 4: # pass nat = (stopb**2 - passb[0]*passb[1]) / (stopb* (passb[0]-passb[1])) nat = min(abs(nat)) GSTOP = 10**(0.1*abs(gstop)) GPASS = 10**(0.1*abs(gpass)) ord = int(ceil( log10((GSTOP-1.0)/(GPASS-1.0)) / (2*log10(nat)))) # Find the butterworth natural frequency W0 (or the "3dB" frequency") # to give exactly gstop at nat. W0 will be between 1 and nat try: W0 = nat / ( ( 10**(0.1*abs(gstop))-1)**(1.0/(2.0*ord))) except ZeroDivisionError: W0 = nat print "Warning, order is zero...check input parametegstop." # now convert this frequency back from lowpass prototype # to the original analog filter if filter_type == 1: # low WN = W0*passb elif filter_type == 2: # high WN = passb / W0 elif filter_type == 3: # stop WN = zeros(2,Numeric.Float) WN[0] = ((passb[1] - passb[0]) + sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN[1] = ((passb[1] - passb[0]) - sqrt((passb[1] - passb[0])**2 + \ 4*W0**2 * passb[0] * passb[1])) / (2*W0) WN = Num.sort(abs(WN)) elif filter_type == 4: # pass W0 = array([-W0, W0],Numeric.Float) WN = -W0 * (passb[1]-passb[0]) / 2.0 + sqrt(W0**2 / 4.0 * \ (passb[1]-passb[0])**2 + \ passb[0]*passb[1]) WN = Num.sort(abs(WN)) else: raise ValueError, "Bad type." if not analog: wn = (2.0/pi)*arctan(WN) else: wn = WN return ord, wn | 675 |
def mathieu_odd_coef(m,q): """Compute expansion coefficients for even mathieu functions and modified mathieu functions. """ if not (isscalar(m) and isscalar(q)): raise ValueError, "m and q must be scalars." if (q < 0): raise ValueError, "q >=0" if (m != floor(m)) or (m<=0): raise ValueError, "m must be an integer > 0" if (q <= 1): qm = 7.5+56.1*sqrt(q)-134.7*q+90.7*sqrt(q)*q else: qm=17.0+3.1*sqrt(q)-.126*q+.0037*sqrt(q)*q km = int(qm+0.5*m) if km > 251: print "Warning, too many predicted coefficients." kd = 4 m = int(floor(m)) if m % 2: kd = 3 b = mathieu_b(m,q) fc = specfunc.fcoef(kd,m,q,b) return fc[:km] | defmathieu_odd_coef(m,q):"""Computeexpansioncoefficientsforevenmathieufunctionsandmodifiedmathieufunctions."""ifnot(isscalar(m)andisscalar(q)):raiseValueError,"mandqmustbescalars."if(q<0):raiseValueError,"q>=0"if(m!=floor(m))or(m<=0):raiseValueError,"mmustbeaninteger>0"if(q<=1):qm=7.5+56.1*sqrt(q)-134.7*q+90.7*sqrt(q)*qelse:qm=17.0+3.1*sqrt(q)-.126*q+.0037*sqrt(q)*qkm=int(qm+0.5*m)ifkm>251:print"Warning,toomanypredictedcoefficients."kd=4m=int(floor(m))ifm%2:kd=3b=mathieu_b(m,q)fc=specfunc.fcoef(kd,m,q,b)returnfc[:km] | 676 |
def lpmn(m,n,z): """Associated Legendre functions of the second kind, Pmn(z) and its derivative, Pmn'(z) of order m and degree n. Returns two arrays of size (m+1,n+1) containing Pmn(z) and Pmn'(z) for all orders from 0..m and degrees from 0..n. z can be complex. """ if not isscalar(m) or (m<0): raise ValueError, "m must be a non-negative integer." if not isscalar(n) or (n<0): raise ValueError, "n must be a non-negative integer." if not isscalar(z): raise ValueError, "z must be scalar." if iscomplex(z): p,pd = specfun.clpmn(m,n,z) else: p,pd = specfun.lpmn(m,n,z) return p,pd | def lpmn(m,n,z): """Associated Legendre functions of the second kind, Pmn(z) and its derivative, Pmn'(z) of order m and degree n. Returns two arrays of size (m+1,n+1) containing Pmn(z) and Pmn'(z) for all orders from 0..m and degrees from 0..n. z can be complex. """ if not isscalar(m) or (abs(m)>n): raise ValueError, "m must be <= n." if not isscalar(n) or (n<0): raise ValueError, "n must be a non-negative integer." if not isscalar(z): raise ValueError, "z must be scalar." if iscomplex(z): p,pd = specfun.clpmn(m,n,z) else: p,pd = specfun.lpmn(m,n,z) return p,pd | 677 |
def lpmn(m,n,z): """Associated Legendre functions of the second kind, Pmn(z) and its derivative, Pmn'(z) of order m and degree n. Returns two arrays of size (m+1,n+1) containing Pmn(z) and Pmn'(z) for all orders from 0..m and degrees from 0..n. z can be complex. """ if not isscalar(m) or (m<0): raise ValueError, "m must be a non-negative integer." if not isscalar(n) or (n<0): raise ValueError, "n must be a non-negative integer." if not isscalar(z): raise ValueError, "z must be scalar." if iscomplex(z): p,pd = specfun.clpmn(m,n,z) else: p,pd = specfun.lpmn(m,n,z) return p,pd | def lpmn(m,n,z): """Associated Legendre functions of the second kind, Pmn(z) and its derivative, Pmn'(z) of order m and degree n. Returns two arrays of size (m+1,n+1) containing Pmn(z) and Pmn'(z) for all orders from 0..m and degrees from 0..n. z can be complex. """ if not isscalar(m) or (m<0): raise ValueError, "m must be a non-negative integer." if not isscalar(n) or (n<0): raise ValueError, "n must be a non-negative integer." if not isscalar(z): raise ValueError, "z must be scalar." if iscomplex(z): p,pd = specfun.clpmn(mp,n,real(z),imag(z)) else: p,pd = specfun.lpmn(m,n,z) return p,pd | 678 |
def lpmn(m,n,z): """Associated Legendre functions of the second kind, Pmn(z) and its derivative, Pmn'(z) of order m and degree n. Returns two arrays of size (m+1,n+1) containing Pmn(z) and Pmn'(z) for all orders from 0..m and degrees from 0..n. z can be complex. """ if not isscalar(m) or (m<0): raise ValueError, "m must be a non-negative integer." if not isscalar(n) or (n<0): raise ValueError, "n must be a non-negative integer." if not isscalar(z): raise ValueError, "z must be scalar." if iscomplex(z): p,pd = specfun.clpmn(m,n,z) else: p,pd = specfun.lpmn(m,n,z) return p,pd | def lpmn(m,n,z): """Associated Legendre functions of the second kind, Pmn(z) and its derivative, Pmn'(z) of order m and degree n. Returns two arrays of size (m+1,n+1) containing Pmn(z) and Pmn'(z) for all orders from 0..m and degrees from 0..n. z can be complex. """ if not isscalar(m) or (m<0): raise ValueError, "m must be a non-negative integer." if not isscalar(n) or (n<0): raise ValueError, "n must be a non-negative integer." if not isscalar(z): raise ValueError, "z must be scalar." if iscomplex(z): p,pd = specfun.clpmn(m,n,z) else: p,pd = specfun.lpmn(mp,n,z) if (m < 0): p = p * fixarr pd = pd * fixarr return p,pd | 679 |
def _valfrommode(mode): try: val = _modedict[mode] except KeyError: if val not in [0,1,2]: raise ValueError, "Acceptable mode flags are 'valid' (0), 'same' (1), or 'full' (2)." val = mode return val | def _valfrommode(mode): try: val = _modedict[mode] except KeyError: if mode not in [0,1,2]: raise ValueError, "Acceptable mode flags are 'valid' (0), 'same' (1), or 'full' (2)." val = mode return val | 680 |
def __init__(self, mat_stream, byte_order=None, base_name='raw', matlab_compatible=False, squeeze_me=True, chars_as_strings=True, ): # Initialize stream self.mat_stream = mat_stream self.dtypes = {} if not byte_order: byte_order = self.guess_byte_order() self.order_code = byte_order # sets dtypes and other things too self.base_name = base_name self.squeeze_me = squeeze_me self.chars_as_strings = chars_as_strings self.matlab_compatible = matlab_compatible | def __init__(self, mat_stream, byte_order=None, base_name='raw', matlab_compatible=False, squeeze_me=True, chars_as_strings=True, ): # Initialize stream self.mat_stream = mat_stream self.dtypes = {} if not byte_order: byte_order = self.guess_byte_order() self.order_code = byte_order # sets dtypes and other things too self.base_name = base_name self._squeeze_me = squeeze_me self._chars_as_strings = chars_as_strings self.matlab_compatible = matlab_compatible | 681 |
def set_matlab_compatible(self, matlab_compatible): self._matlab_compatible = matlab_compatible if matlab_compatible: self.squeeze_me = False self.char_as_strings = False self.processor_func = self.get_processor_func() | def set_matlab_compatible(self, m_l_c): self._matlab_compatible = m_l_c if m_l_c: self._squeeze_me = False self._chars_as_strings = False self.processor_func = self.get_processor_func() | 682 |
def func(arr, getter): if arr.dtype.kind == 'U' and self.chars_as_strings: # Convert char array to string or array of strings dims = arr.shape if len(dims) >= 2: # return array of strings dtt = self.order_code + 'U' n_dims = dims[:-1] str_arr = reshape(arr, (small_product(n_dims), dims[-1])) arr = empty(n_dims, dtype=object) for i in range(0, n_dims[-1]): arr[...,i] = self.chars_to_str(str_arr[i]) else: # return string arr = self.chars_to_str(arr) if self.matlab_compatible: # Apply options to replicate matlab's (TM) # load into workspace if getter.mat_dtype: arr = arr.astype(getter.mat_dtype) if self.squeeze_me: arr = squeeze(arr) if not arr.size: arr = array([]) elif not arr.shape: # 0d coverted to scalar arr = arr.item() return arr | def func(arr, getter): if arr.dtype.kind == 'U' and self.chars_as_strings: # Convert char array to string or array of strings dims = arr.shape if len(dims) >= 2: # return array of strings dtt = self.order_code + 'U' n_dims = dims[:-1] str_arr = reshape(arr, (small_product(n_dims), dims[-1])) arr = empty(n_dims, dtype=object) for i in range(0, n_dims[-1]): arr[...,i] = self.chars_to_str(str_arr[i]) else: # return string arr = self.chars_to_str(arr) if self.matlab_compatible: # Apply options to replicate matlab's (TM) # load into workspace if getter.mat_dtype is not None: arr = arr.astype(getter.mat_dtype) if self.squeeze_me: arr = squeeze(arr) if not arr.size: arr = array([]) elif not arr.shape: # 0d coverted to scalar arr = arr.item() return arr | 683 |
def all_subroutines(interface_in): # remove comments comment_block_exp = re.compile(r'/\*(?:\s|.)*?\*/') subroutine_exp = re.compile(r'subroutine (?:\s|.)*?end subroutine.*') function_exp = re.compile(r'function (?:\s|.)*?end function.*') interface = comment_block_exp.sub('',interface_in) subroutine_list = subroutine_exp.findall(interface) function_list = function_exp.findall(interface) #function_list = [] subroutine_list = subroutine_list + function_list subroutine_list = map(lambda x: string.strip(x),subroutine_list) return subroutine_list | defall_subroutines(interface_in):#removecommentscomment_block_exp=re.compile(r'/\*(?:\s|.)*?\*/')subroutine_exp=re.compile(r'subroutine(?:\s|.)*?endsubroutine.*')function_exp=re.compile(r'function(?:\s|.)*?endfunction.*')interface=comment_block_exp.sub('',interface_in)subroutine_list=subroutine_exp.findall(interface)function_list=function_exp.findall(interface)#function_list=[]subroutine_list=subroutine_list+function_listsubroutine_list=map(lambdax:string.strip(x),subroutine_list)returnsubroutine_list | 684 |
def __init__(self,x,y,z,kind='linear', copy=True,bounds_error=0,fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('nearest', 'linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if self.x > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'qunitic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('nearest', 'linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if self.x > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'qunitic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | 685 |
def __init__(self,x,y,z,kind='linear', copy=True,bounds_error=0,fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('nearest', 'linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if self.x > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'qunitic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | def __init__(self,x,y,z,kind='linear', copy=True,bounds_error=0,fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if self.x > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'qunitic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | 686 |
def __init__(self,x,y,z,kind='linear', copy=True,bounds_error=0,fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('nearest', 'linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if self.x > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'qunitic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | def __init__(self,x,y,z,kind='linear', copy=True,bounds_error=0,fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('nearest', 'linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if rank(self.x) > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'qunitic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | 687 |
def __init__(self,x,y,z,kind='linear', copy=True,bounds_error=0,fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('nearest', 'linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if self.x > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'qunitic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | def __init__(self,x,y,z,kind='linear', copy=True,bounds_error=0,fill_value=None): """ Input: x,y - 1-d arrays defining 2-d grid (or 2-d meshgrid arrays) z - 2-d array of grid values kind - interpolation type ('nearest', 'linear', 'cubic', 'quintic') copy - if true then data is copied into class, otherwise only a reference is held. bounds_error - if true, then when out_of_bounds occurs, an error is raised otherwise, the output is filled with fill_value. fill_value - if None, then NaN, otherwise the value to fill in outside defined region. """ self.x = atleast_1d(x).copy() self.y = atleast_1d(y).copy() if self.x > 2 or rank(self.y) > 2: raise ValueError, "One of the input arrays is not 1-d or 2-d." if rank(self.x) == 2: self.x = self.x[:,0] if rank(self.y) == 2: self.y = self.y[0] self.z = array(z,copy=True) if rank(z) != 2: raise ValueError, "Grid values is not a 2-d array." try: kx = {'linear' : 1, 'cubic' : 3, 'quintic' : 5}[kind] except: raise ValueError, "Unsupported interpolation type." | 688 |
def __call__(self,x,y,dx=0,dy=0): """ Input: x,y - 1-d arrays defining points to interpolate. dx,dy - order of partial derivatives in x and y, respectively. 0<=dx<kx, 0<=dy<ky Output: z - 2-d array of interpolated values """ x = atleast_1d(x) y = atleast_1d(y) z,ier=fitpack._fitpack._bispev(*(self.tck+[x,y,dx,dy])) if ier==10: raise ValueError,"Invalid input data" if ier: raise TypeError,"An error occurred" z.shape=len(x),len(y) z = transpose(z) if len(z)==1: z = z[0] return array(z) | def __call__(self,x,y,dx=0,dy=0): """ Input: x,y - 1-d arrays defining points to interpolate. dx,dy - order of partial derivatives in x and y, respectively. 0<=dx<kx, 0<=dy<ky Output: z - 2-d array of interpolated values """ x = atleast_1d(x) y = atleast_1d(y) z,ier=fitpack.bisplev(self.tck, x, y, dx, dy) if ier==10: raise ValueError, "Invalid input data" if ier: raise TypeError, "An error occurred" z.shape=len(x),len(y) z = transpose(z) if len(z)==1: z = z[0] return array(z) | 689 |
def __call__(self,x,y,dx=0,dy=0): """ Input: x,y - 1-d arrays defining points to interpolate. dx,dy - order of partial derivatives in x and y, respectively. 0<=dx<kx, 0<=dy<ky Output: z - 2-d array of interpolated values """ x = atleast_1d(x) y = atleast_1d(y) z,ier=fitpack._fitpack._bispev(*(self.tck+[x,y,dx,dy])) if ier==10: raise ValueError,"Invalid input data" if ier: raise TypeError,"An error occurred" z.shape=len(x),len(y) z = transpose(z) if len(z)==1: z = z[0] return array(z) | def __call__(self,x,y,dx=0,dy=0): """ Input: x,y - 1-d arrays defining points to interpolate. dx,dy - order of partial derivatives in x and y, respectively. 0<=dx<kx, 0<=dy<ky Output: z - 2-d array of interpolated values """ x = atleast_1d(x) y = atleast_1d(y) z,ier=fitpack._fitpack._bispev(*(self.tck+[x,y,dx,dy])) if ier==10: raise ValueError,"Invalid input data" if ier: raise TypeError,"An error occurred" z.shape=len(x),len(y) z = transpose(z) if len(z)==1: z = z[0] return array(z) | 690 |
def gmres(A,b,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector restrt -- A restart value Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros(5*n,typ) work2 = sb.zeros(restrt*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | def gmres(A,b,restrt=None,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector restrt -- A restart value Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros(5*n,typ) work2 = sb.zeros(restrt*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | 691 |
def gmres(A,b,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector restrt -- A restart value Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros(5*n,typ) work2 = sb.zeros(restrt*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | def gmres(A,b,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros(5*n,typ) work2 = sb.zeros(restrt*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | 692 |
def gmres(A,b,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector restrt -- A restart value Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros(5*n,typ) work2 = sb.zeros(restrt*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | def gmres(A,b,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector restrt -- A restart value Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros(5*n,typ) work2 = sb.zeros(restrt*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | 693 |
def gmres(A,b,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector restrt -- A restart value Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros(5*n,typ) work2 = sb.zeros(restrt*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | def gmres(A,b,x0=None,tol=1e-5,maxiter=None): """Use Generalized Minimal RESidual iteration to solve A x = b Inputs: A -- An array or an object with a matvec(x) method to represent A * x. May also have a psolve(b) methods for representing solution to the preconditioning equation M * x = b. b -- An n-length vector restrt -- A restart value Outputs: x -- The converged solution info -- output result 0 : successful exit >0 : convergence to tolerance not achieved, number of iterations <0 : illegal input or breakdown Optional Inputs: x0 -- (0) default starting guess tol -- (1e-5) relative tolerance to achieve maxiter -- (10*n) maximum number of iterations """ b = sb.asarray(b) n = len(b) typ = b.typecode() if maxiter is None: maxiter = n*10 x = x0 if x is None: x = sb.zeros(n,typ) matvec, psolve = (None,)*2 ltr = _type_conv[typ] revcom = _iterative.__dict__[ltr+'gmresrevcom'] stoptest = _iterative.__dict__[ltr+'stoptest2'] restrt = n resid = tol ndx1 = 1 ndx2 = -1 work = sb.zeros((6+restrt)*n,typ) work2 = sb.zeros((restrt+1)*(2*restrt+2),typ) ijob = 1 info = 0 ftflag = True bnrm2 = -1.0 iter_ = maxiter while 1: x, iter_, resid, info, ndx1, ndx2, sclr1, sclr2, ijob = \ revcom(b, x, restrt, work, work2, iter_, resid, info, ndx1, ndx2, ijob) slice1 = slice(ndx1-1, ndx1-1+n) slice2 = slice(ndx2-1, ndx2-1+n) if (ijob == -1): break elif (ijob == 1): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(x) elif (ijob == 2): if psolve is None: psolve = get_psolve(A) work[slice1] = psolve(work[slice2]) elif (ijob == 3): if matvec is None: matvec = get_matvec(A) work[slice2] *= sclr2 work[slice2] += sclr1*matvec(work[slice1]) elif (ijob == 4): if ftflag: info = -1 ftflag = False bnrm2, resid, info = stoptest(work[slice1], b, bnrm2, tol, info) ijob = 2 return x, info | 694 |
fpedef = "-DFPU_HPUX" | fpedef = "-DFPU_HPUX" | 695 |
fpedef = "-DFPU_HPUX" | fpedef = "-DFPU_HPUX" | 696 |
def check_axpy(self): for p in 'sd': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2,3],[2,-1,3]),[7,9,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2,3],[2,-1,3]),[7,9,18],a=5) for p in 'cz': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2j,3],[2,-1,3]),[7,10j-1,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2j,3],[2,-1,3]),[7,10j-1,18],a=5) | def check_axpy(self): for p in 'sd': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2,3],[2,-1,3]),[7,9,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2,3],[2,-1,3],a=5),[7,9,18]) for p in 'cz': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2j,3],[2,-1,3]),[7,10j-1,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2j,3],[2,-1,3]),[7,10j-1,18],a=5) | 697 |
def check_axpy(self): for p in 'sd': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2,3],[2,-1,3]),[7,9,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2,3],[2,-1,3]),[7,9,18],a=5) for p in 'cz': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2j,3],[2,-1,3]),[7,10j-1,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2j,3],[2,-1,3]),[7,10j-1,18],a=5) | def check_axpy(self): for p in 'sd': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2,3],[2,-1,3]),[7,9,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2,3],[2,-1,3]),[7,9,18],a=5) for p in 'cz': f = getattr(cblas,p+'axpy') assert_array_almost_equal(f(5,[1,2j,3],[2,-1,3]),[7,10j-1,18]) f = getattr(fblas,p+'axpy') assert_array_almost_equal(f([1,2j,3],[2,-1,3]),[7,10j-1,18],a=5) | 698 |
def check_basic(self): ba = [1,2,10,11,6,5,4] ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]] for ctype in ['1','b','s','i','l','f','d','F','D']: a = array(ba,ctype) a2 = array(ba2,ctype) if ctype in ['1', 'b']: self.failUnlessRaises(ArithmeticError, cumprod, a) self.failUnlessRaises(ArithmeticError, cumprod, a2, 1) self.failUnlessRaises(ArithmeticError, cumprod, a) else: assert_array_equal(cumprod(a), array([1, 2, 20, 220, 1320, 6600, 26400],ctype)) assert_array_equal(cumprod(a2), array([[ 1, 2, 3, 4], [ 5, 12, 21, 36], [50, 36, 84, 180]],ctype)) assert_array_equal(cumprod(a2,axis=1), array([[ 1, 2, 6, 24], [ 5, 30, 210, 1890], [10, 30, 120, 600]],ctype)) | def check_basic(self): ba = [1,2,10,11,6,5,4] ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]] for ctype in ['1','b','s','i','l','f','d','F','D']: a = array(ba,ctype) a2 = array(ba2,ctype) if ctype in ['1', 'b']: self.failUnlessRaises(ArithmeticError, cumprod, a) self.failUnlessRaises(ArithmeticError, cumprod, a2, 1) self.failUnlessRaises(ArithmeticError, cumprod, a) else: assert_array_equal(cumprod(a), array([1, 2, 20, 220, 1320, 6600, 26400],ctype)) assert_array_equal(cumprod(a2), array([[ 1, 2, 3, 4], [ 5, 12, 21, 36], [50, 36, 84, 180]],ctype)) assert_array_equal(cumprod(a2,axis=1), array([[ 1, 2, 6, 24], [ 5, 30, 210, 1890], [10, 30, 120, 600]],ctype)) | 699 |
Subsets and Splits