Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

SciPy: Linear Algebra, Optimization, Integration, Signal and Stats

SciPy packages decades of battle-tested numerical algorithms behind NumPy-style interfaces: scipy.linalg (LU, Cholesky, QR, SVD, least squares), scipy.optimize (root finding, minimization, curve fitting), scipy.integrate (quadrature and ODE solvers with events), scipy.signal (filter design, filtering, spectra) and scipy.stats (distributions, tests, confidence intervals), plus special functions. This topic shows how to choose and call the right routine and check its answer. In the exercises you solve a nonlinear pendulum and match the elliptic-integral period, solve Kepler's equation, fit a damped oscillation, then measure how a causal low-pass filter's phase lag destroys the SNR gain that zero-phase filtering keeps.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A toolbox of proven numerical recipes

Solving an equation, finding the lowest point of a function, adding up the area under a curve, removing noise from a signal, testing whether two measurements differ: engineers need these constantly, and writing them correctly is hard. SciPy is a carefully tested toolbox of such recipes, many built on Fortran and C libraries refined over decades. Your job becomes choosing the right tool, calling it correctly, and checking the answer makes sense.

The pendulum: an ODE solver, an event and an elliptic integral
θ(t): orange nonlinear (RK4), dashed small-angleperiod T/T₀ vs θ0 (exact)θ0 (deg) → 180
exact period 2.75409 s · RK4 + event 2.75409 s (error 5.7e-7 s) · small-angle 2.00607 s (37.3% short)
The linear approximation sin θ ≈ θ predicts the same period at every amplitude; the real pendulum slows down dramatically near 180°, where K diverges. SciPy gives you all three tools used here: solve_ivp (adaptive Runge–Kutta), events (find when θ crosses 0), and special.ellipk. Make the RK4 step coarse to see the error grow (∝ h⁴ until the event interpolation dominates).
Why engineers care

Orbit propagation (solve_ivp), attitude estimation (linalg), trajectory and controller tuning (optimize), sensor filtering (signal), test-campaign statistics (stats): SciPy is the everyday engine of aerospace and robotics analysis in Python, and many flight-software prototypes start as SciPy scripts.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Which SciPy module solves differential equations?
  2. 2. Which module fits a model curve to data?
  3. 3. The big-swing pendulum's period is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

The main modules

module typical calls
scipy.linalg solve, lu_factor/lu_solve, cho_factor, lstsq, svd, expm, eigh
scipy.optimize brentq, root, minimize, least_squares, curve_fit, linprog
scipy.integrate quad, solve_ivp (RK45, DOP853, Radau, BDF, LSODA), events
scipy.signal butter, sosfilt, sosfiltfilt, welch, spectrogram, find_peaks
scipy.stats distributions (norm, t, chi2), ttest_ind, pearsonr, bootstrap
scipy.special ellipk, gamma, erf, Bessel functions
scipy.spatial cKDTree, Rotation (quaternions and Euler angles)

A first ODE

from scipy.integrate import solve_ivp
sol = solve_ivp(lambda t, y: [y[1], -9.81 * np.sin(y[0])], (0, 10), [1.0, 0.0],
                rtol=1e-9, atol=1e-12, dense_output=True)
sol.t, sol.y, sol.sol(3.2)      # time points, states, interpolant
📝 Quick check (Level 1)
0/3 answered
  1. 1. For a stiff ODE (fast and slow dynamics) use…
  2. 2. To find E with E − e sin E = M on a known bracket, use…
  3. 3. scipy.spatial.transform.Rotation handles…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

Choosing and checking

  • Linear systems: never invert, use solve or a factorization. Reuse lu_factor across many right-hand sides. Prefer cho_factor for SPD matrices.
  • Root finding: bracketing (brentq) is guaranteed when you have a sign change; Newton-type (root, newton) is faster but needs a good start.
  • Minimization: gradients help (jac=). Use BFGS/L-BFGS-B for smooth problems, Nelder–Mead for rough ones, least_squares for residual problems with bounds.
  • ODEs: set rtol/atol deliberately; check by halving the tolerances; use events for crossings (apsis, ground impact).
  • Filters: design as second-order sections (output="sos") for numerical stability. Offline, sosfiltfilt gives zero phase; in real time only causal filtering exists, and it lags.
  • Always verify: residuals, conservation laws, known special cases.
🐍 Exercise 1: an ODE, an event, a special function, a root and a fit
Measure a nonlinear pendulum's period with solve_ivp and an event function and compare it with 4√(L/g)·ellipk(sin²(θ0/2)); solve Kepler's equation with brentq; fit a damped oscillation with curve_fit; fit a line with linalg.lstsq.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Why design filters as second-order sections?
  2. 2. filtfilt-style filtering is…
  3. 3. To check an ODE solution's accuracy, you can…

Level 3: Advanced

★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.

The pendulum period exactly

Energy conservation gives θ˙2=2gL(cos⁡θ−cos⁡θ0)\dot\theta^2 = \tfrac{2g}L(\cos\theta - \cos\theta_0), so T=4∫0θ0dθ(2g/L)(cos⁡θ−cos⁡θ0)T = 4\int_0^{\theta_0}\frac{d\theta}{\sqrt{(2g/L)(\cos\theta - \cos\theta_0)}}. The substitution sin⁡(θ/2)=ksin⁡ϕ\sin(\theta/2) = k\sin\phi with k=sin⁡(θ0/2)k = \sin(\theta_0/2) turns this into T=4L/g K(k)T = 4\sqrt{L/g}\,K(k), with K(k)=∫0π/2dϕ1−k2sin⁡2ϕK(k) = \int_0^{\pi/2}\frac{d\phi}{\sqrt{1 - k^2\sin^2\phi}}. Note that SciPy’s ellipk(m) takes the parameter m=k2m = k^2, a classic gotcha. As θ0→π\theta_0\to\pi, K diverges logarithmically.

Why causal filters lag

A causal low-pass filter’s phase response ϕ(ω)\phi(\omega) is negative, delaying each frequency by −ϕ(ω)/ω-\phi(\omega)/\omega (group delay). For a Butterworth filter of fixed order the low-frequency group delay scales like 1/fc1/f_c (and grows with the order): in exercise 2 the order-4 filter delays by 205 ms at 2 Hz and 80 ms at 5 Hz, a ratio of 2.6 for a 2.5× change in cutoff. Forward–backward filtering applies H(ω)H(\omega) and then H∗(ω)H^*(\omega), giving ∣H∣2|H|^2 with zero phase, at the cost of needing the whole signal.

Welch’s method

Average periodograms of overlapping, windowed segments: the variance drops by roughly the number of segments, at the cost of frequency resolution (fs/Nsegf_s/N_{seg}).

📝 Quick check (Level 3)
0/3 answered
  1. 1. scipy.special.ellipk(m) expects…
  2. 2. Lower low-pass cutoff → group delay…
  3. 3. Welch averaging trades…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

SciPy, measured

Exercise 1. Event-based periods from solve_ivp (rtol 10⁻¹⁰) match the elliptic formula to better than 10⁻⁸ s. At θ0 = 3 rad the period is 5.158 s against 2.006 s for the small-angle formula (2.6× longer). brentq solves Kepler’s equation to 10⁻¹² even at e = 0.95. curve_fit recovers A = 2.00, γ = 0.300 and ω = 3.097 from noisy data (true 2, 0.3, 3.1).

Exercise 2: filtering a 0.5 Hz attitude signal with 37 Hz vibration and noise (raw SNR 4.7 dB; Welch finds the vibration at 36.9 Hz). Butterworth, order 4:

cutoff zero-phase SNR causal SNR causal delay
2 Hz 22.2 dB 3.9 dB 205 ms
5 Hz 20.8 dB 11.3 dB 80 ms
20 Hz 14.9 dB 14.0 dB 20 ms
50 Hz 6.4 dB 6.2 dB 5 ms

Offline, the lowest cutoff is best. In real time, the 2 Hz filter’s 205 ms lag makes it worse than the raw signal. The best causal choice here is a 20 Hz cutoff: the classic noise-versus-lag trade-off of every control loop.

🐍 Exercise 2 (research): the price of real-time filtering
Build a slow attitude signal with structural vibration and noise, locate the vibration with a Welch PSD, low-pass it with Butterworth filters of several cutoffs both causally (sosfilt) and with zero phase (sosfiltfilt), and measure SNR and delay (cross-correlation lag).

SciPy in AI, robotics and aerospace

  • Orbit and attitude propagation with solve_ivp and events (eclipse entry, apoapsis, impact).
  • Estimation: least_squares for orbit determination and calibration; linalg for Kalman filters.
  • Signal conditioning of IMU, vibration and audio data; causal filters in loops, zero-phase in post-processing.
  • Statistics for test campaigns, sensor characterization and Monte Carlo dispersion analysis.

References

  1. P. Virtanen et al. (2020). “SciPy 1.0: fundamental algorithms for scientific computing in Python.” Nature Methods, 17.
  2. SciPy documentation (docs.scipy.org): integrate.solve_ivp, optimize, signal, special.ellipk.
  3. E. Hairer, S. P. Nørsett, G. Wanner (1993). Solving Ordinary Differential Equations I. Springer.
  4. A. V. Oppenheim, R. W. Schafer (2010). Discrete-Time Signal Processing, 3rd ed. Pearson.
  5. P. D. Welch (1967). “The use of fast Fourier transform for the estimation of power spectra.” IEEE Transactions on Audio and Electroacoustics, 15(2).