def Simulacao(self, t, u, w, X0=0): """ Simula um sistema dado as entradas u e w e um vetor de tempo qualquer para condições iniciais nulas (X0 = 0). """ Sr = self.SistemaR() # Sistema considerando a entrada r(t) Sw = self.SistemaW() # Sistema considerando a entrada w(t) # Simulation is done separately (input R and input W) # Simulating input R: T,youtR,xoutR = signal.lsim2(Sr, u, t,self.X0r,hmax=1)#, numpy.array([0,0]),full_output=0) # Set hmax=1 of odeint otherwise solver "do not see" when one delay the input. self.X0r = xoutR[-1] # Simulating input W: if (self.Type == 0 or self.Type == 1) and self.Malha == 'Aberta': # If system is LTI0 or LTI1 and with openloop, output due to W is equal to W. youtW = w else: # Set hmax=1 of odeint otherwise solver "do not see" when one delay the input. T,youtW,xoutW = signal.lsim2(Sw, w, t, self.X0w,hmax=1,full_output=0) # Store initial conditions: self.X0w = xoutW[-1] self.tfinal = t[-1] self.Rfinal = u[-1] self.Wfinal = w[-1] return youtR + youtW
def Simulacao(self, t, u, w, X0=0): """ Simula um sistema dado as entradas u e w e um vetor de tempo qualquer para condições iniciais nulas (X0 = 0). """ Sr = self.SistemaR() # Sistema considerando a entrada r(t) Sw = self.SistemaW() # Sistema considerando a entrada w(t) # Simulation is done separately (input R and input W) # Simulating input R: T,youtR,xoutR = signal.lsim2(Sr, u, t,self.X0r,hmax=1)#, numpy.array([0,0]),full_output=0) # Set hmax=1 of odeint otherwise solver "do not see" when one delay the input. self.X0r = xoutR[-1] # Simulating input W: if (self.Type == 0 or self.Type == 1) and self.Malha == 'Aberta': # If system is LTI0 or LTI1 and with openloop, output due to W is equal to W. youtW = w else: # Set hmax=1 of odeint otherwise solver "do not see" when one delay the input. T,youtW,xoutW = signal.lsim2(Sw, w, t, self.X0w,hmax=1,full_output=0) # Store initial conditions: self.X0w = xoutW[-1] return youtR + youtW
def cost_function(control_input): #lsim2 uses ODE integration, #lsim uses convolution (maybe FFT in high N cases, haven't checked) _, x_v, _ = signal.lsim2(virus_system, U=control_input, T=t, atol=1e-9) _, x_h, _ = signal.lsim2(host_system, U=control_input, T=t, atol=1e-9) #rtol e-11 rho = 1.0 return -rho * np.sum(x_v * x_v) + np.sum(x_h * x_h)
def step_resp_SecondOrder2(t=None, Q=None, w0=None, Amp=None): if t is None: tt = np.array([]) y_out = np.array([]) else: if Q is None: tt = np.array([]) y_out = np.array([]) else: if w0 is None: # w0 = 1 [rad/seg] "Normalizado" NUM = [1] DEN = [1, 1 / Q, 1] else: z = np.array([]) p = np.roots([1, w0 / Q, w0**2]) k = w0**2 NUM, DEN = sig.zpk2tf(z, p, k) if Amp is None: u = 1 * esc(t) else: u = Amp * esc(t) tt, y_out, x = sig.lsim2((NUM, DEN), u, t) return tt, y_out
def run(self, fig_num, is_noise=True, noise_level=10**(-2), output_csv=OUTPUT_CSV): """ run simulation and save result :return: """ tout, self.y, x = signal.lsim2(self.system, self.u, self.t) noise = np.zeros(len(self.t)) if is_noise: noise = np.random.rand(len(self.t)) * noise_level * max(self.y) self.y += noise mycsv.save(self.t, self.u, self.y, save_name=self.path + output_csv, header=("t", "u", "y")) myplot.plot(fig_num, self.t, self.u) myplot.plot(fig_num, self.t, self.y) myplot.save(fig_num, label=("time [s]", "u/y []"), save_name=self.path + "Simulation_Result", leg=("u", "y"))
def test_02(self): t = np.array([0.0, 1.0, 1.0, 3.0]) u = np.array([0.0, 0.0, 1.0, 1.0]) # Simple integrator: x'(t) = u(t) system = ([1.0],[1.0,0.0]) tout, y, x = lsim2(system, u, t, X0=[1.0]) expected_x = np.maximum(1.0, tout) assert_almost_equal(x[:,0], expected_x)
def test_03(self): t = np.array([0.0, 1.0, 1.0, 1.1, 1.1, 2.0]) u = np.array([0.0, 0.0, 1.0, 1.0, 0.0, 0.0]) # Simple integrator: x'(t) = u(t) system = ([1.0],[1.0, 0.0]) tout, y, x = lsim2(system, u, t, hmax=0.01) expected_x = np.array([0.0, 0.0, 0.0, 0.1, 0.1, 0.1]) assert_almost_equal(x[:,0], expected_x)
def test_02(self): t = np.array([0.0, 1.0, 1.0, 3.0]) u = np.array([0.0, 0.0, 1.0, 1.0]) # Simple integrator: x'(t) = u(t) system = ([1.0], [1.0, 0.0]) tout, y, x = lsim2(system, u, t, X0=[1.0]) expected_x = np.maximum(1.0, tout) assert_almost_equal(x[:, 0], expected_x)
def test_03(self): t = np.array([0.0, 1.0, 1.0, 1.1, 1.1, 2.0]) u = np.array([0.0, 0.0, 1.0, 1.0, 0.0, 0.0]) # Simple integrator: x'(t) = u(t) system = ([1.0], [1.0, 0.0]) tout, y, x = lsim2(system, u, t, hmax=0.01) expected_x = np.array([0.0, 0.0, 0.0, 0.1, 0.1, 0.1]) assert_almost_equal(x[:, 0], expected_x)
def test_01(self): t = np.linspace(0,10,1001) u = np.zeros_like(t) # First order system: x'(t) + x(t) = u(t), x(0) = 1. # Exact solution is x(t) = exp(-t). system = ([1.0],[1.0,1.0]) tout, y, x = lsim2(system, u, t, X0=[1.0]) expected_x = np.exp(-tout) assert_almost_equal(x[:,0], expected_x)
def test_06(self): # Test use of the default values of the arguments `T` and `U`. # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0. # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution # is (1-t)*exp(-t). system = ([1.0], [1.0, 2.0, 1.0]) tout, y, x = lsim2(system, X0=[1.0, 0.0]) expected_x = (1.0 - tout) * np.exp(-tout) assert_almost_equal(x[:,0], expected_x)
def test_01(self): t = np.linspace(0, 10, 1001) u = np.zeros_like(t) # First order system: x'(t) + x(t) = u(t), x(0) = 1. # Exact solution is x(t) = exp(-t). system = ([1.0], [1.0, 1.0]) tout, y, x = lsim2(system, u, t, X0=[1.0]) expected_x = np.exp(-tout) assert_almost_equal(x[:, 0], expected_x)
def test_06(self): # Test use of the default values of the arguments `T` and `U`. # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0. # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution # is (1-t)*exp(-t). system = ([1.0], [1.0, 2.0, 1.0]) tout, y, x = lsim2(system, X0=[1.0, 0.0]) expected_x = (1.0 - tout) * np.exp(-tout) assert_almost_equal(x[:, 0], expected_x)
def test_04(self): t = np.linspace(0, 10, 1001) u = np.zeros_like(t) # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0. # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution # is (1-t)*exp(-t). system = ([1.0], [1.0, 2.0, 1.0]) tout, y, x = lsim2(system, u, t, X0=[1.0, 0.0]) expected_x = (1.0 - tout) * np.exp(-tout) assert_almost_equal(x[:,0], expected_x)
def test_04(self): t = np.linspace(0, 10, 1001) u = np.zeros_like(t) # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0. # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution # is (1-t)*exp(-t). system = ([1.0], [1.0, 2.0, 1.0]) tout, y, x = lsim2(system, u, t, X0=[1.0, 0.0]) expected_x = (1.0 - tout) * np.exp(-tout) assert_almost_equal(x[:, 0], expected_x)
def ramp_response_BF(num, den, feedback=1, t=None): if t == None: t = np.linspace(0, 10, 101) u = t # calcul de la BF sys = ctl.tf(num, den) sys_BF = g = ctl.feedback(sys, feedback) lti_BF = sys_BF.returnScipySignalLti()[0][0] t, s, x = signal.lsim2(lti_BF, u, t) return t, s
def find_x_init(trans_func): """Calculates the state-vector resulting from long -0.5 input. Args: trans_func (scipy.signal.ltisys.TransferFunctionContinuous) Returns: np.ndarray[float]: System's response. """ U = np.array([-0.5] * 480) T = np.linspace(0, 40e-9, 480) (_, _, xout) = signal.lsim2(trans_func, U=U, T=T, X0=None, atol=1e-13) return xout[-1]
def test_StateSpace(): """Test of StateSpace Class """ t = linspace(0, 10, 101) u = ones(t.shape) A, B = [[0.0, 1.0], [0.0, 0.0]], [[0.0], [1.0]] C, D = [[1.0, 0.0]], [[0.0]] scipy_ss = lti(A, B, C, D) _, y_scipy, _ = lsim2(scipy_ss, u, t) ss = StateSpace(A, B, C, D) y_ss = zeros(t.shape) for index in range(t.shape[0]): y_ss[index] = ss.step(t[index], u[index]) assert (absolute(y_ss - y_scipy) < 0.1).all()
def test_tfest(): """Test of tfest Method """ t = linspace(0, 10, 101) u = ones(t.shape) num = [1.0, 3.0, 3.0] den = [1.0, 2.0, 1.0] scipy_tf = lti(num, den) _, y_scipy, _ = lsim2(scipy_tf, u, t) tf, _ = tfest(t, y_scipy, u, np=3, nz=3) y_tf = zeros(t.shape) for index in range(t.shape[0]): y_tf[index] = tf.step(t[index], u[index]) assert (absolute(y_tf - y_scipy) < 0.1).all()
def test_TransferFunction(): """Test of TransferFunction Class """ t = linspace(0, 10, 101) u = ones(t.shape) num = [1.0, 3.0, 3.0] den = [1.0, 2.0, 1.0] tf = TransferFunction(num, den) scipy_tf = lti(num, den) _, y_scipy, _ = lsim2(scipy_tf, u, t) y_tf = zeros(t.shape) for index in range(t.shape[0]): y_tf[index] = tf.step(t[index], u[index]) assert (absolute(y_tf - y_scipy) < 0.1).all()
def find_y_ss(trans_func, input_ss): """Calculates the output resulting from long input. Args: trans_func (scipy.signal.ltisys.TransferFunctionContinuous) input_ss (float) Returns: float: The output signal level. """ U = np.array([input_ss] * 480) T = np.linspace(0, 40e-9, 480) (_, yout, _) = signal.lsim2(trans_func, U=U, T=T, X0=None, atol=1e-13) return yout[-1]
def find_x_init(tf): """ This method calculates the state-vector from a long -1 drive signal. Must call before sending / receiving signals to / from transfer function model Args: - tf = transfer function Returns: - X0 = system's state-vector result for steady state """ U = np.array([-1.0] * 480) T = np.linspace(0, 40e-9, 480) (_, _, xout) = signal.lsim2(tf, U=U, T=T, X0=None, atol=1e-13) X0 = xout[-1] return X0
def FiltroAntiAlias(x, t): poles = [ -9301.394085541 - 140211.376204937j, -9301.394085541 + 140211.376204937j, -26913.411651489 - 122396.327932432j, -26913.411651489 + 122396.327932432j, -42190.990306100 + 90265.322107311j, -42190.990306100 - 90265.322107311j, -52352.499344307 - 47970.9501448564j, -52352.499344307 + 47970.9501448564j, -55540.15182371682 ] num = (-1)**len(poles) * np.abs(np.prod(poles)) den = np.poly(poles) time, xaa, algo = signal.lsim2((num, den), x, t) return xaa
def getTransferFunctionOutput(tf, U, T, X0, atol=1e-12): """ This method sends a drive signal to a transfer function model and gets the output Args: - tf = transfer function - U = signal to drive transfer function with - T = array of time values - X0 = initial value - atol = scipy ode func parameter Returns: - PV = resultant output signal of transfer function """ (_, PV, _) = signal.lsim2(tf, U, T, X0=X0, atol=atol) return PV
def test_TransferFunction_udelay(): """Test of TransferFunction Class with input delay """ t = linspace(0, 10, 101) u = ones(t.shape) num = [1.0, 3.0, 3.0] den = [1.0, 2.0, 1.0] tf = TransferFunction(num, den) scipy_tf = lti(num, den) _, y_scipy, _ = lsim2(scipy_tf, u, t) tf = TransferFunction(num, den, 1.0) tf.set_initial_value(0.0) y_tf = zeros(t.shape) for index in range(t.shape[0]): y_tf[index] = tf.step(t[index], u[index]) assert (absolute( y_tf[argmax(t >= 1.0):] - y_scipy[:-argmax(t >= 1.0)] < 0.1).all())
def sim_step(self, dose, sim_step): """ provede krok simulace krevniho tlaku pacienta do instancni promenne y uklada chovani tlaku pacienta :param dose: mnozstvi davky podane pacientovi v kroku sim_step :param sim_step: zacina od 1 :return: tlak pacienta v aktualnim kroku """ tspan = [self.time_points[sim_step - 1], self.time_points[sim_step]] dose2 = [dose, dose] tout, yout, xout = signal.lsim2( self.sys, dose2, tspan, self.x[sim_step + self.infusion_delay - 1]) self.y[sim_step + self.infusion_delay] = yout[1] self.p[sim_step + self.infusion_delay] = self.start_pressure - yout[1] self.x[sim_step + self.infusion_delay] = xout[1] return self.p[sim_step + self.infusion_delay]
def response_sim(self, t, inputs): # Put together poles and zeros num = [1] den = [1] if not self.tf_2nd_order: for i in range(len(self.zeros)): num = np.polymul(num, self.zeros[i]) num = np.dot(self.k, num) for i in range(len(self.poles)): den = np.polymul(den, self.poles[i]) else: [num, den] = self.second_order_tf(self.k, self.w, self.z) print(self.second_order_tf(self.k, self.w, self.z)) # Create TF object Gs = sig.TransferFunction(num, den) print(Gs) # Return tsim, ysim, xsim return sig.lsim2(Gs, U=inputs, T=t)
def test_discrete_approx(self): """ Test that the solution to the discrete approximation of a continuous system actually approximates the solution to the continuous system. This is an indirect test of the correctness of the implementation of cont2discrete. """ def u(t): return np.sin(2.5 * t) a = np.array([[-0.01]]) b = np.array([[1.0]]) c = np.array([[1.0]]) d = np.array([[0.2]]) x0 = 1.0 t = np.linspace(0, 10.0, 101) dt = t[1] - t[0] u1 = u(t) # Use lsim2 to compute the solution to the continuous system. t, yout, xout = lsim2((a, b, c, d), T=t, U=u1, X0=x0, rtol=1e-9, atol=1e-11) # Convert the continuous system to a discrete approximation. dsys = d2c((a, b, c, d), dt, method='bilinear') # Use dlsim with the pairwise averaged input to compute the output # of the discrete system. u2 = 0.5 * (u1[:-1] + u1[1:]) t2 = t[:-1] td2, yd2, xd2 = dlsim(dsys, u=u2.reshape(-1, 1), t=t2, x0=x0) # ymid is the average of consecutive terms of the "exact" output # computed by lsim2. This is what the discrete approximation # actually approximates. ymid = 0.5 * (yout[:-1] + yout[1:]) assert_allclose(yd2.ravel(), ymid, rtol=1e-4)
def test_StateSpace_ydelay(): """Test of StateSpace Class with output delay """ t = linspace(0, 10, 101) u = ones(t.shape) A, B = [[0.0, 1.0], [0.0, 0.0]], [[0.0], [1.0]] C, D = [[1.0, 0.0]], [[0.0]] scipy_ss = lti(A, B, C, D) _, y_scipy, _ = lsim2(scipy_ss, u, t) A = [[[0.0, 1.0], [0.0, 0.0]], [[0.0, 0.0], [0.0, 0.0]]] B = [[[0.0], [1.0]], [[0.0], [0.0]]] C = [[[0., 0.]], [[1.0, 0.0]]] D = [[[0.0]]] ss = StateSpace(A, B, C, D, delays=[0.0, 1.0]) y_ss = zeros(t.shape) for index in range(t.shape[0]): y_ss[index] = ss.step(t[index], u[index]) assert (absolute( y_ss[argmax(t >= 1.0):] - y_scipy[:-argmax(t >= 1.0)] < 0.1).all())
def NLsysSimulate(self,R): """ R is the input vector. """ y_out = numpy.zeros(self.N) for i in numpy.arange(0,self.N): # Calculates the error signal: if (self.Malha == 'Fechada'): e = self.K * (R[i] - self.y0[0]) else: e = self.K * R[i] # Check if C(s) is defined. if (len(self.Cden) > 1): # Solve one step of the C(s) differential equation: t, yc, xout = signal.lsim2((self.Cnum,self.Cden),numpy.array([self.e0,e]),numpy.array([0,self.delta_t]),self.X0) self.u = yc[1] self.X0 = xout[1] # Save the last state. else: self.u = e self.e0 = e # Solve one step of the non-linear differential equation: if (self.order == 1): y = odeint(self.NLsysODE1,self.y0[0],numpy.array([0,self.delta_t])) self.y0[0]=y[1] y_out[i] = y[0] elif (self.order == 2): y = odeint(self.NLsysODE2,self.y00,numpy.array([0,self.delta_t])) self.y00=y[1] y_out[i] = y[0][0] #self.tfinal = t[-1] #self.Rfinal = u[-1] #self.Wfinal = w[-1] return y_out
def simulation_fitness(U, T, X0, trans_func, ss_low, ss_high): """Calculates fitness of a match. Args: U (np.ndarray[float]): Driving signal of length 1000. T (np.ndarray[float]) X0 (float): System's steady-state response to a -1 input. trans_func (scipy.signal.ltisys.TransferFunctionContinuous) ss_low (float): Low steady-state for MSE calculation. ss_high (float): High steady_state for MSE calculation. Returns: Tuple[Float]: MSE. """ if not valid_driver_signal(U): return (1000.0, ) else: sp = [ss_low] * 120 + [ss_high] * 120 (_, yout, _) = signal.lsim2(trans_func, U=U, T=T, X0=X0, atol=1e-12) sp_mse = np.mean((np.array(yout) - np.array(sp))**2) return (sp_mse, )
def __getTransferFunctionOutput(self, tf, U, T, X0, atol=1e-12): """ This method sends a drive signal to a transfer function model and gets the output Args: - tf = transfer function - U = signal to drive transfer function with - T = array of time values - X0 = initial value - atol = scipy ode func parameter Returns: - PV = resultant output signal of transfer function """ T = np.linspace(T[0], T[-1], 240) U = np.array(U) sample = 240 p = upsampling.ups(sample) input_init = np.copy(U) PV = np.zeros((self.q, sample)) for j in range(self.q): if j > 0: X0 = self.__find_x_init(tf[j-1]) input = input_init[:self.m] input = p.create(input) (_, PV[j], _) = signal.lsim2(tf[j], input, T, X0=X0, atol=atol) input_init = input_init[self.m:] min_PV = np.copy(min(PV[j])) if min_PV < 0: for i in range(0, len(PV[j])): PV[j][i] = PV[j][i] + abs(min_PV) return PV
def test_discrete_approx(self): """ Test that the solution to the discrete approximation of a continuous system actually approximates the solution to the continuous sytem. This is an indirect test of the correctness of the implementation of cont2discrete. """ def u(t): return np.sin(2.5 * t) a = np.array([[-0.01]]) b = np.array([[1.0]]) c = np.array([[1.0]]) d = np.array([[0.2]]) x0 = 1.0 t = np.linspace(0, 10.0, 101) dt = t[1] - t[0] u1 = u(t) # Use lsim2 to compute the solution to the continuous system. t, yout, xout = lsim2((a, b, c, d), T=t, U=u1, X0=x0, rtol=1e-9, atol=1e-11) # Convert the continuous system to a discrete approximation. dsys = c2d((a, b, c, d), dt, method='bilinear') # Use dlsim with the pairwise averaged input to compute the output # of the discrete system. u2 = 0.5 * (u1[:-1] + u1[1:]) t2 = t[:-1] td2, yd2, xd2 = dlsim(dsys, u=u2.reshape(-1, 1), t=t2, x0=x0) # ymid is the average of consecutive terms of the "exact" output # computed by lsim2. This is what the discrete approximation # actually approximates. ymid = 0.5 * (yout[:-1] + yout[1:]) assert_allclose(yd2.ravel(), ymid, rtol=1e-4)
def step_response_BF_pert(num1, den1, num2, den2, feedback=1, pert=0.25, pert_time=1, t=None): if t == None: t = np.linspace(0, 10, 101) sys1 = ctl.tf(num1, den1) sys2 = ctl.tf(num2, den2) sys_BO1 = ctl.series(sys1, sys2) sys_BF1 = g = ctl.feedback(sys_BO1, feedback) lti_BF1 = sys_BF1.returnScipySignalLti()[0][0] sys_BF2 = g = ctl.feedback(sys2, sys1) lti_BF2 = sys_BF2.returnScipySignalLti()[0][0] u = pert * (t > pert_time) t, s1 = signal.step2(lti_BF1, None, t) t, s2, trash = signal.lsim2(lti_BF2, u, t) s = s1 + s2 return t, s
def test_05(self): # The call to lsim2 triggers a "BadCoefficients" warning from # scipy.signal.filter_design, but the test passes. I think the warning # is related to the incomplete handling of multi-input systems in # scipy.signal. # A system with two state variables, two inputs, and one output. A = np.array([[-1.0, 0.0], [0.0, -2.0]]) B = np.array([[1.0, 0.0], [0.0, 1.0]]) C = np.array([1.0, 0.0]) D = np.zeros((1, 2)) t = np.linspace(0, 10.0, 101) with suppress_warnings() as sup: sup.filter(BadCoefficients) tout, y, x = lsim2((A,B,C,D), T=t, X0=[1.0, 1.0]) expected_y = np.exp(-tout) expected_x0 = np.exp(-tout) expected_x1 = np.exp(-2.0 * tout) assert_almost_equal(y, expected_y) assert_almost_equal(x[:,0], expected_x0) assert_almost_equal(x[:,1], expected_x1)
def test_05(self): # The call to lsim2 triggers a "BadCoefficients" warning from # scipy.signal.filter_design, but the test passes. I think the warning # is related to the incomplete handling of multi-input systems in # scipy.signal. # A system with two state variables, two inputs, and one output. A = np.array([[-1.0, 0.0], [0.0, -2.0]]) B = np.array([[1.0, 0.0], [0.0, 1.0]]) C = np.array([1.0, 0.0]) D = np.zeros((1, 2)) t = np.linspace(0, 10.0, 101) with suppress_warnings() as sup: sup.filter(BadCoefficients) tout, y, x = lsim2((A, B, C, D), T=t, X0=[1.0, 1.0]) expected_y = np.exp(-tout) expected_x0 = np.exp(-tout) expected_x1 = np.exp(-2.0 * tout) assert_almost_equal(y, expected_y) assert_almost_equal(x[:, 0], expected_x0) assert_almost_equal(x[:, 1], expected_x1)
def plot_time(analog_system, discrete_system, response='step', num_samples=100, sample_rate=48e3, plot_error=False): n = np.arange(num_samples) t = n/sample_rate fig, ax1 = plt.subplots() if response == 'impulse': ta, ya = signal.impulse2(analog_system, T=t) _, yd = signal.dimpulse((*discrete_system,1/sample_rate), t=t) ax1.set_title('Resposta ao impulso') elif response == 'step': ta, ya = signal.step2(analog_system, T=t) _, yd = signal.dstep((*discrete_system,1/sample_rate), t=t) ax1.set_title('Resposta ao degrau') elif response == 'ramp': ramp_factor = 1 ta = np.arange(int(num_samples*ramp_factor))/(ramp_factor*sample_rate) print(ta.shape) ta, ya, xa = signal.lsim2(analog_system, U=ta, T=ta, printmessg=True) _, yd = signal.dlsim((*discrete_system,1/sample_rate), u=t, t=t, x0=None) ax1.set_title('Resposta a rampa') ax1.plot(ta*sample_rate,ya,'b') ax1.plot(n,np.ravel(yd),'k.') ax1.set_ylabel('Amplitude', color='b') ax1.set_xlabel('Amostras') ax1.grid(True) ax1.legend(['Analógico', 'Discreto']) if plot_error: ax2 = ax1.twinx() ax2.plot(n, np.abs(ya-np.ravel(yd)), 'r') ax2.set_ylabel('Erro', color='r') ax2.axis('tight')
def getTransferFunctionOutput(tf, U, T, atol=1e-12): """ This method sends a drive signal to a transfer function model and gets the output Args: - tf = transfer function - U = signal to drive transfer function with - T = array of time values - X0 = initial value - atol = scipy ode func parameter Returns: - PV = resultant output signal of transfer function """ X0 = find_x_init(tf) (_, PV, _) = signal.lsim2(tf, U, T, X0=X0, atol=atol) min_PV = np.copy(min(PV)) if min_PV < 0: for i in range(0, len(PV)): PV[i] = PV[i] + abs(min_PV) # translate signal up return PV
def getTransferFunctionOutput(tf, U, T, atol=1e-12): """ This method sends a drive signal to a transfer function model and gets the output Args: - tf = transfer function - U = signal to drive transfer function with - T = array of time values - X0 = initial value - atol = scipy ode func parameter Returns: - PV = resultant output signal of transfer function """ X0 = find_x_init(tf) (_, PV, _) = signal.lsim2(tf, U, T, X0=X0, atol=atol) # ENSURE LOWEST POINT OF SIGNAL >= 0 (OCCURS FOR SIMULATIONS) OTHERWISE WILL MESS UP ST, OS & RT ANALYSIS min_PV = np.copy(min(PV)) if min_PV < 0: for i in range(0, len(PV)): PV[i] = PV[i] + abs(min_PV) # translate signal up return PV
def time_lsim2(self): signal.lsim2(self.system, self.u, self.t)
def time_lsim2(self): lsim2(self.system, self.u, self.t)
(c) 2014-Feb-04 Christian MÃŒnker - Files zur Vorlesung "DSV auf FPGAs" =========================================================================== """ from __future__ import division, print_function, unicode_literals import numpy as np import numpy.random as rnd from numpy import (pi, log10, exp, sqrt, sin, cos, tan, angle, arange, linspace, array, zeros, ones) from numpy.fft import fft, ifft, fftshift, ifftshift, fftfreq import scipy.signal as sig import matplotlib.pyplot as plt from matplotlib.pyplot import (figure, plot, stem, grid, xlabel, ylabel, subplot, title, clf, xlim, ylim) t = linspace(0,4*pi, 1000) x = sig.waveforms.square(t * 40) y = sin(t * 2 * pi) #y = np.sign(y) b = [1,3]; a = [1,1] my_t = arange(len(t)) z = arange(len(t)) for i in t: my_t[i], z[i], xout = sig.lsim2((b,a),y , i) q = z > 0 plot(my_t, z, t, y, t, x, t, q) plt.show()
def test_linear_invariant(self, sys, sample_time, samples_number): time = np.arange(samples_number) * sample_time _, yout_cont, _ = lsim2(sys, T=time, U=time, **self.tolerances) _, yout_disc, _ = dlsim(c2d(sys, sample_time, method='foh'), u=time) assert_allclose(yout_cont.ravel(), yout_disc.ravel())
tm.append(float(row[5])) machine_flow_rate.append(float(row[6])) elif row[4].isnumeric(): tm.append(float(row[5])) machine_flow_rate.append(float(row[6])) # origin signal. # plt.plot(ts, setting_flow_rate, 'b.-', label='setting flow rate') # resample signal. f = interp1d(ts, setting_flow_rate) ts = tm setting_flow_rate = f(tm) plt.plot(ts, setting_flow_rate, 'k.-', label='setting flow rate') wn = 33 zeta = 0.0087 tout, yout, xout = lsim2(([1, wn * wn], [1, zeta * wn * wn, wn * wn]), U=setting_flow_rate[:-25], T=ts[:-25]) plt.plot(tm, machine_flow_rate, 'r.-', label='machine flow rate') plt.plot(tout, yout, 'b.-', label='simulation') plt.xticks(np.linspace(0, 5, num=11, endpoint=True)) plt.yticks(np.linspace(0, 50, num=11, endpoint=True)) plt.title('sheet3') plt.legend() plt.grid() plt.savefig('./img/data_restruct.png') plt.show()
def lsim2(self, u, t, returnall=False, X0=None): #tempsys=signal.lti(self.num,self.den) if returnall: return signal.lsim2(self, u, t, X0=X0) else: return signal.lsim2(self, u, t, X0=X0)[1]