def main():
    dt = 0.0001
    T = np.arange(0, 0.25, dt)

    # Make plant
    J = 3.2284e-6  # kg-m^2
    b = 3.5077e-6  # N-m-s
    Ke = 0.0274  # V/rad/s
    Kt = 0.0274  # N-m/Amp
    K = Ke  # Ke = Kt
    R = 4  # Ohms
    L = 2.75e-6  # H

    # Unstable plant
    # s((Js + b)(Ls + R) + K^2)
    # s(JLs^2 + JRs + bLs + bR + K^2)
    # JLs^3 + JRs^2 + bLs^2 + bRs + K^2s
    # JLs^3 + (JR + bL)s^2 + (bR + K^2)s
    G = cnt.TransferFunction(K, [J * L, J * R + b * L, b * R + K**2, 0])
    cnt.root_locus(G, grid=True)
    plt.xlabel("Real Axis (seconds$^{-1}$)")
    plt.ylabel("Imaginary Axis (seconds$^{-1}$)")
    if "--noninteractive" in sys.argv:
        latexutils.savefig("highfreq_unstable_rlocus")

    plt.figure(2)
    plt.xlabel("Time ($s$)")
    plt.ylabel("Position ($m$)")
    sim(cnt.TransferFunction(1, 1), T, "Reference")
    Gcl = make_closed_loop_plant(G, 3)
    sim(Gcl, T, "Step response")
    if "--noninteractive" in sys.argv:
        latexutils.savefig("highfreq_unstable_step")
    else:
        plt.show()
Пример #2
0
    def test_rlocus_default_wn(self):
        """Check that default wn calculation works properly"""
        #
        # System that triggers use of y-axis as basis for wn (for coverage)
        #
        # This system generates a root locus plot that used to cause the
        # creation (and subsequent deletion) of a large number of natural
        # frequency contours within the `_default_wn` function in `rlocus.py`.
        # This unit test makes sure that is fixed by generating a test case
        # that will take a long time to do the calculation (minutes).
        #
        import scipy as sp
        import signal

        # Define a system that exhibits this behavior
        sys = ct.tf(*sp.signal.zpk2tf(
            [-1e-2, 1-1e7j, 1+1e7j], [0, -1e7j, 1e7j], 1))

        # Set up a timer to catch execution time
        def signal_handler(signum, frame):
            raise Exception("rlocus took too long to complete")
        signal.signal(signal.SIGALRM, signal_handler)

        # Run the command and reset the alarm
        signal.alarm(2)         # 2 second timeout
        ct.root_locus(sys)
        signal.alarm(0)         # reset the alarm
Пример #3
0
def main():
    dt = 0.0001
    T = np.arange(0, 0.25, dt)

    # Make plant
    J = 3.2284e-6  # kg-m^2
    b = 3.5077e-6  # N-m-s
    Ke = 0.0181  # V/rad/s
    Kt = 0.0181  # N-m/Amp
    K = Ke  # Ke = Kt
    R = 0.0902  # Ohms
    L = 230e-6  # H

    # Stable plant (L = 0)
    # s((Js + b)R + K^2)
    # s(JRs + bR + K^2)
    # JRs^2 + bRs + K^2s
    # JRs^2 + (bR + K^2)s
    G = ct.TransferFunction(K, [J * R, b * R + K**2, 0])
    ct.root_locus(G, grid=True)
    plt.xlabel("Real Axis (seconds$^{-1}$)")
    plt.ylabel("Imaginary Axis (seconds$^{-1}$)")
    if "--noninteractive" in sys.argv:
        latex.savefig("highfreq_stable_rlocus")

    plt.figure(2)
    plt.xlabel("Time ($s$)")
    plt.ylabel("Position ($m$)")
    sim(ct.TransferFunction(1, 1), T, "Reference")
    Gcl = make_closed_loop_plant(G, 1)
    sim(Gcl, T, "Step response")
    if "--noninteractive" in sys.argv:
        latex.savefig("highfreq_stable_step")
    else:
        plt.show()
def root_locus_design(sys):
    """return root locus."""
    pyplot.style.use('fivethirtyeight')
    root_locus(sys)
    damping_ratio = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

    for i in damping_ratio:
        x = [-100, 0]
        phi = arccos(i)
        y_pos = [100 * tan(phi), 0]
        y_neg = [-100 * tan(phi), 0]
        pyplot.plot(x, y_pos, 'k--', linewidth=1)
        pyplot.plot(x, y_neg, 'k--', linewidth=1)
Пример #5
0
def main():
    #          1
    # G(s) = -----
    #        s - 1
    G = cnt.tf([1], [1, -1])
    cnt.root_locus(G, grid=True)

    plt.title("Root Locus")
    plt.xlabel("Real Axis (seconds$^{-1}$)")
    plt.ylabel("Imaginary Axis (seconds$^{-1}$)")
    if "--noninteractive" in sys.argv:
        latexutils.savefig("rlocus_infty")
    else:
        plt.show()
def main():
    #              1
    # G(s) = --------------
    #        (s + 2)(s + 3)
    G = ct.tf(1, conv([1, 0], [1, 2], [1, 3]))
    ct.root_locus(G, grid=True)

    plt.title("Root Locus")
    plt.xlabel("Real Axis (seconds$^{-1}$)")
    plt.ylabel("Imaginary Axis (seconds$^{-1}$)")
    if "--noninteractive" in sys.argv:
        latex.savefig("rlocus_asymptotes")
    else:
        plt.show()
def analyze_sys(sys,H):
    Go = sys*H
    Gc = control.feedback(Go)
    control.root_locus(Go)
    
    plt.figure()
    plt.title('system')
    t1,x1 = control.step_response(sys)
    plt.plot(t1,x1)
    
    plt.figure()
    plt.title('controlled system w/ step response')
    t2,x2 = control.step_response(Gc)
    print(x2)
    plt.plot(t2,x2)
Пример #8
0
 def plot(self, type, entry1, entry2):
     transfer_function = self.get_TF(entry1, entry2)
     if type == "bode":
         co.bode_plot(transfer_function)
     elif type == "nyquist":
         co.nyquist(transfer_function)
     elif type == "rootlocus":
         co.root_locus(transfer_function)
     else:
         [t1, y1] = self.plot_type(type, transfer_function)
         plt.plot(t1, y1)
         plt.xlabel('Time(s)')
         plt.ylabel('Amplitude')
         plt.grid()
     plt.show()
Пример #9
0
 def PI_RootLocusMultiple(self):
     self.SM = SpringMassVis(l=1.0, k=40.0, b=8.80)  #cm
     self.C = PIDController(t=0.01, P=50, I=100)
     self.C.sysOpenCE(self.SM.CE)
     self.C.sysClosedCE()
     f, axx = plt.subplots(1, 1)
     self.C.sysRecomp(I=100)
     out = control.root_locus(self.C.sysOCE / self.C.I, Plot=False)
     self.C.plotRootLocus(out, axx, 'x')
     self.C.sysRecomp(I=500)
     out = control.root_locus(self.C.sysOCE / self.C.I, Plot=False)
     self.C.plotRootLocus(out, axx, ':')
     self.C.sysRecomp(I=2000)
     out = control.root_locus(self.C.sysOCE / self.C.I, Plot=False)
     self.C.plotRootLocus(out, axx, '--')
Пример #10
0
 def PI_RootLocusMultiple(self):
     self.P = PendulumVis(l=1.0, m=1.0, b=0.001, g=9.8)
     self.C = PIDController(t=0.01, P=500, I=100)
     self.C.sysOpenCE(self.P.CE)
     self.C.sysClosedCE()
     f, axx = plt.subplots(1, 1)
     self.C.sysRecomp(I=100)
     out = control.root_locus(self.C.sysOCE / self.C.I, Plot=False)
     self.C.plotRootLocus(out, axx, 'x')
     self.C.sysRecomp(I=500)
     out = control.root_locus(self.C.sysOCE / self.C.I, Plot=False)
     self.C.plotRootLocus(out, axx, ':')
     self.C.sysRecomp(I=2000)
     out = control.root_locus(self.C.sysOCE / self.C.I, Plot=False)
     self.C.plotRootLocus(out, axx, '--')
Пример #11
0
    def LoadModelTriggered(self, q):

        options = QFileDialog.Options()
        filename, _ = QFileDialog.getOpenFileName(
            self,
            "Select linearized model file:",
            "U:/Loads/i115_gl2012_2B12_IC/Linearization/LinMod/",
            "Matlab Files (*.mat)",
            options=options)
        azimuth_index = 0
        wtg = WTG(filename, azimuth_index)
        kvect = np.linspace(0, 2e10, 1000)

        start = time.time()
        rlist, klist = ctrl.root_locus(wtg.T_G_1, kvect, Plot=False)
        omega_vect = np.logspace(-2, 2, 1000)
        mag, phase, omega = ctrl.bode(wtg.T_G_1, omega_vect, Plot=False)
        magdb = 20 * np.log10(mag)
        phasedeg = phase * 180 / np.pi
        omegahz = omega / 2 / np.pi
        self.frame_plot_1_2.plot_bode(phase, magdb, omegahz)
        self.frame_plot_2_1.plot_bode(phase, magdb, omegahz)
        self.frame_plot_2_2.plot_bode(phase, magdb, omegahz)

        for ii in range(0, rlist.shape[1]):
            locs = rlist[:, ii]
            x = locs.real
            y = locs.imag
            self.frame_plot_1_1.plot_rlocus.plot(
                x, y, pen=pg.mkPen('k', width=1, style=QtCore.Qt.SolidLine))

        plt.show()
        end = time.time()
        print(end - start)
        print('done')
Пример #12
0
def main():
    #        (s - 9 + 9i)(s - 9 - 9i)
    # G(s) = ------------------------
    #               s(s + 10)
    G = cnt.tf(conv([1, -9 + 9j], [1, -9 - 9j]), conv([1, 0], [1, 10]))
    cnt.root_locus(G, grid=True)

    # Show plot
    plt.title("Root Locus")
    plt.xlabel("Real Axis (seconds$^{-1}$)")
    plt.ylabel("Imaginary Axis (seconds$^{-1}$)")
    plt.gca().set_aspect("equal")
    if "--noninteractive" in sys.argv:
        latexutils.savefig("rlocus_zeroes")
    else:
        plt.show()
Пример #13
0
def my_rlocus(G, k):
    rmat, kout = control.root_locus(G, k, Plot=False)
    plot(real(rmat), imag(rmat))
    poles = G.pole()
    plot(real(poles), imag(poles), 'x')
    zeros = G.zero()
    if zeros:
        plot(real(zeros), imag(zeros), 'o')
Пример #14
0
def my_rlocus(G, k):
    rmat, kout = control.root_locus(G, k, Plot=False)
    plot(real(rmat), imag(rmat))
    poles = G.pole()
    plot(real(poles), imag(poles), 'x')
    zeros = G.zero()
    if zeros:
        plot(real(zeros), imag(zeros), 'o')
Пример #15
0
    def plot_rlocus(self, fig):
        tf = self.tf if self.loop_type == 'ol' else self.tf_plant * self.tf_comp

        fig.clf()
        ax = fig.add_subplot(1, 1, 1)

        klist = np.linspace(500.0, 0, num=1000)
        rlist, _ = control.root_locus(tf, kvect=klist, Plot=False)

        rlist = np.vstack(rlist)

        poles = np.array(control.pole(tf))
        ax.plot(np.real(poles), np.imag(poles), 'x')

        zeros = np.array(control.zero(tf))
        if zeros.size > 0:
            ax.plot(np.real(zeros), np.imag(zeros), 'o')

        ax.plot(np.real(rlist), np.imag(rlist))

        ax.axhline(0., linestyle=':', color='k', zorder=-20)
        ax.axvline(0., linestyle=':', color='k')

        ax.set_xlabel('Real axis')
        ax.set_ylabel('Imaginary axis')

        if not self.settings.is_rlocus_default():
            zeta = self.settings.get_rlocus_zeta()
            wn = self.settings.get_rlocus_omega()

            x0 = -np.arccos(zeta) * wn if wn else ax.get_xlim()[0]
            xt = np.arange(x0, 0, 0.01)
            ax.plot(xt,
                    -np.arccos(zeta) * xt,
                    '--',
                    linewidth=0.5,
                    color='black')
            ax.plot(xt,
                    np.arccos(zeta) * xt,
                    '--',
                    linewidth=0.5,
                    color='black')

            x = np.arange(0, wn + 0.01, 0.01)
            y = np.sqrt(wn**2 - x**2)
            x = -np.concatenate([x, x[::-1]])
            y = np.concatenate([y, -y[::-1]])
            ax.plot(x, y, '--', linewidth=0.5, color='black')

            xmin = self.settings.get_rlocus_xmin()
            xmax = self.settings.get_rlocus_xmax()
            ymin = self.settings.get_rlocus_ymin()
            ymax = self.settings.get_rlocus_ymax()
            ax.set_xlim(xmin, xmax)
            ax.set_ylim(ymin, ymax)

        return fig
Пример #16
0
 def PID_RootLocusMultiple(self):
     self.SM = SpringMassVis(l=1.0, k=40.0, b=8.80)  #cm
     self.C = PIDController(t=0.01, P=50, I=0, D=25.6)
     self.C.sysOpenCE(self.SM.CE)
     self.C.sysClosedCE()
     f, axx = plt.subplots(1, 1)
     self.C.sysRecomp(P=15, I=50, D=1)
     out = control.root_locus(self.C.sysCCE / self.C.D, Plot=False)
     self.C.plotRootLocus(out, axx, 'x')
Пример #17
0
    def test_rlocus_default_wn(self):
        """Check that default wn calculation works properly"""
        #
        # System that triggers use of y-axis as basis for wn (for coverage)
        #
        # This system generates a root locus plot that used to cause the
        # creation (and subsequent deletion) of a large number of natural
        # frequency contours within the `_default_wn` function in `rlocus.py`.
        # This unit test makes sure that is fixed by generating a test case
        # that will take a long time to do the calculation (minutes).
        #
        import scipy as sp
        import signal

        # Define a system that exhibits this behavior
        sys = ct.tf(*sp.signal.zpk2tf([-1e-2, 1 - 1e7j, 1 +
                                       1e7j], [0, -1e7j, 1e7j], 1))

        ct.root_locus(sys)
Пример #18
0
    def draw_root_locus(self):
        co.root_locus(co.feedback(0.00001 * self.process * self.pid),
                      Plot=True,
                      grid=False)

        st = -self.sigma + self.wp * 1j
        poles_and_zeros = np.append(np.append(self.zeros, self.poles),
                                    [st, np.conj(st)])
        ymin = np.min(np.imag(poles_and_zeros)) - 2
        ymax = np.max(np.imag(poles_and_zeros)) + 2
        xmin = np.min(np.real(poles_and_zeros)) - 2
        xmax = np.max(np.real(poles_and_zeros)) + 2
        plt.ylim(ymin, ymax)
        plt.xlim(xmin, xmax)

        for root in co.pole(self.closed_loop):
            plt.plot(np.real(root), np.imag(root), color='red', marker='*')
            plt.text(np.real(root) + 0.1,
                     np.imag(root) + (ymax - ymin) / 20 *
                     (1 if np.imag(root) > 0 else -1),
                     f'{root:.2f}',
                     color='red')

        x = np.real(st)
        y = np.imag(st)
        plt.fill_between([0, xmax * 1.1],
                         ymin * 1.1,
                         ymax * 1.1,
                         color='red',
                         alpha=0.1)
        plt.fill_between([xmin * 1.1, 0],
                         ymax * 1.1, [-self.tan_phi * xmin * 1.1, 0],
                         color='red',
                         alpha=0.1)
        plt.fill_between([xmin * 1.1, 0], [self.tan_phi * xmin * 1.1, 0],
                         ymin * 1.1,
                         color='red',
                         alpha=0.1)
        plt.fill_between([x, 0], [y, 0], [-y, 0], color='red', alpha=0.1)

        plt.grid()
        plt.show()
Пример #19
0
def root_locus_plot(G, k=None, xlim=None, ylim=None, fmtstr='-'):
    rmat, kout = control.root_locus(G, k, plot=False)
    plot(real(rmat), imag(rmat), fmtstr)
    poles = G.pole()
    plot(real(poles), imag(poles), 'x')
    zeros = G.zero()
    if len(zeros) > 0:
        plot(real(zeros), imag(zeros), 'o')
    if xlim is not None:
        plt.xlim(xlim)
    if ylim is not None:
        plt.ylim(ylim)
Пример #20
0
def plot_root_locus(g: Union[sp.Expr, ct.TransferFunction], ki: float = 0, kf: float = 5e3,
                    points: int = 500, k_space: str = "lin", print_critical: bool = False,
                    critical_tolerance: float = 0.01) -> plt.Line2D:
    """
    Plot a medium fidelity Root Locus of your G, K and H transfer functions
    :param g: Your plant transfer function
    :param ki: Gain range start (default: 0)
    :param kf: Gain range end (default: 5000)
    :param points: Fine Grain or measured points of your Gain range (default: 500)
    :param k_space: Your kind of space generated for your Gain range
    :param print_critical: If you want to print Critical Gain (pass for imag axis)
    :param critical_tolerance: The minimal threshold distance to imag axis
    :return: A Plot Line2D object, ready to show
    """
    # s = sp.var("s")

    if isinstance(g, ct.TransferFunction):
        sys = g
    else:
        sys = core.symbolic_transfer_function(g)

    # plt.title(f"Root locus of $G={sp.latex(g)}$", fontsize='x-large')
    plt.xlabel("$Real\\ Axis\\ [s^{-1}]$")
    plt.ylabel("$Imaginary\\ Axis\\ [s^{-1}]$")

    if k_space == "lin":
        range_space = np.linspace(ki, kf, points)
    elif k_space == "log":
        range_space = np.logspace(ki, kf, points)
    else:
        raise BaseException("invalid space, use \"lin\" o \"log\"")

    paths, gains = ct.root_locus(sys, kvect=range_space, Plot=False)

    for i, gain in enumerate(gains):
        points = paths[i]
        for point in points:
            if print_critical and abs(point.real) < critical_tolerance:
                print("Critical gain K = %.3f at %.3f + %.3fi" % (gain, point.real, point.imag))

    plt.axvline(0, color='k')
    plt.axhline(0, color='k')
    plt.grid()

    plt.plot(np.real(paths), np.imag(paths))

    n_poles = sys.pole()
    n_zeros = sys.zero()

    plt.plot(np.real(n_poles), np.imag(n_poles), "kx")

    return plt.plot(np.real(n_zeros), np.imag(n_zeros), "ko")
Пример #21
0
    def P_Bode(self):
        s = control.tf([1, 0], [1])
        CE = 1 / (s**2 + 8.8 * s + 40)
        P = control.tf([1], [1])
        OL = P * CE
        CL = control.feedback(OL, 1, sign=-1)
        control.root_locus(CL, Plot=True)
        plt.figure()
        P = control.tf([100], [1])
        OL1 = P * CE
        CL1 = control.feedback(OL1, 1, sign=-1)
        P = control.tf([500], [1])
        OL2 = P * CE
        CL2 = control.feedback(OL2, 1, sign=-1)
        P = control.tf([2000], [1])
        OL3 = P * CE
        CL3 = control.feedback(OL3, 1, sign=-1)
        print("Closed Loop")
        print([CL1, CL2, CL3])
        control.bode_plot([OL1, OL2, OL3], Plot=True)

        print(CL)
Пример #22
0
def plot():
    numerator_tf_arg = numerator.get().split(" ")
    denominator_tf_arg = denominator.get().split(" ")

    numerator_tf_arg = [float(zeroes) for zeroes in numerator_tf_arg]
    denominator_tf_arg = [float(poles) for poles in denominator_tf_arg]
    rlist, klist = control.root_locus(control.TransferFunction(
        numerator_tf_arg, denominator_tf_arg),
                                      kvect=np.linspace(100.0,
                                                        -100.0,
                                                        num=1000))
    try:
        plt.show()
    except:
        pass
Пример #23
0
def locusplot(num,den):
	G = control.tf(num,den)
	control.root_locus(G)
	s1="("
	s2="("
	s=str(G)
	s=s.split('\n')
	s[1]=s[1].strip()
	s[3]=s[3].strip()
	s1=s1+s[1]+')'
	s2=s2+s[3]+')'
	plt.grid(True)
	plt.title('Root Locus of G(s)='+(s1)+'/'+(s2))
	if not os.path.isdir('static'):
		os.mkdir('static')
	else:
		for filename in glob.glob(os.path.join('static', 'RootLocus','rlp.png')):
			os.remove(filename)
	rlp=os.path.join('static','RootLocus','rlp.png')
	plt.savefig(rlp)
	plt.clf()
	plt.cla()
	plt.close()
	return rlp
Пример #24
0
 def RLChange(self):
     self.SM = SpringMassVis(l=0.0, k=40.0, b=8.80)  #cm
     self.C = PIDController(t=0.01, P=50, I=0, D=0)
     self.C.sysOpenCE(self.SM.CE)
     self.C.sysClosedCE()
     f, axx = plt.subplots(1, 1)
     self.C.sysRecomp(P=1, I=0, D=0)
     out = control.root_locus(self.C.sysCCE / self.C.P, Plot=False)
     self.C.plotRootLocus(out, axx, 'x')
     self.C.sysRecomp(P=1, I=3, D=0)
     out = control.root_locus(self.C.sysCCE / self.C.P, Plot=False)
     self.C.plotRootLocus(out, axx, 'x')
     self.C.sysRecomp(P=1, I=0, D=0.1)
     out = control.root_locus(self.C.sysCCE / self.C.D, Plot=False)
     self.C.plotRootLocus(out, axx, 'x')
     self.C.sysRecomp(P=1, I=5, D=0.1)
     out = control.root_locus(self.C.sysCCE / self.C.D, Plot=False)
     self.C.plotRootLocus(out, axx, 'x')
     control.root_locus(self.C.sysCCE / self.C.D, Plot=True)
g = (s + 1) / ((s - 1) * (s - 4))
h1 = 1
h2 = 1 / (s - 1)

# a)
k = 120
gf = co.feedback(
    k * lead_comp(-60, -10) * g, h2, -1
)  # υπολογίζω τους πόλου και τα μηδενικά του κλειστού συστήματος με Κ = 120 και feedback=h2
poles = co.pole(gf)
zeros = co.zero(gf)
print(f"poles: {poles}")
print(f"zeros: {zeros}")

plt.figure(1)
co.root_locus(
    lead_comp(-60, -10) * g * h2,
    grid=False)  # σχεδιάζω την γραφική παράστασή μου με lead_compensator
plt.plot(poles.real, poles.imag, 'rx')
plt.plot(zeros.real, zeros.imag, 'ro')

plt.figure(2)
t = np.linspace(0, 3, 1000)
t1, yout = co.step_response(gf, t)
plt.xlabel('Time')
plt.ylabel('Amplitude')
plt.grid()
plt.plot(t1, yout)
plt.show()
Пример #26
0
                       text=gain_text,
                       marker=gr.Marker(color='black'),
                       mode="markers"))

    data.append(open_loop_poles)
    data.append(last_poles)

    return gr.Figure(data=gr.Data(data), layout=layout)


# The root locus can be computed with Python Control's `root_locus` function. Let's see if various negative feedback gains will stabilize the system.

# In[11]:

neg_feedback_roots, neg_feedback_gains = cn.root_locus(theta_delta,
                                                       kvect=np.linspace(
                                                           0.0, 10.0, num=500))

# The root locus shows that for increasing negative feedback gains the bicycle will simply fall over even faster. (Use the "Show closest data on hover" option in the Plotly graph and hover over the traces to see the value of the gain.) I already know that the right steer makes the bicycle fall to the left. So if the bicycle is falling to the left a positive error causes steering to the right! Which, of course, causes the bicycle to fall over even faster. So what if I use positive feedback instead?

# In[12]:

pl.iplot(plot_root_locus(neg_feedback_gains, neg_feedback_roots))

# Now this is much better. It seems that if positive feedback is applied the system can indeed be stabilized by the controller. So if one commands a roll angle the bicycle must steer in the same direction to obtain that roll angle. This proves that we must steer into the fall in order to keep a bicycle upright.

# In[13]:

pos_feedback_roots, pos_feedback_gains = cn.root_locus(
    theta_delta, kvect=np.linspace(0.0, -20.0, num=500))
pl.iplot(plot_root_locus(pos_feedback_gains, pos_feedback_roots))
Пример #27
0
 def plotRootLocus(self):
     control.root_locus(self.CE)
     plt.axvline(x=0, color='k', lw=1)
     plt.grid(True, which='both')
     plt.show()
Пример #28
0
s = co.tf('s')

g = (s + 1) / ((s - 1) * (s - 4))
h1 = 1
h2 = 1 / (s - 1)

#b)
k = 60
gf = co.feedback(
    k * pd_comp(-4.4) * g, h2, -1
)  # υπολογίζω τους πόλου και τα μηδενικά του κλειστού συστήματος με Κ = 60 και feedback=h2
poles = co.pole(gf)
zeros = co.zero(gf)
print(f"poles: {poles}")
print(f"zeros: {zeros}")

plt.figure(1)
co.root_locus(
    pd_comp(-4.4) * g * h2,
    grid=False)  # σχεδιάζω την γραφική παράστασή μου με pd_compensator
plot_ts(2)
plt.xlim(-15, 5)

plt.plot(poles.real, poles.imag, 'rx')

t = np.linspace(0, 3, 1000)
t1, yout = co.step_response(gf, t)
step_info(t1, yout)

plt.show()
#!/usr/bin/env python3

import matplotlib as mpl
mpl.use("svg")
import control as cnt
from frccontrol import conv
import matplotlib.pyplot as plt

#        (s - 9 + 9i)(s - 9 - 9i)
# G(s) = ------------------------
#               s(s + 10)
G = cnt.tf(conv([1, -9 + 9j], [1, -9 - 9j]), conv([1, 0], [1, 10]))
cnt.root_locus(G)

# Show plot
plt.title("Root Locus")
plt.xlabel("Real Axis (seconds$^{-1}$)")
plt.ylabel("Imaginary Axis (seconds$^{-1}$)")
plt.gca().set_aspect("equal")
plt.savefig("rlocus_zeroes.svg")
    
    for r, i in zip(real_vals.T, imag_vals.T):
        data.append(gr.Scatter(x=r, y=i, text=gain_text,
                               marker=gr.Marker(color='black'), mode="markers"))
                
    data.append(open_loop_poles)
    data.append(last_poles)
    
    return gr.Figure(data=gr.Data(data), layout=layout)


# The root locus can be computed with Python Control's `root_locus` function. Let's see if various negative feedback gains will stabilize the system.

# In[11]:

neg_feedback_roots, neg_feedback_gains = cn.root_locus(theta_delta, kvect=np.linspace(0.0, 10.0, num=500))


# The root locus shows that for increasing negative feedback gains the bicycle will simply fall over even faster. (Use the "Show closest data on hover" option in the Plotly graph and hover over the traces to see the value of the gain.) I already know that the right steer makes the bicycle fall to the left. So if the bicycle is falling to the left a positive error causes steering to the right! Which, of course, causes the bicycle to fall over even faster. So what if I use positive feedback instead?

# In[12]:

pl.iplot(plot_root_locus(neg_feedback_gains, neg_feedback_roots))


# Now this is much better. It seems that if positive feedback is applied the system can indeed be stabilized by the controller. So if one commands a roll angle the bicycle must steer in the same direction to obtain that roll angle. This proves that we must steer into the fall in order to keep a bicycle upright.

# In[13]:

pos_feedback_roots, pos_feedback_gains = cn.root_locus(theta_delta, kvect=np.linspace(0.0, -20.0, num=500))
pl.iplot(plot_root_locus(pos_feedback_gains, pos_feedback_roots))
Пример #31
0
import control
import matplotlib.pyplot as plt

from data import setup_sim

sim = setup_sim.SimData(12000)

A = sim.system
B = np.matrix([0, 1, 0, 1]).T
C = np.matrix([1, 0, 0, 0])
D = np.matrix([0])

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

print(ss_sys)

# control.root_locus(ss_sys)

# plt.plot([1, 2, 3, 4])
# plt.show()

num = np.array([2, 5, 1])
den = np.array([1, 2, 3])

h = control.tf(num, den)

print(h)

control.root_locus(h, grid=True)
plt.show()
Пример #32
0
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import control
tf = control.tf([1, 2, 4, 8], [1, 2, -15])
[x, y] = control.root_locus(tf)