Simulating in Python
The three patterns every lab uses: vectorised formulas, a time-stepping loop, and an ODE solver, plus the bugs to avoid.
20 min
On this page
Every TP lab is a simulation. You turn an equation into code, run it, plot it, and explain what it shows. Three patterns cover all five labs.
1. Sweep a formula over an array
Used in Lab I for the torque-slip curve. NumPy applies the formula to every element at once.
import numpy as np
import matplotlib.pyplot as plt
s = np.linspace(1e-4, 1, 2000) # never start at 0: R2/s divides by zero
ws = 2 * np.pi * 1500 / 60 # rad/s, not rpm
T = 3 * V1**2 * (R2 / s) / (ws * ((R1 + R2 / s)**2 + X**2))
plt.plot(1500 * (1 - s), T)
plt.xlabel("Speed (rpm)")
plt.ylabel("Torque (N·m)")
2. A time-stepping loop
Used in Labs II, III and V for anything that changes over time. This is explicit Euler integration of Newton's law from lesson A3.
dt, T_end = 0.01, 60
t = np.arange(0, T_end, dt)
w = 0.0
w_log = np.zeros_like(t)
for k, tk in enumerate(t):
T_load = ... # depends on the state and the time
T_motor = controller(...) # for example a PI on the speed error
w += dt * (T_motor - T_load) / J # J dw/dt = sum of torques
w_log[k] = w
3. An ODE solver
Used in Lab IV for the swinging load. SciPy picks the step size for you.
from scipy.integrate import solve_ivp
def f(t, y):
theta, omega = y
return [omega, -(g / L) * theta - a_trolley(t) / L] # eq. (4.1)
sol = solve_ivp(f, (0, 25), [0, 0], max_step=0.005) # max_step: a(t) jumps
Bugs you will meet
| Symptom | Cause |
|---|---|
| Torque 10 times too big or small | rpm used instead of rad/s |
| A sine curve looks wrong | degrees passed to np.sin; use np.radians |
inf at the first point | slip array starts at 0 |
| Regenerated power larger than the mechanical power | divided by η when generating |
| A stable system oscillates or explodes | time step too large |
| PID output slams to zero at t = 0 | no bias for a bumpless start |
| The pendulum ignores the acceleration pulse | solve_ivp without max_step |
Plots that earn their marks
Five of the 20 marks of each lab report are for plots. Every axis needs a label and a unit, every figure a number and a caption, and every figure must be referred to in your text. Give numbers to three significant figures, with units.
ExplorerGo deeper: derivations and open questions
Beyond Euler. Explicit Euler is first-order accurate: halve dt and the error halves. Runge-Kutta 4 is fourth-order: halve dt and the error drops sixteen-fold. Try both on the pendulum of Lab IV with the same dt and compare the residual sway after 25 s.