Lesson 12: Vectorized Engineering Calculus β€” Numerical Derivatives, Work Integrals & 2D Conduction

The β€œBoring Stuff” Problem: Differentiating & Integrating Experimental Curves Without Analytical Formulas

In textbooks, deflection is always a neat polynomial \(w(x) = ax^4 + bx^3 + cx^2\). On a real dynamometer, wind tunnel, or laser displacement rig, all you have are discrete noisy (x, y) columns inside a CSV file! There is no closed-form derivative to take by hand.

In this lesson, you will use NumPy’s vectorized numerical calculus tools:

  1. np.gradient(y, x) β€” computes accurate central-difference \(dy/dx\) derivatives across entire experimental arrays in 1 line (turning displacement into velocity/acceleration, or beam deflection into slope & bending moment!).
  2. np.trapz(y, x) (trapezoidal quadrature) β€” integrates pressure-volume work \(\oint P\,dV\), impulse \(\int F\,dt\), or daily energy without hand rectangles.
  3. Vectorized Array Slicing (T[1:-1, 1:-1]) β€” relaxes a 2D steady heat conduction PDE \(\nabla^2 T = 0\) across a turbine-blade cooling fin 50x faster than nested Python loops!
import numpy as np
from pathlib import Path

# Example 1 (Calculus I + Solids + Dynamics): Numerical Velocity/Accel & Indicator Work
dyn_path = next(
    p for p in [
        Path("datasets/Dynamics_Mass_Spring_Accelerometer_Data.csv"),
        Path("../datasets/Dynamics_Mass_Spring_Accelerometer_Data.csv"),
    ] if p.exists()
)
d_arr = np.loadtxt(dyn_path, delimiter=",", skiprows=1)
t_s, disp_mm, vel_meas_mms, acc_meas_ms2 = d_arr.T

# Finite-difference differentiation directly on measured displacement
vel_num_mms = np.gradient(disp_mm, t_s)
acc_num_ms2 = np.gradient(vel_num_mms / 1000.0, t_s)  # m/s^2

# Trapezoidal integration check: velocity integrated back over time ~ displacement!
disp_reconstructed_mm = np.trapz(vel_meas_mms, t_s)

print("=== Experimental Seismometer Vectorized Calculus Check ===")
print(f"Peak Measured Vel  : {np.max(np.abs(vel_meas_mms)):6.2f} mm/s | Peak Gradient Vel : {np.max(np.abs(vel_num_mms)):6.2f} mm/s")
print(f"Net Disp via trapz : {disp_reconstructed_mm:6.3f} mm   | True Net Disp (end-start): {disp_mm[-1] - disp_mm[0]:6.3f} mm")
=== Experimental Seismometer Vectorized Calculus Check ===
Peak Measured Vel  : 301.59 mm/s | Peak Gradient Vel : 282.12 mm/s
Net Disp via trapz : -0.000 mm   | True Net Disp (end-start): -0.000 mm
# Example 2 (Heat & Mass Transfer Module 1): Vectorized 2D Steady Plate Conduction + Contour Plot
import matplotlib.pyplot as plt

Nx, Ny = 31, 31
T = np.full((Ny, Nx), 40.0)
# Boundary Conditions: Top = 220 degC (hot gas face), Left/Right/Bottom = 40 degC (coolant channels)
T[-1, :] = 220.0
T[0, :] = 40.0
T[:, 0] = 40.0
T[:, -1] = 40.0

# Vectorized Jacobi / vectorized slice relaxation (ZERO inner pixel loops!)
for sweep in range(600):
    T_old = T.copy()
    T[1:-1, 1:-1] = 0.25 * (
        T_old[2:, 1:-1] + T_old[:-2, 1:-1] + T_old[1:-1, 2:] + T_old[1:-1, :-2]
    )
    if sweep > 10 and np.max(np.abs(T - T_old)) < 1e-4:
        break

print(f"2D Conduction converged in {sweep+1} vectorized sweeps | Center T = {T[Ny//2, Nx//2]:.2f} degC")

fig, ax = plt.subplots(figsize=(6.2, 4.4))
x = np.linspace(0, 1.0, Nx)
y = np.linspace(0, 1.0, Ny)
cf = ax.contourf(x, y, T, levels=20, cmap="inferno")
fig.colorbar(cf, ax=ax, label="Temperature [degC]")
ax.set_title("2D Steady Conduction in Cooled Plate (Vectorized NumPy)")
ax.set_xlabel("Dimensionless Width x/L")
ax.set_ylabel("Dimensionless Height y/H")
fig.tight_layout()
Vectorized Engineering Calculus β€” Numerical Derivatives, Work Integrals & 2D Conduction Output Plot 1
2D Conduction converged in 600 vectorized sweeps | Center T = 82.30 degC

Look at that T[1:-1, 1:-1] expression! Because we sliced T_old[2:, 1:-1] (top neighbors), T_old[:-2, 1:-1] (bottom neighbors), T_old[1:-1, 2:] (right), and T_old[1:-1, :-2] (left), NumPy updates all 841 interior mesh points simultaneously in pure C!


Practice Questions (Concept Check)

  1. What does np.gradient(y, x) return compared to np.diff(y) / np.diff(x)? (Hint: check the array length!)
  2. In a closed thermodynamic cycle on a \(P\)-\(V\) diagram, why does np.trapz(P, V) across expansion + compression automatically compute net cyclic work?
  3. Why did the 2D conduction relaxation keep T_old = T.copy() before updating T[1:-1, 1:-1]?
  4. When using np.gradient on noisy experimental displacement measurements to compute second derivatives (like beam bending moment \(M = E I w''\)), why can raw sensor noise spike wildly?

Guided Practice Problem 1 (Worked Self-Check): Solar Collector Hourly Thermal Energy via np.trapz (Solar Thermal)

Load hour and G_T_W_m2 and efficiency_percent from datasets/Solar_Collector_FlatPlate_Hourly_Data.csv, compute instantaneous thermal rate \(\dot{Q}_u(t) = A_c G_T (\eta/100)\) (\(A_c = 4.0\text{ m}^2\)) as a single NumPy array, and integrate daily thermal output \(\text{kWh}\) using np.trapz.

Hint: Compare np.trapz(q_kw, hours) against simple sum(q_kw)

Because endpoints at midnight are \(0\text{ W}\), trapezoidal quadrature matches hourly rectangle sums closely while remaining accurate even on uneven sensor timestamps!

# Worked Practice Problem 1 Solution: Vectorized Solar Collector Energy Integration
sol_path = next(p for p in [Path("datasets/Solar_Collector_FlatPlate_Hourly_Data.csv"), Path("../datasets/Solar_Collector_FlatPlate_Hourly_Data.csv")] if p.exists())
s_arr = np.loadtxt(sol_path, delimiter=",", skiprows=1)
hours, G_T, _, _, eff_pct = s_arr.T
q_kw = (4.0 * G_T * (eff_pct / 100.0)) / 1000.0
daily_kwh = np.trapz(q_kw, hours)
print(f"Peak Collector Output : {q_kw.max():.3f} kW")
print(f"Integrated Yield      : {daily_kwh:.3f} kWh/day via np.trapz")
Peak Collector Output : 2.383 kW
Integrated Yield      : 18.203 kWh/day via np.trapz

End-of-Chapter Practice Problems (Try Yourself!)

  1. Gas Turbine Expansion Work via np.trapz (ME 200): Integrate \(W = \int_{V_1}^{V_2} P\,dV\) across 500 points along \(P V^{1.35} = P_1 V_1^{1.35}\) (\(P_1 = 900\text{ kPa}, V_1 = 0.05\text{ m}^3, V_2 = 0.30\text{ m}^3\)) using np.trapz and check error vs.Β analytical formula.
  2. Beam Slope & Curvature Check (Solids): Load datasets/Solids_Cantilever_Beam_Deflection_Data.csv (\(x\) in \(\text{m}\), \(w\) in \(\text{mm}\)), compute beam slope \(\theta(x) = dw/dx\) (\(\text{mrad}\)) using np.gradient, and print maximum slope at the free end.
  3. 2D Conduction Heat Sink Check: Modify Example 2 to include a constant uniform heat generation term \(\dot{q}\Delta x^2 / k = 2.0\text{ K}\) inside T[1:-1, 1:-1] and observe how much hotter the center node becomes!

🎬 Concept & Engineering Animation

🎬 Finite Difference Stencil2 D