Skip to content

About

First-principles Python library for MIMO controls and Kalman filtering

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

ย 

History

48 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

PyControls

A comprehensive, first-principles Python library for modeling, analysis, design, simulation, and estimation of linear and nonlinear control systems.

Focus: MIMO Systems, Derivative-Free Optimization, Real-Time MPC, and Hardware-in-the-Loop (HIL)


๐Ÿ“– Introduction

PyControls is designed to bridge the gap between abstract control theory and reliable numerical implementation. Unlike standard libraries that often wrap compiled binaries (such as LAPACK/BLAS) behind opaque function calls, PyControls implements core algorithms in pure, JIT-compiled Python. This ensures conceptual clarity for students and inspectability for researchers, without sacrificing performance.


๐Ÿ›  Design Goals and Implementation Philosophy

1. Mathematical Transparency

Every algorithm exposes its internal mechanics:

  • The Extended Kalman Filter (EKF) computes Jacobians dynamically using Complex-Step Differentiation rather than accepting pre-computed matrices.
  • The Model Predictive Controller (MPC) explicitly pre-computes condensed quadratic program (QP) matrices, allowing inspection of Hessians and gradients before optimization.

2. Numerical Honesty & Robustness

PyControls prioritizes numerically stable methods:

  • Complex-Step Differentiation replaces finite differences to eliminate subtractive cancellation errors (core/ekf.py).
  • Adaptive Integrators (RK45) are implemented from scratch with access to internal error metrics (core/solver.py).
  • Numba JIT Compilation accelerates tight computational loops while preserving Python readability.

3. MIMO by Default

All systems are treated as Multiple-Input Multiple-Output (MIMO). Single-input single-output (SISO) systems are handled as degenerate MIMO cases. All state-space representations (A, B, C, D) enforce matrix semantics.


โšก Core Engines & Numerical Methods

Matrix Exponentials: Scaling and Squaring

File: core/solver.py
Function: manual_matrix_exp

Discretization of linear systems requires computing the matrix exponential:

exp(A t)

Eigen-decomposition methods are numerically unstable for defective matrices. PyControls instead implements Scaling and Squaring:

  1. Scaling โ€“ The matrix A is divided by 2^s until its norm is below 0.5.
  2. Approximation โ€“ A truncated Taylor series or Padรฉ approximant evaluates exp(A / 2^s).
  3. Squaring โ€“ The result is squared s times to recover exp(A).

This routine is JIT-compiled with Numba, achieving near C-level performance without reliance on heavy external libraries.


Nonlinear Integration: Adaptive RK5(4)7M

File: core/solver.py
Class: NonlinearSolver

PyControls implements an adaptive Dormandโ€“Prince (RK45) integrator:

  • Two simultaneous state estimates are computed: 4th-order (xโ‚„) and 5th-order (xโ‚…).

  • The local truncation error is estimated as ||xโ‚… โˆ’ xโ‚„||.

  • Step size adapts dynamically:

    • Error > tolerance โ†’ step rejected and reduced.
    • Error โ‰ช tolerance โ†’ step size increased.

This maximizes simulation speed while maintaining accuracy, even for stiff systems.


Jacobian Computation: Complex-Step Differentiation

Files: core/ekf.py, core/mpc.py

Jacobian computation avoids finite differences:

f(x + iยทh) โ‰ˆ f(x) + iยทhยทf'(x)

Taking the imaginary part yields exact derivatives to machine precision:

f'(x) = Im(f(x + iยทh)) / h

PyControls uses h = 1e-20, achieving high accuracy with zero subtractive cancellation error.


๐ŸŽฎ Model Predictive Control (MPC)

File: core/mpc.py

The MPC module features a dual-mode solver that automatically selects the appropriate algorithm.

Mode 1: ADMM for Linear Systems

Trigger: When A and B matrices are provided.

  • Uses Alternating Direction Method of Multipliers (ADMM).
  • Employs a condensed formulation, optimizing only the input sequence.
  • Hessian and inverse are pre-computed during initialization.
  • Online execution uses only matrixโ€“vector products and clipping for constraints.

This results in constant-time execution with respect to horizon length during runtime.

Mode 2: iLQR for Nonlinear Systems

Trigger: When a nonlinear model_func is supplied.

  • Uses Iterative Linear Quadratic Regulator (iLQR).
  • Avoids forming a global Hessian, maintaining O(N) memory and time complexity.
  • Includes Levenbergโ€“Marquardt regularization for robustness.
  • Forward-pass line search ensures monotonic cost reduction.

๐Ÿ“ก Estimation and Filtering

Extended Kalman Filter (EKF)

File: core/ekf.py

  • Supports simultaneous state and parameter estimation.
  • Jacobians are computed using Complex-Step Differentiation.
  • Automatically detects vectorized user models for efficient Jacobian evaluation.
  • Physical parameters can be modeled as slowly varying states, enabling real-time model adaptation.

Unscented Kalman Filter (UKF)

File: core/ukf.py

  • Implements the Van der Merwe scaled sigma-point formulation.
  • Ideal for highly nonlinear systems where EKF linearization is insufficient.

๐ŸŽ› Hardware-in-the-Loop (HIL) Support

The HIL_PWM_Firmware directory contains embedded firmware for real-time hardware interfacing via Arduino/PlatformIO.

Firmware Highlights (src/main.cpp):

  • Minimal ASCII serial protocol (Q:VALUE, A:VALUE).
  • ADC oversampling with averaging to reduce noise and increase effective resolution.
  • Watchdog safety logic zeros actuators on communication loss.

This enables safe and robust real-time control experiments.


๐Ÿ“‚ Project Structure

โ”œโ”€โ”€ benchmarking/
โ”‚   โ”œโ”€โ”€ benchmark_csd.py
โ”‚   โ”œโ”€โ”€ benchmark_dare.py
โ”‚   โ”œโ”€โ”€ benchmark_ekf_ukf_timing.py
โ”‚   โ”œโ”€โ”€ benchmark_expm.py
โ”‚   โ”œโ”€โ”€ benchmark_jit.py
โ”‚   โ”œโ”€โ”€ benchmark_mpc.py
โ”‚   โ”œโ”€โ”€ benchmark_mpc_optimality.py
โ”‚   โ”œโ”€โ”€ benchmark_ode.py
โ”‚   โ”œโ”€โ”€ benchmark_scalability.py
โ”‚   โ”œโ”€โ”€ benchmark_scipy_speed.py
โ”‚   โ”œโ”€โ”€ benchmark_stability_margins.py
โ”‚   โ”œโ”€โ”€ control_metrics.py
โ”‚   โ””โ”€โ”€ estimation_metrics.py
โ”œโ”€โ”€ core/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ analysis.py
โ”‚   โ”œโ”€โ”€ control_utils.py
โ”‚   โ”œโ”€โ”€ ekf.py
โ”‚   โ”œโ”€โ”€ ekf_discrete.py
โ”‚   โ”œโ”€โ”€ estimator.py
โ”‚   โ”œโ”€โ”€ exceptions.py
โ”‚   โ”œโ”€โ”€ math_utils.py
โ”‚   โ”œโ”€โ”€ mpc.py
โ”‚   โ”œโ”€โ”€ solver.py
โ”‚   โ”œโ”€โ”€ state_space.py
โ”‚   โ”œโ”€โ”€ transfer_function.py
โ”‚   โ””โ”€โ”€ ukf.py
โ”œโ”€โ”€ docs/
โ”‚   โ”œโ”€โ”€ Benchmarks Guide.md
โ”‚   โ”œโ”€โ”€ Complexity Analysis.md
โ”‚   โ”œโ”€โ”€ Equations and Formulae.md
โ”‚   โ”œโ”€โ”€ LICENSE
โ”‚   โ””โ”€โ”€ README.md
โ”œโ”€โ”€ helpers/
โ”‚   โ”œโ”€โ”€ config.py
โ”‚   โ”œโ”€โ”€ exit.py
โ”‚   โ”œโ”€โ”€ plot.py
โ”‚   โ”œโ”€โ”€ simulation_runner.py
โ”‚   โ””โ”€โ”€ system_registry.py
โ”œโ”€โ”€ modules/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ interactive_lab.py
โ”‚   โ””โ”€โ”€ physics_engine.py
โ”œโ”€โ”€ systems/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ battery.py
โ”‚   โ”œโ”€โ”€ dc_motor.py
โ”‚   โ”œโ”€โ”€ pendulum.py
โ”‚   โ””โ”€โ”€ thermistor.py
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ test_analysis.py
โ”‚   โ”œโ”€โ”€ test_control.py
โ”‚   โ”œโ”€โ”€ test_jit_vec.py
โ”‚   โ”œโ”€โ”€ test_kf_ekf.py
โ”‚   โ”œโ”€โ”€ test_math.py
โ”‚   โ”œโ”€โ”€ test_models.py
โ”‚   โ”œโ”€โ”€ test_modules.py
โ”‚   โ”œโ”€โ”€ test_solver.py
โ”‚   โ”œโ”€โ”€ test_systems.py
โ”‚   โ””โ”€โ”€ test_ukf_mpc.py
โ”œโ”€โ”€ benchmark_runner.py
โ”œโ”€โ”€ main.py
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ script.py
โ””โ”€โ”€ test_runner.py

๐Ÿ“Š Benchmarks & Empirical Performance

PyControls includes a comprehensive 13-suite automated benchmarking harness evaluated across 5-run statistical averages:

Module / Operation PyControls Metric Comparison vs SciPy / Industry Key Engineering Advantage
Matrix Exponential ($4\times4$) $3.02\mu\text{s}$ $10.9\times$ faster than SciPy ($33.02\mu\text{s}$) JIT zero-overhead execution for online LPV discretization
Numerical Jacobian (CSD) $10.43\mu\text{s}$ $20.7\times$ faster than SciPy ($215.87\mu\text{s}$) Machine-precision derivatives ($<10^{-16}$) without cancellation error
DARE Solver (SDA, $4\times4$) $32.92\mu\text{s}$ $8.9\times$ faster than SciPy ($291.39\mu\text{s}$) Quadratic doubling algorithm ($2^k$) vs QZ decomposition
ZOH Discretization ($4\times4$) $6.38\mu\text{s}$ $3.1\times$ faster than SciPy ($19.82\mu\text{s}$) Exact block matrix exponential with zero wrapper overhead
Numba JIT Acceleration ($8\times8$) $6.59\mu\text{s}$ $327.8\times$ speedup over pure Python LLVM compilation to native x86 machine instructions
Linear MPC (ADMM, $H=10$) $0.53\text{ ms}$ Real-time capable up to $1.9\text{ kHz}$ Condensed pre-factored QP matrices with vector clipping
Nonlinear Estimation (UKF) $0.0133\text{ RMSE}$ $37.9%$ lower RMSE than EKF Superior sigma-point tracking through Coulomb stiction

For complete derivations, mathematical concepts, and metrics, see docs/Benchmarks Guide.md.


๐Ÿš€ Getting Started

Install Dependencies

pip install -r requirements.txt

Note: numba is heavily used for solver performance. Ensure it is correctly installed for your architecture.

Run a Test Simulation (Pendulum)

python main.py

Run Unit Tests

python test_runner.py

Run Benchmarks Suite (5-Iteration Average)

python benchmark_runner.py

๐Ÿ“œ License

This project is licensed under the MIT License. See docs/LICENSE for details.


Version: 5.5.0
Last Updated: 18 August 2026

About

First-principles Python library for MIMO controls and Kalman filtering

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages