def setRoots(self, tau, m, pa, theta=.5*pi, verbose = False): """Laplace-transformed function Required Inputs b :: float :: Laplace-transformed time tau :: float :: average trajectory length m :: float :: mass parameter - the lowest frequency mode pa :: float :: average acceptance probability Optional Inputs theta :: float :: mixing angle verbose :: bool :: prints out residues, poles and constant from scipy's residuez function Numerator and Denominator are defined as polynomial arrays increasing in order stating from 0th order and ending at nth order """ self.tau = tau self.r = r = 1./tau self.m = m self.theta = theta self.pa = pa if theta == .5*pi: m2 = m*m phi = m*tau phi2 = phi*phi r2 = r*r r3 = r2*r if pa > self.p_thresh: numerator = [r, 2*r2, 2*m2*r + r3] denominator = [1, 2*r, r2 + 4*m2, 2*m2*r] else: numerator = [r, 2*r2, (4 - 2*pa)*phi2*r + r3] denominator = [1, 2*r, (4*phi2 + 1)*r2, 2*pa*r3*phi2] # get the roots self.res, self.poles, self.const = map(array, residuez(numerator, denominator)) if verbose: display = lambda t, x: '\n{}: {}'.format(t, x) print display('Residues', self.res) print display('Poles', self.poles) print display('Constant', self.const) else: if pa > self.p_thresh: denominator = numerator = None else: denominator = numerator = None self.d = denominator self.n = numerator return self.poles
def gen_speech(F, bw, sig, fs): """ Args : F: formant frequencies (np array) sig: original signal to filter fs: sampling frequency [Hz] """ nsecs = len(F) R = np.exp(-np.pi * bw / fs) # pope radii theta = 2 * np.pi * F / fs # pole angles poles = R * np.exp(1j * theta) A = np.real(np.poly(np.concatenate([poles, poles.conj()], axis=0))) B = np.zeros(A.shape) B[0] = 1 r, p, f = signal.residuez(B, A) As = np.zeros((nsecs, 3), dtype=np.complex) Bs = np.zeros((nsecs, 3), dtype=np.complex) for idx, i in enumerate(range(1, 2 * nsecs + 1, 2)): j = i - 1 Bs[idx] = [r[j] + r[j + 1], -(r[j] * p[j + 1] + r[j + 1] * p[j]), 0] As[idx] = [1, -(p[j] + p[j + 1]), p[j] * p[j + 1]] sos = np.concatenate([As, Bs], axis=1) iperr = np.abs(np.imag(sos)) / (np.abs(sos) + 1e-10) sos = np.real(sos) Bh, Ah = signal.sos2tf(sos) nfft = 512 H = np.zeros((nsecs + 1, nfft)) for i in range(nsecs): Hiw, w = signal.freqz(Bs[i, :], As[i, :]) H[i + 1, :] = np.conj(Hiw[:]) H[0, :] = np.sum(H[1:, :], axis=0) speech = signal.lfilter([1], A, sig) speech = speech - speech.mean() speech = speech / np.max(np.abs(speech)) return speech
import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig import scipy import control import control as con #%% #Consider the causal function, #y[k] = 2x[k] − 40x[k − 1] + 10y[k − 1] − 16y[k − 2], #where y[k] is the output and x[k] is the input. Assume that the system is initally at rest num = [2, -40] den = [1, -10, 16] sig.residuez(num, den) #%% import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig #%% Zplane function # # Copyright (c) 2011 Christopher Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. #
# r = 1.5; plt.axis('scaled'); plt.axis([-r, r, -r, r]) # ticks = [-1, -.5, .5, 1]; plt.xticks(ticks); plt.yticks(ticks) if filename is None: plt.show() else: plt.savefig(filename) return z, p, k # Task 3 num = [2, -40] den = [1, -10, 16] r, p, k = sig.residuez(num, den) # r, p, and k returned from residue are the residue, poles, and gain print("Task 3 Residue Results:\n r = {}\n p = {}\n k = {}\n ".format(r, p, k)) # Task 4 z, p, k = zplane(num, den) print('Zeros = ', z, '\nPoles = ', p) # dotted circle is unit circle; if zeros or poles are outside of it, the system is unstable # Task 5 w, h = sig.freqz(num, den, whole=True) plt.figure(figsize=(10, 7)) plt.subplot(2, 1, 1) plt.ylabel('|H(jω)| (dB)') plt.semilogx(w / np.pi, 20 * np.log10(np.abs(h)))
# r = 1.5; plt.axis('scaled'); plt.axis([-r, r, -r, r]) # ticks = [-1, -.5, .5, 1]; plt.xticks(ticks); plt.yticks(ticks) if filename is None: plt.show() else: plt.savefig(filename) return z, p, k ############################################################################# num = [2, -40] denom = [1, -10, 16] [R, P, _] = sig.residuez(num, denom) print('R = ', R, '\nP = ', P) R, P, K = zplane(num, denom) w, h = sig.freqz(num, denom, whole=True) mag = 20 * np.log10(np.abs(h)) phase = np.angle(h) myFigSize = (12, 12) plt.figure(figsize=myFigSize) plt.subplot(2, 1, 1) plt.plot(w / np.pi, mag) plt.grid(True)
#figure("Zplane plot") #gfiltpak.zplane(b, a) ########################################## # Residues b = [0.5, 0.5, 0.25] a = [1, 0.5, 0.5, 0.75] ylims = [-50, 0] multipole = figure("Multipole") mag_p = multipole.add_subplot(2,1,1) ang_p = multipole.add_subplot(2,1,2) w, Ht = gfiltpak.gfreqz(b, a, N = 2048, magfig = mag_p, angfig = ang_p, logx = True, threedb = True, ylimmag = ylims) r, p, k = si.residuez(b, a) multipole.hold(True) # filter 1 b1 = r[0] a1 = [1, -p[0]] w, H1 = gfiltpak.gfreqz(b1, a1, N = 2048, color = 'r', magfig = mag_p, angfig = ang_p, logx = True, threedb = True, ylimmag = ylims) # filter 2 b1 = r[1] a1 = [1, -p[1]] w, H2 = gfiltpak.gfreqz(b1, a1, N = 2048, color = 'm', magfig = mag_p, angfig = ang_p, logx = True, threedb = True, ylimmag = ylims) # filter 2 b1 = r[2] a1 = [1, -p[2]]
# ticks = [-1, -.5, .5, 1]; plt.xticks(ticks); plt.yticks(ticks) if filename is None: plt.show() else: plt.savefig(filename) return z, p, k #%% Part 1 Task 3- Verying Partial Fraction Expanision numz = [2, -40] denz = [1, -10, 16] [r, p, _] = sig.residuez(numz, denz) print('r = ', r, '\np = ', p) #%% Part 1 Task 4- Obtaining the pole-zero plot for H(z) plt.figure(figsize=(10, 7)) [z, p, _] = zplane(numz, denz) print('z = ', z, '\np = ', p) #%% Part 1 Task 5- Plotting magnitude and phase response of H(z) w, h = sig.freqz(numz, denz) fig = plt.figure(figsize=(10, 7)) plt.subplot(2, 1, 1) plt.plot(w / np.pi, 20 * np.log10(np.abs(h)))
# -*- coding: utf-8 -*- """ Created on Tue Nov 12 19:25:23 2019 @author: katea """ import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig num = [2, -40] den = [1, -10, 16] #H_transfer = num/den [r, p, k] = sig.residuez(num, den) print("r= ", r) #non-zeros values of the fourier series were printed print("p = ", p) print("k = ", k) # -*- coding: utf-8 -*- """ @author: Phillip Hagen Description:zplane() """ #%% Zplane function # # Copyright (c) 2011 Christopher Felton # # This program is free software: you can redistribute it and/or modify
poles = R*exp(theta*1j) ## Get the monic polynomials. This is an all-pole filter. B = np.ones((1)) # Denominator. A = np.real(np.poly(np.concatenate((poles, np.conj(poles))))) ## Verify if the frequency response looks good. pfig = pyl.figure('Frequency response of formants') mag_fig = pfig.add_subplot(211) ang_fig = pfig.add_subplot(212) gfreqz(B,A,N=512,magfig = mag_fig, angfig = ang_fig, ylimmag = [-40, 40], logy = True, normalize = False) ## Convert to parallel complex ONE POLE sections (complex resonators). ## Get the pole residues. f is the FIR section which will be 0. [r, p, f] = si.residuez(B, A) ## Conjugate poles seem adjacent with scipy as well. So the creation of a ## genuine SOS is trivial without the need for cplxpair(...). As = np.zeros((nsecs, 3)) ## 3 coefficients per. Bs = np.zeros((nsecs, 3)) ## " ## This specific biquad section follows from JOS's derivation of conjugate ## complex (single) pole resonators. Suffice to say, each complex resonator ## biquad can be reduce to, ## (r + r' - (r*p'+r'*p)z^-1)/(1-(p+p')z^-1+(p*p')z^-2) where r/p' is the ## complex conjugate of r/p. for i in np.arange(0, 2*nsecs - 1, 2): k = i / 2 #print('+++++++++++', r[i] + r[i + 1]) #print('+++++++++++', -(r[i] * p[i + 1] + p[i] * r[i + 1]))
# Kevin Russell # # ECE 351-51 # # Lab 11 # # November 10, 2020 # # # # # # ############################################################### import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig hz_num = [2, -40] hz_den = [1, -10, 16] zeros, poles, k = sig.residuez(hz_num, hz_den) print("Zeros:", zeros) print("Poles:", poles) #%% Zplane function # # Copyright (c) 2011 Christopher Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful,
a = [1, 0.5, 0.5, 0.75] ylims = [-50, 0] multipole = figure("Multipole") mag_p = multipole.add_subplot(2, 1, 1) ang_p = multipole.add_subplot(2, 1, 2) w, Ht = gfiltpak.gfreqz(b, a, N=2048, magfig=mag_p, angfig=ang_p, logx=True, threedb=True, ylimmag=ylims) r, p, k = si.residuez(b, a) multipole.hold(True) # filter 1 b1 = r[0] a1 = [1, -p[0]] w, H1 = gfiltpak.gfreqz(b1, a1, N=2048, color='r', magfig=mag_p, angfig=ang_p, logx=True, threedb=True, ylimmag=ylims)
from scipy import signal #from matplotlib import pyplot as plt import numpy as np input_signal,fs=sf.read('Sound_Noise.wav') sampl=fs order=4 cutoff=4000 Wn=2*cutoff/sampl b, a=signal.butter(order,Wn,'low') b1,a1,k=signal.residuez(b,a) h=[] n=[] for i in range(0,30): temp=0 n.append(i) for j in range(0,len(b1)): temp=temp+b1[j]*(a1[j]**i) h.append(temp.real) h[0]+=k[0] y=np.convolve(input_signal,h) # plt.stem(n,h) # plt.show() sf.write('Soundlol.wav',y,fs)
def residuez(): b = [1, -0.5] a = [1, 0.75, 0.125] RPC = signal.residuez(b, a) print(RPC)
# -*- coding: utf-8 -*- """ Created on Tue Nov 12 19:15:38 2019 @author: holt3393 """ import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig numZ = [2, -40] denZ = [1, -10, 16] Z, P, K = sig.residuez(numZ, denZ) print(Z, P, K) #%% Zplane function # # Copyright (c) 2011 Christopher Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License
## Verify if the frequency response looks good. pfig = pyl.figure('Frequency response of formants') mag_fig = pfig.add_subplot(211) ang_fig = pfig.add_subplot(212) gfreqz(B, A, N=512, magfig=mag_fig, angfig=ang_fig, ylimmag=[-40, 40], logy=True, normalize=False) ## Convert to parallel complex ONE POLE sections (complex resonators). ## Get the pole residues. f is the FIR section which will be 0. [r, p, f] = si.residuez(B, A) ## Conjugate poles seem adjacent with scipy as well. So the creation of a ## genuine SOS is trivial without the need for cplxpair(...). As = np.zeros((nsecs, 3)) ## 3 coefficients per. Bs = np.zeros((nsecs, 3)) ## " ## This specific biquad section follows from JOS's derivation of conjugate ## complex (single) pole resonators. Suffice to say, each complex resonator ## biquad can be reduce to, ## (r + r' - (r*p'+r'*p)z^-1)/(1-(p+p')z^-1+(p*p')z^-2) where r/p' is the ## complex conjugate of r/p. for i in np.arange(0, 2 * nsecs - 1, 2): k = i / 2 #print('+++++++++++', r[i] + r[i + 1]) #print('+++++++++++', -(r[i] * p[i + 1] + p[i] * r[i + 1]))
import control import matplotlib.pyplot as plt # plt.style.use('classic') import numpy as np import scipy.signal as signal from base.impseq import * from base.stepseg import * b = np.array([0, 0.866, 0.0306, -2.486, 3.2094, -1.62, 0.84]) a = np.array([1, -2.9, 4.8, -4.7, 2.8, -0.9]) R, p, c = signal.residuez(b, a) # print(R) print("poles:") print(p) # print(c) print("roots:") roots = np.roots(b) # b = np.array([3]) # a = np.array([1,-1]) delta, n1 = impseg(0, 0, 10) delta = delta.astype('float64') xb1 = signal.lfilter(b, a, delta) step, n2 = stepseg(0, 0, 10) step_minus_2, _ = stepseg(2, 0, 10) xb2 = n2 * np.sin(np.pi / 3 * n2) * step + np.power(0.9, n2) * step_minus_2 err = xb1 - xb2 print(err)
plt.title('Formant Filter Frequency Response') ax1 = freqPlot.add_subplot(111) plt.plot(w, 20 * np.log10(abs(h)), 'b') plt.ylabel('amplitude[dB]', color = 'b') plt.xlabel('frequency [rad/sample]') ax2 = ax1.twinx() angles = np.unwrap(np.angle(h)) plt.plot(w, angles, 'g') plt.ylabel('Angle (radians)', color='g') plt.grid() plt.axis('tight') plt.show() """ # convert to parallel complex one-poles (PFE): [r, p, f] = signal.residuez([B], A) As = np.zeros((nsecs, 3), dtype=complex) Bs = np.zeros((nsecs, 3), dtype=complex) #complex-conjugate pairs are adjacent in r and p: for i in xrange(0, nsecs): k = i * 2 Bs[i] = [r[k] + r[k + 1], -(r[k + 1] * p[k] + r[k] * p[k + 1]), 0] As[i] = [1, -(p[k] + p[k + 1]), p[k] * p[k + 1]] sos = np.concatenate((Bs, As), axis=1) # standard second order system form (n*6 matrix) iperr = np.linalg.norm(np.imag(sos) / np.linalg.norm(sos)) # make sure sos is ~real sos = np.real(sos)
def setRoots(self, tau, m, pa, theta): """Gets the roots Required Inputs tau :: float :: average trajectory length m :: float :: mass parameter - the lowest frequency mode pa :: float :: average acceptance probability theta :: float :: mixing angle Numerator and Denominator are defined as polynomial arrays increasing in order stating from 0th order and ending at nth order """ self.tau = tau self.m = m self.theta = theta self.pa = pa if theta==.5*pi: # checked with Mathematica # no scipy needed for theta = pi/2 self.res = self.poles = self.const = None if pa > self.p_thresh: self.poles = array(cos(m*tau)**2) else: self.poles = array(pa*cos(m*tau)**2 + 1 - pa) # poles are 1/B_k as defined in the paper for pi/2 case else: cos_phi = cos(m*tau) cos_phi2 = cos_phi*cos_phi cos_theta = cos(theta) cos_theta2 = cos_theta*cos_theta cos_theta3 = cos_theta2*cos_theta if self.warnImpRoots0: print "\nWarning: Implementation may be incorrect." \ + "\n> Read http://tinyurl.com/hjlkgsq for more information" self.warnImpRoots0 = False if pa > self.p_thresh: numerator = [ # checked and verified with Mathematica 0, -cos_phi2, 2*cos_phi2*cos_theta2 + cos_phi2*cos_theta \ - cos_theta2, -cos_theta3] denominator = [ # checked and verified with Mathematica 1, -cos_phi2*cos_theta2 - 2*cos_phi2*cos_theta - cos_phi2 + cos_theta, cos_theta*cos_phi2 + cos_theta3*cos_phi2 + cos_theta2*(-1 + 2*cos_phi2), -cos_theta3] else: numerator = [ # checked with mathematica 0, pa*cos_phi2 - pa + 1, -2*pa*cos_phi2*cos_theta2 - pa*cos_phi2*cos_theta \ + 2*pa*cos_theta2 - pa*cos_theta - cos_theta2 \ + cos_theta, (-1 + 2*pa)*cos_theta3] denominator = [ 1, -pa*cos_phi2*cos_theta2 \ - 2*pa*cos_phi2*cos_theta - pa*cos_phi2 \ + pa*cos_theta2 + pa - cos_theta2 \ + cos_theta - 1, (-1 + pa + pa*cos_phi2)*cos_theta \ + (1 - 2*pa + 2*pa*cos_phi2)*cos_theta2 \ + (-1 + pa + pa*cos_phi2)*cos_theta3, -2*pa*cos_theta3 + cos_theta3] self.d = denominator self.n = numerator self.res, self.poles, self.const = map(array, residuez(numerator, denominator)) return self.poles
# -*- coding: utf-8 -*- """ Created on Tue Nov 12 19:29:12 2019 @author: alexa """ import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig num = [2, -40] den = [1, -10, 16] [Z, P, _] = sig.residuez(num, den) print('Z = ', Z) print('P = ', P) # # Copyright (c) 2011 Christopher Felton # # This program is free software : you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation , either version 3 of the License , or # (at your option ) any later version . # # This program is distributed in the hope that it will be useful , # but WITHOUT ANY WARRANTY ; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the # GNU Lesser General Public License for more details .
print 'Fixed Residues', mf.res print 'Fixed Constant', mf.const print print 'Exp Poles', me.poles print 'Exp Residues', me.res print 'Exp Constant', me.const print t = np.linspace(0, 10, 1000) fE = lambda t: np.real( np.asarray( [a_i * np.exp(b_i * t) for a_i, b_i in zip(me.res, me.poles)]).sum(0)) mu = np.cos(m * tau)**2 r, p, k = residuez([mu, 0], [1, -np.cos(m * tau)**2]) fF = lambda t: np.real( np.sum(k) + np.asarray( [a_i / b_i * b_i**(t / tau) for a_i, b_i in zip(r, p)]).sum(0)) lines = { 0: [(t, fE(t), r'\verb|scipy.signal.residuez()|'), (t, me.eval(t), r'Analytical partial fractioning')], 1: [(t, fF(t), r'\verb|scipy.signal.residuez()|'), (t, mf.eval(t), r'Analytical partial fractioning')] } app = r"$\tau={:4.2f};m={:3.1f}$".format(tau, m) subtitles = { 0: "Exponentially Distributed Trajectories " + app, 1: "Fixed Trajectories " + app