def sanityCheck(N=8, fc=2*np.pi*0.25, bw=2*np.pi*0.2): cc = LinSys.create(N,fc,bw); (b,a) = cc.getBA() s = np.zeros( 106, 'int32' ) si = np.zeros( 106 ) mx = 0 pi = 0 to = 0.5 for pol in cc.get(): n = pol.numer(to)[0,:] ni= pol.numerApprox(np.array(to)) d = pol.denom() u = np.concatenate( (n, np.zeros(100)) ) h = sig.dlsim((1,d,1), u)[1] h = np.array( np.round(h*2**17), 'int32' ) thism = np.max(np.abs(h)) if thism > mx: mx = thism mi = pi s = (s + h) % 65536 s[s>32765]-=65536 ui= np.concatenate( (ni, np.zeros(100)) ) hi= sig.dlsim((1,d,1), ui)[1] si= si + hi pi= pi + 1 plt.plot( h ) h = sig.impulse((b,a)) print("Max of superposition: {}".format(np.max(np.abs(s)))) print("Max: {} for pole-pair {}".format(mx, mi)) plt.plot( to+np.linspace(0,99,100), s [6:] ) plt.plot( to+np.linspace(0,99,100), si[6:] ) plt.plot( h[0], h[1] ) plt.show() return cc
def __init__(self): self.root = Tk() self.root.title("Tc Example") #------------------------------------------------------------------------ toolbar = Frame(self.root) buttonPhase = Button(toolbar,text="Bode Phase",command=self.plotPhase) buttonPhase.pack(side=LEFT,padx=2,pady=2) buttonMag = Button(toolbar,text="Bode Mag",command=self.plotMag) buttonMag.pack(side=LEFT,padx=2,pady=2) buttonStep = Button(toolbar,text="Step",command=self.plotStep) buttonStep.pack(side=LEFT,padx=2,pady=2) buttonImp = Button(toolbar,text="Impulse",command=self.plotImp) buttonImp.pack(side=LEFT,padx=2,pady=4) toolbar.pack(side=TOP,fill=X) graph = Canvas(self.root) graph.pack(side=TOP,fill=BOTH,expand=True,padx=2,pady=4) #------------------------------------------------------------------------------- f = Figure() self.axis = f.add_subplot(111) self.sys = signal.TransferFunction([1],[1,1]) self.w,self.mag,self.phase = signal.bode(self.sys) self.stepT,self.stepMag = signal.step(self.sys) self.impT,self.impMag = signal.impulse(self.sys) self.dataPlot = FigureCanvasTkAgg(f, master=graph) self.dataPlot.draw() self.dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=True) nav = NavigationToolbar2Tk(self.dataPlot, self.root) nav.update() self.dataPlot._tkcanvas.pack(side=TOP, fill=X, expand=True) self.plotMag() #------------------------------------------------------------------------------- self.root.mainloop()
def coupledSysSolver(n_coeff, d_coeff): H_n = poly1d(n_coeff) H_d = poly1d(d_coeff) Hs = sp.lti(H_n, H_d) t, h = sp.impulse(Hs, None, linspace(0, 100, 1000)) return t, h
def generate_Impulse(position, duration): #returns an impusle signal with duration = durationa and position = position impulse = signal.impulse(duration,position) waveform = TimeSeries(impulse, delta_t=1/4096) return waveform
def plot_impulse(system, n=1000): t, y= signal.impulse(system, N=n) fig = go.Figure() fig.add_trace(go.Scatter(x=t, y=y)) fig.update_xaxes(title="Time (s)") fig.update_layout(title="Impulse response") fig.show()
def compute(num, den): """Return filename of plot of the damped_vibration function.""" print(os.getcwd()) num = list(map(int, num.split())) den = list(map(int, den.split())) sys = signal.TransferFunction(num, den) tf = control.tf(num, den) t1, y1 = signal.step(sys) t2, y2 = signal.impulse(sys) s = str(tf) s = s.split('\n') s1 = '(' + s[1].strip() + ')' s2 = '(' + s[3].strip() + ')' plt.title('Time Response of H(s)=' + s1 + '/' + s2) plt.plot(t1, y1, 'b--', linewidth=3, label='Step Response') plt.plot(t2, y2, 'r', linewidth=3, label='Impulse Response') plt.xlabel('Time') plt.ylabel('Response (y)') plt.legend(loc='best') if not os.path.isdir('static'): os.mkdir('static') else: # Remove old plot files for filename in glob.glob( os.path.join('static', 'Time_Response', 'Plot1.png')): os.remove(filename) plotfile = os.path.join('static', 'Time_Response', 'Plot1' + '.png') plt.savefig(plotfile) plt.clf() plt.cla() plt.close() return plotfile
def solve_2(num, den): num = poly1d(num) den = poly1d(den) Hs = sp.lti(num, den) #converting H(s) to h(t) t, h = sp.impulse(Hs, None, linspace(0, 100, 1000)) return t, h
def stepresponse(Y, title): num, den = symToTransferFn(Y) den.append(0) H = sp.lti(num, den) t, y = sp.impulse(H, T=np.linspace(0, 1e-3, 10000)) plotter(t, y, title, "t", "output") return
def laplaceSolver(decay, w): Xn = poly1d([1, decay]) Xd = polymul([1, 0, pow(1.5, 2)], [1, 2 * decay, (pow(w, 2) + pow(decay, 2))]) # Computes the impulse response of the transfer function Xs = sp.lti(Xn, Xd) t, x = sp.impulse(Xs, None, linspace(0, 100, 10000)) return Xs, t, x
def coupled(): '''solving the coupled springs problem''' t = np.linspace(0, 20, 200) #Transfer function for X X = sp.lti([1, 0, 2], [1, 0, 3, 0]) #Transfer function for Y Y = sp.lti([2], [1, 0, 3, 0]) t, x = sp.impulse(X, None, t) t, y = sp.impulse(Y, None, t) plotter(1, t, x, "t", "f(t)", title="Coupled Spring system, plot of x") plotter(1, t, y, "t", "f(t)", title="Coupled Spring system, plot of y", arg3="g-") plt.legend(["f(t) = x(t)", "f(t) = y(t)"])
def set_band_pass(self): self.num = [1, 0] self.den = [1, 1, 1] self.sys = signal.TransferFunction([1, 0], [1, 1, 1]) self.w, self.mag, self.phase = signal.bode(self.sys) self.stepT, self.stepMag = signal.step(self.sys) self.impT, self.impMag = signal.impulse(self.sys) self.pzg = signal.tf2zpk(self.sys.num, self.sys.den) self.GDfreq, self.gd = signal.group_delay((self.num, self.den)) self.plotMag()
def solve(d, w): M = [1, 0, 2.25] tmp = polymul([1, d], [1, d]) tmp = polyadd(tmp, w * w) a = polymul(M, tmp) X = sp.lti([1, d], a) #Converts the X in 'laplace' domain to 'time' domain t, x = sp.impulse(X, None, linspace(0, 100, 1001)) return t, x
def DrawDiag_GtkAgg(X, Y, FigureNum=None, NumSubplot=None, FigTitle='No title', FigSuptitle='No suptitle', Xlabel=None, Ylabel=None, type='normal', geometry=(8, 5), render=False): figure(figsize=geometry, facecolor='w', edgecolor='w') clf() suptitle(FigTitle, fontsize=12) suptitle('\n\n' + FigSuptitle + '\n', fontsize=9) subplots_adjust(left=.16, bottom=.11, right=.96, top=.9, hspace=.2) for numSub in range(NumSubplot): subplot(NumSubplot, 1, numSub + 1) if len(Xlabel) == NumSubplot and len(Ylabel) == NumSubplot: xlabel(Xlabel[numSub], fontsize=11) #, style='italic') ylabel(Ylabel[numSub]) else: print 'Error: not enough labels for subplots' if type == 'normal': grid() plot(X[numSub], Y[numSub]) elif type == 'semilogx': grid(which='major') grid(which='minor') semilogx(X[numSub], Y[numSub]) elif type == 'step': grid() plot(step(Y[numSub])[0], step(Y[numSub])[1]) elif type == 'impulse': grid() plot(impulse(Y[numSub])[0], impulse(Y[numSub])[1]) else: print 'Error: Specify plot type' if render: show()
def inverseLaplace(Y_s, t=None): """ Finds the inverse laplace transform of a sympy expression using sp.impulse. """ # load the step response as a system in scipy.signal num, den = symToTransferFn(Y_s) # evaluate in time domain t, y = sp.impulse((num, den), T=t) return t, y
def solveProblem(decay): """Find the response to the given system to a decaying cosine.""" inN, inD = F_s(decay=decay) HN, HD = secondOrderH() outN,outD = inN*HN, inD*HD out_s = sp.lti(outN.coeffs, outD.coeffs) t = linspace(0,50,1000) return sp.impulse(out_s,None,t)
def get_output_time_domain(Y, t, steps): simplY = simplify(Y) num = fraction(simplY)[0] den = fraction(simplY)[1] num2, den2 = get_numpy_array_from_Poly(num, den) num2 = np.poly1d(num2) den2 = np.poly1d(den2) Y = sp.lti(num2, den2) t = np.linspace(0.0, t, steps) t, y = sp.impulse(Y, None, t) return t, y
def plot_impulse_response(self): # Calculating plot points self.t_imp_res, self.impulse_response = ss.impulse(self.tf) # Plotting impulse response self.axes.clear() self.axes.plot(self.t_imp_res, self.impulse_response) self.axes.grid(which='major') self.axes.grid(which='minor') self.axes.set_xlabel('Time (s)') self.axes.set_ylabel('Impulse Response (V)') self.canvas.draw()
def exp_sin_resp(decay, zeta, freq, tvec): num = poly1d([1, decay]) den = polyadd(polymul(num, num), poly1d([freq * freq])) den_x = poly1d([1, 2 * zeta * freq, freq * freq]) den = polymul(den, den_x) X = sp.lti( num.coeffs, den.coeffs ) #num and den are poly1d objects, poly1d.coeffs is an array with the polymonial coefficient values t, x = sp.impulse(X, None, tvec) plot(t, x) title("Decay factor = " + str(decay)) savefig("./Images/expsin_" + str(decay) + ".png") close() return 0
def solve(decay): '''using the convolution property of the laplace transform to solve for the output of the LTI system''' Hn, Hd = transfer_fn() Fn, Fd = input_fn(decay) np.polymul(Fn, Hn) t = np.linspace(0, 50, 200) Y = sp.lti(np.polymul(Fn, Hn), np.polymul(Fd, Hd)) t, y = sp.impulse(Y, None, t) plotter(1, t, y, "t", "x(t)", title="System response with decay {}".format(decay)) plt.show()
def TranformadaZ(titutlo,num,den): h1 = control.TransferFunction(num,den) [zeros,poles,gain] = signal.tf2zpk(num,den) print(titutlo) print("zeros") print(zeros) print("polos ") print(poles) print("\n") control.pzmap(h1, Plot=True, grid=False, title=titutlo) [t,y] = signal.impulse( (num,den) ) plt.figure() plt.suptitle(titutlo) plt.plot(t, y) plt.title('Respuesta al impulso')
def func(decay): ### Frequency response of a spring is being calculated f_spring_num = p.poly1d([1, decay]) f_den = p.poly1d([1, 2 * decay, 2.25 + decay**2]) diff_coeff = p.poly1d([1, 0, 2.25]) f_spring_den = p.polymul(f_den, diff_coeff) ### Converting the coefficients to LTI system type for generating impulse response f_lti = sp.lti(f_spring_num, f_spring_den) t, x = sp.impulse(f_lti, None, p.linspace(0, 50, 1000)) ### Plotting the response p.plot(t, x) p.xlabel('time$\\rightarrow$') p.ylabel('x$\\rightarrow$') p.show()
def accept(self): print(self.selector) if self.selector == 'impuse': t, u = impulse((self.block.num, self.block.den)) self.get = [t, u] if self.selector == 'step': t, u = step((self.block.num, self.block.den)) self.get = [t, u] if self.selector == 'custom': time = float(self.ts_edit.text()) count = self.methodbox.currentIndex() dd, d1, d3d = cont2discrete((self.block.num, self.block.den), time, self.indcator[count]) if self.sigtmp: t, u = self.calcc2d(self.sigtmp, dd[0], d1, d3d) self.get = [t, u] super(c2ddlg, self).accept()
def plotter(f,t): transfer_function = sp.lti([1],[1,0,2.25]) t,h_t = sp.impulse(transfer_function,None,t) t,y,svec = sp.lsim(transfer_function, f, t) plt.subplot(3,1,1) plt.plot(t,f, 'r') plt.grid(True) plt.title("Input") plt.subplot(3,1,2) plt.plot(t, h_t, 'y') plt.grid(True) plt.title('Impulse response') plt.subplot(3,1,3) plt.plot(t,y,'b') plt.title('Output') plt.grid(True) plt.show()
def update(**kwargs): lti.update(**kwargs) g_impulse.data_source.data['x'], g_impulse.data_source.data['y'] = ( impulse(lti.sys, T=t)) g_step.data_source.data['x'], g_step.data_source.data['y'] = ( step(lti.sys, T=t)) g_poles.data_source.data['x'] = lti.sys.poles.real g_poles.data_source.data['y'] = lti.sys.poles.imag w, mag, phase, = bode(lti.sys) g_bode_mag.data_source.data['x'] = w g_bode_mag.data_source.data['y'] = mag g_bode_phase.data_source.data['x'] = w g_bode_phase.data_source.data['y'] = phase push_notebook()
def InvertedPendulum(): x0 = 0 dx0 = 0 theta0 = np.pi dtheta0 = 0 M = .5 m = 0.2 b = 0.1 I = 0.006 g = 9.8 l = 0.3 F = symbols('F') x, theta, dx, dtheta = symbols('x, theta, dx, dtheta') X = Matrix([x, dx, theta, dtheta]) U = Matrix([F]) RHS = Matrix([[M + m, -m * l * cos(theta)], [m * l * cos(theta), I + m * l**2]]) LHS1 = RHS.inv() * Matrix([ -b * x + m * l * dtheta**2 * sin(theta), -m * l * g * sin(theta) ]) #Dynamics LHS2 = RHS.inv() * Matrix([F, 0]) #Input Force A = LHS1.jacobian(X).subs([(x, x0), (theta, theta0), (dx, dx0), (dtheta, dtheta0)]) B = LHS2.jacobian(U).subs([(x, x0), (theta, theta0), (dx, dx0), (dtheta, dtheta0)]) A = np.reshape( np.matrix(np.vstack( (np.matrix([0, 1, 0, 0]), A[0, :], np.matrix([0, 0, 0, 1]), A[1, :])), dtype=np.float), (4, 4)) B = np.matrix([0, B[0, 0], 0, B[1, 0]], dtype=np.float).T C = np.matrix([[1, 0, 0, 0], [0, 0, 1, 0]]) D = np.matrix([[0], [0]]) ss = sig.StateSpace(A, B, C, D) dt = .025 ssd = sig.cont2discrete((A, B, C, D), dt) tc, yc = sig.impulse(ss) td, yd = sig.dimpulse(ssd) plt.plot(td, [y[0, 0] for y in yd]) plt.show() plt.plot(td, [y[1, 0] for y in yd]) plt.show() f00 = 9
def __init__(self, parent, controller): # parent representa el Frame principal del programa, tenemos que indicarle # cuando MenuInputOutput será dibujado # controller lo utilizamos cuando necesitamos que el controlador principal del programa haga algo # llamamos al constructor del padre de MenuInputOutput, que es tk.Frame tk.Frame.__init__(self, parent) self.x = linspace(0, 20, num=1000) self.Vin = [1] self.Vout = [1] self.H = ss.TransferFunction(self.Vout, self.Vin) self.h = ss.impulse(self.H, T=self.x) # Impulse response. self.Step_Response = ss.step(self.H, T=self.x) # Response to step. self.Cos_Response = ss.lsim(self.H, U=cos(self.x), T=self.x) # Response to other input signals. self.controller = controller self.parent = parent self.title = tk.Label( self, height=1, width=50, text="Entrada - Salida gráfico", font=Config.LARGE_FONT, background="#ffccd5" ) # con pack provocamos que los widgets se dibujen efectivamente en la pantalla self.title.pack(side=tk.TOP, fill=tk.BOTH) # boton para volver self.backButton = tk.Button( self, height=2, width=50, text="Back to Mode", font=Config.SMALL_FONT, background="#cfffd5", command=self.goBack ) self.backButton.pack(side=tk.TOP, fill=tk.BOTH)
def low_pass_output(laplace_fn=None, time_fn=None, t=np.linspace(0, 1e-5, 1e5), C=10**-11): A, b, V = lowpass(C1=C, C2=C) v_low_pass = V[-1] temp = expand(simplify(v_low_pass)) n, d = fraction(temp) n, d = Poly(n, s), Poly(d, s) num, den = n.all_coeffs(), d.all_coeffs() H_v_low_pass = sp.lti([-float(f) for f in num], [float(f) for f in den]) if laplace_fn != None: temp = expand(simplify(laplace_fn)) n, d = fraction(temp) n, d = Poly(n, s), Poly(d, s) num, den = n.all_coeffs(), d.all_coeffs() lap = sp.lti([float(f) for f in num], [float(f) for f in den]) t, u = sp.impulse(lap, None, t) else: u = time_fn t, V_out, svec = sp.lsim(H_v_low_pass, u, t) return (t, V_out)
def solve(self, time, bode=False): self.initial_conditions_polynomial = np.poly1d( np.multiply(self.initial_conditions, np.array(self.D)[:-1])) #self.H=sp.lti(self.f[0],self.f[1]*self.D) self.H = sp.lti( self.f[0] + self.initial_conditions_polynomial * self.f[1], self.f[1] * self.D) if bode: w, S, phi = self.H.bode() fig, (ax1, ax2) = plt.subplots(2, 1) ax1.semilogx(w, S) ax1.set_title("Magnitude plot") ax2.semilogx(w, phi) ax2.set_title("Phase plot") fig.tight_layout() plt.show() print(self.H) t, x = sp.impulse(self.H, None, time) plt.title("Response with time") plt.plot(t, x) plt.show()
def time_impulse(self): signal.impulse(self.system, T=self.t)
y = g_mag/np.abs(omega) * np.exp(alpha*t) * np.sin(np.abs(omega)*t + g_angle)*step_func(t) return y steps = 1e-6 # define step size t_step = 1.2e-3 t = np.arange(0, t_step + steps, steps) # from 0 to 1.2 ms R = 1e3 L = 27e-3 C = 100e-9 h1 = sine_method(R, L, C, t) # using values from prelab circuit num = [0, 1/(R*C),0] den = [1, 1/(R*C), 1/(L*C)] tout, yout = sig.impulse((num, den), T = t) plt.figure(figsize = (10, 7)) plt.subplot(2, 1, 1) # 3 rows, 1 column, 1st subplot plt.ylabel('calculated') plt.ticklabel_format(style='scientific', scilimits=(0, 1)) plt.plot(t, h1) plt.grid() plt.subplot(2, 1, 2) plt.ylabel('scipy.signal.impulse') plt.plot(tout, yout) plt.grid() plt.xlabel('t') plt.ticklabel_format(style='scientific', scilimits=(0, 1)) plt.suptitle('Impulse Response h(t)')
for i in arange(1.4,1.6,0.05): function3 = ([1.0,0.05],[1.0,0.1,2.25+i**2+0.05**2,0.1*2.25,2.25*(0.05**2+i**2)]) x,y,svec = sp.lsim(function3,damping(t1,i),linspace(0,100,501)) plt.plot(x,y) plt.plot(x,y) plt.xlabel(r't',size=15) plt.ylabel(r'X(t)',size=15) plt.title(r'plot for system response vs t for i = {}'.format(i)) plt.show() ''' #Q4 t2 = linspace(0, 20, 201) system_x = ([1, 0, 2, 0], [1, 0, 3, 0, 0]) t2, x = sp.impulse(system_x, None, t2) plt.plot(t2, x) plt.xlabel(r't', size=15) plt.ylabel(r'X(t)', size=15) plt.title(r'plot for coupled system X vs t') plt.show() system_y = ([2], [1, 0, 3, 0]) t, y = sp.impulse(system_y, None, t2) plt.plot(t, y) plt.xlabel(r't', size=15) plt.ylabel(r'Y(t)', size=15) plt.title(r'plot for coupled system Y vs t') plt.show() ''' #Q5
def impresp(): tf = transfunc() t, yout = scisig.impulse(tf) return yout
import os import numpy as np from scipy import signal import matplotlib.pyplot as plt plt.rc('text', usetex=True) plt.rc('font', family='serif') # Parameters for mechanical oscillator m = 1.0 # Mass [kg] k = 0.8 # Spring constant [N/m] c = 0.3 # Damping constant [Ns/m] sys = signal.lti([ 1 ], [ m, c, k ]) # Time range n = 500+1 t = np.linspace(0, 40, num=n) # Simulate T, yout = signal.impulse(sys, T=t) # Plot result plt.plot(T, yout, '-k') plt.grid() plt.xlabel('Time (s)') plt.ylabel('Output (m)') plt.savefig(os.path.splitext(__file__)[0] + '.pdf') plt.show()
import numpy as np import matplotlib.pyplot as plt from scipy import signal num = np.poly1d([1, 0]) den = np.poly1d([1, 3, 2, 1]) sys = signal.TransferFunction(num, den) t, y = signal.impulse(sys) plt.plot(t, y) plt.xlabel('$t$') plt.ylabel('$y$') plt.grid() # minor plt.axis() plt.show()
def analyze_lti(lti, t=np.linspace(0,10,100)): """Create a set of plots to analyze an lti system Args: lti (instance of an Interactive LTI system subclass ): lti system to interact with t (numpy array): Timepoints at which to evaluate the impulse and step responses """ t_impulse, y_impulse = impulse(lti.sys) fig_impulse = figure( title="impulse response", x_range=(0, 10), y_range=(-0.1, 3), x_axis_label='time') g_impulse = fig_impulse.line(x=t_impulse, y=y_impulse) t_step, y_step = step(lti.sys) fig_step = figure( title="step response", x_range=(0, 10), y_range=(-0.04, 1.04) ) g_step = fig_step.line(x=t_step, y=y_step) fig_pz = figure(title="poles and zeroes", x_range=(-4, 1), y_range=(-2,2)) g_poles = fig_pz.circle( x=lti.sys.poles.real, y=lti.sys.poles.imag, size=10, fill_alpha=0 ) g_rootlocus = fig_pz.line(x=[0, -10], y=[0, 0], line_color='red') w, mag, phase, = bode(lti.sys) fig_bode_mag = figure(x_axis_type="log") g_bode_mag = fig_bode_mag.line(w, mag) fig_bode_phase = figure(x_axis_type="log") g_bode_phase = fig_bode_phase.line(w, phase) fig_bode = gridplot( [fig_bode_mag], [fig_bode_phase], nrows=2, plot_width=300, plot_height=150, sizing_mode="fixed") grid = gridplot( [fig_impulse, fig_step], [fig_pz, fig_bode], plot_width=300, plot_height=300, sizing_mode="fixed" ) show(grid, notebook_handle=True) def update(**kwargs): lti.update(**kwargs) g_impulse.data_source.data['x'], g_impulse.data_source.data['y'] = ( impulse(lti.sys, T=t)) g_step.data_source.data['x'], g_step.data_source.data['y'] = ( step(lti.sys, T=t)) g_poles.data_source.data['x'] = lti.sys.poles.real g_poles.data_source.data['y'] = lti.sys.poles.imag w, mag, phase, = bode(lti.sys) g_bode_mag.data_source.data['x'] = w g_bode_mag.data_source.data['y'] = mag g_bode_phase.data_source.data['x'] = w g_bode_phase.data_source.data['y'] = phase push_notebook() interact(update, **lti.update_kwargs)
def heav(x): if x == 0: return 0.5 return 0 if x < 0 else 1 m = 1 b = 10 k = 50 num = [b, k] den = [m, b, k] sys = lti(num, den) t, i = impulse(sys) t, s = step(sys) # -- Plot of impulse response plt.plot(t, i, t, s) plt.title('Impulse and Unit Step Response') plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.xlim(xmax = max(t)) plt.legend(('Impulse Response', 'Unit Step Response'), loc = 0) plt.grid() plt.show() # -- Plot of frequency response