示例#1
0
num_lp_butter, den_lp_butter = sig.lp2lp(num_lp, den_lp, eps**(-1 / nn))

# obtengo la transferencia normalizada del pasabanda
num_bp_n, den_bp_n = sig.lp2bp(num_lp_butter, den_lp_butter, wo=1, bw=1 / .253)

# obtengo la transferencia desnormalizada del pasabanda
num_bp, den_bp = sig.lp2bp(num_lp_butter, den_lp_butter, wo=8.367, bw=33)

# Averiguo los polos y ceros
z_bp_n, p_bp_n, k_bp_n = sig.tf2zpk(num_bp_n, den_bp_n)

str_aux = 'Pasabanda normalizado'
print(str_aux)
print('-' * len(str_aux))

this_lti = sig.TransferFunction(num_bp_n, den_bp_n)
pretty_print_lti(this_lti)
print('\n\n')

#%matplotlib qt5
# visualizo el modelo matemático normalizado
#analyze_sys([sig.TransferFunction(num_bp_n,den_bp_n)], ['mp'])
# o el modelo matemático desnormalizado
#analyze_sys([sig.TransferFunction(num_bp,den_bp)], ['mp'])

# visualización de cada sección

##
# Factorización en BP - BP
###########################
示例#2
0
def movingAverageOrde2():
    #cara berfikir dimatlab berbeda dengan dipython
    #MAx/yk matlab = MAx/yk.T python
    MAxk = np.transpose(np.matrix(Vin2))  #transpose matrix 1D
    MAyk = np.transpose(np.matrix(Vout2))

    MAxk1 = Vin2.copy()
    MAxk1 = np.insert(MAxk1, 0, 0)
    MAxk1 = np.delete(MAxk1, len(MAxk1) - 1)
    MAxk1 = np.transpose(np.matrix(MAxk1))

    MAxk2 = Vin2.copy()
    MAxk2 = np.insert(MAxk2, 0, 0)
    MAxk2 = np.insert(MAxk2, 1, 0)
    MAxk2 = np.delete(MAxk2, len(MAxk2) - 1)
    MAxk2 = np.delete(MAxk2, len(MAxk2) - 1)
    MAxk2 = np.transpose(np.matrix(MAxk2))

    MApi = (np.vstack((MAxk.T, MAxk1.T, MAxk2.T))).T  #tidka bisa langsung
    MA = np.linalg.inv(MApi.T.dot(MApi)).dot(MApi.T).dot(MAyk)

    a = MA[0].dot(MAxk[0]) + MA[1].dot(0) + MA[2].dot(0)
    MAy = ([a])
    a = MA[0].dot(MAxk[1]) + MA[1].dot(MAy[0]) + MA[2].dot(0)
    MAy = np.insert(MAy, 1, a)

    for i in range(2, len(MAxk)):
        a = MA[0].dot(MAxk[i]) + MA[1].dot(MAxk[i - 1]) + MA[2].dot(
            MAxk[i - 2])
        MAy = np.insert(MAy, i, a)

    dataMA = np.vstack((MAxk.T, MAy)).T

    num = [1]
    den = MA.A1  #merubah menjadi rank 1
    den = list(den)  #list ==> menambah koma diantara elements
    sys = signal.TransferFunction(
        num, den, dt=1
    )  # selalu menghasilkan tf dg s pangkat tertinggi berubah menjadi (s^n),
    # sehingga hasil tersebut merupakan angka hasil bagi den[0]
    # misal 1/4s^2+2s+1 menjadi 0.25/s^2+0.5s+0.25
    # aku sudah mensimulasikannya hasilnya sama, secara matematis dan logika pun juga sama
    # jika menemukan solusinya silahkan PR ke https://github.com/ahmaddidiks/pis_py

    print(" MAxk1 = ")
    print(MAxk1)
    print("\n MAxk2 = ")
    print(MAxk2)
    print("\n MApi = ")
    print(MApi)
    print("\n MA = ")
    print(MA)
    print("\n MAy = ")
    print(MAy)
    print("\n dataMA = ")
    print(dataMA)
    print("\n Transfer Fungsi = ")
    print(sys)

    plt.plot(MAxk, MAy)
    plt.plot(Vin2, Vout2)
    plt.title('Hubungan Vin-Vout Metode MA Orde 2', fontdict=font)
    plt.xlabel('Vin', fontdict=font)
    plt.ylabel('Vout', fontdict=font)
    plt.legend(['MA', 'Data'])
    plt.show()
示例#3
0
def autoRegresiveOrde2():
    #cara berfikir dimatlab berbeda dengan dipython
    #ARx/yk matlab = ARx/yk.T python
    ARxk = np.transpose(np.matrix(Vin2))  #transpose matrix 1D
    ARyk = np.transpose(np.matrix(Vout2))

    ARyk1 = Vout2.copy()
    ARyk1 = np.insert(ARyk1, 0, 0)
    ARyk1 = np.delete(ARyk1, len(ARyk1) - 1)
    ARyk1 = np.transpose(np.matrix(ARyk1))

    ARyk2 = Vout2.copy()
    ARyk2 = np.insert(ARyk2, 0, 0)
    ARyk2 = np.insert(ARyk2, 1, 0)
    ARyk2 = np.delete(ARyk2, len(ARyk2) - 1)
    ARyk2 = np.delete(ARyk2, len(ARyk2) - 1)
    ARyk2 = np.transpose(np.matrix(ARyk2))

    ARpi = (np.vstack((ARxk.T, ARyk1.T, ARyk2.T))).T  #tidak bisa langsung
    AR = np.linalg.inv(ARpi.T.dot(ARpi)).dot(ARpi.T).dot(ARyk)

    a = AR[0].dot(ARxk[0]) + AR[1].dot(0) + AR[2].dot(0)
    ARy = ([a])  #ARy[0] di python = ARy(1)

    a = AR[0].dot(ARxk[1]) + AR[1].dot(ARy[0]) + AR[2].dot(0)
    ARy = np.insert(ARy, 1, a)

    for i in range(2, len(ARxk)):
        a = AR[0].dot(ARxk[i]) + AR[1].dot(ARy[i - 1]) + AR[2].dot(ARy[i - 2])
        ARy = np.insert(ARy, i, a)

    dataAR = np.vstack((ARxk.T, ARy)).T

    num = [1]
    den = AR.A1  #merubah menjadi rank 1
    den = list(den)  #list ==> menambah koma diantara elements
    sys = signal.TransferFunction(
        num, den, dt=1
    )  # selalu menghasilkan tf dg s pangkat tertinggi berubah menjadi (s^n),
    # sehingga hasil tersebut merupakan angka hasil bagi den[0]
    # misal 0.25/4s^2+2s+1 menjadi 0.4/s^2+0.5s+0.25
    # aku sudah mensimulasikannya hasilnya sama, secara matematis dan logika pun juga sama
    # jika menemukan solusinya silahkan PR ke https://github.com/ahmaddidiks/pis_py

    print(" ARyk1 = ")
    print(ARyk1)
    print("\n ARyk2 = ")
    print(ARyk2)
    print("\n ARpi = ")
    print(ARpi)
    print("\n AR = ")
    print(AR)
    print("\n ARy = ")
    print(ARy)
    print("\n dataAR = ")
    print(dataAR)
    print("\n Transfer Fungsi = ")
    print(sys)

    plt.plot(ARxk, ARy)
    plt.plot(Vin2, Vout2)
    plt.title('Hubungan Vin-Vout Metode AR Orde 2', fontdict=font)
    plt.xlabel('Vin', fontdict=font)
    plt.ylabel('Vout', fontdict=font)
    plt.legend(['AR', 'Data'])
    plt.show()
示例#4
0
def plot_dtlti_analysis(z, p, k, fs=1, Nf=2**10, Nt=2**5):
    """Plot linear, time-invariant, discrete-time system.

    Impulse, step, frequency response (level/phase/group delay) and z-plane
    of transfer function H(z) given as zeros/poles/gain description

    Note that we use fs only for the frequency responses

    """
    # still hard coded, TBD:
    # figure size
    # group_delay discontinuities and automatic ylim, yticks is not
    # useful sometimes

    plt.figure(figsize=(9, 9), tight_layout=True)

    mu = np.arange(Nf)
    df = fs / Nf
    dW = 2 * np.pi / Nf
    f = mu * df  # frequency vector [0...fs)
    W = mu * dW  # digital angular frequency [0...2pi)

    sys = signal.dlti(z, p, k, dt=True)
    sys_ba = signal.TransferFunction(sys)
    b = sys_ba.num  # we need coeff b,a for group_delay()
    a = sys_ba.den

    [W, H] = signal.dlti.freqresp(sys, W)
    [W, gd] = signal.group_delay((b, a), w=W)  # gd in samples
    h = signal.dimpulse(sys, n=Nt)
    he = signal.dstep(sys, n=Nt)

    # plot frequency response: level
    ax1 = plt.subplot(3, 2, 1)
    ax1t = ax1.twiny()

    ax1.grid(True, color='lavender', which='major')
    # plotted below grid :-(
    # ax1t.grid(True, color='mistyrose', which='minor')

    ax1.plot(W / (2 * np.pi), 20 * np.log10(np.abs(H)), color='C0', lw=2)
    ax1.set_xscale('linear')
    ax1.set_xlim([0, 1])
    ax1.tick_params(axis='x', labelcolor='C0')
    ax1.set_xlabel(r'$\frac{\Omega}{2\pi} = \frac{f}{f_s}$', color='C0')
    ax1.set_xticks(np.arange(11) / 10)
    ax1.set_ylabel('level in dB   or   20 lg|H| / dB', color='k')
    ax1.set_axisbelow(True)

    ax1t.plot(f, 20 * np.log10(np.abs(H)), color='C3', lw=2)
    ax1t.set_xscale('log')
    ax1t.set_xlim([f[1], f[-1]])
    ax1t.tick_params(axis='x', labelcolor='C3')
    ax1t.set_xlabel('frequency in Hz   or   f / Hz for $f_s$ = ' +
                    '{0:5.2f}'.format(fs) + ' Hz',
                    color='C3')
    ax1t.set_axisbelow(True)

    # plot impulse response
    ax2 = plt.subplot(3, 2, 2)
    ax2.stem(np.squeeze(h[0]),
             np.squeeze(h[1]),
             use_line_collection=True,
             linefmt='C0:',
             markerfmt='C0o',
             basefmt='C0:')
    ax2.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax2.grid(True)
    ax2.set_xlabel(r'$k$')
    ax2.set_ylabel(r'impulse response $h[k]$')

    # plot frequency response: phase
    ax3 = plt.subplot(3, 2, 3)
    ax3.plot(W, np.unwrap(np.angle(H)))
    ax3.set_xlabel(
        r'digital angular frequency in radian   or   $\Omega$ / rad')
    ax3.set_ylabel(r'phase in radian   or $\angle$ H / rad')
    ax3.set_xlim([0, 2 * np.pi])
    ax3.set_xticks(np.arange(9) * np.pi / 4)
    ax3.set_xticklabels([
        r'0', r'$\pi/4$', r'$\pi/2$', r'$3/4\pi$', r'$\pi$', r'$5/4\pi$',
        r'$3/2\pi$', r'$7/4\pi$', r'$2\pi$'
    ])
    # ax3.set_ylim([-180, +180])
    # ax3.set_yticks(np.arange(-180, +180+45, 45))
    ax3.grid(True)

    # plot step response
    ax4 = plt.subplot(3, 2, 4)
    ax4.stem(np.squeeze(he[0]),
             np.squeeze(he[1]),
             use_line_collection=True,
             linefmt='C0:',
             markerfmt='C0o',
             basefmt='C0:')
    ax4.xaxis.set_major_locator(MaxNLocator(integer=True))
    ax4.grid(True)
    ax4.set_xlabel(r'$k$')
    ax4.set_ylabel(r'step response $h_\epsilon[k]$')

    # plot frequency response: group delay
    ax5 = plt.subplot(3, 2, 5)
    ax5.plot(W / np.pi, gd / fs)
    ax5.set_xscale('linear')
    ax5.set_xlim([0, 2])
    ax5.set_xlabel(r'$\frac{\Omega}{\pi}$')
    ax5.set_ylabel(r'group delay in seconds   or   $\tau_\mathrm{GD}$ / s')
    ax5.grid(True, which='both')

    # zplane
    ax6 = plt.subplot(3, 2, 6)
    plot_zplane(sys.zeros, sys.poles, sys.gain)  # see function above
示例#5
0
文件: Q4.py 项目: flav1s/pds
# Plot t segundos de sinal ruidoso
plt.figure()
plt.plot(x, y)
plt.title("Intervalo de " + str(t) + " segundos")
plt.ylabel("Amplitude")
plt.xlabel("Tempo [s]")
plt.grid()

# Filtro Notch
f0 = 60.0  # frequencia a ser removida do sinal
Q = 1.0  # Quality factor
w0 = f0/(fs/2)  # frequencia normalizada

b, a = signal.iirnotch(w0, Q)
y_f = signal.filtfilt(b, a, np.ravel(data))
tf = signal.TransferFunction(b, a)

# Plot sinal ruidoso
plt.figure()
plt.plot(T,y_f)
plt.title("Sinal filtrado")
plt.ylabel("Amplitude")
plt.xlabel("Tempo [s]")
plt.grid()

b, a = signal.iirnotch(w0, Q)
y_t = signal.filtfilt(b, a, np.ravel(y))

# Plot t segundos de sinal filtrado
plt.figure()
plt.plot(x, y_t)
示例#6
0
def modelPT2(x, t, u):
    x1 = x[0]
    x2 = x[1]
    dx1dt = x2
    dx2dt = u - x2 - x1
    dxdt = [dx1dt, dx2dt]
    return dxdt


if __name__ == "__main__":

    import matplotlib.pyplot as plt

    nomSys = [1.0]
    denSys = [1.0, 2.0, 1.0]
    mySys = signal.TransferFunction(nomSys, denSys)

    kSys = 1.0
    nomSys = []
    denSys = [-1.0, -1.0]
    mySys2 = signal.ZerosPolesGain(nomSys, denSys, kSys)

    t, y = signal.step(mySys2)

    figure = plt.figure()
    axis = figure.add_subplot(111)
    # ax1.set_xlim([0, 6])
    # ax2.set_ylim([-2, 2])
    axis.plot(t, y)

    plt.show()
from scipy import signal
import matplotlib.pyplot as plt

sys = signal.TransferFunction([1], [1, 1])
w, mag, phase = sys.bode()

plt.figure()
plt.semilogx(w, mag)    # Bode magnitude plot
plt.figure()
plt.semilogx(w, phase)  # Bode phase plot
plt.show()
示例#8
0
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
from scipy.integrate import odeint

# Change these values based on graphical fit
Kp = 1.0
taus = 1.0
zeta = 1.0

# Transfer Function
#  Kp / (taus * s**2 + 2 * zeta * taus * s + 1) 
num = [Kp]
den = [taus**2,2.0*zeta*taus,1]
sys1 = signal.TransferFunction(num,den)
t1,y1 = signal.step(sys1)

plt.figure(1)
plt.plot(t1,y1,'b--',linewidth=3,label='Transfer Fcn')
plt.xlabel('Time')
plt.ylabel('Response (y)')
plt.legend(loc='best')
plt.show()
示例#9
0
def main_TanQua():
    #### gerar configurações da entrada e do tempo de avaliação
    
    #input_ pode ser - degrau, impulso, senoide, aleatoria, superposi, ponto_dif
    #cada entrada refere-se a um experimento apresentado na documentação
    input_ = 'superposi'
    gain = 3
    #referente ao primeiro segundo degrau da superposição
    gains = [2,4]
    #para senoide
    freq = 0.01
    ponto_medio = 3
    cont_time=100000
    #variaveis de tempo de execução
    t0 = 0
    tf = 4000
    h = 0.01
    t = np.arange(t0, tf, h)
    
    #setando valores de pontos iniciais são necessários para execução em questão
    init_ = [10.1]
    
    #executando simulação 
    x_f = []
    for point_stt in init_:
        x0 = np.array([[point_stt], [point_stt], [point_stt], [point_stt]])

        dc = np.zeros((len(x0), len(t) - 1))
        x = x0.copy()
        x = np.append(x, dc, axis=1)
        #Seleção de entrada
        if input_ == 'degrau':
            u = degrau(t,gain)
        elif input_ == 'senoide':
            u = seno(t, gain, freq, ponto_medio)
        elif input_ == 'impulso':
            u = impulso(t, 15)
        elif input_ == 'aleatoria':
            u = aleatorio(t,0,6)
        elif input_ == 'superposi':
            u = signal_super(t,gains)
        else:
            u = np.zeros(len(t))

        for k in range(1, len(t)):
            result = rkTanQua(x[:, k - 1], u[k], u[k], h, t[k])
            x[:, k] = result
        x_f.append(x)
            
    
    plot_mode = 'segOrd'
    mode_ = 'exc'
    
    #valores encontrados modelando com base no video do prof Aguirre
    #https://www.youtube.com/watch?v=J-ZQ29dcmJU&feature=youtu.be
    #https://www.youtube.com/watch?v=dm5cdpsuxlM&feature=youtu.be
    
    
    if plot_mode == 'primOrd':
        #criando sistemas de primeira ordem com valores calculados como no video do prof. Aguirre
        num = [4]
        den = [200, 1]
        sist1 = signal.TransferFunction(num, den)
        num = [2.7]
        den = [200, 1]
        sist2 = signal.TransferFunction(num, den)
        num = [0.5]
        den = [50, 1]
        sist3 = signal.TransferFunction(num, den)
        num = [0.3]
        den = [50, 1]
        sist4 = signal.TransferFunction(num, den)
        #estabelecendo valores entre 0 e 3000
        t_v = t[:-cont_time]

        #resposta ao degrau de cada sistema
        t1, out1 = signal.step(sist1, X0=None, T=t_v, N=None)
        plt.plot(t1,out1, '--')
        t2, out2 = signal.step(sist2, X0=None, T=t_v, N=None)
        plt.plot(t2,out2, '--')
        t3, out3 = signal.step(sist3, X0=None, T=t_v, N=None)
        plt.plot(t3,out3, '--')
        t4, out4 = signal.step(sist4, X0=None, T=t_v, N=None)
        plt.plot(t4,out4, '--')
        
        plotsignals(x_f,u,t,input_,init_)
    
    elif  plot_mode == 'segOrd':
        #criando sistemas de segunda ordem
        num = [4]
        den = [0.575, 7.656, 1]
        sist1 = signal.TransferFunction(num, den)
        num = [2.7]
        den = [0.575, 7.656, 1]
        sist2 = signal.TransferFunction(num, den)
        num = [0.5]
        den = [8672, 259, 1]
        sist3 = signal.TransferFunction(num, den)
        num = [0.3]
        den = [8672, 259, 1]
        sist4 = signal.TransferFunction(num, den)
        #estabelecendo uma quantidade de 3000 valores
        t_v = t[:-cont_time]
        
        #plots referentes a cada questão específica.
        if mode_ == 'normal':
            #plotando as a resposta ao degrau 
            t1, out1 = signal.step(sist1, X0=None, T=t_v, N=None)
            plt.plot(t1,out1, '--')
            t2, out2 = signal.step(sist2, X0=None, T=t_v, N=None)
            plt.plot(t2,out2, '--')
            t3, out3 = signal.step(sist3, X0=None, T=t_v, N=None)
            plt.plot(t3,out3, '--')
            t4, out4 = signal.step(sist4, X0=None, T=t_v, N=None)
            plt.plot(t4,out4, '--')
            plotsignals(x_f,u,t,input_,init_)
        elif mode_ == 'normaliz':
            plotsignals_p(x_f,u,t,input_,init_)
        elif mode_ == 'exc':
            t1, out1 =sist1.output(u, t, X0=None)
            plt.plot(t1,out1[:-cont_time], '--')
            t2, out2 =sist2.output(u, t, X0=None)
            plt.plot(t1,out1[:-cont_time], '--')
            t3, out3 =sist3.output(u, t, X0=None)
            plt.plot(t1,out1[:-cont_time], '--')
            t4, out4 =sist4.output(u, t, X0=None)
            plt.plot(t1,out1[:-cont_time], '--')
            plotsignals(x_f,u,t,input_,init_)

        else:

            w, mag, phase = sist1.bode()
            plt.figure()
            plt.legend('Saida 1 Magnitude')
            plt.semilogx(w, mag)    # Bode magnitude plot
            plt.figure()
            plt.legend('Saida 1 Fase')
            plt.semilogx(w, phase)  # Bode phase plot
            plt.show()
            w, mag, phase = sist2.bode()
            plt.figure()
            plt.legend('Saida 2 Magnitude')
            plt.semilogx(w, mag)    # Bode magnitude plot
            plt.figure()
            plt.legend('Saida 2 Fase')
            plt.semilogx(w, phase)  # Bode phase plot
            plt.show()
            w, mag, phase = sist3.bode()
            plt.figure()
            plt.legend('Saida 3 Magnitude')
            plt.semilogx(w, mag)    # Bode magnitude plot
            plt.figure()
            plt.legend('Saida 3 Fase')
            plt.semilogx(w, phase)  # Bode phase plot
            plt.show()
            w, mag, phase = sist4.bode()
            plt.figure()
            plt.legend('Saida 4 Magnitude')
            plt.semilogx(w, mag)    # Bode magnitude plot
            plt.figure()
            plt.legend('Saida 4 Fase')
            plt.semilogx(w, phase)  # Bode phase plot
            plt.show()
示例#10
0
 def concatenateSystems(self,H1,H2):
     H = signal.TransferFunction(np.polymul(H1.num,H2.num),np.polymul(H1.den,H2.den))
     return H
示例#11
0
 def inverseMultiple(self,H1,H2):
     H = signal.TransferFunction(np.polymul(H1.num,H2.den),np.polymul(H1.den,H2.num))
     return H
#tf_num = [2*K_T*I_Q]
#tf_den = [J, 2*zeta]
"""
motor with PI feedback
(b*k_p*s + b*k_i)/(s^2 + (a + b*k_p)*s + b*k_i)
#from Notebook #4, pg 130
"""
b = 2 * K_T / J
a = 2 * zeta / J
k_p = 0.02
k_i = 0.01

tf_num = [b * k_p, b * k_i]
tf_den = [1, (a + b * k_p), b * k_i]

motor_tf = signal.TransferFunction(tf_num, tf_den)
t1, y1 = signal.step(motor_tf)  #t1 in seconds, y1 in rad/s
y1 = y1 / (2 * pi)  #convert y1 to Hz

plt.figure(1)
plt.plot(t1, y1)
plt.xlabel('time (s)')
plt.ylabel('motor freq (Hz)')

f = logspace(-1, 8)
w = 2 * pi * f

w, mag, phase = signal.bode(motor_tf, w)

plt.figure(2)
plt.semilogx(f, mag)
示例#13
0
#######################

if aprox_type != 'LP':

    print_console_alert('Frequency transformation LP -> ' + aprox_type)

    if aprox_type == 'HP':

        num, den = sig.lp2hp(lowpass_proto_lti.num, lowpass_proto_lti.den)

    if aprox_type == 'BP':

        num, den = sig.lp2bp(lowpass_proto_lti.num,
                             lowpass_proto_lti.den,
                             wo=1,
                             bw=BWbp)

    xp_tf = sig.TransferFunction(num, den)

    print_console_subtitle('Transformed transfer function')
    pretty_print_lti(xp_tf)

    print_console_subtitle('Cascade of second order systems (SOS' 's)')
    xp_sos = tf2sos_analog(num, den)
    pretty_print_SOS(xp_sos)
    pretty_print_SOS(xp_sos, mode='omegayq')

    print_console_subtitle('Respuesta en frecuencia')

    analyze_sys(xp_sos, str_designed_filter, same_figs=False)
        eps = np.sqrt(10**(this_ripple / 10) - 1)
        num, den = sig.zpk2tf(z, p, k)
        num, den = sig.lp2lp(num, den, eps**(-1 / this_order))

        z, p, k = sig.tf2zpk(num, den)

    elif aprox_name == 'Chebyshev1':

        z, p, k = sig.cheb1ap(this_order, this_ripple)

    elif aprox_name == 'Chebyshev2':

        z, p, k = sig.cheb2ap(this_order, this_ripple)

    elif aprox_name == 'Bessel':

        z, p, k = sig.besselap(this_order, norm='mag')

    elif aprox_name == 'Cauer':

        z, p, k = sig.ellipap(this_order, this_ripple, this_att)

    num, den = sig.zpk2tf(z, p, k)

    all_sys.append(sig.TransferFunction(num, den))
    filter_names.append(aprox_name + '_ord_' + str(this_order) + '_rip_' +
                        str(this_ripple) + '_att_' + str(this_att))

analyze_sys(all_sys, filter_names)
示例#15
0
axs[1].set_xlabel('Time [ms]')
axs[1].set_ylabel('Step Response')
axs[1].grid()

fig.align_ylabels(axs[:])

plt.show()
""" Second Order Response """
tau = 1e-3
w0 = 1 / tau
s = 1j * w
Q = 1.5
mag_second = (abs(w0**2 / (s**2 + s * w0 / Q + w0**2)))
tin = np.linspace(0, 10e-3, 100)

sys_second = signal.TransferFunction([w0**2], [1, w0 / Q, w0**2])
w, mag_second, phase = sys_second.bode()  # rad/s, dB, degrees
f = w / 2 / np.pi
tout, step_second = signal.step(sys_second, X0=None, T=tin)

# Plot the frequency response
fig, axs = plt.subplots(2)
fig.suptitle('$2^{nd}$ Order System Magnitude and Step Responses')
axs[0].semilogx(f, mag_second)
axs[0].grid()
axs[0].set_ylabel('Magnitude Response [dB]')
axs[0].set_xlabel('Frequency [Hz]')

axs[1].plot(1e3 * tin, step_second)
axs[1].grid()
axs[1].set_ylabel('Step Response')
示例#16
0
    def denormalize(self):
        self.den=np.poly1d([1])
        self.num=np.poly1d([1])
        tempPoles=[]
        tempZeros=[]
        self.denorm_gain=1

        if self.name=='LowPass': #If required filter is LP
            #Denormalize poles
            for i in range(0,len(self.poles)):#For each pole denormalization is realized
                if self.poles[i] != 0:#If pole is not zero
                    pol=np.poly1d([-1/(self.wpl*self.poles[i]),1])
                    if np.real(np.roots(pol))<=0:
                        self.den= self.den*pol #Filter is denormalized by frequency scaling it S=Sn/wc
                        tempPoles.append(np.roots(pol)[0])
                else:
                    pol=np.poly1d([1/(self.wpl),0])
                    self.den=self.den*pol
                    tempPoles.append(np.roots(pol)[0])
            #Denormalize zeroes
            for i in range(0,len(self.zeroes)):#For each zero denormalization is realized
                if self.zeroes[i] != 0:#If zero is not located in origin
                    pol=np.poly1d([1/(self.wpl*self.zeroes[i]),1])
                    self.num= self.num*pol #Filter is denormalized by frequency scaling it S=Sn/wc
                    tempZeros.append(np.roots(pol)[0])
                else:
                    pol=np.poly1d([1/(self.wpl),0])
                    self.num=self.num*pol
                    tempZeros.append(np.roots(pol)[0])

        elif self.name=='HighPass': #If required filter is HP
            #Denormalize poles
            self.num=np.poly1d(np.zeros(len(self.poles)),r=True) #Zeroes created after doing HP denormalization to poles
            for i in range(0,len(np.roots(self.num))):
                tempZeros.append(np.roots(self.num)[i])
            for i in range(0,len(self.poles)):
                if self.poles[i] != 0:#If pole is not zero
                    pol=np.poly1d([1,-self.wpl/(self.poles[i])])
                    self.denorm_gain=(-(self.poles[i])/self.wpl)*self.denorm_gain
                    if np.real(np.roots(pol))<=0:
                        self.den= self.den*pol #Filter is denormalized by frequency scaling it S=wc/Sn
                        tempPoles.append(np.roots(pol)[0])
                else:
                    pol=np.poly1d([-self.wpl])
                    self.denorm_gain=self.denorm_gain*-self.wpl
                    self.den= self.den*pol #Filter is denormalized by frequency scaling it S=wc/Sn
                    #tempPoles.append(np.roots(pol)[0])
            #Denormalize zeroes
            pol=np.poly1d(np.zeros(len(self.zeroes)),r=True)
            self.den=self.den*pol #Poles created after doing HP denormalization to zeroes
            for i in range(0,len(np.roots(pol))):
                tempPoles.append(np.roots(pol)[i])
            for i in range(0,len(self.zeroes)):
                if self.zeroes[i] != 0:#If zero is not located in origin
                    pol=np.poly1d([1,self.wpl/(self.zeroes[i])])
                    self.num= self.num*pol #Filter is denormalized by frequency scaling it S=wc/Sn
                    tempZeros.append(np.roots(pol)[0])
                    self.denorm_gain=self.denorm_gain*(self.zeroes[i])/self.wpl
                else:
                    pol=np.poly1d([self.wpl])
                    self.num= self.num*pol #Filter is denormalized by frequency scaling it S=wc/Sn
                    tempZeros.append(np.roots(pol)[0])
                    self.denorm_gain=self.denorm_gain*1/self.wpl

        elif self.name=='BandPass': #If required filter is BP
            wo=np.sqrt(self.wpl*self.wph)
            B=(self.wph-self.wpl)/wo
            #Denormalize poles
            self.num=np.poly1d(np.zeros(len(self.poles)),r=True) #Zeroes created after doing HP denormalization to poles
            for i in range(0,len(np.roots(self.num))):
                tempZeros.append(np.roots(self.num)[i])
            for i in range (0,len(self.poles)):
                if self.poles[i] != 0:#If pole is not zero
                    if np.absolute(np.real(self.poles[i]))<0.0000001:
                        self.poles[i]=1j*np.imag(self.poles[i])
                    pol=np.poly1d([-1/(wo*B*self.poles[i]), 1, -wo/(B*self.poles[i])])
                    self.den=self.den*pol
                    tempPoles.append(np.roots(pol)[0])
                    tempPoles.append(np.roots(pol)[1])
                    self.denorm_gain=self.denorm_gain*1*(-B*self.poles[i]/(wo))
                else:
                    pol=np.poly1d([-1/(wo*B), 0, -wo/B])
                    self.den=self.den*pol
                    tempPoles.append(np.roots(pol)[0])
                    tempPoles.append(np.roots(pol)[1])
                    self.denorm_gain=self.denorm_gain*1*(-B/(wo))
            #Denormalize zeroes
            pol=np.poly1d(np.zeros(len(self.zeroes)),r=True)
            self.den=self.den*pol #Zeroes created after doing HP denormalization to poles
            for i in range(0,len(np.roots(pol))):
                tempPoles.append(np.roots(pol)[i])
            for i in range (0,len(self.zeroes)):
                if self.zeroes[i] != 0:#If zero is not located in origin
                    if np.absolute(np.real(self.zeroes[i]))<0.0000001:
                        self.zeroes[i]=1j*np.imag(self.zeroes[i])
                    pol=np.poly1d([1/(wo*B*self.zeroes[i]), 1, wo/(B*self.zeroes[i])])
                    self.num=self.num*pol
                    tempZeros.append(np.roots(pol)[0])
                    tempZeros.append(np.roots(pol)[1])
                    self.denorm_gain=self.denorm_gain*1/(-B*self.poles[i]/(wo))
                else:
                    pol=np.poly1d([1/(wo*B), 0, wo/B])
                    self.num=self.num*pol
                    tempZeros.append(np.roots(pol)[0])
                    tempZeros.append(np.roots(pol)[1])
                    self.denorm_gain=self.denorm_gain*1/(B/(wo))

        elif self.name=='StopBand': #If required filter is SB
            wo=np.sqrt(self.wal*self.wah)
            tempwph=self.wal*self.wah/self.wpl
            tempwpl=self.wal*self.wah/self.wph
            if (tempwph<self.wph) and (tempwpl>self.wpl):
                B=(tempwph-tempwpl)/wo
            elif (tempwph>self.wph) and (tempwpl>self.wpl):
                B=(self.wph-tempwpl)/wo
            elif (tempwph<self.wph) and (tempwpl<self.wpl):
                B=(tempwph-self.wpl)/wo            
            else:
                B=(self.wph-self.wpl)/wo
            bool=True
            #Denormalize poles
            for i in range (0,len(self.poles)):
                if self.poles[i] != 0:#If pole is not zero
                    if np.absolute(np.real(self.poles[i]))<0.0001:
                        self.poles[i]=1j*np.imag(self.poles[i])
                    pol=np.poly1d([1/wo, B/(-self.poles[i]), wo])
                    self.den=self.den*pol
                    tempPoles.append(np.roots(pol)[0])
                    tempPoles.append(np.roots(pol)[1])
                else:
                    pol=np.poly1d([B,0])
                    self.den=self.den*pol
                    tempPoles.append(np.roots(pol)[0])
                if (len(self.zeroes)!=0) and np.mod(self.n,2)==0:
                    bool=False
                if bool==True: 
                    pol=np.poly1d([1/wo,0,wo])
                    self.num=self.num*pol
                    tempZeros.append(np.roots(pol)[0])
                    tempZeros.append(np.roots(pol)[1])
                if len(self.zeroes)!=0:
                    bool=False

            #Denormalize zeroes
            for i in range (0,len(self.zeroes)):
                if self.zeroes[i] != 0:#If pole is not zero
                    pol=np.poly1d([1/wo, B/(self.zeroes[i]), wo])
                    self.num=self.num*pol
                    tempZeros.append(np.roots(pol)[0])
                    tempZeros.append(np.roots(pol)[1])
                else:
                    pol=np.poly1d([B,0])
                    self.num=self.num*pol
                    tempZeros.append(np.roots(pol)[0])

        elif self.name=='Group Delay':
            #Denormalize poles
            for i in range(0,len(self.poles)):#For each pole denormalization is realized
                if self.poles[i] != 0:#If pole is not zero
                    pol=np.poly1d([-self.tao0/(self.poles[i]),1])
                    self.den= self.den*pol #Filter is denormalized by frequency scaling it S=Sn/wc
                    tempPoles.append(np.roots(pol)[0])
                else:
                    pol=np.poly1d([self.tao0,0])
                    self.den=self.den*pol
                    tempPoles.append(np.roots(pol)[0])
            #Denormalize zeroes
            for i in range(0,len(self.zeroes)):#For each zero denormalization is realized
                if self.zeroes[i] != 0:#If zero is not located in origin
                    pol=np.poly1d([self.tao0/self.zeroes[i],1])
                    self.num= self.num*pol #Filter is denormalized by frequency scaling it S=Sn/wc
                    tempZeros.append(np.roots(pol)[0])
                else:
                    pol=np.poly1d([self.tao0,0])
                    self.num=self.num*pol
                    tempZeros.append(np.roots(pol)[0])
        else:
            pass
        self.zeroes=tempZeros
        self.poles=tempPoles
        self.den=np.real(self.den)
        self.num=np.real(self.num)

        for i in range(0,len(self.poles)):
            if np.real(self.poles[i])>0:
                self.poles[i]=-np.real(self.poles[i])+1j*np.imag(self.poles[i])
        for sing_pole in self.poles:
            if np.real(sing_pole) !=0:
                if (-np.absolute(sing_pole)/(2*np.real(sing_pole)))>self.q:
                    self.q=(-np.absolute(sing_pole)/(2*np.real(sing_pole)))
            else:
                self.q=float('inf')
        self.K=np.power(10,self.gain/20)*self.aprox_gain
        self.num=self.num*self.K
        self.denorm_n=len(self.den)-1
        self.K=np.power(10,self.gain/20)*self.aprox_gain*self.denorm_gain
        #if self.name== 'StopBand':
        #    self.denorm_sys=signal.ZerosPolesGain.to_tf(signal.ZerosPolesGain(self.zeroes,self.poles,self.K))
        #else:
        self.denorm_sys = signal.TransferFunction(self.num,self.den) #Denormalized system is obtained