Ejemplo n.º 1
0
    def test_response_transpose(self, nstate, nout, ninp, squeeze, ysh_in,
                                ysh_no, xsh_in):
        sys = ct.rss(nstate, nout, ninp)
        T = np.linspace(0, 1, 8)

        # Step response - input indexed
        t, y, x = ct.step_response(sys,
                                   T,
                                   transpose=True,
                                   return_x=True,
                                   squeeze=squeeze)
        assert t.shape == (T.size, )
        assert y.shape == ysh_in
        assert x.shape == xsh_in

        # Initial response - no input indexing
        t, y, x = ct.initial_response(sys,
                                      T,
                                      1,
                                      transpose=True,
                                      return_x=True,
                                      squeeze=squeeze)
        assert t.shape == (T.size, )
        assert y.shape == ysh_no
        assert x.shape == (T.size, sys.nstates)
Ejemplo n.º 2
0
    def test_squeeze_0_8_4(self, nstate, nout, ninp, squeeze, shape):
        # Set defaults to match release 0.8.4
        ct.config.use_legacy_defaults('0.8.4')
        ct.config.use_numpy_matrix(False)

        # Generate system, time, and input vectors
        sys = ct.rss(nstate, nout, ninp, strictly_proper=True)
        tvec = np.linspace(0, 1, 8)
        uvec =np.ones((sys.ninputs, 1)) @ np.reshape(np.sin(tvec), (1, 8))

        _, yvec = ct.initial_response(sys, tvec, 1, squeeze=squeeze)
        assert yvec.shape == shape
Ejemplo n.º 3
0
def initial_value_s(title, sys, time, X0):
    num_response = ctrl.initial_response(sys, time, X0)
    num_response = num_response[1]

    fig, axs = plt.subplots(4, 1, constrained_layout=True)
    fig.suptitle(title, fontsize=16)
    axs[0].plot(time, num_response[0], lw=1, c='blue')
    axs[0].set_ylabel('True airspeed [m/s]')
    axs[0].grid()
    axs[1].plot(time, num_response[1], lw=1, c='orange')
    axs[1].set_ylabel('pitch angle [rad]')
    axs[1].grid()
    axs[2].plot(time, num_response[2], lw=1, c='red')
    axs[2].set_ylabel('AoA [rad]')
    axs[2].grid()
    axs[3].plot(time[:200], num_response[3][:200], lw=1, c='green')
    axs[3].set_ylabel('pitch rate [rad/s]')
    axs[3].grid()
    plt.show()
    return
Ejemplo n.º 4
0
def initial_value_a(title, sys, time, X0):
    sys_a = num_solution[2]
    num_response = ctrl.initial_response(sys, time, X0)
    num_response = num_response[1]

    fig, axs = plt.subplots(4, 1, constrained_layout=True)
    fig.suptitle(title, fontsize=16)
    axs[0].plot(time, num_response[0], lw=1, c='blue')
    axs[0].set_ylabel('yaw angle [rad]')
    axs[0].grid()
    axs[1].plot(time, num_response[1], lw=1, c='orange')
    axs[1].set_ylabel('roll angle  [rad]')
    axs[1].grid()
    axs[2].plot(time, num_response[2], lw=1, c='red')
    axs[2].set_ylabel('yaw rate [rad/s]')
    axs[2].grid()
    axs[3].plot(time, num_response[3], lw=1, c='green')
    axs[3].set_ylabel('roll rate [rad/s]')
    axs[3].grid()
    plt.show()
Ejemplo n.º 5
0
num = [1/m]
den = [1,2.*z*wn,wn**2]

sys = control.tf(num,den)


# Set up simulation parameters
t = np.linspace(0,5,500)            # time for simulation, 0-5s with 500 points in-between

F = np.zeros_like(t)

# Define the initial conditions x_dot(0) = 0, x(0) = 1
x0 = [0.,1.]

# run the simulation - utilize the built-in initial condition response function
[T,yout] = control.initial_response(sys,t,x0)

# Make the figure pretty, then plot the results
#   "pretty" parameters selected based on pdf output, not screen output
#   Many of these setting could also be made default by the .matplotlibrc file
fig = figure(figsize=(6,4))
ax = gca()
subplots_adjust(bottom=0.17,left=0.17,top=0.96,right=0.96)
setp(ax.get_ymajorticklabels(),family='CMU Serif',fontsize=18)
setp(ax.get_xmajorticklabels(),family='CMU Serif',fontsize=18)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.grid(True,linestyle=':',color='0.75')
ax.set_axisbelow(True)
th0    = pitch[startvalue]*(np.pi/180)      # pitch angle in the stationary flight condition [rad]

# Aircraft mass
m      = 6378.821            # mass [kg]

A_sym,B_sym,A_asym,B_asym = statespacematrix(hp0[0],V0[0],alpha0[0],th0[0],m)     #Calling state space matrix

C = np.identity(4)
D = np.array([[0],
              [0],
              [0],
              [0]])

sys = ctrl.ss(A_sym,B_sym,C,D)
xinit = np.array([10*(np.pi/180),0,0,0])
T ,yout  = ctrl.initial_response(sys, T=np.arange(0,100,0.1), X0=xinit)

sideslip_sim = yout[0]*(180/np.pi)         #from radians to degree
rollangle_sim = yout[1]*(180/np.pi)        #from radians to degree
rollrate_sim = yout[2]*(180/np.pi)         #from radians/s to degree/s
yawrate_sim = yout[3]*(180/np.pi)          #from radians/s to degree/s

plt.figure(1)
plt.title('NIEEEEK')
plt.subplot(2,2,1)
plt.plot(T, sideslip_sim)
plt.grid()
plt.ylabel('Side slip change [degree]')
plt.xlabel('Time [s]')
plt.subplot(2,2,2)
plt.plot(T, rollangle_sim)
B = [[0], [1]]

C = [[1, 0], [0, 1]]

D = [[0], [0]]

sys = control.ss(A, B, C, D)

# Set up simulation parameters
t = np.linspace(0, 5,
                500)  # time for simulation, 0-5s with 500 points in between
x0 = [[1], [0]]  # initial condition, x=1, x_dot=0

# run the simulation - utilize the built-in initial condition response function
[T, yout] = control.initial_response(sys, t, x0)

# Make the figure pretty, then plot the results
fig = figure(figsize=(6, 4))
ylim(-1.5, 1.5)
ax = gca()
subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.98)
setp(ax.get_ymajorticklabels(), family='CMU Serif', fontsize=18)
setp(ax.get_xmajorticklabels(), family='CMU Serif', fontsize=18)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

xlabel('Time (s)', family='CMU Serif', fontsize=22, weight='bold')
ylabel('Position (m)', family='CMU Serif', fontsize=22, weight='bold')
Ejemplo n.º 8
0
    def test_squeeze(self, fcn, nstate, nout, ninp, squeeze, shape1, shape2):
        # Figure out if we have SciPy 1+
        scipy0 = StrictVersion(sp.__version__) < '1.0'

        # Define the system
        if fcn == ct.tf and (nout > 1 or ninp > 1) and not slycot_check():
            pytest.skip("Conversion of MIMO systems to transfer functions "
                        "requires slycot.")
        else:
            sys = fcn(ct.rss(nstate, nout, ninp, strictly_proper=True))

        # Generate the time and input vectors
        tvec = np.linspace(0, 1, 8)
        uvec = np.ones((sys.ninputs, 1)) @ np.reshape(np.sin(tvec), (1, 8))

        #
        # Pass squeeze argument and make sure the shape is correct
        #
        # For responses that are indexed by the input, check against shape1
        # For responses that have no/fixed input, check against shape2
        #

        # Impulse response
        if isinstance(sys, StateSpace):
            # Check the states as well
            _, yvec, xvec = ct.impulse_response(
                sys, tvec, squeeze=squeeze, return_x=True)
            if sys.issiso():
                assert xvec.shape == (sys.nstates, 8)
            else:
                assert xvec.shape == (sys.nstates, sys.ninputs, 8)
        else:
            _, yvec = ct.impulse_response(sys, tvec, squeeze=squeeze)
        assert yvec.shape == shape1

        # Step response
        if isinstance(sys, StateSpace):
            # Check the states as well
            _, yvec, xvec = ct.step_response(
                sys, tvec, squeeze=squeeze, return_x=True)
            if sys.issiso():
                assert xvec.shape == (sys.nstates, 8)
            else:
                assert xvec.shape == (sys.nstates, sys.ninputs, 8)
        else:
            _, yvec = ct.step_response(sys, tvec, squeeze=squeeze)
        assert yvec.shape == shape1

        # Initial response (only indexed by output)
        if isinstance(sys, StateSpace):
            # Check the states as well
            _, yvec, xvec = ct.initial_response(
                sys, tvec, 1, squeeze=squeeze, return_x=True)
            assert xvec.shape == (sys.nstates, 8)
        else:
            _, yvec = ct.initial_response(sys, tvec, 1, squeeze=squeeze)
        assert yvec.shape == shape2

        # Forced response (only indexed by output)
        if isinstance(sys, StateSpace):
            # Check the states as well
            _, yvec, xvec = ct.forced_response(
                sys, tvec, uvec, 0, return_x=True, squeeze=squeeze)
            assert xvec.shape == (sys.nstates, 8)
        else:
            # Just check the input/output response
            _, yvec = ct.forced_response(sys, tvec, uvec, 0, squeeze=squeeze)
        assert yvec.shape == shape2

        # Test cases where we choose a subset of inputs and outputs
        _, yvec = ct.step_response(
            sys, tvec, input=ninp-1, output=nout-1, squeeze=squeeze)
        if squeeze is False:
            # Shape should be unsqueezed
            assert yvec.shape == (1, 1, 8)
        else:
            # Shape should be squeezed
            assert yvec.shape == (8, )

        # For InputOutputSystems, also test input/output response
        if isinstance(sys, ct.InputOutputSystem) and not scipy0:
            _, yvec = ct.input_output_response(sys, tvec, uvec, squeeze=squeeze)
            assert yvec.shape == shape2

        #
        # Changing config.default to False should return 3D frequency response
        #
        ct.config.set_defaults('control', squeeze_time_response=False)

        _, yvec = ct.impulse_response(sys, tvec)
        if squeeze is not True or sys.ninputs > 1 or sys.noutputs > 1:
            assert yvec.shape == (sys.noutputs, sys.ninputs, 8)

        _, yvec = ct.step_response(sys, tvec)
        if squeeze is not True or sys.ninputs > 1 or sys.noutputs > 1:
            assert yvec.shape == (sys.noutputs, sys.ninputs, 8)

        _, yvec = ct.initial_response(sys, tvec, 1)
        if squeeze is not True or sys.noutputs > 1:
            assert yvec.shape == (sys.noutputs, 8)

        if isinstance(sys, ct.StateSpace):
            _, yvec, xvec = ct.forced_response(
                sys, tvec, uvec, 0, return_x=True)
            assert xvec.shape == (sys.nstates, 8)
        else:
            _, yvec = ct.forced_response(sys, tvec, uvec, 0)
        if squeeze is not True or sys.noutputs > 1:
            assert yvec.shape == (sys.noutputs, 8)

        # For InputOutputSystems, also test input_output_response
        if isinstance(sys, ct.InputOutputSystem) and not scipy0:
            _, yvec = ct.input_output_response(sys, tvec, uvec)
            if squeeze is not True or sys.noutputs > 1:
                assert yvec.shape == (sys.noutputs, 8)
Ejemplo n.º 9
0
def test_trdata_shapes(nin, nout, squeeze):
    # SISO, single trace
    sys = ct.rss(4, nout, nin, strictly_proper=True)
    T = np.linspace(0, 1, 10)
    U = np.outer(np.ones(nin), np.sin(T) )
    X0 = np.ones(sys.nstates)

    #
    # Initial response
    #
    res = ct.initial_response(sys, X0=X0)
    ntimes = res.time.shape[0]

    # Check shape of class members
    assert len(res.time.shape) == 1
    assert res.y.shape == (sys.noutputs, ntimes)
    assert res.x.shape == (sys.nstates, ntimes)
    assert res.u is None

    # Check dimensions of the response
    assert res.ntraces == 0     # single trace
    assert res.ninputs == 0     # no input for initial response
    assert res.noutputs == sys.noutputs
    assert res.nstates == sys.nstates

    # Check shape of class properties
    if sys.issiso():
        assert res.outputs.shape == (ntimes,)
        assert res._legacy_states.shape == (sys.nstates, ntimes)
        assert res.states.shape == (sys.nstates, ntimes)
        assert res.inputs is None
    elif res.squeeze is True:
        assert res.outputs.shape == (ntimes, )
        assert res._legacy_states.shape == (sys.nstates, ntimes)
        assert res.states.shape == (sys.nstates, ntimes)
        assert res.inputs is None
    else:
        assert res.outputs.shape == (sys.noutputs, ntimes)
        assert res._legacy_states.shape == (sys.nstates, ntimes)
        assert res.states.shape == (sys.nstates, ntimes)
        assert res.inputs is None

    #
    # Impulse and step response
    #
    for fcn in (ct.impulse_response, ct.step_response):
        res = fcn(sys, squeeze=squeeze)
        ntimes = res.time.shape[0]

        # Check shape of class members
        assert len(res.time.shape) == 1
        assert res.y.shape == (sys.noutputs, sys.ninputs, ntimes)
        assert res.x.shape == (sys.nstates, sys.ninputs, ntimes)
        assert res.u.shape == (sys.ninputs, sys.ninputs, ntimes)

        # Check shape of class members
        assert res.ntraces == sys.ninputs
        assert res.ninputs == sys.ninputs
        assert res.noutputs == sys.noutputs
        assert res.nstates == sys.nstates

        # Check shape of inputs and outputs
        if sys.issiso() and squeeze is not False:
            assert res.outputs.shape == (ntimes, )
            assert res.states.shape == (sys.nstates, ntimes)
            assert res.inputs.shape == (ntimes, )
        elif res.squeeze is True:
            assert res.outputs.shape == \
                np.empty((sys.noutputs, sys.ninputs, ntimes)).squeeze().shape
            assert res.states.shape == \
                np.empty((sys.nstates, sys.ninputs, ntimes)).squeeze().shape
            assert res.inputs.shape == \
                np.empty((sys.ninputs, sys.ninputs, ntimes)).squeeze().shape
        else:
            assert res.outputs.shape == (sys.noutputs, sys.ninputs, ntimes)
            assert res.states.shape == (sys.nstates, sys.ninputs, ntimes)
            assert res.inputs.shape == (sys.ninputs, sys.ninputs, ntimes)

        # Check legacy state space dimensions (not affected by squeeze)
        if sys.issiso():
            assert res._legacy_states.shape == (sys.nstates, ntimes)
        else:
            assert res._legacy_states.shape == \
                (sys.nstates, sys.ninputs, ntimes)

    #
    # Forced response
    #
    res = ct.forced_response(sys, T, U, X0, squeeze=squeeze)
    ntimes = res.time.shape[0]

    # Check shape of class members
    assert len(res.time.shape) == 1
    assert res.y.shape == (sys.noutputs, ntimes)
    assert res.x.shape == (sys.nstates, ntimes)
    assert res.u.shape == (sys.ninputs, ntimes)

    # Check dimensions of the response
    assert res.ntraces == 0     # single trace
    assert res.ninputs == sys.ninputs
    assert res.noutputs == sys.noutputs
    assert res.nstates == sys.nstates

    # Check shape of inputs and outputs
    if sys.issiso() and squeeze is not False:
        assert res.outputs.shape == (ntimes,)
        assert res.states.shape == (sys.nstates, ntimes)
        assert res.inputs.shape == (ntimes,)
    elif squeeze is True:
        assert res.outputs.shape == \
            np.empty((sys.noutputs, 1, ntimes)).squeeze().shape
        assert res.states.shape == \
            np.empty((sys.nstates, 1, ntimes)).squeeze().shape
        assert res.inputs.shape == \
            np.empty((sys.ninputs, 1, ntimes)).squeeze().shape
    else:                       # MIMO or squeeze is False
        assert res.outputs.shape == (sys.noutputs, ntimes)
        assert res.states.shape == (sys.nstates, ntimes)
        assert res.inputs.shape == (sys.ninputs, ntimes)

    # Check state space dimensions (not affected by squeeze)
    assert res.states.shape == (sys.nstates, ntimes)
Ejemplo n.º 10
0
Q = np.matrix(
    '-1.0029 -0.0896 1.1050; -0.0896 1.6790 -0.5762; 1.1050 -0.5762 -0.4381')
N = np.matrix('-0.0420; 0.2112; -0.2832')
R = np.matrix('0.6192')

# convexify cost matrices
dHc, dQc, dRc, dNc = convexifier.convexify(A, B, Q, R, N)

# stabilizing LQR with tuned weighting matrices
Pc, Ec, Kc = control.mateqn.dare(A, B, Q + dQc[0], R + dRc[0], N + dNc[0],
                                 np.eye(A.shape[0]))

# stabilizing LQR
P, E, K = control.mateqn.dare(A, B, Q, R, N, np.eye(A.shape[0]))

# check equivalence
assert np.linalg.norm(K - Kc) < 1e-5, 'Feedback laws should be identical.'

# define closed-loop systems
sys0 = control.ss(A - np.matmul(B, K), B, np.eye(A.shape[0]),
                  np.zeros((A.shape[0], B.shape[1])), 1)
sysc = control.ss(A - np.matmul(B, Kc), B, np.eye(A.shape[0]),
                  np.zeros((A.shape[0], B.shape[1])), 1)

# check equivalence visually
T, Yout = control.initial_response(sys0, T=range(30), X0=np.matrix('1;0;0'))
T, Youtc = control.initial_response(sysc, T=range(30), X0=np.matrix('1;0;0'))
plt.plot(T, Yout[0])
plt.plot(T, Youtc[0])
plt.show()
Ejemplo n.º 11
0
def CalcResponse(mode,inputparam):
    '''
    Calculates the response of the specified system and reports by showing initial response, impulse response, and step response. Also shows a pole-zero map and prints in the log the pole and system information.

    Input
    ------
    mode:
        "symmetric" or "symm" calculates using the symmetric case
        "asymmetric" or "asymm" calculates using the asymmetric configuration
        
    Returns
    ------
    Success on completion
    '''

    sys, sysEig, inputindex, stVec, inputtitle = ResponseInputHandler(mode, inputparam)

    

    # Pole and zeroes map #
    plt.scatter(sys.pole().real, sys.pole().imag)
    #plt.scatter(sys.zero().real, sys.zero.imag)
    plt.suptitle("Pole-Zero map, asymmetric")
    plt.xlabel("Re")
    plt.ylabel("Im")
    plt.grid()
    syspoles = sys.damp()
    print("------------------")
    print("Pole information.\n wn: ",syspoles[0],"\n Zeta: ",syspoles[1],"\n Poles: ",syspoles[2])
    print("Eigenvalues: ", sysEig)
    print("------------------")

    ## System Responses ##
    initials = [0,0,0,0]
    T = np.linspace(0,200,4000)
    forcedInput = 2                                                            # Needs to be of length equal to the length of T
    (time,yinit) = ctrl.initial_response(sys, T, initials, input=inputindex)
    _, y_impulse  = ctrl.impulse_response(sys,T, initials, input=inputindex)
    _, y_step = ctrl.step_response(sys, T, initials, input=inputindex)
    _, y_forced, _ = ctrl.forced_response(sys,T,forcedInput, initials)


    fig1, axs1 = plt.subplots(4, sharex=True, figsize=(12,9))
    fig1.suptitle("Initial Condition Response"+inputtitle)
    axs1[0].plot(time,yinit[0])
    axs1[0].set_title(stVec[0] + " response")
    axs1[1].plot(time,yinit[1])
    axs1[1].set_title(stVec[1]+ " response")
    axs1[2].plot(time,yinit[2])
    axs1[2].set_title(stVec[2]+ " response")
    axs1[3].plot(time,yinit[3])
    axs1[3].set_title(stVec[3]+" response")

    axs1.flat[3].set(xlabel='time [s]')
    

    fig2, axs2 = plt.subplots(4, sharex=True, figsize=(12,9))
    fig2.suptitle("Impulse Response"+inputtitle)
    axs2[0].plot(time,y_impulse[0])
    axs2[0].set_title(stVec[0]+ " response")
    axs2[1].plot(time,y_impulse[1])
    axs2[1].set_title(stVec[1]+"  response")
    axs2[2].plot(time,y_impulse[2])
    axs2[2].set_title(stVec[2]+" response")
    axs2[3].plot(time,y_impulse[3])
    axs2[3].set_title(stVec[3]+" response")

    axs2.flat[3].set(xlabel='time [s]')

    fig3, axs3 = plt.subplots(4, sharex=True, figsize=(12,9))
    fig3.suptitle("Step Response"+inputtitle)
    axs3[0].plot(time,y_step[0])
    axs3[0].set_title(stVec[0]+" response")
    axs3[1].plot(time,y_step[1])
    axs3[1].set_title(stVec[1]+" response")
    axs3[2].plot(time,y_step[2])
    axs3[2].set_title(stVec[2]+" response")
    axs3[3].plot(time,y_step[3])
    axs3[3].set_title(stVec[3]+ " response")

    axs3.flat[3].set(xlabel='time [s]')

    fig4, axs4 = plt.subplots(4, sharex=True, figsize=(12,9))
    fig4.suptitle("Forced Function Response"+inputtitle)
    axs4[0].plot(time,y_forced[0])
    axs4[0].set_title(stVec[0]+ " response")
    axs4[1].plot(time,y_forced[1])
    axs4[1].set_title(stVec[1]+" response")
    axs4[2].plot(time,y_forced[2])
    axs4[2].set_title(stVec[2]+ " response")
    axs4[3].plot(time,y_forced[3])
    axs4[3].set_title(stVec[3]+" response")

    axs4.flat[3].set(xlabel='time [s]')

    plt.show()
    return True
Ejemplo n.º 12
0
Tc, Yc = control.step_response(Cantsys_con, tspan)

#%%  LQR Controller + Observer
rhoo = 0.01
Qo = np.eye((2 * n_md))
Ro = rhoo
LT, Po, Eo = control.lqr(A_r.transpose(), C_r.transpose(), Qo, Ro)
Lobs = LT.transpose()
Observer = control.StateSpace(A_r - B_r @ G - Lobs @ C_r, Lobs, -G, 0)
Cantsys_obs = control.feedback(Cantsys_m, Observer, sign=1)

# Simulation of controlled system with and without linear observer
x_0 = np.concatenate((np.array([[0], [1]]), np.zeros((2 * (n_md - 1), 1))))
tn, y, x = control.initial_response(Cantsys_m,
                                    tspan,
                                    np.concatenate(
                                        (x_0, np.zeros((2 * (nx - n_md), 1)))),
                                    return_x=True)
tc, yc, xc = control.initial_response(Cantsys_con, tspan, x_0, return_x=True)
to, yo, xo = control.initial_response(Cantsys_obs,
                                      tspan,
                                      np.concatenate((x_0, np.zeros(
                                          (2 * nx, 1)))),
                                      return_x=True)

# Initialization of contorl and kinetic energy vectors
E = np.zeros((len(tn), 1))
u = np.zeros((len(tn), 1))
Ec = np.zeros((len(tc), 1))
uc = np.zeros((len(tc), 1))
Eo = np.zeros((len(to), 1))
        [-rho * Ve * CD * S / m, -g * cos(Gammae)],
        [rho * CL * S / m, g * sin(Gammae) / Ve],
    ]
)
B = np.zeros((2, 1))
C = np.identity(2)
D = np.zeros((2, 1))
sys1 = ss(A, B, C, D)

X0a = np.array([Ve, Gammae])
X0b = np.array([Ve, 0])
X0c = np.array([1.5 * Ve, 0])
X0d = np.array([3 * Ve, 0])

tl = np.linspace(to, tf, int((tf - to) / 0.01))
_, ya = initial_response(sys1, X0=X0a, T=tl)
_, yb = initial_response(sys1, X0=X0b, T=tl)
_, yc = initial_response(sys1, X0=X0c, T=tl)
_, yd = initial_response(sys1, X0=X0d, T=tl)


# step control input
Ahat = np.array(
    [
        [2 * g * sin(Gammae) / Ve, -g * cos(Gammae)],
        [2 * g * cos(Gammae) / (Ve ** 2), g * sin(Gammae) / Ve],
    ]
)
Bhat = np.array(
    [[2 * g * cos(Gammae) * kappa * CLa], [g * cos(Gammae) / (Ve * Alphae)]]
)
Ejemplo n.º 14
0
def initial(sys, T=None, X0=0.0, input=0, output=None, transpose=False, return_x=False, squeeze=True):
    """
    Initial condition response of a linear system

    If the system has multiple outputs (MIMO), optionally, one output
    may be selected. If no selection is made for the output, all
    outputs are given.

    For information on the **shape** of parameters `T`, `X0` and
    return values `T`, `yout`, see :ref:`time-series-convention`.

    Parameters
    ----------
    sys: StateSpace, or TransferFunction
        LTI system to simulate

    T: array-like object, optional
        Time vector (argument is autocomputed if not given)

    X0: array-like object or number, optional
        Initial condition (default = 0)

        Numbers are converted to constant arrays with the correct shape.

    input: int
        Ignored, has no meaning in initial condition calculation. Parameter
        ensures compatibility with step_response and impulse_response

    output: int
        Index of the output that will be used in this simulation. Set to None
        to not trim outputs

    transpose: bool
        If True, transpose all input and output arrays (for backward
        compatibility with MATLAB and scipy.signal.lsim)

    return_x: bool
        If True, return the state vector (default = False).

    squeeze: bool, optional (default=True)
        If True, remove single-dimensional entries from the shape of
        the output.  For single output systems, this converts the
        output response to a 1D array.

    Returns
    -------
    T: array
        Time values of the output
    yout: array
        Response of the system
    xout: array
        Individual response of each x variable

    See Also
    --------
    forced, impulse, step

    Notes
    -----
    This function uses the `forced` function with the input set to
    zero.

    Examples
    --------
    >>> T, yout = initial(sys, T, X0)
    """
    yout, T = initial_response(sys,T,X0,input,output,transpose, return_x, squeeze)
    plt.plot(yout,T)
    plt.title("Response to Initial Conditions")
    plt.xlabel("Time (seconds)")
    plt.ylabel("Amplitude")
    plt.show()
                [Cl_b, 0, Cl_p * b / 2 / V, Cl_r * b / 2 / V],
                [Cn_b, 0, Cn_p * b / 2 / V, Cn_r * b / 2 / V]])
C3 = -np.matrix([[-CY_da, -CY_dr], [0, 0], [-Cl_da, -Cl_dr], [-Cn_da, -Cn_dr]])
A = -np.linalg.inv(C1) * C2
B = np.linalg.inv(C1) * C3
C = np.matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
D = np.matrix([[0, 0], [0, 0], [0, 0], [0, 0]])
eigs = np.linalg.eigvals(A)

#time vector
T = time_eigenmotion  #choose time range for plotting
dt = 0.008  #INPUT
t = np.arange(0, T, dt)

sys_Ass = control.StateSpace(A, B, C, C3)
T0, yout = control.initial_response(sys_Ass, t, X0=[0, 0, 0.5, 0])
#T1,yout1=control.step_response(sys_Ass,t,[0,0,0,0])
'''plt.figure()
plt.plot(T1,yout[0])
plt.figure()
plt.plot(T1,yout[1])
plt.figure()
plt.plot(T1,yout[2])
plt.figure()
plt.plot(T1,yout[3])
plt.show()'''
#Symmetric

C1s = np.matrix([[-2 * mju_c * c / V, 0, 0, 0],
                 [0, (CZ_adot - 2 * mju_c) * c / V, 0, 0], [0, 0, -c / V, 0],
                 [0, Cm_adot * c / V, 0, -2 * mju_c * Kyy2 * c / V * c / V]])
Ejemplo n.º 16
0
def main():
    # plot exercise 1 e)

    # simulation parameter
    step_time = 0.1  # in sec
    sim_time = 20  # in sec
    num_steps = int(sim_time / step_time)
    x_0 = np.array([0, 0])
    U = np.array(np.linspace(1, 1, num_steps))

    # plot
    plt.figure()
    ODE = ode_f1
    [X1, Y1, T1] = sr1.nlsim(ODE, x_0, U, step_time, output_g)
    plt.plot(T1, Y1, label="Funktion 1", color="green")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)")
    plt.legend()
    plt.grid(True)

    ODE = ode_f2
    [X2, Y2, T2] = sr1.nlsim(ODE, x_0, U, step_time, output_g)
    plt.plot(T2, Y2, label="Funktion 2", color="blue")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)")
    plt.legend()
    plt.grid(True)

    ODE = ode_f3
    [X3, Y3, T3] = sr1.nlsim(ODE, x_0, U, step_time, output_g)
    plt.plot(T3, Y3, label="Funktion 3", color="red")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)")
    plt.legend()
    plt.grid(True)

    ODE = ode_f4
    [X4, Y4, T4] = sr1.nlsim(ODE, x_0, U, step_time, output_g)
    plt.plot(T4, Y4, label="Funktion 4", color="yellow")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)")
    plt.legend()
    plt.grid(True)

    plt.savefig("plots/plots_1e.png")
    plt.clf()

    # plot exercise 1 g)
    plt.figure()
    plt.plot(T4, Y4, label="Funktion 4", color="yellow")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)")
    plt.legend()
    plt.grid(True)

    # plot
    ODE = ode_f2
    [X5, Y5, T5] = sr1.nlsim(ODE, x_0, U, step_time, output_g)
    T5 = np.linspace(1, 20, int(num_steps / 2))
    plt.plot(T5,
             Y5[:int((len(Y5) - 1) / 2)],
             label="Funktion 2 verlangsamt",
             color="blue")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)$")
    plt.legend()
    plt.grid(True)

    plt.savefig("plots/plots_1g.png")
    plt.clf()

    # control simulation
    sys1 = control_sim()

    # step response
    [T6, Y6] = ctl.step_response(sys1)
    plt.figure()
    plt.plot(T6, Y6, label="Sprungantwort")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)$")
    plt.legend()
    plt.grid(True)
    plt.savefig("plots/plot_2b.png")
    plt.clf()

    # calculate t_settling
    dc_gain = Y6[-1]
    for i in range(len(Y6)):
        if Y6[i] <= dc_gain + abs(0.02 * dc_gain):
            print(T6[i])
            break

    # initial response
    X_0 = [1, -1, 1]
    [T7, Y7] = ctl.initial_response(sys1, X0=X_0)
    plt.figure()
    plt.plot(T7, Y7, label="Antwortfunktion")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)$")
    plt.legend()
    plt.grid(True)
    plt.savefig("plots/plot_2c.png")

    # forced response
    # Rectangular wave signal
    sim_time = 5
    num_steps = 2000
    omega1 = 0.2 * np.pi
    U = np.multiply(
        np.sign(
            np.sin(2 * np.pi * omega1 * np.linspace(0, sim_time, num_steps))),
        0.5)
    T8 = np.linspace(0, sim_time, num_steps)
    [T8, Y8, X8] = ctl.forced_response(sys1, T=T8, U=U)
    plt.figure()
    plt.plot(T8, Y8, label="Ausgang $y(t)$")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)$")
    plt.plot(T8, U, label="Eingang $u(t)$")
    plt.legend()
    plt.grid(True)
    plt.savefig("plots/plot_2d_0.1.png")
    plt.clf()

    # forced response
    # Rectangular wave signal
    sim_time = 0.5
    num_steps = 2000
    omega1 = 2 * np.pi
    U = np.multiply(
        np.sign(
            np.sin(2 * np.pi * omega1 * np.linspace(0, sim_time, num_steps))),
        0.5)
    T9 = np.linspace(0, sim_time, num_steps)
    [T9, Y9, X9] = ctl.forced_response(sys1, T=T9, U=U)
    plt.figure()
    plt.plot(T9, Y9, label="Ausgang $y(t)$")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)$")
    plt.plot(T9, U, label="Eingang $u(t)$")
    plt.legend()
    plt.grid(True)
    plt.savefig("plots/plot_2d_1.png")
    plt.clf()

    # forced response
    # Rectangular wave signal
    sim_time = 0.05
    num_steps = 2000
    omega1 = 20 * np.pi
    U = np.multiply(
        np.sign(
            np.sin(2 * np.pi * omega1 * np.linspace(0, sim_time, num_steps))),
        0.5)
    T10 = np.linspace(0, sim_time, num_steps)
    [T10, Y10, X10] = ctl.forced_response(sys1, T=T10, U=U)
    plt.figure()
    plt.plot(T10, Y10, label="Ausgang $y(t)$")
    plt.xlabel("$t$ in s")
    plt.ylabel("$y(t)$")
    plt.plot(T10, U, label="Eingang $u(t)$")
    plt.legend()
    plt.grid(True)
    plt.savefig("plots/plot_2d_10.png")
    plt.clf()