def test_impulse(self):
        A, B, C, D = self.make_SISO_mats()
        sys = ss(A, B, C, D)

        figure()

        #everything automatically
        t, y = impulse(sys)
        plot(t, y, label='Simple Case')

        #supply time and X0
        T = linspace(0, 2, 100)
        X0 = [0.2, 0.2]
        t, y = impulse(sys, T, X0)
        plot(t, y, label='t=0..2, X0=[0.2, 0.2]')

        #Test system with direct feed-though, the function should print a warning.
        D = [[0.5]]
        sys_ft = ss(A, B, C, D)
        t, y = impulse(sys_ft)
        plot(t, y, label='Direct feedthrough D=[[0.5]]')

        #Test MIMO system
        A, B, C, D = self.make_MIMO_mats()
        sys = ss(A, B, C, D)
        t, y = impulse(sys)
        plot(t, y, label='MIMO System')

        legend(loc='best')
Exemple #2
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
Exemple #3
0
    def test_impulse(self):
        A, B, C, D = self.make_SISO_mats()
        sys = ss(A, B, C, D)

        figure()

        #everything automatically
        t, y = impulse(sys)
        plot(t, y, label='Simple Case')

        #supply time and X0
        T = linspace(0, 2, 100)
        X0 = [0.2, 0.2]
        t, y = impulse(sys, T, X0)
        plot(t, y, label='t=0..2, X0=[0.2, 0.2]')

        #Test system with direct feed-though, the function should print a warning.
        D = [[0.5]]
        sys_ft = ss(A, B, C, D)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            t, y = impulse(sys_ft)
            plot(t, y, label='Direct feedthrough D=[[0.5]]')

        #Test MIMO system
        A, B, C, D = self.make_MIMO_mats()
        sys = ss(A, B, C, D)
        t, y = impulse(sys)
        plot(t, y, label='MIMO System')

        legend(loc='best')
 def testImpulse_mimo(self, mimo):
     """Test impulse() for MIMO system"""
     t = np.linspace(0, 1, 10)
     youttrue = np.array([86., 70.1808, 57.3753, 46.9975, 38.5766, 31.7344,
                          26.1668, 21.6292, 17.9245, 14.8945])
     sys = mimo.ss1
     with pytest.warns(UserWarning, match="System has direct feedthrough"):
         y_00, _t = impulse(sys, T=t, input=0, output=0)
         y_11, _t = impulse(sys, T=t, input=1, output=1)
     np.testing.assert_array_almost_equal(y_00, youttrue, decimal=4)
     np.testing.assert_array_almost_equal(y_11, youttrue, decimal=4)
    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 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()
Exemple #7
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
Exemple #8
0
    def test_impulse_mimo(self, MIMO_mats, mplcleanup):
        #Test MIMO system
        A, B, C, D = MIMO_mats
        sys = ss(A, B, C, D)
        y, t = impulse(sys)
        plot(t, y[:, :, 0], label='MIMO System')

        legend(loc='best')
    def testImpulse(self, siso):
        """Test impulse()"""
        t = np.linspace(0, 1, 10)
        # test transfer function
        yout, tout = impulse(siso.tf1, T=t)
        youttrue = np.array([
            0., 0.0994, 0.1779, 0.2388, 0.2850, 0.3188, 0.3423, 0.3573, 0.3654,
            0.3679
        ])
        np.testing.assert_array_almost_equal(yout, youttrue, decimal=4)
        np.testing.assert_array_almost_equal(tout, t)

        sys = siso.ss1
        youttrue = np.array([
            86., 70.1808, 57.3753, 46.9975, 38.5766, 31.7344, 26.1668, 21.6292,
            17.9245, 14.8945
        ])
        # produce a warning for a system with direct feedthrough
        with pytest.warns(UserWarning, match="System has direct feedthrough"):
            # Test SISO system
            yout, tout = impulse(sys, T=t)
            np.testing.assert_array_almost_equal(yout, youttrue, decimal=4)
            np.testing.assert_array_almost_equal(tout, t)

        # produce a warning for a system with direct feedthrough
        with pytest.warns(UserWarning, match="System has direct feedthrough"):
            # Play with arguments
            yout, tout = impulse(sys, T=t, X0=0)
            np.testing.assert_array_almost_equal(yout, youttrue, decimal=4)
            np.testing.assert_array_almost_equal(tout, t)

        # produce a warning for a system with direct feedthrough
        with pytest.warns(UserWarning, match="System has direct feedthrough"):
            X0 = np.array([0, 0])
            yout, tout = impulse(sys, T=t, X0=X0)
            np.testing.assert_array_almost_equal(yout, youttrue, decimal=4)
            np.testing.assert_array_almost_equal(tout, t)

        # produce a warning for a system with direct feedthrough
        with pytest.warns(UserWarning, match="System has direct feedthrough"):
            yout, tout, xout = impulse(sys, T=t, X0=0, return_x=True)
            np.testing.assert_array_almost_equal(yout, youttrue, decimal=4)
            np.testing.assert_array_almost_equal(tout, t)
Exemple #10
0
    def test_impulse(self, SISO_mats, mplcleanup):
        A, B, C, D = SISO_mats
        sys = ss(A, B, C, D)

        figure()

        #everything automatically
        t, y = impulse(sys)
        plot(t, y, label='Simple Case')

        #supply time and X0
        T = linspace(0, 2, 100)
        X0 = [0.2, 0.2]
        t, y = impulse(sys, T, X0)
        plot(t, y, label='t=0..2, X0=[0.2, 0.2]')

        #Test system with direct feed-though, the function should print a warning.
        D = [[0.5]]
        sys_ft = ss(A, B, C, D)
        with pytest.warns(UserWarning, match="has direct feedthrough"):
            t, y = impulse(sys_ft)
            plot(t, y, label='Direct feedthrough D=[[0.5]]')
Exemple #11
0
def validation(SYS,u,y,Time, k = 1, centering = 'None'):
    # check dimensions
    y = 1. * np.atleast_2d(y)
    u = 1. * np.atleast_2d(u)
    [n1, n2] = y.shape
    ydim = min(n1, n2)
    ylength = max(n1, n2)
    if ylength == n1:
        y = y.T
    [n1, n2] = u.shape
    udim = min(n1, n2)
    ulength = max(n1, n2)  
    if ulength == n1:
        u = u.T
    
    Yval = np.zeros((ydim,ylength))
    
    # Data centering
    #y_rif = np.zeros(ydim)
    #u_rif = np.zeros(udim)
    if centering == 'InitVal':
        y_rif = 1. * y[:, 0]
        u_rif = 1. * u[:, 0]
    elif centering == 'MeanVal':
        for i in range(ydim):
            y_rif = np.mean(y,1)
            #y_rif[i] = np.mean(y[i, :])
        for i in range(udim):
            u_rif = np.mean(u,1)
            #u_rif[i] = np.mean(u[i, :])
    elif centering == 'None':
        y_rif = np.zeros(ydim)
        u_rif = np.zeros(udim)
    else:
    # elif centering != 'None':
        sys.stdout.write("\033[0;35m")
        print("Warning! \'Centering\' argument is not valid, its value has been reset to \'None\'")
        sys.stdout.write(" ")   
    
    # MISO approach  
    # centering inputs and outputs
    for i in range(u.shape[0]):
        u[i,:] = u[i,:] - u_rif[i]
    for i in range(ydim):
        # one-step ahead predictor 
        if k == 1:
            Y_u, T, Xv = cnt.lsim((1/SYS.H[i,0])*SYS.G[i,:], u, Time)
            Y_y, T, Xv = cnt.lsim(1 - (1/SYS.H[i,0]), y[i,:] - y_rif[i], Time)
            Yval[i,:] = np.atleast_2d(Y_u + Y_y + y_rif[i])
        else:
        # k-step ahead predictor
            # impulse response of disturbance model H
            hout, T = cnt.impulse(SYS.H[i,0], Time)
            # extract first k-1 coefficients
            h_k_num = hout[0:k]
            # set denumerator
            h_k_den = np.hstack((np.ones((1,1)), np.zeros((1,k-1))))
            # FdT of impulse response
            Hk = cnt.tf(h_k_num,h_k_den[0],SYS.ts)
            # plot impulse response
            # plt.subplot(ydim,1,i+1)
            # plt.plot(Time,hout)
            # plt.grid()
            # if i == 0:
            #     plt.title('Impulse Response')
            # plt.ylabel("h_j ")
            # plt.xlabel("Time [min]")
            # k-step ahead prediction
            Y_u, T, Xv = cnt.lsim(Hk*(1/SYS.H[i,0])*SYS.G[i,:], u, Time)
            #Y_y, T, Xv = cnt.lsim(1 - Hk*(1/SYS.H[i,0]), y[i,:] - y[i,0], Time)
            Y_y, T, Xv = cnt.lsim(1 - Hk*(1/SYS.H[i,0]), y[i,:] - y_rif[i], Time)
            #Yval[i,:] = np.atleast_2d(Y_u + Y_y + y[i,0])
            Yval[i,:] = np.atleast_2d(Y_u + Y_y + y_rif[i]) 
      
    return Yval
    )


k = 5
b = 2
m1 = 10
m2 = 80
t = np.linspace(0, 1000, 10001)

s = co.tf('s')
g1 = 1 / (m1 * s**2 + b * s + k)
g2 = 1 / (m2 * s**2 + b * s + k)

print(g1, g2)

imp1, t1 = cm.impulse(g1, t)
stp1, t2 = cm.step(g1, t)
imp2, t3 = cm.impulse(g2, t)
stp2, t4 = cm.step(g2, t)

# sample = co.step_info(stp1, t, SettlingTimeThreshold=0.01, RiseTimeLimits=(0.1, 0.9))

print("g1 impulse info")
signal_info(imp1, t1)
print("g1 step info")
signal_info(stp1, t2)
print("g2 impulse info")
signal_info(imp2, t3)
print("g2 step info")
signal_info(stp2, t4)
Exemple #13
0
import numpy as np
import control.matlab as ctrl
import matplotlib.pyplot as plt
import matplotlib.patches as patches

m = 1  # 質量 [kg] 非負
c = 1  # 減衰係数 [N/m] 非負
k = 10  # バネ係数 [Ns/m] 非負

# 伝達関数
sys = ctrl.tf((1), (m, c, k))
print(sys)

t_range = (0, 10)
y, t = ctrl.impulse(sys, T=np.arange(*t_range, 0.01))

fig, ax = plt.subplots(2, 1)

ax[0].hlines(0, *t_range, colors='gray', ls=':')
ax[0].plot(t, y)
ax[0].grid()

ax[1].set_xlim((y.min() - 1, y.max() + 1))
ax[1].set_ylim((0, 0.5))
ax[1].grid()
ax[1].set_aspect("equal")

for i in range(len(t)):
    r = patches.Rectangle(xy=(y[i] - 0.2, 0.1),
                          width=0.4,
B = np.array([[2.], [0.], [0.], [0.]])
C = np.array([[0.5, 0.6875, 0.7031, 0.5]])
D = np.array([[0.]])

# The full system
fsys = StateSpace(A, B, C, D)

# The reduced system, truncating the order by 1
n = 3
rsys = msimp.balred(fsys, n, method='truncate')

# Comparison of the step responses of the full and reduced systems
plt.figure(1)
y, t = mt.step(fsys)
yr, tr = mt.step(rsys)
plt.plot(t.T, y.T)
plt.plot(tr.T, yr.T)

# Repeat balanced reduction, now with 100-dimensional random state space
sysrand = mt.rss(100, 1, 1)
rsysrand = msimp.balred(sysrand, 10, method='truncate')

# Comparison of the impulse responses of the full and reduced random systems
plt.figure(2)
yrand, trand = mt.impulse(sysrand)
yrandr, trandr = mt.impulse(rsysrand)
plt.plot(trand.T, yrand.T, trandr.T, yrandr.T)

if 'PYCONTROL_TEST_EXAMPLES' not in os.environ:
    plt.show()
Exemple #15
0
den = [J, C, 0]
G = matlab.tf(num, den)

# feedback loop
sys = matlab.feedback(K * G, 1)

# step response
t = np.linspace(0, 3, 1000)
yout, T = matlab.step(sys, t)
plt.plot(T, yout)
plt.axhline(1, color="b", linestyle="--")
plt.xlim(0, 3)
plt.show()

# impulse response
yout, T = matlab.impulse(sys, t)
plt.plot(T, yout)
plt.axhline(0, color="b", linestyle="--")
plt.xlim(0, 3)
#plt.show()

# nyquist diagram
matlab.nyquist(sys)
#plt.show()

# bode diagram
matlab.bode(sys)
#plt.show()

# root locus
matlab.rlocus(sys)
C = np.matrix('0.5, 0.6875, 0.7031, 0.5')
D = np.matrix('0.')

# The full system
fsys = StateSpace(A,B,C,D)
# The reduced system, truncating the order by 1
ord = 3
rsys = msimp.balred(fsys,ord, method = 'truncate')

# Comparison of the step responses of the full and reduced systems
plt.figure(1)
y, t = mt.step(fsys)
yr, tr = mt.step(rsys)
plt.plot(t.T, y.T)
plt.plot(tr.T, yr.T)

# Repeat balanced reduction, now with 100-dimensional random state space
sysrand = mt.rss(100, 1, 1)
rsysrand = msimp.balred(sysrand,10,method ='truncate')

# Comparison of the impulse responses of the full and reduced random systems
plt.figure(2)
yrand, trand = mt.impulse(sysrand)
yrandr, trandr = mt.impulse(rsysrand)
plt.plot(trand.T, yrand.T, trandr.T, yrandr.T) 


if 'PYCONTROL_TEST_EXAMPLES' not in os.environ:
    plt.show()

Exemple #17
0
c = 1  # 減衰係数 [N/m] 非負
k = 10  # バネ係数 [Ns/m] 非負

A = [[0, 1], [-k / m, -c / m]]
B = [[0], [1 / m]]
C = [[1, 0], [0, 1]]
D = 0

# 状態空間モデル
sys = ctrl.ss(A, B, C, D)
print(sys)

t_range = (0, 10)

# x1(=変位)の初期値を 0.1 に設定。x2(=速度)の初期値は 0 に設定
y, t = ctrl.impulse(sys, T=np.arange(*t_range, 0.05), X0=[0.1, 0.0])

fig, ax = plt.subplots(3, 1)

ax[0].hlines(0, *t_range, colors='gray', ls=':')
ax[0].plot(t, y[:, 0])
ax[0].grid()
ax[0].set_title("position")
ax[1].hlines(0, *t_range, colors='gray', ls=':')
ax[1].plot(t, y[:, 1])
ax[1].grid()
ax[1].set_title("velocity")

ax[2].set_xlim((y.min() - 1, y.max() + 1))
ax[2].set_ylim((0, 0.5))
ax[2].grid()