def nqstplot(num,den): G = control.tf(num,den) w = numpy.logspace(-3,3,5000) control.nyquist(G,w) 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('Nyquist Diagram of G(s)H(s) = '+(s1)+'/'+(s2)) plt.xlabel('Re(s)') plt.ylabel('Im(s)') if not os.path.isdir('static'): os.mkdir('static') else: # Remove old plot files for filename in glob.glob(os.path.join('static', 'NyquistPlot','Plot3.png')): os.remove(filename) nqst=os.path.join('static','NyquistPlot', 'Plot3.png') plt.savefig(nqst) plt.clf() plt.cla() plt.close() return nqst
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()
def plot(self): G = control.TransferFunction((1), (1, 1)) real, imag, freq = control.nyquist(G) plt.title('Nyquist Plot') plt.gcf().canvas.set_window_title('Nyquist Plot') plt.xlabel('Real') plt.ylabel('Imaginary') plt.grid() plt.show()
def nyq(self): """ Display Nyquist plot for the system. Uses nyquist plotting functionality of the module control. """ plt.clf() plt.figure(1) real, imag, freq = control.nyquist(self.sys, Plot=True) plt.title("Nyquist Plot") plt.xlabel("Re($\omega$)") plt.ylabel("Im($\omega$)") plt.grid() plt.show()
def loop_analysis(name, sys, zeta, wd, k, t_vect, k_vect, omega_vect): sysc = control.feedback(sys * k, 1) closed_loop_poles = control.pole(sysc) plt.figure(figsize=(10, 5)) rlocus(name, sys, k_vect, k) plt.axis([-16, 0, -8, 8]) theta = np.arccos(zeta) plt.plot([0, -10], [0, 10 * np.tan(theta)], 'r--') plt.vlines(-wd, -8, 8, linestyle='--', color='r') plt.figure(figsize=(10, 5)) bode(name, sys, omega_vect, margins=True) plt.figure(figsize=(10, 5)) control.nyquist(sys, omega=omega_vect) plt.title(name + ' nyquist') plt.axis([-10, 10, -10, 10]) plt.figure(figsize=(10, 5)) step_reponse(name, sysc, t_vect) plt.figure(figsize=(10, 5)) bode(name + ' closed loop ', sysc, np.logspace(-2, 2))
def plot_nyquist(self, fig): tf = self.tf if self.loop_type == 'ol' else self.tf_plant * self.tf_comp w = np.logspace(-100, 100, 50000) x, y, _ = control.nyquist(tf, omega=w) fig.clf() ax = fig.add_subplot(1, 1, 1) ax.plot(x, y) ax.plot(x, -y, '--') ax.plot([-1], [0], color='r', marker='x', markersize=10) ax.set_xlabel('Real axis') ax.set_ylabel('Imaginary axis') if not self.settings.is_nyquist_default(): xmin = self.settings.get_nyquist_xmin() xmax = self.settings.get_nyquist_xmax() ymin = self.settings.get_nyquist_ymin() ymax = self.settings.get_nyquist_ymax() ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) return fig
m = np.arange(0, 3, 0.2) for num in m: if num != 1: p = M_circle(num) plt.plot(p[0], p[1]) if (num >= 0.6 and num <= 1): plt.text(0.8 * (p[3] + p[2]), 0.8 * (p[4] + p[2]), np.around(num, decimals=2)) elif (num >= 1.4 and num <= 1.6): plt.text(0.8 * (p[3] - p[2]), 0.8 * (p[4] - p[2]), np.around(num, decimals=2)) plt.axvline(x=-0.5, label='M=1') w = np.logspace(-100, 100, 10000) control.nyquist(G, w, label='nyquistplot') plt.grid(True) plt.title('M Circles and Nyquist plot') plt.axis('equal') plt.xlim(-4, 4) plt.xlabel('Real') plt.ylim(-3, 3) plt.ylabel('Imaginary') plt.legend(loc='best', prop={'size': 11}) #N circles plot subplot(2, 1, 2) n = np.arange(-2, 2, 0.2) for num in n:
def M_circle(m): theta = np.linspace(0, 2*np.pi, 100) x0 = np.around(m**2/(1-m**2),decimals=2) y0 = np.around(0,decimals=2) r = abs(m/(1-m**2)) x = x0 + r*np.cos(theta) y = y0 + r*np.sin(theta) return np.around(x,decimals=2),np.around(y,decimals=2) #Creating a transfer function G = num/den nume = 1000 deno = [1,18,119,342,360] G = control.tf(nume,deno) niq = np.around(control.nyquist(G,Plot=0),decimals=2) #finding the point of intersection mag=np.empty(0) freq=np.empty(0) m=np.arange(0,8,0.02) for num in m: if num != 1: for i in range (len(niq[0])): for j in range (len(M_circle(num)[0])): if niq[0][i] == M_circle(num)[0][j] and niq[1][i] == M_circle(num)[1][j]: mag=np.append(mag,num) freq=np.append(freq,niq[2][i]) print(mag) print(len(mag))
B = matrix([[0.0], [1 / m]]) C = matrix([[1.0, 0.0]]) D = matrix([[0.0]]) G = ss(A, B, C, D) P = ss2tf(G) #------ W = matrix([[1.0]]) V = 1e8 * matrix([[1.0, 0.0], [0.0, 1.0]]) Y = linalg.solve_continuous_are(A.transpose(), C.transpose(), V, W) L = Y * C.transpose() * inv(W) #------------------- R = matrix([[1.0]]) Q = matrix([[1e2, 0.0], [0.0, 1.]]) X = linalg.solve_continuous_are(A, B, Q, R) K = inv(R) * B.transpose() * X # synthesis, controller in state space Ac = A - B * K Bc = matrix([[0.0], [0.0]]) Cc = K Dc = D H = ss(Ac, Bc, Cc, Dc) F = ss2tf(H) # show open loop controller and plant plt.figure() bode(F * P) plt.figure() nyquist(F * P) plt.figure() T, yout = step_response(F * P / (1 + F * P), T=np.linspace(0, 50, 10000)) plt.plot(T, yout)
def Lab2(numZ, denZ, numR, denR, n): w1 = tf(numZ, denZ) # Передаточная и переходная функции y1, x1 = step(w1) print("\nПередаточная функция замкнутой САУ - ", w1) w2 = tf(numR, denR) y2, x2 = step(w2) print("\nПередаточная функция разомкнутой САУ - ", w2) plt.plot(x1, y1, "r", label="Название") plt.title("Переходная функция замкнутой системы") plt.xlabel("Время, с") plt.ylabel("Амплитуда") plt.grid(True) plt.show() plt.plot(x2, y2, "r", label="Название") plt.title("Переходная функция разомкнутой системы") plt.xlabel("Время, с") plt.ylabel("Амплитуда") plt.grid(True) plt.show() G = control.tf(numR, denR) # Найквист GG = num.logspace(-3, 3, 10000) real, imag, freq = control.nyquist(G, GG) real = list(real) imag = list(imag) y = [] x = [] for i in range(-1, 2, 1): y.append(i) for i in range(-1, 2, 1): x.append(-1) plt.plot(x, y, "r") for i in range(0, len(real)): z = abs(complex(real[i], imag[i])) if 0.999 < z < 1.001 and real[i] < 0 and imag[i] < 0: fi = atan(imag[i] / real[i]) * 180 / math.pi print("Запас по фазе - ", real[i], imag[i]) plt.plot(real[i], imag[i], '-x') print("Угол - ", fi) plt.plot() xx, yy = [0, real[i]], [0, imag[i]] plt.plot(xx, yy) break for i in range(0, len(real)): z = abs(complex(real[i], imag[i])) if -0.0001 < imag[i] < 0.0001 and abs(real[i]) > 0.05: print("Запас по амплитуде - ", real[i], imag[i]) plt.plot(real[i], imag[i], '-o') xx1, yy1 = [-1, -1], [0, -1.1] xx2, yy2 = [real[i], real[i]], [0, -1.1] plt.plot(xx1, yy1, "r", xx2, yy2, "r") break phi = num.linspace(0, 2 * num.pi, 100) r = num.sqrt(1.0) x1 = r * num.cos(phi) x2 = r * num.sin(phi) plt.plot(x1, x2) plt.title("Диаграмма Найквиста") plt.plot(label="Название") plt.xlabel("+1") plt.ylabel("+j") plt.grid(True) plt.show() mag, phase, omega = bode(w1, dB=True) # ЛАЧХ и ЛФЧХ plt.title("ЛАЧХ и ЛФЧХ") plt.grid(True) plt.show() print("Полюса - %s" % pole(w1)) pzmap(w1) plt.title("Расположение полюсов на комплексной плоскости") plt.grid(True) plt.show() plt.figure() w = symbols("w", real=True) # Годограф Михайлова if n == 1: z = factor(160 * (I * w) ** 3 + 89 * (I * w) ** 2 + 16.4 * I * w + 2) elif n == 2: z = factor(160 * (I * w) ** 3 + 89 * (I * w) ** 2 + 16.4 * I * w + 9.1225) elif n == 3: z = factor(160 * (I * w) ** 3 + 89 * (I * w) ** 2 + 16.4 * I * w + 10) zR = re(z) zIm = im(z) x = [zR.subs({w: q}) for q in arange(0, 100, 0.1)] y = [zIm.subs({w: q}) for q in arange(0, 100, 0.1)] print(z) plt.title("Годограф Михайлова") plt.axis([-150, 10, -45, 5]) plt.plot(x, y) plt.grid(True) plt.show() if n == 1: Matrix = num.matrix([[89, 2], [160, 16.4]]) elif n == 2: Matrix = num.matrix([[89, 9.1225], [160, 16.4]]) elif n == 3: Matrix = num.matrix([[89, 10], [160, 16.4]]) Det = num.linalg.det(Matrix) print("Уравнение - ", denZ, "\nМатрица - \n", Matrix) print(" Определитель - ", Det)
import numpy as np import matplotlib.pyplot as plt H = 1121. m = 200 kp = 0.091 T = 1 Td = 2 num = H * kp * np.array([Td, 1.]) den = m * np.array([T, 1, 0, 0]) G = ctr.tf(num, den) fig1, ax = plt.subplots() mag, phase, omega = ctr.nyquist(G, [0.01, 1000]) t = np.linspace(0, 2 * np.pi, 100) ax.plot(np.cos(t), np.sin(t)) fig2 = plt.figure() ws = np.geomspace(0.01, 100, 50) mag, phase, omega = ctr.bode(G, ws) zero_db = np.argmin(abs(np.log10(mag))) for ax in fig2.axes: ax.axvline(ws[zero_db], color='tab:orange') print(ws[zero_db]) print(phase[zero_db]) plt.show()
from control.matlab import * import control import matplotlib.pyplot as plt import numpy as num from sympy import * from sympy import I from numpy import arange import math G = control.tf([0, 2], [160, 89, 16.4, 1]) # Найквист GG = num.logspace(-3, 3, 10000) real, imag, freq = control.nyquist(G, GG) real = list(real) imag = list(imag) y1 = [] x1 = [] y2 = [] x2 = [] for i in range(0, len(real)): # запас по фазе z = abs(complex(real[i], imag[i])) if 0.999 < z < 1.001 and real[i] < 0 and imag[i] < 0: fi = atan(imag[i] / real[i]) * 180 / math.pi print("Запас по фазе - ", real[i], imag[i]) plt.plot(real[i], imag[i], '-x') print("Угол - ", fi) plt.plot() xx, yy = [0, real[i]], [0, imag[i]] plt.plot(xx, yy) break
#end if #coefficents of open loop transfer function den = [4,1,0,0] num1 = [1] num2 = [2] #Creating a transfer function G = num/den G1 = control.tf(num1,den) G2 = control.tf(num2,den) #plotting the nyquist plot for three different transfer functions for a variable K control.nyquist(G1,label='K=1') control.nyquist(G2,label='K=2') plt.xlim(-4,0) plt.ylim(-2,2) plt.legend() plt.annotate("-1+0j",(-1,0)) plt.xlabel('Re(s)') plt.ylabel('Im(s)') #if using termux plt.savefig('./figs/ee18btech11034/ee18btech11034_2.pdf') plt.savefig('./figs/ee18btech11034/ee18btech11034_2.eps') subprocess.run(shlex.split("termux-open ./figs/ee18btech11034/ee18btech11034_2.pdf")) #else #plt.show()
plt.text(0.8 * (p[3] + p[2]), 0.8 * (p[4] + p[2]), np.around(num, decimals=2)) elif (num >= 1.4 and num <= 1.6): plt.text(0.8 * (p[3] - p[2]), 0.8 * (p[4] - p[2]), np.around(num, decimals=2)) plt.xlim(-5, 5) plt.ylim(-2, 2) #Creating a transfer function G = num/den nume = 1000 deno = [1, 18, 119, 342, 360] G = control.tf(nume, deno) w = np.logspace(-100, 100, 10000) control.nyquist(G, w) plt.text(2, 0, "niquest plot") plt.grid(True) plt.title('M circles and niquest plot') plt.xlabel('Re(s)') plt.ylabel('Im(s)') plt.savefig("M_circles.eps") plt.show() #if using termux #plt.savefig('M_circles.eps') #subprocess.run(shlex.split("termux-open M_circles.pdf")) #plt.show() #N_circles plot n = np.arange(-2, 2, 0.2)
Q = np.eye(4,4) R = np.eye(2,2) #S1 = sp.linalg.solve_continuous_are(A, B, Q, R) #K1 = np.linalg.inv(R).dot(B.T).dot(S1) #E1 = np.linalg.eigvals(A-B.dot(K1)) #print("S1 =\n", S1) #print("K1 =\n", K1) #print("E1 =\n", E1) S2, E2, K2 = ct.care(Ap, Bp, Q, R) #print("\nS2 =\n", S2) #print("K2 =\n", K2) #print("E2 =\n", E2) print "ctrb = "+ str(np.linalg.matrix_rank(ct.ctrb(Ap,Bp))) print "obsv = " + str(np.linalg.matrix_rank(ct.obsv(Ap,Cp))) #K3, S3, E3 = ct.matlab.lqr(Ap, Bp, Q, R) #print("\nS3 =\n", S3) #print("K3 =\n", K3) #print("E3 =\n", E3) ss_P = ct.ss(Ap,Bp,Cp,Dp) print ss_P t = np.linspace(0, 3, 1000) stepy = ct.step(ss_P,t) #plt.plot(t,stepy) #ct.impulse(ss_P) ct.nyquist(ss_P) #bode plot only implemented for SISO system.omg #ct.bode(ss_P)
[n2,d2]=control.pade(0.5,10) #Creating delay of 0.5 [n3,d3]=control.pade(0.0005,10) #Creating delay of 0.0005 #Creating a transfer function G = num/den G = control.tf(num,den) G1=control.tf(n1,d1) G2=control.tf(n2,d2) G3=control.tf(n3,d3) #assigning delay to system G G4=G*G1 G5=G*G2 G6=G*G3 #plotting nyquist plot with variable tau control.nyquist(G4,label='$t=0.1744$') control.nyquist(G5,label='$t=0.5$') control.nyquist(G6,label='$t=0.0005$') plt.grid(True) plt.xlim(-4,0) plt.ylim(-2,2) plt.legend() plt.annotate("-1+0j",(-1,0)) plt.xlabel('Re(s)') plt.ylabel('Im(s)') #if using termux plt.savefig('./figs/ee18btech11035/ee18btech11035_1.pdf') plt.savefig('./figs/ee18btech11035/ee18btech11035_1.eps') subprocess.run(shlex.split("termux-open ./figs/ee18btech11035/ee18btech11035_1.pdf")) #else #plt.show()
#if using termux import subprocess import shlex #end if import control import matplotlib.pyplot as plt import numpy as np G1 = control.tf([1], [1, 2, 2, 2, 1]) G2 = control.tf([1], [1, 2, 0, 0, -1]) G3 = control.tf([1], [1, 2, 1, 1, 0]) w = np.linspace(-50, 50, 5000) control.nyquist(G1, w, label='k=1') control.nyquist(G2, w, label='k=-1') control.nyquist(G3, w, label='k=0') plt.legend() #if using termux plt.savefig('./figs/ee18btech11042/ee18btech11042_1.pdf') plt.savefig('./figs/ee18btech11042/ee18btech11042_1.eps') subprocess.run( shlex.split("termux-open ./figs/ee18btech11042/ee18btech11042_1.pdf")) #else #plt.show() plt.show()
#M circles plot subplot(2,1,1) m=np.arange(0,3,0.2) for num in m: if num != 1: p=M_circle(num) plt.plot(p[0],p[1] ) if (num >= 0.6 and num <= 1): plt.text(0.8*(p[3]+p[2]),0.8*(p[4]+p[2]),np.around(num,decimals=2)) elif (num >=1.4 and num <= 1.6): plt.text(0.8*(p[3]-p[2]),0.8*(p[4]-p[2]),np.around(num,decimals=2)) plt.axvline(x=-0.5,label='M=1') w=np.logspace(-100,100,1000) control.nyquist(G,w,label='Rect coord') plt.grid(True) plt.title('M Contors in rect coordinates') plt.axis('equal') plt.xlim(-4,4) plt.xlabel('Real') plt.ylim(-3,3) plt.ylabel('Imaginary') plt.legend(loc='best',prop={'size':11}) #N circles plot subplot(2,1,2) n=np.arange(-2,2,0.2)
nrows, ncols = A.shape dtype = { 'names': ['f{}'.format(i) for i in range(ncols)], 'formats': ncols * [A.dtype] } return A.view(dtype) #M circle intersection num = [50, 150] den = [1, 6, 8, 0] G = control.tf(num, den) w = np.logspace(-3, 3, 1000) Real, Imag, Freq = np.around(control.nyquist(G, w), decimals=2) # Rounding Off NyQ_Data = np.append(np.expand_dims(Real, axis=1), np.expand_dims(Imag, axis=1), axis=1) M = list(np.arange(0.01, 5, 0.3)) #finds intersection points and return M and frequency def Extract(M, NyQ_Data, Freq): Output = [] for m in M: Circle_Data = list(Intersection(Circle_M(m))) ND = list(Intersection(NyQ_Data)) Int = np.intersect1d(Circle_Data, ND) for p in Int:
#end if num1 = [81] den1 = [1, 18, 103, 198, 121] num2 = [100] den2 = [1, 18, 101, 180, 100] num3 = [121] den3 = [1, 18, 99, 162, 81] #Creating a transfer function G = num/den G1 = control.tf(num1, den1) G2 = control.tf(num2, den2) G3 = control.tf(num3, den3) w = np.logspace(-3, 3, 5000) #Plotting the Nyquist plot control.nyquist(G1, w, label='k=-9') control.nyquist(G2, w, label='k=-10') control.nyquist(G3, w, label='k=-11') plt.plot(1, 0, 'o') plt.annotate("(1,0)", (1, 0)) plt.legend() #if using termux plt.savefig('./figs/ee18btech11029/ee18btech11029_1.pdf') plt.savefig('./figs/ee18btech11029/ee18btech11029_1.eps') subprocess.run( shlex.split("termux-open ./figs/ee18btech11029/ee18btech11029_1.pdf")) #else #plt.show()
import control import matplotlib.pyplot as plt num = [0, 0, 1, 3] den = [1, -3, 0, 0] #Transfer function GH = num/den G = control.tf(num, den) control.nyquist(G) plt.grid(True) plt.scatter(-1, 0, s=40) plt.annotate("-1+0j", (-1, 0)) plt.title('Nyquist Diagram of G(s)H(s)') plt.xlabel('Re(s)') plt.ylabel('Im(s)') plt.show()
Q = np.eye(4, 4) R = np.eye(2, 2) #S1 = sp.linalg.solve_continuous_are(A, B, Q, R) #K1 = np.linalg.inv(R).dot(B.T).dot(S1) #E1 = np.linalg.eigvals(A-B.dot(K1)) #print("S1 =\n", S1) #print("K1 =\n", K1) #print("E1 =\n", E1) S2, E2, K2 = ct.care(Ap, Bp, Q, R) #print("\nS2 =\n", S2) #print("K2 =\n", K2) #print("E2 =\n", E2) print "ctrb = " + str(np.linalg.matrix_rank(ct.ctrb(Ap, Bp))) print "obsv = " + str(np.linalg.matrix_rank(ct.obsv(Ap, Cp))) #K3, S3, E3 = ct.matlab.lqr(Ap, Bp, Q, R) #print("\nS3 =\n", S3) #print("K3 =\n", K3) #print("E3 =\n", E3) ss_P = ct.ss(Ap, Bp, Cp, Dp) print ss_P t = np.linspace(0, 3, 1000) stepy = ct.step(ss_P, t) #plt.plot(t,stepy) #ct.impulse(ss_P) ct.nyquist(ss_P) #bode plot only implemented for SISO system.omg #ct.bode(ss_P)
import control import matplotlib.pyplot as plt import sys #if using termux import subprocess import shlex #end if s = control.TransferFunction.s GH = 41 * (s + 4) / (s**2 * (s + 3)) #open looop transfer function G(s)H(s) control.nyquist(GH) plt.xlim(-2, 1) plt.ylim(-0.5, 0.5) plt.text(-1, 0, "(-1,0)") plt.title('Zoomed in Nyquist Plot of G(s)H(s)') plt.grid(True) plt.xlabel('Re(s)') plt.ylabel('Im(s)') #if using termux plt.savefig('./figs/ee18btech11041_1.pdf') plt.savefig('ee18btech11041_1.eps') subprocess.run(shlex.split("termux-open ./figs/ee18btech11041_1.pdf")) #else #plt.show()
from scipy import signal from matplotlib import style import control from control import tf # style.use('seaborn') systems=[50,60,70,100] plt.figure() # mag=20*np.log(mag) for i in systems: sys=tf([i],[1,6,11,6]) gm,pm,wg,wp= control.margin(sys) control.nyquist(sys, label=i) plt.legend() plt.show() # plt.show()