Midterm 2 Codes
Midterm 2 Codes
December 2, 2023
Collecting control
Downloading control-0.9.4-py3-none-any.whl (455 kB)
���������������������������������������� 455.1/455.1
kB 6.8 MB/s eta 0:00:00
Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-
packages (from control) (1.23.5)
Requirement already satisfied: scipy>=1.3 in /usr/local/lib/python3.10/dist-
packages (from control) (1.11.3)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.10/dist-
packages (from control) (3.7.1)
Requirement already satisfied: contourpy>=1.0.1 in
/usr/local/lib/python3.10/dist-packages (from matplotlib->control) (1.2.0)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.10/dist-
packages (from matplotlib->control) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in
/usr/local/lib/python3.10/dist-packages (from matplotlib->control) (4.44.3)
Requirement already satisfied: kiwisolver>=1.0.1 in
/usr/local/lib/python3.10/dist-packages (from matplotlib->control) (1.4.5)
Requirement already satisfied: packaging>=20.0 in
/usr/local/lib/python3.10/dist-packages (from matplotlib->control) (23.2)
Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.10/dist-
packages (from matplotlib->control) (9.4.0)
Requirement already satisfied: pyparsing>=2.3.1 in
/usr/local/lib/python3.10/dist-packages (from matplotlib->control) (3.1.1)
Requirement already satisfied: python-dateutil>=2.7 in
/usr/local/lib/python3.10/dist-packages (from matplotlib->control) (2.8.2)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-
packages (from python-dateutil>=2.7->matplotlib->control) (1.16.0)
Installing collected packages: control
Successfully installed control-0.9.4
1
Collecting matlab
Downloading matlab-0.1.tar.gz (538 bytes)
Preparing metadata (setup.py) … done
Building wheels for collected packages: matlab
Building wheel for matlab (setup.py) … done
Created wheel for matlab: filename=matlab-0.1-py3-none-any.whl size=1156
sha256=e25a1bdd5ec7b87af81ca2a8cef0cd4ba7f7bcd98e4935bb9616e48e0b799a30
Stored in directory: /root/.cache/pip/wheels/d1/d3/76/5314058ee22e7957a18eec02
91788462f1df178bb08223bdd2
Successfully built matlab
Installing collected packages: matlab
Successfully installed matlab-0.1
1 QUESTION 1
[54]: from control.matlab import *
import matplotlib.pyplot as plt
import control
2
[55]: from scipy.optimize import fsolve
import numpy as np
# Define the equation to solve for the damping ratio (zeta) given the overshoot␣
↪(OS)
# Use fsolve to find the damping ratio that corresponds to 20% overshoot
zeta_initial_guess = 0.5
damping_ratio = fsolve(overshoot_to_damping_ratio, zeta_initial_guess)[0]
print(f"The damping ratio for 20% overshoot is: {damping_ratio}")
3
from control import step_response
# For the purpose of this example, let's assume we've calculated it to be at␣
↪-10 (this would normally be done
# This value should be calculated based on the specific system response and is␣
↪typically done iteratively.
lag_pole = 0.01
lag_zero = 0.001 # This value is an assumption and should be fine-tuned based␣
↪on the system response
# Step 5: Calculate the steady-state error for a ramp input and adjust for the␣
↪desired reduction
4
def adjust_gain_for_steady_state_error(Kv_reduction, G_s):
# Calculate the necessary Kv
Kv_original = (G_s.horner(0))[0][0].real
desired_Kv = Kv_original * Kv_reduction
# Adjust the gain K to achieve the desired Kv
K_adjusted = min(desired_Kv*60, 1000) # because Kv = K/60 for the given␣
↪G(s)
return K_adjusted
# The final open-loop transfer function with compensator and adjusted gain
G_s_compensated = K_adjusted * C_s * G_s
print("\n\n")
print("======================================================================================"
# Plotting the root locus, Bode plot, or step response of the compensated␣
↪system to fine-tune the compensator:
print("\n\n")
print("======================================================================================"
5
plt.figure()
mag, phase, omega = bode(G_s_compensated, dB=True, Hz=True, deg=True, Plot=True)
plt.tight_layout()
plt.show()
print("\n\n")
print("======================================================================================"
1
-------------------
s^3 + 16 s^2 + 60 s
1000
================================================================================
======
6
================================================================================
======
/usr/local/lib/python3.10/dist-packages/control/freqplot.py:187: FutureWarning:
'Plot' keyword is deprecated in bode_plot; use 'plot'
warnings.warn("'Plot' keyword is deprecated in bode_plot; use 'plot'",
7
================================================================================
======
8
2 QUESTION 2
[28]: from scipy.signal import step, TransferFunction
import numpy as np
import matplotlib.pyplot as plt
# Time vector for step response (we choose enough time to see the full response)
9
t = np.linspace(0, 2, 1000)
np.polymul(den_uncompensated,␣
↪den_compensated))
# Calculate the percent overshoot and peak time for the uncompensated system
peak_uncompensated = np.max(response_uncompensated)
percent_overshoot_uncompensated = (peak_uncompensated - 1) * 100
peak_time_uncompensated = t_uncompensated[np.argmax(response_uncompensated)]
# Calculate the percent overshoot and peak time for the compensated system
peak_compensated = np.max(response_compensated)
percent_overshoot_compensated = (peak_compensated - 1) * 100
peak_time_compensated = t_compensated[np.argmax(response_compensated)]
10
Uncompensated System: Percent Overshoot = 684.8888888888632%, Peak Time = 2.0s
Compensated System: Percent Overshoot = 6958.798296093113%, Peak Time = 2.0s
3 QUESTION 3
[27]: import numpy as np
import matplotlib.pyplot as plt
11
plt.plot(Gs.real, -Gs.imag, linestyle='--') # Mirror image for symmetry
plt.scatter([-1], [0], color='red') # Stability reference point (-1,0)
plt.xlabel('Real Axis')
plt.ylabel('Imaginary Axis')
plt.title('Nyquist Plot for K1={}, K2={}'.format(K1, K2))
plt.legend()
plt.grid()
plt.axis('equal') # To maintain the aspect ratio
plt.show()
12
[47]: import numpy as np
import matplotlib.pyplot as plt
13
plt.plot(Gs.real, Gs.imag, label='Nyquist Plot for K1={}, K2={}'.format(K1,␣
↪K2))
plt.plot(Gs.real, -Gs.imag, linestyle='--') # Mirror image for symmetry
plt.scatter([-1], [0], color='red', zorder=3) # Stability reference point␣
↪(-1,0)
plt.xlabel('Real Axis')
plt.ylabel('Imaginary Axis')
plt.title('Nyquist Plot for K1={}, K2={}\n'.format(K1, K2))
plt.legend()
plt.grid(True)
plt.axis('equal') # To maintain the aspect ratio
plt.xlim(-4, 4) # Set x-axis limits to zoom in around the critical point
plt.ylim(-4, 4) # Set y-axis limits to have a clear view of the critical␣
↪point
plt.show()
14
15