Example #1
0
def test_matlab():
    zeros_tf = [
        0, -50, -640, (1, -0.1422, 8.303), (1, 0.04791, 8.765),
        (1, -1.963, 45.63), (1, 0.1592, 266.9), (1, 9.724, 378.4),
        (1, 7.78, 724.3)
    ]
    poles_tf = [
        -51.61, -3.333, -0.06996, -0.01306, (1, 0.03257, 8.386),
        (1, 0.3603, 8.647), (1, 4.279, 46.71), (1, 2.556, 214.2),
        (1, 0.9348, 280.6), (1, 4.368, 391.3), (1, 1.574, 668.3)
    ]
    gain = -90.9477
    sys_pitch_14 = zpk_tf2(zeros_tf, poles_tf, gain)

    zeros_tf = [(1, 0.04271, 8.081), (1, 0.1098, 23.67), (1, 0.1615, 274.1),
                (1, 9.724, 378.4), (1, 0.544, 456.3)]
    poles_tf = [
        -51.66, -0.04851, (1, 0.03507, 8.386), (1, 2.661, 214.3),
        (1, 1.003, 280.4), (1, 4.177, 397.6), (1, 1.557, 674.3)
    ]
    gain = -0.8323
    sys_torque_8 = zpk_tf2(zeros_tf, poles_tf, gain)

    sys_drive_train = matlab.tf([73.19, 568900, 309800, 217100000],
                                [1, 50.41, 585.2, 28290, 53290, 2516000])

    omega = np.power(10, np.linspace(-1, 3, 300))
    fig = plt.figure(facecolor='w')
    mag, phase, omega = matlab.bode(sys_pitch_14, omega)
    fig = plt.figure(facecolor='w')
    mag, phase, omega = matlab.bode(sys_torque_8, omega)
    fig = plt.figure(facecolor='w')
    mag, phase, omega = matlab.bode(sys_drive_train, omega)
    #    test_plot(sys_pitch_14)
    plt.show()
Example #2
0
def update_num(val):
    global num
    num=num+val
    print(num)
    tf = matlab.tf(map(float,num),map(float,den))
    matlab.bode(tf)
    plt.show()
Example #3
0
def update_den(val):
    global den
    den=den+val
    print(den)
    tf = matlab.tf(map(float,num),map(float,den))
    matlab.bode(tf)
    plt.show()
Example #4
0
    def test_discrete(self):
        # Test discrete time frequency response

        # SISO state space systems with either fixed or unspecified sampling times
        sys = rss(3, 1, 1)
        siso_ss1d = StateSpace(sys.A, sys.B, sys.C, sys.D, 0.1)
        siso_ss2d = StateSpace(sys.A, sys.B, sys.C, sys.D, True)

        # MIMO state space systems with either fixed or unspecified sampling times
        A = [[-3., 4., 2.], [-1., -3., 0.], [2., 5., 3.]]
        B = [[1., 4.], [-3., -3.], [-2., 1.]]
        C = [[4., 2., -3.], [1., 4., 3.]]
        D = [[-2., 4.], [0., 1.]]
        mimo_ss1d = StateSpace(A, B, C, D, 0.1)
        mimo_ss2d = StateSpace(A, B, C, D, True)

        # SISO transfer functions
        siso_tf1d = TransferFunction([1, 1], [1, 2, 1], 0.1)
        siso_tf2d = TransferFunction([1, 1], [1, 2, 1], True)

        # Go through each system and call the code, checking return types
        for sys in (siso_ss1d, siso_ss2d, mimo_ss1d, mimo_ss2d, siso_tf1d,
                    siso_tf2d):
            # Set frequency range to just below Nyquist freq (for Bode)
            omega_ok = np.linspace(10e-4, 0.99, 100) * np.pi / sys.dt

            # Test frequency response
            ret = sys.freqresp(omega_ok)

            # Check for warning if frequency is out of range
            import warnings
            warnings.simplefilter('always', UserWarning)  # don't supress
            with warnings.catch_warnings(record=True) as w:
                # Set up warnings filter to only show warnings in control module
                warnings.filterwarnings("ignore")
                warnings.filterwarnings("always", module="control")

                # Look for a warning about sampling above Nyquist frequency
                omega_bad = np.linspace(10e-4, 1.1, 10) * np.pi / sys.dt
                ret = sys.freqresp(omega_bad)
                print("len(w) =", len(w))
                self.assertEqual(len(w), 1)
                self.assertIn("above", str(w[-1].message))
                self.assertIn("Nyquist", str(w[-1].message))

            # Test bode plots (currently only implemented for SISO)
            if (sys.inputs == 1 and sys.outputs == 1):
                # Generic call (frequency range calculated automatically)
                ret_ss = bode(sys)

                # Convert to transfer function and test bode again
                systf = tf(sys)
                ret_tf = bode(systf)

                # Make sure we can pass a frequency range
                bode(sys, omega_ok)

            else:
                # Calling bode should generate a not implemented error
                self.assertRaises(NotImplementedError, bode, (sys, ))
   def test_discrete(self):
      # Test discrete time frequency response

      # SISO state space systems with either fixed or unspecified sampling times
      sys = rss(3, 1, 1)
      siso_ss1d = StateSpace(sys.A, sys.B, sys.C, sys.D, 0.1)
      siso_ss2d = StateSpace(sys.A, sys.B, sys.C, sys.D, True)

      # MIMO state space systems with either fixed or unspecified sampling times
      A = [[-3., 4., 2.], [-1., -3., 0.], [2., 5., 3.]]
      B = [[1., 4.], [-3., -3.], [-2., 1.]]
      C = [[4., 2., -3.], [1., 4., 3.]]
      D = [[-2., 4.], [0., 1.]]
      mimo_ss1d = StateSpace(A, B, C, D, 0.1)
      mimo_ss2d = StateSpace(A, B, C, D, True)

      # SISO transfer functions
      siso_tf1d = TransferFunction([1, 1], [1, 2, 1], 0.1)
      siso_tf2d = TransferFunction([1, 1], [1, 2, 1], True)

      # Go through each system and call the code, checking return types
      for sys in (siso_ss1d, siso_ss2d, mimo_ss1d, mimo_ss2d,
                siso_tf1d, siso_tf2d):
         # Set frequency range to just below Nyquist freq (for Bode)
         omega_ok = np.linspace(10e-4,0.99,100) * np.pi/sys.dt

         # Test frequency response
         ret = sys.freqresp(omega_ok)

         # Check for warning if frequency is out of range
         import warnings
         warnings.simplefilter('always', UserWarning)   # don't supress
         with warnings.catch_warnings(record=True) as w:
            # Set up warnings filter to only show warnings in control module
            warnings.filterwarnings("ignore")
            warnings.filterwarnings("always", module="control")

            # Look for a warning about sampling above Nyquist frequency
            omega_bad = np.linspace(10e-4,1.1,10) * np.pi/sys.dt
            ret = sys.freqresp(omega_bad)
            print("len(w) =", len(w))
            self.assertEqual(len(w), 1)
            self.assertIn("above", str(w[-1].message))
            self.assertIn("Nyquist", str(w[-1].message))

         # Test bode plots (currently only implemented for SISO)
         if (sys.inputs == 1 and sys.outputs == 1):
            # Generic call (frequency range calculated automatically)
            ret_ss = bode(sys)

            # Convert to transfer function and test bode again
            systf = tf(sys);
            ret_tf = bode(systf)

            # Make sure we can pass a frequency range
            bode(sys, omega_ok)

         else:
            # Calling bode should generate a not implemented error
            self.assertRaises(NotImplementedError, bode, (sys,))
Example #6
0
def bode_diagram():
    a=[]
    b=[]
    print("分子の最高次は?")
    bunshi = int(input("入力:"))
    print("分子の高次の項の係数を入れてください")
    for i in range(bunshi+1):
        print("s^",(bunshi-i),"の係数を入力してください",sep='')
        a.append(float(input("入力:")))
    print('\n')    
    print("分母の最高次は?")
    bunbo = int(input("入力:"))
    print("分母の高次の項の係数を入れてください")
    for i in range(bunbo+1):
        print("s^",(bunbo-i),"の係数を入力してください",sep='')
        b.append(float(input("入力:")))
    print('\n')  

    Ga=matlab.tf(a,b)
    print(Ga)
    fig=plt.figure()
    matlab.bode(Ga)
    plt.show()
    fig.savefig("ボード線図.jpg")
    fig = plt.figure()
    matlab.nyquist(Ga)
    plt.show()
    fig.savefig("ナエキスト線図")
    def analysis(self, w, block, which):
        nume = [int(n) for n in block.nume_coef]
        if block.deno_coef == []:
            deno = [1]
        else:
            deno = [int(d) for d in block.deno_coef]
        nume.reverse()
        deno.reverse()
        print(nume)
        print(deno)
        system = matlab.tf(nume, deno)

        if which == 'bode':
            matlab.bode(system)
            plt.show()
        elif which == 'rlocus':
            matlab.rlocus(system)
            plt.show()
        elif which == 'nyquist':
            matlab.nyquist(sys)
            plt.show()
        elif which == 'impulse':
            t = np.linspace(0, 3, 1000)
            yout, T = matlab.impulse(system, t)
            plt.plot(T, yout)
            plt.axhline(0, color="b", linestyle="--")
            plt.xlim(0, 3)
            plt.show()
        elif which == 'step':
            t = np.linspace(0, 3, 1000)
            yout, T = matlab.step(system, t)
            plt.plot(T, yout)
            plt.axhline(1, color="b", linestyle="--")
            plt.xlim(0, 3)
            plt.show()
Example #8
0
 def test_doubleint(self):
     # 30 May 2016, RMM: added to replicate typecast bug in freqresp.py
     A = np.matrix('0, 1; 0, 0')
     B = np.matrix('0; 1')
     C = np.matrix('1, 0')
     D = 0
     sys = ss(A, B, C, D)
     bode(sys)
 def test_doubleint(self):
    # 30 May 2016, RMM: added to replicate typecast bug in freqresp.py
    A = np.matrix('0, 1; 0, 0');
    B = np.matrix('0; 1');
    C = np.matrix('1, 0');
    D = 0;
    sys = ss(A, B, C, D);
    bode(sys);
Example #10
0
def main():
    # 制御対象を定義(今回はモータを想定)
    J = 0.6  # 慣性
    D = 0.2  # 粘性
    Kt = 0.15  # トルク定数
    P = crl.tf([Kt], [J, D, 0])  # モータ角度の電流制御

    # 参照モデルの定義
    M = crl.tf([50], [1, 50])

    # シミュレーション条件を定義
    Ts = 0.001  # サンプリング時間

    # 制御器構造の定義
    beta = crl.ss("0", "1", "0; 1", "1; 0")  # PI制御器
    print(crl.tf(beta))
    beta = crl.c2d(beta, Ts)

    # 制御対象と参照モデルのゲイン線図
    plt.figure(1)
    crl.bode([P, M])
    plt.legend(["Plant", "Ref. model"])

    # prbsを生成する
    n = 12  # m系列信号の次数
    Tp = 5  # 何周期印加するか?
    Ap = 0.5  # 振幅 [A]
    u0 = 2 * prbs(n)
    u0 = Ap * (u0 - np.average(u0))
    u0 = np.tile(u0, Tp)
    t = np.linspace(0, Ts * u0.shape[0], u0.shape[0])
    plt.figure(2)
    plt.plot(t, u0)
    plt.xlabel("Time [s]")
    plt.ylabel("Current [A]")

    # 実験データの取得
    print("=== Start Experiment ===")
    Pd = crl.c2d(P, Ts, "tustin")  # 双一次変換で離散時間モデルを作成
    t = np.arange(start=0, stop=Tp * Ts * (2**n - 1), step=Ts)
    (y0, t0, xout) = crl.lsim(Pd, u0[:], t[:])  # 応答を取得
    plt.figure(3)
    plt.plot(y0)

    # VRFTを実行する
    print("=== Start VRFT ===")
    W = crl.tf([50], [1, 50])  # 周波数重み
    L = crl.minreal((1 - M) * M * W)  # プレフィルタ
    Ld = crl.c2d(L, Ts, "tustin")
    (ul, tl, xlout) = crl.lsim(Ld, u0, t)
    (phi_l, tl, xlout) = crl.lsim(beta, y0[:])
    print(phi_l)
    rho = np.linalg.solve(phi_l, ul)
    print(rho)

    plt.show()
def test_doubleint():
    """Test typcast bug with double int

    30 May 2016, RMM: added to replicate typecast bug in frequency_response.py
    """
    A = np.array([[0, 1], [0, 0]])
    B = np.array([[0], [1]])
    C = np.array([[1, 0]])
    D = 0
    sys = ss(A, B, C, D)
    bode(sys)
def test_bode_basic(ss_siso):
    """Test bode plot call (Very basic)"""
    # TODO: proper test
    tf_siso = tf(ss_siso)
    bode(ss_siso)
    bode(tf_siso)
    assert len(bode_plot(tf_siso, plot=False, omega_num=20)[0] == 20)
    omega = bode_plot(tf_siso, plot=False, omega_limits=(1, 100))[2]
    assert_allclose(omega[0], 1)
    assert_allclose(omega[-1], 100)
    assert len(bode_plot(tf_siso, plot=False, omega=np.logspace(-1,1,10))[0])\
         == 10
    def BAGUVIX(GG1, name_gg1, GG2, name_gg2,
                t):  # функция для построения графиков характеристик
        topic = {
            'G1': 'безынерционного звена',
            'G2': 'апериодического звена',
            'G3': 'интегрирующего звена',
            'G4': 'реального диф. звена',
            'G5': 'идеального диф. звена',
        }  # словарь для графика
        if name_gg1 in topic:  # определяем какой именно строим, для графика
            k1 = topic[name_gg1]

        plt.figure(1)  # Вывод графиков в отдельном окне
        y1, t1 = con.step(GG1, t)
        y2, t2 = con.step(GG2, t)
        lines = [y1, y2]
        # plt.subplot(1, 1, 1)  # 1цифра - количество строк в графике, 2 -тьиьтиколичество графиков в строке, 3 -номер графика
        lines[0], lines[1] = plt.plot(t, y1, "r", t, y2, "b")
        plt.legend(lines, ['h(t) для 1', 'h(t) для 2'],
                   loc='best',
                   ncol=2,
                   fontsize=10)
        plt.title('Переходная характеристика' + '\n для ' + k1, fontsize=10)
        plt.ylabel('h')
        plt.xlabel('t, c')
        plt.grid()

        plt.figure(2)
        y2, t2 = con.impulse(GG2, t)
        y1, t1 = con.impulse(GG1, t)
        lines[0], lines[1] = plt.plot(t, y1, "r", t, y2, "b")
        plt.legend(lines, ['w(t) для 1', 'w(t) для 2'],
                   loc='best',
                   ncol=2,
                   fontsize=10)
        plt.title('Импульсная характеристика' + '\n для ' + k1, fontsize=10)
        plt.ylabel('w')
        plt.xlabel('t, c')
        plt.grid()

        plt.figure(3)
        mag1, phase1, omega1 = con.bode(GG1, dB=False)
        # plt.plot()
        plt.title('Частотные характеристики' + "\n для " + k1,
                  fontsize=10,
                  y=2.2)
        mag1, phase1, omega1 = con.bode(GG2, dB=False)
        plt.plot()
        plt.title('Частотные характеристики' + "\n для " + k1,
                  fontsize=10,
                  y=2.2)
        plt.show()
def test_discrete(dsystem_type):
    """Test discrete time frequency response"""
    dsys = dsystem_type
    # Set frequency range to just below Nyquist freq (for Bode)
    omega_ok = np.linspace(10e-4, 0.99, 100) * np.pi / dsys.dt

    # Test frequency response
    dsys.frequency_response(omega_ok)

    # Check for warning if frequency is out of range
    with pytest.warns(UserWarning, match="above.*Nyquist"):
        # Look for a warning about sampling above Nyquist frequency
        omega_bad = np.linspace(10e-4, 1.1, 10) * np.pi / dsys.dt
        dsys.frequency_response(omega_bad)

    # Test bode plots (currently only implemented for SISO)
    if (dsys.ninputs == 1 and dsys.noutputs == 1):
        # Generic call (frequency range calculated automatically)
        bode(dsys)

        # Convert to transfer function and test bode again
        systf = tf(dsys)
        bode(systf)

        # Make sure we can pass a frequency range
        bode(dsys, omega_ok)

    else:
        # Calling bode should generate a not implemented error
        with pytest.raises(NotImplementedError):
            bode((dsys, ))
Example #15
0
   def test_siso(self):
      B = np.matrix('0;1')
      D = 0
      sys = StateSpace(self.A,B,self.C,D)

      # test frequency response
      frq=sys.freqresp(self.omega)

      # test bode plot
      bode(sys)

      # Convert to transfer function and test bode
      systf = tf(sys)
      bode(systf)
Example #16
0
    def test_siso(self):
        B = np.matrix('0;1')
        D = 0
        sys = StateSpace(self.A, B, self.C, D)

        # test frequency response
        frq = sys.freqresp(self.omega)

        # test bode plot
        bode(sys)

        # Convert to transfer function and test bode
        systf = tf(sys)
        bode(systf)
    def test_matlab_wrapper_exceptions(self):
        """Test out exceptions in matlab/wrappers.py"""
        sys = tf([1], [1, 2, 1])

        # Extra arguments in bode
        with pytest.raises(ControlArgument, match="not all arguments"):
            bode(sys, 'r-', [1e-2, 1e2], 5.0)

        # Multiple plot styles
        with pytest.warns(UserWarning, match="plot styles not implemented"):
            bode(sys, 'r-', sys, 'b--', [1e-2, 1e2])

        # Incorrect number of arguments to dcgain
        with pytest.raises(ValueError, match="needs either 1, 2, 3 or 4"):
            dcgain(1, 2, 3, 4, 5)
Example #18
0
def create_Plot(var,name,num, den):
    W=ml.tf(num,den)
    if var!=5:
        #Переходная функция
        plt.figure().canvas.set_window_title(name)
        y,x=ml.step(W,timeVector)
        plt.plot(x,y,"b")
        plt.title('Переходная функция')
        plt.ylabel('Амплитуда, о.е.')
        plt.xlabel('Время, с.')
        plt.grid(True)
        #TimeLine=[]
        #for i in range(0;3000):
        #   TimeLine = [i/1000]
        plt.show()
            #Импульсная функция
        plt.figure().canvas.set_window_title(name)
        y,x=ml.impulse(W,  timeVector)
        plt.plot(x,y,"r")
        plt.title('Импульсная функция')
        plt.ylabel('Амплитуда, о.е.')
        plt.xlabel('Время, с.')
        plt.grid(True)
        plt.show()
    #Диаграмма Боде
    plt.figure().canvas.set_window_title(name)
    mag, phase, omega = ml.bode(W, dB=False)
    plt.plot()
    plt.xlabel('Частота, Гц')
    plt.show()
    return
Example #19
0
def test_plot(sys):
    fig = plt.figure(facecolor='w')
    mag, phase, omega = matlab.bode(sys)
    fig = plt.figure(facecolor='w')
    real, imag, freq = matlab.nyquist(sys)
    fig = plt.figure(facecolor='w')
    matlab.nichols(sys)

    rlist, klist = matlab.rlocus(sys, klist=None)

    #    fig = plt.figure(facecolor = 'w')
    #    #对数幅相特性曲线
    #    ax = fig.add_subplot(221)
    #    ax.grid(True)
    ##    real = mag*np.sin(phase)
    ##    imag = mag*np.cos(phase)
    #    plt.plot(real, imag)
    #    ax = fig.add_subplot(223)
    #    ax.grid(True)
    #    real = np.log(mag)*np.sin(phase)
    #    imag = np.log(mag)*np.cos(phase)
    #    plt.plot(real, imag)
    #    #对数频率特性曲线
    #    ax = fig.add_subplot(222)
    #    ax.grid(True)
    #    plt.plot(np.log(omega), np.log(mag))
    #    ax = fig.add_subplot(224)
    #    ax.grid(True)
    #    plt.plot(np.log(omega), phase)
    plt.show()
Example #20
0
def bode_as(num, den, freq_range=None):
    '''Creates the asymptotic log-magnitude Bode plot for type zero transfer 
    functions.
    
    Example : for the system G(s) = (4s + 1) / (3s + 2), use
    bode_as([4, 1], [3, 2])
    
    for the system G(s) = [(s + 1)(s + 20)] / [(s + 2)(s + 8)], use
    bode_as(poly((-1, -20)), poly((-2, -8)))
    '''
    
    G = tf(num, den)
    
    # If the user provides the range of frequencies, take it
    # Else calculate the most suitable range
    if freq_range:
        freq_min, freq_max = freq_range
    else:
        freq_min, freq_max = plot_range(num, den)
        
    omega = logspace(log10(freq_min), log10(freq_max), 1000)
    
    # The actual Bode plot calculation
    mag, phase, freq = bode(G, omega, dB=True, Plot=False)
    
    # Asymptotic log-magnitude Bode plot calculation
    asymptotic_plot_data = asymptote(num, den)
    omega_as, mag_as = asymptotic_plot_data[:, 0], asymptotic_plot_data[:, 1]
    
    plot_config(mag, omega, mag_as, omega_as)
Example #21
0
def process_data(num11, den11, num21, den21):
    w11 = ctrl.tf(num11, den11)
    w21 = ctrl.tf(num21, den21)
    print('результат w11={} w21={}'.format(w11, w21))
    TimeLine = []
    for i in range(1, 3000):
        TimeLine.append(i / 1000)
    plt.figure(0, figsize=[7, 6])

    [y11, x11] = ctrl.step(w11, TimeLine)
    [y21, x21] = ctrl.step(w21, TimeLine)
    plt.plot(x11, y11, "r", label='Исходная')
    plt.plot(x21, y21, "b", label='Увеличенная k и уменшенная Т')
    plt.title('Переходная функция звена')
    plt.ylabel('Амплитуда')
    plt.xlabel('Время(с)')
    plt.grid(True)
    plt.show()

    [y11, x11] = ctrl.impulse(w11, TimeLine)
    [y21, x21] = ctrl.impulse(w21, TimeLine)
    plt.plot(x11, y11, "r", label='Исходная')
    plt.plot(x21, y21, "b", label='Увеличенная k и уменшенная Т')
    plt.title('Импульсная функция  звена')
    plt.ylabel('Амплитуда')
    plt.xlabel('Время(с)')
    plt.grid(True)
    plt.show()

    ctrl.mag, ctrl.phase, ctrl.omega = ctrl.bode(w11, w21, dB=False)
    plt.plot()
    plt.show()
    return w11, w21
Example #22
0
def tf(sys,omega):
    mag, phase, omega = matlab.bode(sys,omega,Plot=False)
    mag = np.squeeze(mag)
    phase = np.squeeze(phase)
    G = mag*np.exp(1j*phase)
    freq = omega/(2.0*np.pi)
    hoge = FrequencySeries(G,frequencies=freq)
    return hoge
Example #23
0
    def set_parameters(self, x, y):
        self.a = x
        self.b = y
        from sympy.parsing.sympy_parser import parse_expr
        #parse_expr(self.a)
        #parse_expr(self.b)
        G1 = parse_expr(self.a) / parse_expr(self.b)
        #parse_expr(G1)

        num = Poly(G1.as_numer_denom()[0], s).all_coeffs()
        den = Poly(G1.as_numer_denom()[1], s).all_coeffs()
        num_coe_lenght = len(num)
        den_coe_lenght = len(den)

        tf = matlab.tf(map(float, num), map(float, den))
        matlab.bode(tf)
        plt.show()
    def testFreqResp(self):
        """Compare the bode reponses of the SS systems and TF systems to the original SS
           They generally are different realizations but have same freq resp. 
           Currently this test may only be applied to SISO systems.
        """              
        for states in range(1,self.maxStates):
            for testNum in range(self.numTests):                       
                for inputs in range(1,1):
                    for outputs in range(1,1):       
                        ssOriginal = matlab.rss(states, inputs, outputs)
                        
                        tfOriginal_Actrb, tfOriginal_Bctrb, tfOriginal_Cctrb, tfOrigingal_nctrb, tfOriginal_index,\
                            tfOriginal_dcoeff, tfOriginal_ucoeff = tb04ad(states,inputs,outputs,\
                            ssOriginal.A,ssOriginal.B,ssOriginal.C,ssOriginal.D,tol1=0.0)
                        
                        ssTransformed_nr, ssTransformed_A, ssTransformed_B, ssTransformed_C, ssTransformed_D\
                            = td04ad('R',inputs,outputs,tfOriginal_index,tfOriginal_dcoeff,tfOriginal_ucoeff,tol=0.0)
                        
                        tfTransformed_Actrb, tfTransformed_Bctrb, tfTransformed_Cctrb, tfTransformed_nctrb,\
                            tfTransformed_index, tfTransformed_dcoeff, tfTransformed_ucoeff = tb04ad(\
                            ssTransformed_nr,inputs,outputs,ssTransformed_A, ssTransformed_B, ssTransformed_C,\
                            ssTransformed_D,tol1=0.0)

                        numTransformed = np.array(tfTransformed_ucoeff)
                        denTransformed = np.array(tfTransformed_dcoeff)
                        numOriginal = np.array(tfOriginal_ucoeff)
                        denOriginal = np.array(tfOriginal_dcoeff)
                                              
                        ssTransformed = matlab.ss(ssTransformed_A,ssTransformed_B,ssTransformed_C,ssTransformed_D)
                        for inputNum in range(inputs):
                            for outputNum in range(outputs):
                                [ssOriginalMag,ssOriginalPhase,freq] = matlab.bode(ssOriginal,Plot=False) 
                                [tfOriginalMag,tfOriginalPhase,freq] = matlab.bode(matlab.tf(numOriginal[outputNum][inputNum],denOriginal[outputNum]),Plot=False)
                                [ssTransformedMag,ssTransformedPhase,freq] = matlab.bode(ssTransformed,freq,Plot=False)
                                [tfTransformedMag,tfTransformedPhase,freq] = matlab.bode(matlab.tf(numTransformed[outputNum][inputNum],denTransformed[outputNum]),freq,Plot=False)
                                #print 'numOrig=',numOriginal[outputNum][inputNum]
                                #print 'denOrig=',denOriginal[outputNum]
                                #print 'numTrans=',numTransformed[outputNum][inputNum]
                                #print 'denTrans=',denTransformed[outputNum]
                                np.testing.assert_array_almost_equal(ssOriginalMag,tfOriginalMag,decimal=3)
                                np.testing.assert_array_almost_equal(ssOriginalPhase,tfOriginalPhase,decimal=3)       
                                np.testing.assert_array_almost_equal(ssOriginalMag,ssTransformedMag,decimal=3)
                                np.testing.assert_array_almost_equal(ssOriginalPhase,ssTransformedPhase,decimal=3)
                                np.testing.assert_array_almost_equal(tfOriginalMag,tfTransformedMag,decimal=3)
                                np.testing.assert_array_almost_equal(tfOriginalPhase,tfTransformedPhase,decimal=2)
Example #25
0
 def set_parameters(self,x,y):
     self.a=x
     self.b=y
     from sympy.parsing.sympy_parser import parse_expr
     #parse_expr(self.a)
     #parse_expr(self.b)
     G1= parse_expr(self.a)/parse_expr(self.b)
     #parse_expr(G1)
     
     num = Poly(G1.as_numer_denom()[0],s).all_coeffs()
     den = Poly(G1.as_numer_denom()[1],s).all_coeffs()
     num_coe_lenght = len(num)
     den_coe_lenght = len(den)
     
     
     tf = matlab.tf(map(float,num),map(float,den))
     matlab.bode(tf)
     plt.show()
Example #26
0
def test_siso():
    """Test SISO frequency response"""
    A = np.array([[1, 1], [0, 1]])
    B = np.array([[0], [1]])
    C = np.array([[1, 0]])
    D = 0
    sys = StateSpace(A, B, C, D)
    omega = np.linspace(10e-2, 10e2, 1000)

    # test frequency response
    sys.freqresp(omega)

    # test bode plot
    bode(sys)

    # Convert to transfer function and test bode
    systf = tf(sys)
    bode(systf)
Example #27
0
def test_get_sys():
    omega = np.power(10, np.linspace(-3, 3, 1000))
    root = r'..\Data\sys\sys_%d.mat'
    sys_8 = get_sys_from_mat(root % 8)
    sys_12 = get_sys_from_mat(root % 12)
    sys_14 = get_sys_from_mat(root % 14)
    sys_18 = get_sys_from_mat(root % 18)

    fig = plt.figure(facecolor='w')
    fig.canvas.set_window_title('sys_torque_8')
    mag, phase, omega1 = matlab.bode(sys_8[0], omega)

    fig = plt.figure(facecolor='w')
    fig.canvas.set_window_title('sys_pitch')
    mag, phase, omega1 = matlab.bode(sys_12[1], sys_14[1], sys_18[1], omega)

    fig = plt.figure(facecolor='w')
    fig.canvas.set_window_title('sys_drive_train_%d' % 8)
    mag, phase, omega1 = matlab.bode(sys_8[2], omega)
    plt.show()
Example #28
0
                def TF_V2Vel(f):
                    import matplotlib.pyplot as plt
                    H = tf_120()
                    #f = np.logspace(-3,2,1e5)
                    matlab.bode(H,
                                f * (2. * np.pi),
                                Plot=True,
                                dB=True,
                                Hz=True,
                                deg=True)
                    plt.hold(True)
                    plt.savefig('./hoge_120.png')
                    plt.close()
                    #exit()
                    H_V2vel, phase, omega = matlab.bode(1 / H,
                                                        f * (2. * np.pi),
                                                        Plot=False,
                                                        dB=False)

                    return H_V2vel
Example #29
0
    def tf(self,_input,_output,freq):
        ''' 

        ----
        Parameters:
        
        
        ----
        Returns
        '''
        self.ss(_input,_output)
        mag, phase, omega = matlab.bode(self.ss_siso,freq*2.0*np.pi,Plot=False)
        gain = mag*(np.exp(1j*phase))
        return freq,gain
Example #30
0
def Freq(W):
    print("Оценка по АЧХ и ФЧХ:")
    # t = np.linspace(0, stop=100, num=1000)
    mag, phase, omega = con.bode(W, dB=False)
    plt.plot()
    # plt.close()
    plt.show()
    mag_max = max(mag)
    M = (mag_max / mag[0])
    print("Показатель коллебательности М: " + str(M))
    t = True
    n = list(mag).index(mag_max)
    while n < len(mag) and t:
        if ((mag[n] > mag[0] - 0.01) and
            (mag[n] < mag[0] + 0.01)) or mag[n] < mag[0]:
            wc = omega[n]
            phase_res = phase[n]
            print("Время регулирования: " + str(2 * math.pi / wc))
            """ В хорошо демпфированных системах запас устойчивости по амплитуде колеблется 
            в пределах от 6 до 20 дБ, а запас по фазе от 30 до 60"""
            print("Запас по фазе: " + str(180 - abs(phase_res)))
            t = False
        n = n + 1

    t_magn = True
    n = 0
    while n < len(phase) and t_magn:
        if -179.7 > phase[n] > -180.7:
            index_phase_180 = list(phase).index(phase[n])
            print("Запас по амплитуде: " +
                  str(round(mag[0] - mag[index_phase_180], 3)))
            t_magn = False
        n = n + 1
    """запас по амплитуде может быть равен бесконечности, если фазовая характеристика не 
    пересекает линию −180°"""
    if t_magn:
        print(
            "Запас по амплитуде равен бесконечности,  фазовая характеристика не пересекает линию −180°"
        )
Example #31
0
    def testFreqResp(self):
        """Compare the bode reponses of the SS systems and TF systems to the original SS
           They generally are different realizations but have same freq resp.
           Currently this test may only be applied to SISO systems.
        """
        from slycot import tb04ad, td04ad
        for states in range(1, self.maxStates):
            for testNum in range(self.numTests):
                for inputs in range(1, 1):
                    for outputs in range(1, 1):
                        ssOriginal = matlab.rss(states, outputs, inputs)

                        tfOriginal_Actrb, tfOriginal_Bctrb, tfOriginal_Cctrb,\
                            tfOrigingal_nctrb, tfOriginal_index,\
                            tfOriginal_dcoeff, tfOriginal_ucoeff = tb04ad(
                                states, inputs, outputs, ssOriginal.A,
                                ssOriginal.B, ssOriginal.C, ssOriginal.D,
                                tol1=0.0)

                        ssTransformed_nr, ssTransformed_A, ssTransformed_B,\
                            ssTransformed_C, ssTransformed_D\
                            = td04ad('R', inputs, outputs, tfOriginal_index,
                                     tfOriginal_dcoeff, tfOriginal_ucoeff,
                                     tol=0.0)

                        tfTransformed_Actrb, tfTransformed_Bctrb,\
                            tfTransformed_Cctrb, tfTransformed_nctrb,\
                            tfTransformed_index, tfTransformed_dcoeff,\
                            tfTransformed_ucoeff = tb04ad(
                                ssTransformed_nr, inputs, outputs,
                                ssTransformed_A, ssTransformed_B,
                                ssTransformed_C, ssTransformed_D,
                                tol1=0.0)

                        numTransformed = np.array(tfTransformed_ucoeff)
                        denTransformed = np.array(tfTransformed_dcoeff)
                        numOriginal = np.array(tfOriginal_ucoeff)
                        denOriginal = np.array(tfOriginal_dcoeff)

                        ssTransformed = matlab.ss(ssTransformed_A,
                                                  ssTransformed_B,
                                                  ssTransformed_C,
                                                  ssTransformed_D)
                        for inputNum in range(inputs):
                            for outputNum in range(outputs):
                                [ssOriginalMag, ssOriginalPhase, freq] =\
                                    matlab.bode(ssOriginal, plot=False)
                                [tfOriginalMag, tfOriginalPhase, freq] =\
                                    matlab.bode(matlab.tf(
                                        numOriginal[outputNum][inputNum],
                                        denOriginal[outputNum]), plot=False)
                                [ssTransformedMag, ssTransformedPhase, freq] =\
                                    matlab.bode(ssTransformed,
                                                freq, plot=False)
                                [tfTransformedMag, tfTransformedPhase, freq] =\
                                    matlab.bode(matlab.tf(
                                        numTransformed[outputNum][inputNum],
                                        denTransformed[outputNum]),
                                        freq, plot=False)
                                # print('numOrig=',
                                #  numOriginal[outputNum][inputNum])
                                # print('denOrig=',
                                #  denOriginal[outputNum])
                                # print('numTrans=',
                                #  numTransformed[outputNum][inputNum])
                                # print('denTrans=',
                                #  denTransformed[outputNum])
                                np.testing.assert_array_almost_equal(
                                    ssOriginalMag, tfOriginalMag, decimal=3)
                                np.testing.assert_array_almost_equal(
                                    ssOriginalPhase,
                                    tfOriginalPhase,
                                    decimal=3)
                                np.testing.assert_array_almost_equal(
                                    ssOriginalMag, ssTransformedMag, decimal=3)
                                np.testing.assert_array_almost_equal(
                                    ssOriginalPhase,
                                    ssTransformedPhase,
                                    decimal=3)
                                np.testing.assert_array_almost_equal(
                                    tfOriginalMag, tfTransformedMag, decimal=3)
                                np.testing.assert_array_almost_equal(
                                    tfOriginalPhase,
                                    tfTransformedPhase,
                                    decimal=2)
Example #32
0
G1 = con.tf(1, 1)  # обратная связь
G2 = con.tf([2, 0], [3, 4])  # generator
G3 = con.tf(1, [1, 0])  # turbine
G4 = con.tf(1, [3, 1])  # device
G5 = G2 * G3 * G4
G_raz = G2 * G3 * G4 * G1  # W разомкнутой САУ
G_zam = G5 / (1 + G5)
print(G_zam)

nyquis(G_raz)
plt.show()
plt.figure()
# plt.plot()
plt.title('Частотная характеристика', fontsize=10, y=2.2)
mag1, phase1, omega1 = con.bode(G_raz)
plt.plot()
plt.show()
# pzmap(G_zam)
# mihalych(G_zam)
# gurych(G_zam)
pereh(G_zam, t)
G = True
k1 = 0.3
while G:
    G1 = con.tf(k1, 1)  # обратная связь
    G5 = G2 * G3 * G4
    G_zam = G5.feedback(other=G1, sign=-1)
    G_raz = G5 * G1
    if (gurych(G_zam)):
        print("Система устойчива при k1 = " + str(k1))
plt.xlabel("Time")
plt.ylabel("y_tot")
plt.legend(['System', 'ARMAX', 'ARX', 'OE'])
plt.grid()
plt.show()

#rmse = np.round(np.sqrt(np.mean((Ytotvalid - Yv_armaxi.T) ** 2)), 2)
EV = 100 * (np.round((1.0 - np.mean(
    (Ytotvalid - Yv_armax)**2) / np.std(Ytotvalid)), 2))
#plt.title("Validation: | RMSE ARMAX_i = {}".format(rmse))
plt.title("Validation: | Explained Variance ARMAX = {}%".format(EV))

## Bode Plots
w_v = np.logspace(-3, 4, num=701)
plt.figure(7)
mag, fi, om = cnt.bode(g_sample, w_v)
mag1, fi1, om = cnt.bode(Id_ARMAX.G, w_v)
mag2, fi2, om = cnt.bode(Id_ARX.G, w_v)
mag3, fi3, om = cnt.bode(Id_OE.G, w_v)
plt.subplot(2, 1, 1), plt.loglog(om, mag), plt.grid(),
plt.loglog(om, mag1), plt.loglog(om, mag2), plt.loglog(om, mag3)
plt.xlabel("w"), plt.ylabel("Amplitude Ratio"), plt.title("Bode Plot G(iw)")
plt.subplot(2, 1, 2), plt.semilogx(om, fi), plt.grid()
plt.semilogx(om, fi1), plt.semilogx(om, fi2), plt.semilogx(om, fi3),
plt.xlabel("w"), plt.ylabel("phase")
plt.legend(['System', 'ARMAX', 'ARX', 'OE'])

plt.figure(8)
mag, fi, om = cnt.bode(h_sample, w_v)
mag1, fi1, om = cnt.bode(Id_ARMAX.H, w_v)
mag2, fi2, om = cnt.bode(Id_ARX.H, w_v)
Example #34
0
def BodePlot(TF, freq_range, show_plot):
    mag, phase, w = mt.bode(TF, freq_range)
    if show_plot != 0:
        plt.show()
    return mag, phase, w
plt.legend()
plt.show()

################################################################################
#                               End PID test
################################################################################


################################################################################
#                               Transfer function test
################################################################################
# Open loop control system
# u -> R -> G -> y

# Process transfer function G(s)
G = mtl.tf([1,1],[2,1,1])

# PID Controller R(s)
R = pid.transferFunction()

# Open loop system transfer function
sys = R * G
print('System transfer function',sys)

# Bode plot
mtl.bode(sys)

################################################################################
#                           End transfer function test
################################################################################
Example #36
0
    matlab.bode(tf)
    plt.show()
    
def creates_sliders(v1,v2):
        for nume_slider in range(0,v1):
            master = Tk()
            w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
            w.pack()
        mainloop()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.autoscale(True)
#plt.subplots_adjust(left=0.25, bottom=0.25)
#num_coe_sli = plt.axes([0.25, 0.1, 0.65, 0.03])
#deno_coe_sli = plt.axes([0.25,0.05,0.65,0.03])
#nume_slider = Slider(num_coe_sli, 'Numerator', 0, 99, valinit=0,valfmt='%d')
#deno_slider = Slider(deno_coe_sli, 'Denominator', 0, 99, valinit=0,valfmt='%d')
freqResponse(G2)
print(num)
print(den)
tf = matlab.tf(map(float,num),map(float,den))
matlab.bode(tf)
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.20, 0.1, 0.65, 0.03], axisbg=axcolor)
axamp  = plt.axes([0.20, 0.15, 0.65, 0.03], axisbg=axcolor)
sfreq = Slider(axfreq, 'Numerator', 0.1, 30.0, valinit=0)
samp = Slider(axamp, 'Denominator', 0.1, 10.0, valinit=0)
plt.subplots_adjust(left=0.20, bottom=0.30)
plt.show()
sfreq.on_changed(update_num)
samp.on_changed(update_den)
 def test_matlab_freqplot_passthru(self, mplcleanup):
     """Test nyquist and bode to make sure the pass arguments through"""
     sys = tf([1], [1, 2, 1])
     bode((sys,))            # Passing tuple will call bode_plot
     nyquist((sys,))         # Passing tuple will call nyquist_plot