Search code examples
pythonscipystate-space

Getting strange results from signal.lsim when t[0] != 0


I'm running a simulation of LTI state-space model and I need to run it at different times with varying input. In other words, simulate from t0 = 0 to t1=1second, make changes to the inputs of the system based on the result at t1, then continue from t1= 1 second to t2= 2 seconds.

I've tried running with initial condition X0=array([0,0]) at t[0], then take the last element of xout1 as the initial condition for the next run and give it a new time series that starts at t[0] = 1

import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt

r_wh = 60e-3 / 2.0              # m
m_v = 20                        # kg
R_m = 21.2                      # Ohms
L_m = 1.37e-3                   # Henries
K_t = 21.2e-3                   # Nm.A^-1
K_v = 60 / (450 * 2 * np.pi)    # V.rad^-1.s^-1
I_m = 4.2e-7                    # kg.m^2
I_gb = 0.4e-7                   # kg.m^2
I_wh = 65275e-9                 # kg.m^2
gr = 1.0/19.0

I_eq = ((I_m + I_gb) / gr) + (gr  * (I_wh + 0.25 * m_v * r_wh ** 2))

A = np.array([[-R_m/L_m, (-K_v/L_m) / gr],[K_t/I_eq, 0]])
B = np.array([[1/L_m,0],[0,-1/I_eq]])
C = np.array([[0,0],[0,1]])
D = np.zeros((2,2))

SS = sig.StateSpace(A,B,C,D)


T1 = np.arange(0,1,0.01)
T2 = np.arange(1,2,0.01)

U1 = np.array([12*np.ones_like(T1),np.zeros_like(T1)]).transpose()
U2 = np.array([12*np.ones_like(T2),np.zeros_like(T2)]).transpose()

tout1, yout1, xout1 = sig.lsim(SS,U1,T1)
tout2, yout2, xout2 = sig.lsim(SS,U2,T2,X0=xout1[-1])

plt.plot(T1,xout1[:,1],T2,xout2[:,1])

You'd expect the first element in the state vector output array "xout2" to match the X0 conditions but it doesn't. Does this function "lsim" require that the first time point be 0 ?

plot output


Solution

  • lsim assumes that X0 is the state at time 0, not at time T[0]. You can get the behavior that you expected (almost) by using

    tout2, yout2, xout2 = sig.lsim(SS, U2, T2 - T2[0], X0=xout1[-1])
    

    I say "almost", because there will still be a small gap in the plot at the transition from xout1 to xout2. That is because the values in T1 are [0., 0.01, 0.02, ..., 0.98, 0.99]. Note that 1.0 is not in T1. So the last value in xout1 is the state at t=0.99, not t=1.0. One way to fix that is to include the final t values in T1 and T2, for example by using np.linspace instead of np.arange:

    T1 = np.linspace(0, 1, 101)
    T2 = np.linspace(1, 2, 101)