示例#1
0
def fitness(MSDnum, MSDden, pop, times):
    """Calculates the fitness values of each member in pop[population]
    Also sets the simulation time in timesteps."""
    fit_val = []
    for s in range(len(pop)):
        #Create transfer functions for use by inputting current pop
        GAnum = [pop[s][0], pop[s][1], pop[s][2]]  # kd, kp, ki
        GAden = [0, 1, 0]
        GHs_num = signal.convolve(GAnum, MSDnum)
        GHs_den = signal.convolve(GAden, MSDden)
        #Create CLTF
        cltf_num = GHs_num
        cltf_den = GHs_den + GHs_num
        cltf = signal.TransferFunction(cltf_num, cltf_den)

        #create transfer function with no poles or zeros
        unityF = signal.TransferFunction([1], [1])
        # Step functions
        t1, y1 = signal.step(unityF, T=times)  #signal.step(errorsig)
        t2, y2 = signal.step(cltf, T=times)

        # This is a subtraction from the step function creating an
        # addition to the error value.
        err_vall = 0.0
        err_val = 0.0
        for o in range(len(times)):
            # repeats every s repetition
            err_vall = err_vall + abs(y1[o] - abs(y2[o]))
        err_val = err_vall * err_vall
        fit_val.insert(s, err_val)
    return fit_val
def f(x):
    controler = clt.TransferFunction([x[2], x[0], x[1]],[1,0])
    sys = clt.feedback(controler*H) #fechando a malha
    #Aplica degrau
    sys2 = sys.returnScipySignalLTI()[0][0]
    t2,y2 = step(sys2,N = dots)
    return abs(1-y2[-1]) #retorna o erro
 def plot_transfer_function(self, time_array_line_space, enable_ploting=False):
     time_array, output_array = signal.step(self.transfer_function_generator(), T=time_array_line_space)
     if enable_ploting:
         plt.figure(1)
         plt.plot(time_array, output_array, 'b--', linewidth=1, label='Transfer Fcn')
         # plt.show()
     return pd.Series(output_array, index=time_array, name='Predicted Model Response')
    def work(self, input_items, output_items):
        
        
        
      in0  = input_items[:1] 
      out0 = output_items[:1]
    
            # <+signal processing here+>
	#from multiorder_tf_sci import csim	
    #out[:self.n] = csim(self.param0,self.param1,self.param2,self.param3,self.param4,self.param5,self.param6,self.param7,self.param8,self.param9,self.param10,in0[:self.n].tolist()) 
        
	#print "OUT", out[:self.n]
	
	#self.consume(0,self.n)
	#self.produce(0,self.n)
      num = [self.param3] 
      den = [self.param7,self.param8,self.param9]
     
      tf = lti(num, den)
 
# get t = time, s = unit-step response
      #t, s = step(tf)
      out0[0:] = step(tf)
      self.consume(0,1);
      self.produce(0,1)
示例#5
0
文件: Example.py 项目: sivulich/Clase
    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()
示例#6
0
 def plot_step_response_to_axes(self, axes):
     legend = 'Step Response'
     n_points = 1000
     t, y = signal.step((self.num, self.den), N=n_points)
     axes.plot(t, y, label=legend)
     axes.set_xlabel(r'Time(seg)')
     axes.set_ylabel(r'V[Volts]')
示例#7
0
def plot_step(system, n=1000):
    t, y= signal.step(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="Step response")
    fig.show()
示例#8
0
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
示例#9
0
 def plot(self):
     G = signal.TransferFunction(3, (2,1))
     T, yout = signal.step(G)
     plt.figure(1)
     plt.plot(T,yout)
     plt.title('Step Response')
     plt.grid()
     plt.show()
示例#10
0
def reponse_capteur(entree):
    K = 250
    m = 0.35
    wn = 2000

    tf = signal.lti([entree * K], [(1 / (wn**2)), 2 * m / wn, 1])

    t, y = signal.step(tf)
    return t, y
示例#11
0
def reponse_capteur(entree):
    K=250
    m=0.35
    wn=2000

    tf=signal.lti([entree*K],[(1/(wn**2)),2*m/wn,1])
    
    t,y=signal.step(tf)
    return t,y
示例#12
0
def main():
    X = ModalAnalysis(0.999, 100)
    system = ([2.0], [1.0, 2.0, 1.0])
    #system = ([2.0,1.0],[1.0,2.0,1.0])
    ## impulse response test
    #t,h = impulse(system)
    #ls_result=X.fit_impulseresponse(h,t)
    #system_est = (ls_result['num'],ls_result['den'])
    #t1,h1 = impulse(system_est)
    #plt.plot(t,h,'rs',t1,h1,'bx')
    #plt.show()
    ## step response test
    t, h = step(system)
    ls_result = X.fit_stepresponse(h, t)
    system_est = (ls_result['num'], ls_result['den'])
    t1, h1 = step(system_est)
    plt.plot(t, h, 'rs', t1, h1, 'bx')
    plt.show()
def calc_tset(gain, tot_err, k, tvec):
    w0 = 2 * np.pi * 1e6
    w1 = w0 / gain
    w2 = w0 * k

    num = [gain]
    den = [1/(w1*w2), 1/w1 + 1/w2, gain + 1]
    _, yvec = sig.step((num, den), T=tvec)
    return get_tset(tvec, yvec, tot_err)
def plot_w1w2(Ra,La,Kg,K1,Km,N1,N2,J2,c,br,grid):
    # Pembuatan model transfer function
    A= [[(-Ra/La),(-Kg/La)],[Km/((N2/N1)**2 * J2),(-c+br)]]
    B= [[(K1/La)],[0]]
    C= [[0,1],[0,(N2/N1)]]
    D= [[0],[0]]
    sys1=signal.StateSpace(A,B,C,D)
    t1,y1=signal.step(sys1)
    plt.title("Plot $\\omega_1$ dan $\\omega_2$")
    plt.plot(t1,y1)
示例#15
0
 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 continous_time_step_response(A, B, C, D, plot=True):
    ss = sig.StateSpace(A, B, C, D)
    t, ys = sig.step(system=ss)

    if plot:
        for i in range(ys.shape[1]):
            plt.plot(t, ys[:, i])
            plt.title("Response Y" + str(i))
            plt.show()
    return (t, ys)
示例#17
0
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()
示例#18
0
def cal_step(param, t):
    ws, ls, wg, lg, sig2, gain = param
    num = [gain, 0.]
    den = [
        1., 2 * ls * ws + 2 * lg * wg,
        ws**2 + wg**2 + 4. * ls * ws * lg * wg * (1 - sig2),
        2 * ls * ws * wg**2 + 2 * lg * wg * ws**2, (ws**2) * (wg**2)
    ]
    _, steppulse = step((num, den), T=t)
    steppulse /= max(steppulse)
    return steppulse
示例#19
0
def plot_Seep_Response(pltfile, paz, sName, type):
    poles = paz['poles']
    zeros = paz['zeros']
    scale_fac = paz['gain'] * paz['seismometer_gain']
    from scipy import signal
    system = (zeros, poles, scale_fac)
    t, y = signal.step(system, N=10000)
    fStep = t[len(t) - 1] / len(y)
    y[0] = 0

    if (1000 <= type and type < 2000):
        for i in range(1, len(y)):
            y[i] = y[i - 1] + y[i] * fStep * 0.001  # 输出太大,按 0.001m/s**2 响应计算

    Ymax = max(y)
    Ymin = min(y)
    Tmax = Tmin = Tzero = 0
    index = 0
    for index in range(2, len(y)):
        if (y[index] >= Ymax and Tmax == 0):
            Tmax = index * fStep
        if (y[index] <= Ymin and Tmin == 0):
            Tmin = index * fStep
        if (y[index] * y[index - 1] <= 0 and Tzero == 0):
            Tzero = index * fStep
    if (1000 <= type and type < 2000):
        sInfo = '%s 地震计阶跃理论响应(等效激励=1mm/s**2)\n T=%.3fs:Vmax=%.3fV,  T=%.3fs:V=0,  T=%.3fs:Vmin=%.3fV' \
                % (sName, Tmax, Ymax, Tzero, Tmin, Ymin)
    elif (2000 <= type):
        sInfo = '%s 加速度计阶跃理论响应(等效激励=1m/s**2)' % (sName)
    else:
        sInfo = '仪器 %s 阶跃理论响应' % (sName)

    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12)
    fontTitle = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=18)
    plt.figure(figsize=(16, 12))
    plt.grid(linestyle=':')

    import datetime
    timestr = datetime.datetime.now().strftime('%Y-%m-%d')
    timestr = "Created by 泰德, " + timestr
    x0 = '                                                                    时间(s)                                          ' + timestr
    plt.xlabel(x0, fontproperties=font)
    plt.ylabel('幅度(V)', fontproperties=font)
    plt.suptitle(sInfo, fontproperties=fontTitle)
    plt.plot(t, y)

    # plt.text(1400,200,timestr,fontsize=12,xycoords='•axes pixels')
    # dict0 = dict[width:0,headwidth:0,headlength:0,shrink:0,facecolor:'white']
    # plt.annotate(s=timestr, xy=(1400,200), xytext=(0, 0),xycoords='•axes pixels',arrowprops=dict0)

    plt.savefig(pltfile)
    plt.close('all')
    return (Ymax, Ymin, Tmax, Tmin, Tzero)
def MotorControl():
    J = .01  # kgm**2
    b = .1  # N.m.s
    Ke = .01  # V/rad/sec
    Kt = .01  # N.m/Amp
    R = 1  # Electrical resistance
    L = .5  # Henries
    K = Kt  # or Ke, Ke == Kt here
    # State Space Model
    A = np.matrix([[-b / J, K / J], [-K / L, -R / L]])
    B = np.matrix([[0], [1 / L]])
    C = np.matrix([1, 0])
    D = np.matrix([0])
    dt = .025  # Discrete Sample Time

    ss = sig.StateSpace(A, B, C, D)
    ssd = sig.cont2discrete((A, B, C, D), dt)
    Ad = ssd[0]
    Bd = ssd[1]
    Cd = ssd[2]
    evc, evecc = np.linalg.eig(A)
    evd, evecd = np.linalg.eig(Ad)
    # Create Bode
    #w, mag, phase = sig.bode(ss)
    #plot_SISO(w,mag, "Freq Response Mag vs w")
    #plot_SISO(w, phase, "Freq Response Phase vs w")
    #discrete_time_frequency_repsonse()
    # Transfer Function
    tf = ss.to_tf()
    print(tf)
    t, y = sig.step(ss)
    td, yd = sig.dstep(ssd)
    yd = np.reshape(yd, -1)
    #plot_SISO(t,y)
    #plot_SISO(td, yd)
    #pole_zeros(A, B, C, plot=True)
    #pole_zeros(Ad, Bd, Cd, plot=True)
    T = 10
    N = T / dt
    times = np.arange(0, T, dt)
    U = np.ones(int(N))
    x0 = np.matrix([0, 0]).T
    xr = np.matrix([2.5, 0])
    kp = 15
    kd = 4
    ki = 100
    Q = Cd.T * Cd
    R = np.matrix([.0005])
    discrete_time_response(Ad, Bd, Cd, U, x0, dt, plot=True)
    discrete_time_frequency_repsonse(Ad, Bd, Cd, 20, dt)
    continous_time_frequency_repsonse(A, B, C)
    discrete_pid_response((Ad, Bd, Cd), x0, xr, times, kp, ki, kd)
    sim_dlqr(Ad, Bd, Cd, Q, R, x0, xr, dt, T)
    x = 9
 def simulated_validation_data(self, sample_time=0.1, step_time=10):
     time_array, output_array = signal.step(self.transfer_function_generator(),
                                            T=np.arange(0, step_time, sample_time))
     initial_condition_2 = np.arange(9501) * 0
     initial_condition = output_array * 0
     first_step_up = output_array
     second_step_down = first_step_up[-1] - output_array
     third_step_down = second_step_down[-1] - output_array
     four_step_up = third_step_down[-1] + output_array
     output = np.concatenate((initial_condition_2, initial_condition,
                              first_step_up, second_step_down, third_step_down, four_step_up))
     time = np.arange(0, 17001, sample_time)
     return time, output
示例#22
0
    def plot_step_response(self):
        # Calculating plot points
        self.t_step_res, self.step_response = ss.step(self.tf)

        # Plotting impulse response
        self.axes.clear()
        self.axes.plot(self.t_step_res, self.step_response)
        self.axes.grid(which='major')
        self.axes.grid(which='minor')
        self.axes.set_xlabel('Time (s)')
        self.axes.set_ylabel('Step Response (V)')

        self.canvas.draw()
示例#23
0
def plot_y(gain, f1, f2, t_targ, tot_err):
    n = 5000
    tvec = np.linspace(0, 5 * t_targ, n)
    num = [gain]
    den = [
        1 / (4 * np.pi**2 * f1 * f2), (1 / f1 + 1 / f2) / 2 / np.pi, gain + 1
    ]
    _, yvec = sig.step((num, den), T=tvec)

    plt.figure(1)
    plt.plot(tvec, yvec, 'b')
    plt.plot(tvec, [1 - tot_err] * n, 'r')
    plt.plot(tvec, [1 + tot_err] * n, 'r')
    plt.show()
示例#24
0
    def step_response(self):
        """Computing and plotting STEP response of the filter."""
        (T, yout) = signal.step((self.b, self.a))

        #Plotting step response
        pyplot.figure()
        try:
            pyplot.plot(T, yout)
        except ComplexWarning:
            pass
        pyplot.grid(True)
        pyplot.xlabel('Time')
        pyplot.xlim(min(T), max(T))
        pyplot.title('Impulse response' + "\n" + str(self.ord) + "th order " + self.btype + " " + self.ftype_plot + " filter")
示例#25
0
 def stepplot(self):
      K = self.gain.value()
      tau = self.tau.value()
      sys = signal.TransferFunction([K],[tau,1])
      T, yout = signal.step(sys)
      self.ax.clear()
      self.ax.plot(T,yout)
      self.canvas.draw()
      self.toolbar
      if self.navTools.isChecked():
          self.verticalLayout.addWidget(self.toolbar)
      else:
          self.verticalLayout.removeWidget(self.toolbar)
      print(self.navTools.isChecked())
示例#26
0
    def step_response(self):
        """Computing and plotting STEP response of the filter."""
        (T, yout) = signal.step((self.b, self.a))

        #Plotting step response
        pyplot.figure()
        try:
            pyplot.plot(T, yout)
        except ComplexWarning:
            pass
        pyplot.grid(True)
        pyplot.xlabel('Time')
        pyplot.xlim(min(T), max(T))
        pyplot.title('Impulse response' + "\n" + str(self.ord) + "th order " +
                     self.btype + " " + self.ftype_plot + " filter")
示例#27
0
def get_cal_resp(fA0, fFreq, fFactor):
    omiga = fFreq * 2 * math.pi
    a = -fFactor * omiga
    b = math.sqrt(1 - fFactor * fFactor) * omiga
    poles = [complex(a, b), complex(a, -b)]
    zeros = [complex(0, 0), complex(0, 0)]
    scale_fac = fA0
    from scipy import signal
    system = (zeros, poles, scale_fac)
    t, y = signal.step(system, N=10000)
    fStep = t[len(t) - 1] / len(y)
    y[0] = 0
    for i in range(1, len(y)):
        y[i] = y[i - 1] + y[i] * fStep
    return (t, y)
示例#28
0
    def plot_step(self, ylabel=None, figsize=None):
        t, y = signal.step((self.num, self.den))

        n_zeros = int(t.size * 0.1)
        T = t[1]

        r = np.concatenate((np.zeros(n_zeros), np.ones(t.size)))
        t = np.concatenate(((np.arange(n_zeros) - n_zeros) * T, t))
        y = np.concatenate((np.zeros(n_zeros), y))

        plt.figure(figsize=figsize)
        plt.plot(t, r)
        plt.plot(t, y)
        plt.xlabel('Time [in s]')
        plt.ylabel(ylabel if ylabel is not None else "Amplitude")
        plt.tight_layout()
示例#29
0
 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 get_performance_indicators_pid(self, kp: float, ki: float,
                                       kd: float) -> IndicatorPID:
        # Get lti function about pid
        tf = self.get_lti_by_pid(kp=kp, ki=ki, kd=kd)

        # Analisy signal response a step signal
        t, y = signal.step(tf)

        # Get a time to setpoint
        time_to_setpoint = 0
        for i in range(0, len(y)):
            if y[i] >= 1.0 and y[i - 1] < 1.0:
                time_to_setpoint = t[i]
                break

        return IndicatorPID(overpoint=y.max(),
                            time_to_setpoint=time_to_setpoint)
def run_main():
    interp_method = 'spline'
    sim_env = 'tt'
    nmos_spec = 'specs_mos_char/nch_w0d5.yaml'
    pmos_spec = 'specs_mos_char/pch_w0d5.yaml'
    intent = 'lvt'

    nch_db = get_db(nmos_spec, intent, interp_method=interp_method,
                    sim_env=sim_env)

    nch_op = nch_db.query(vbs=0, vds=0.5, vgs=0.5)

    pprint.pprint(nch_op)
    # building circuit
    cir = LTICircuit()
    cir.add_transistor(nch_op, 'out', 'in', 'gnd', 'gnd', fg=2)
    cir.add_res(10e3, 'out', 'gnd')
    cir.add_cap(100e-15, 'out', 'gnd')

    # get gain/poles/zeros/bode plot
    trans_fun = cir.get_transfer_function('in', 'out', in_type='v')
    print('poles: %s' % trans_fun.poles)
    print('zeros: %s' % trans_fun.zeros)
    # note: don't use the gain attribute.  For some reason it's broken
    print('gain: %.4g' % (trans_fun.num[-1] / trans_fun.den[-1]))
    fvec = np.logspace(5, 10, 1000)
    _, mag, phase = sig.bode(trans_fun, w=2 * np.pi * fvec)
    
    # get transient response
    state_space = cir.get_state_space('in', 'out', in_type='v')
    tvec = np.linspace(0, 1e-8, 1000)
    _, yvec = sig.step(state_space, T=tvec)
    
    _, (ax0, ax1) = plt.subplots(2, sharex=True)
    ax0.semilogx(fvec, mag)
    ax0.set_ylabel('Magnitude (dB)')
    ax1.semilogx(fvec, phase)
    ax1.set_ylabel('Phase (degrees)')
    ax1.set_xlabel('Frequency (Hz)')

    plt.figure(2)
    plt.plot(tvec, yvec)
    plt.ylabel('Output (V/V)')
    plt.xlabel('Time (s)')

    plt.show()
def step_response(sys,sysd,Ts): #Draw the step response for the continuous-time and discrete-time systems
    sysnum = asarray(sys.num)[0][0]
    sysden = asarray(sys.den)[0][0]
    sysdnum = asarray(sysd.num)[0][0]
    sysdden = asarray(sysd.den)[0][0]
    x = arange(0,100,0.1)
    syslti = signal.lti(sysnum,sysden)
    sysdlti = signal.lti(sysdnum,sysdden)
    t,s = signal.step(syslti,T=x)
    t2,s2 = signal.dstep((sysdnum,sysdden,Ts),t=x)
    ax = plt.subplot(3,2,4)
    plt.plot(t, s,color='blue',label='Continuous-time')
    plt.plot(t2, s2[0],color='red',label='Discrete-time')
    plt.title('Step response')
    plt.xlabel('Time [sec]')
    plt.ylabel('Amplitude')
    plt.tight_layout(w_pad = 3.0)
    plt.show()
 def animate(i): 
     k = trange[0]+i*step
     a1, b1 = system.as_numer_denom()
     G = a1.subs(T,k)/b1.subs(T,k)
     a1 = toPoly(a1)
     b1 = toPoly(b1)
     s1 = signal.lti(a1,b1)
     w, mag, phase = s1.bode(w=freqrange)
     
     line_gain.set_data(w, mag)
     line_phase.set_data(w, phase)
     line_gain.set_label("T={0}".format(k))
     line_step.set_data(signal.step(s1))
     legend = ax_gain.legend(loc='upper center', shadow=True)
     
     for axis in [ax_gain,ax_phase,ax_pz,ax_step]:
         axis.relim()                      # reset intern limits of the current axes 
         axis.autoscale_view()   # reset axes limits 
示例#34
0
    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()
示例#35
0
def cavity_tf(RoverQ, Qg, Q0, Qprobe, bw, Kg_r, Kg_i, Ib,
           foffset):

        Rg = RoverQ * Qg
        Kdrive = 2 * np.sqrt(Rg)
        Ql = 1.0 / (1.0/Qg + 1.0/Q0 + 1.0/Qprobe)
        K_beam = RoverQ * Ql
        w_d = 2 * np.pi * foffset

        a = Kdrive * bw
        b = K_beam * bw
        c = bw

	num = a/c
	den = [1.0/c,1.0]
	sys = signal.TransferFunction(num,den)
	t, y = signal.step(sys) 

        return t, y
示例#36
0
    def __init__(self, xinit, yinit, veloc, ang, direction):
        """
        Inicjalizacja. Podajemy wspolrzedne srodka, predkosc poczatkowa i kat. Kat nie musi byc dokladny, byle tylko pokazywal mniej
        wiecej, w ktora strone jedziemy.
        :param xinit: wspolrzedna x srodka
        :param yinit: wspolrzedna y srodka
        :param veloc: predkosc poczatkowa
        :param ang: kat
        :param direction: kierunek ruchu
        """
        threading.Thread.__init__(self)
        self.licznik = t.time()
        self.hamuj = False
        self.ruszaj = False
        self.dir = direction
        numR = 0.5869 * 5.1
        denR = [8.4184, 5.00, 3.000]
        tfR = lti(numR, denR)
        self.czas = 5.
        self.maxVel = veloc
        self.kalmen = kalmen.kalmenFilter()
        tR, stepR = step(tfR, T = linspace(0, self.czas, self.czas*100))
        self.model = {}
        self.modelRev = {}
        for i in range(tR.__len__()):
            time = round(100*tR[i])/100
            val = round(1000*stepR[i])/1000
            self.model[ time ] = val
            self.modelRev[ val ] = time

        czasHalf = self.czas/2.
        self.model [czasHalf] = (self.model [czasHalf - 0.01] + self.model [czasHalf + 0.01])/2

        self.time = 0
        self.czaz = t.time()
        self.brakingVel = 0
        self.x = xinit
        self.y = yinit
        self.angle = math.pi*ang/180
        self.velocity = 0
def analysis(system,symbol,trange,s):
    ############################# startint value #####################################3
    G = system.subs(symbol,1)

    freqrange =[1e-1,1e2]

    a1, b1 = G.as_numer_denom()
    #print a1, b1
    a1 = toPoly(a1)
    b1 = toPoly(b1)
    s1 = signal.lti(a1, b1)
    w, mag, phase = s1.bode(w=freqrange)

    ###################    PLOT   ############################3
    fig = plt.figure()

    ax_gain  = fig.add_subplot(3, 1, 1)
    ax_phase = fig.add_subplot(3, 1, 2)
    ax_step  = fig.add_subplot(3, 2, 5)
    ax_pz    = fig.add_subplot(3, 2, 6)

    ###################     GAIN     ######################################

    ax_gain.set_xlabel('w')
    ax_gain.set_ylabel('gain')

    line_gain = Line2D([], [], color='black',label="...")

    ax_gain.add_line(line_gain)
    ax_gain.semilogx(w,mag)
    ax_gain.set_ylim([-30,10])
    ax_gain.set_xlim(freqrange)

    #####################    PHASE    ##########################
    ax_phase.set_xlabel('omega')
    ax_phase.set_ylabel('theta')

    line_phase = Line2D([], [], color='black')

    ax_phase.add_line(line_phase)

    ax_phase.semilogx(w, phase)  # Bode phase plot
    ax_phase.set_ylim([-180,180])
    ax_phase.set_xlim(freqrange)

    legend = ax_gain.legend(loc='upper center', shadow=True)

    #####################   step  ##################################
    ax_step.set_xlabel('t')
    ax_step.set_ylabel('Y')

    line_step = Line2D([], [], color='black')

    ax_step.add_line(line_step)

    t, response = signal.step(s1)

    ax_step.plot(t, response)  # Bode phase plot
    #ax_phase.set_ylim([-180,180])
    #ax_phase.set_xlim(freqrange)
    #########################   zeros, poles #######################################



    a1, b1 = G.as_numer_denom()
    z, p = roots(a1,s), roots(b1,s)
    #print z.keys(), p.keys()
    z, p = np.array(z.keys(),dtype=np.complex64), np.array(p.keys(), dtype=np.complex64)


    # Add unit circle and zero axes    
    unit_circle = mpatches.Circle((0,0), radius=1, fill=False,
                                 color='black', ls='solid', alpha=0.1)
    ax_pz.add_patch(unit_circle)
    ax_pz.axvline(0, color='0.7')
    ax_pz.axhline(0, color='0.7')

    # Plot the poles and set marker properties
    poles = ax_pz.plot(p.real, p.imag, 'x', markersize=9, alpha=0.5)

    # Plot the zeros and set marker properties
    zeros = ax_pz.plot(z.real, z.imag,  'o', markersize=9, 
             color='red', alpha=0.5,
             #markeredgecolor=poles[0].get_color(), # same color as poles
             )

    # Scale axes to fit
    r = 1.5 * np.amax(np.concatenate((abs(z), abs(p), [1])))
    ax_pz.axis('scaled')
    ax_pz.axis([-r, r, -r, r])
    #    ticks = [-1, -.5, .5, 1]
    #    plt.xticks(ticks)


    ############################################################################


    # initialization function: plot the background of each frame

    # animation function.  This is called sequentially
    step = (trange[1]-trange[0])/10.0
    #print step
    
    def animate(i): 
        k = trange[0]+i*step
        a1, b1 = system.as_numer_denom()
        G = a1.subs(T,k)/b1.subs(T,k)
        a1 = toPoly(a1)
        b1 = toPoly(b1)
        s1 = signal.lti(a1,b1)
        w, mag, phase = s1.bode(w=freqrange)
        
        line_gain.set_data(w, mag)
        line_phase.set_data(w, phase)
        line_gain.set_label("T={0}".format(k))
        line_step.set_data(signal.step(s1))
        legend = ax_gain.legend(loc='upper center', shadow=True)
        
        for axis in [ax_gain,ax_phase,ax_pz,ax_step]:
            axis.relim()                      # reset intern limits of the current axes 
            axis.autoscale_view()   # reset axes limits 

    # call the animator.  blit=True means only re-draw the parts that have changed.
    anim = animation.FuncAnimation(fig, animate, frames=10, interval=50, blit=True)

    # call our new function to display the animatio1
    display_animation(anim)
示例#38
0
 def time_step(self):
     signal.step(self.system, T=self.t)
示例#39
0
def stepResponse(system):
    """Computes the step response for a given system"""
    c1,c2,r1,r2 = system
    num = 1 / (c1*c2*r1*r2)
    den = (1, (r1+r2)/(c1*r1*r2), 1/(c1*c2*r1*r2))
    return sig.step((num,den))
示例#40
0
 
# making transfer function
# example from Ogata Modern Control Engineering 
# 4th edition, International Edition page 307
 
# num and den, can be list or numpy array type
#num = [6.3223, 18, 12.811] 
#den = [1, 6, 11.3223, 18, 12.811]

num = [11] 
den = [1,10,11]
 
tf = lti(num, den)
 
# get t = time, s = unit-step response
t, s = step(tf)

 
# recalculate t and s to get smooth plot
t, s = step(tf, T = linspace(min(t), t[-1], 500))

print "Time",t
print "YEs",s
 
# get i = impulse
#t, i = impulse(tf, T = linspace(min(t), t[-1], 500))
 
from matplotlib import pyplot as plt
 
plt.plot(t, s)
plt.title('Transient-Response Analysis')
示例#41
0
 def test_complex_input(self):
     # Test that complex input doesn't raise an error.
     # `step` doesn't seem to have been designed for complex input, but this
     # works and may be used, so add regression test.  See gh-2654.
     step(([], [-1], 1+0j))
示例#42
0
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.step(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()

from pylab import *     #importation de pylab pour les graphiques
from numpy import *
from scipy.signal import lti,step

m=0.5
wn=1
K=5

tf=lti([K],[(1/(wn**2)),2*m/wn,1])
t,y=step(tf)

fig=figure()
fig.patch.set_alpha(0.0)

plot(t,y)
xlabel("temps(s)")
ylabel("sortie")
plot([0,14],[K,K],'--',color="k")
text(11, K+0.05, 'Valeur finale')
show()
示例#44
0
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

w, H = freqresp(sys)
示例#45
0
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)
示例#46
0
from pylab import *     #importation de pylab pour les graphiques
from numpy import *
from scipy import signal

m=0.5
m_vect=[0.5,0.7,1,1.3,1.6]
wn=10
K=1


for m in m_vect:

    tf=signal.lti([K],[(1/(wn**2)),2*m/wn,1])
    t,y=signal.step(tf)


    #affichage de la RI
    plot(t,y,label="m=%f" %m)

    #calcul de la valeur finale
    vf=y[-1]
    vect_tr=where((y>1.05*vf)|(y<0.95*vf))[0] #Identification des éléments pour lesquelles la réponse indicielle est
    index_tr=vect_tr[-1]                        #Récupération du dernier élément du vecteur
    tr=t[index_tr]

    #calcul du dépassement relatif
    Dr=100*(max(y)-vf)/vf

    print("---------m=%f--------" % m)
    print("Valeur finale:\t %f" % vf)
    print("Temps de réponse: %f" % tr)