Algorithm Search⌘K

Problemcore

Minimum-energy control

Also called minimum-norm control.

Reach a given state at a given time with the input of least energy, solved by a formula in the controllability Gramian.

The minimum-energy control problem asks for the input that moves a linear system x˙=Ax+Bu\dot x = A x + B u from a given state x0x_0 to a given state x1x_1 in a given time t1t_1, with the least energy ∫0t1∣u(t)∣2 dt\int_0^{t_1} |u(t)|^2\, dt. If the controllability Gramian W(t1)=∫0t1eAsBBTeATs dsW(t_1) = \int_0^{t_1} e^{A s} B B^T e^{A^T s}\, ds is invertible, the answer is unique and has a closed form:

u∗(t)=BTeAT(t1−t)W(t1)−1d,d=x1−eAt1x0,u^*(t) = B^T e^{A^T (t_1 - t)} W(t_1)^{-1} d, \qquad d = x_1 - e^{A t_1} x_0,

and the least energy is dTW(t1)−1dd^T W(t_1)^{-1} d. The Gramian is invertible exactly when the system has controllability, so the problem is also the standard proof that a controllable system can reach every state. The discrete-time problem has the same form with the NN-step Gramian and is a least-norm solution of a linear system. The formula belongs to the controllability theory of linear systems that Kalman, Ho and Narendra developed in the early 1960s; textbooks such as Brockett (1970) present it as a least-norm problem in a space of functions, and Van Loan (1978) gave the block exponential method that computes the Gramian.

In plain words

You must bring the system to a target at a fixed time and you pay for the square of the input. Of all the inputs that arrive on time, take the one that is cheapest. Without the free motion, the system would need to cover the distance dd. The input that does this cheaply pushes hardest in the directions where the input moves the state easily, and the Gramian measures how easily each direction is reached. A target in a direction where WW has a small eigenvalue is expensive, and a short time t1t_1 makes every target expensive.

Definition

Input. Real matrices AA (n×nn \times n) and BB (n×mn \times m), states x0,x1∈Rnx_0, x_1 \in \mathbb{R}^n and a time t1>0t_1 > 0.

Output. An input u∗:[0,t1]→Rmu^* : [0, t_1] \to \mathbb{R}^m, square integrable, such that the solution of x˙=Ax+Bu∗\dot x = A x + B u^*, x(0)=x0x(0) = x_0 has x(t1)=x1x(t_1) = x_1, and

∫0t1∣u∗(t)∣2 dt≤∫0t1∣u(t)∣2 dt\int_0^{t_1} |u^*(t)|^2\, dt \le \int_0^{t_1} |u(t)|^2\, dt

for every input uu with the same property; or the answer that no input reaches x1x_1.

Solution. Let d=x1−eAt1x0d = x_1 - e^{A t_1} x_0. If W(t1)W(t_1) is invertible, the unique optimal input is the formula above. The proof (proofs/correctness.md) writes the reached state as eAt1x0+Lue^{A t_1} x_0 + \mathcal{L} u for a linear map L\mathcal{L} from inputs to Rn\mathbb{R}^n, shows that LL∗=W\mathcal{L} \mathcal{L}^* = W, and finds that u∗=L∗W−1du^* = \mathcal{L}^* W^{-1} d is orthogonal to every input that L\mathcal{L} maps to 0. Any other admissible input is u∗+vu^* + v with Lv=0\mathcal{L} v = 0, and its energy is ∣u∗∣2+∣v∣2|u^*|^2 + |v|^2. If W(t1)W(t_1) is singular, the reachable values of dd lie in a proper subspace, the range of W(t1)W(t_1); for dd in that range the formula holds with the pseudoinverse.

Variants

  • Discrete time. For xk+1=Axk+Bukx_{k+1} = A x_k + B u_k and NN steps, minimize ∑k=0N−1∣uk∣2\sum_{k=0}^{N-1} |u_k|^2 with xN=x1x_N = x_1. With WN=∑j=0N−1AjBBT(AT)jW_N = \sum_{j=0}^{N-1} A^j B B^T (A^T)^j and d=x1−ANx0d = x_1 - A^N x_0, the answer is uk=BT(AT)N−1−kWN−1du_k = B^T (A^T)^{N-1-k} W_N^{-1} d, energy dTWN−1dd^T W_N^{-1} d. It is rational for rational data.
  • Weighted energy. Minimize ∫uTRu dt\int u^T R u\, dt with R>0R > 0: replace BBTB B^T by BR−1BTB R^{-1} B^T in the Gramian and BTB^T by R−1BTR^{-1} B^T in the input.
  • Time-varying systems. Replace eA(t−s)e^{A (t - s)} by the state transition matrix Φ(t,s)\Phi(t, s) in all formulas.
  • Soft target. Penalize x(t1)−x1x(t_1) - x_1 in place of requiring it to be zero. This is a finite-horizon LQR problem with Q=0Q = 0 and a terminal weight QfQ_f, and as Qf→∞Q_f \to \infty its solution tends to the minimum-energy input.
  • Input bounds. With ∣ui∣≤1|u_i| \le 1 there is no closed form. Minimum time with bounded input gives bang-bang control, and minimum fuel ∫∣u∣ dt\int |u|\, dt gives inputs that switch between −1-1, 00 and 11; both follow from the maximum principle.

Examples

Double integrator. A=[0100]A = \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}, B=[01]B = \begin{bmatrix} 0 \\ 1 \end{bmatrix}, so eAsB=[s1]e^{A s} B = \begin{bmatrix} s \\ 1 \end{bmatrix} and

W(t1)=∫0t1[s2ss1]ds=[t13/3t12/2t12/2t1].W(t_1) = \int_0^{t_1} \begin{bmatrix} s^2 & s \\ s & 1 \end{bmatrix} ds = \begin{bmatrix} t_1^3/3 & t_1^2/2 \\ t_1^2/2 & t_1 \end{bmatrix}.

Move from rest at 0 to rest at 1 in t1=1t_1 = 1: d=(1,0)d = (1, 0), W−1=[12−6−64]W^{-1} = \begin{bmatrix} 12 & -6 \\ -6 & 4 \end{bmatrix}, η=W−1d=(12,−6)\eta = W^{-1} d = (12, -6). With eATτη=(12,12τ−6)e^{A^T \tau} \eta = (12, 12 \tau - 6) and τ=1−t\tau = 1 - t, the input is u∗(t)=6−12tu^*(t) = 6 - 12 t: full push at the start, full brake at the end, and it changes sign at t=1/2t = 1/2. The energy is ∫01(6−12t)2 dt=12=dTη\int_0^1 (6 - 12 t)^2\, dt = 12 = d^T \eta. For a general time the energy is 12/t1312 / t_1^3, so half the time costs eight times the energy.

A stable scalar plant. a=−1a = -1, b=1b = 1: W(t1)=(1−e−2t1)/2W(t_1) = (1 - e^{-2 t_1})/2. From 00 to 11 in t1=1t_1 = 1 the energy is 2/(1−e−2)≈2.31302/(1 - e^{-2}) \approx 2.3130, and u∗(t)=e−(1−t)/W(1)u^*(t) = e^{-(1 - t)} / W(1) grows toward the end, since an early push decays before t1t_1.

Discrete scalar plant. xk+1=2xk+ukx_{k+1} = 2 x_k + u_k from 0 to 21 in 3 steps: C=[4,2,1]C = [4, 2, 1], W3=21W_3 = 21, η=1\eta = 1, so u=(4,2,1)u = (4, 2, 1) and the energy is 21. Early inputs are larger because the plant doubles them.

No solution. A=I2A = I_2, B=(1,1)TB = (1, 1)^T. Both states move together, WW is a multiple of [1111]\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix} and is singular, and the target (1,0)(1, 0) from 00 cannot be reached.

Known algorithms

The closed form is computed in a fixed number of matrix operations:

  1. MINIMUM-ENERGY-CONTROL(A, B, x_0, x_1, t_1)
  2. 1W ← Gramian(A, B, t_1) ▷ e^{M t_1}, M = [[-A, B B^T], [0, A^T]] (Van Loan)
  3. 2if W is not positive definite then return "x_1 cannot be reached from every x_0"
  4. 3d ← x_1 - e^{A t_1} x_0
  5. 4η ← W^(-1) d
  6. 5u(t) ← B^T e^{A^T (t_1 - t)} η, for 0 ≤ t ≤ t_1
  7. 6return u and the energy d^T η

Line L1 uses Van Loan's block method (1978): if eMt1=[⋅G0F]e^{M t_1} = \begin{bmatrix} \cdot & G \\ 0 & F \end{bmatrix}, then F=eATt1F = e^{A^T t_1}, G=e−At1W(t1)G = e^{-A t_1} W(t_1), and W(t1)=FTGW(t_1) = F^T G. Other ways to compute the Gramian are numerical quadrature of the integral, and the Lyapunov equation AW+WAT+BBT=eAt1BBTeATt1A W + W A^T + B B^T = e^{A t_1} B B^T e^{A^T t_1}, which has a unique solution when λi+λj≠0\lambda_i + \lambda_j \ne 0 for all eigenvalues λi,λj\lambda_i, \lambda_j of AA, including i=ji = j. Line L4 should use a Cholesky factorization, as WW is symmetric positive definite. The discrete-time problem is the least-norm solution of Cu=dC u = d for the reachability matrix C=[AN−1B,…,B]C = [A^{N-1} B, \dots, B], solved exactly in rational arithmetic by u=CT(CCT)−1du = C^T (C C^T)^{-1} d.

The implementation computes both versions. Its tests compare the Gramian with the Lyapunov equation on 500 random systems, simulate the plant together with the optimal input (RK4, step 0.010.01) and check that the state reaches x1x_1 within 10−610^{-6} with the stated energy, check that piecewise constant inputs on finer grids cost more and tend to the optimum, and compare the discrete answer with the solution of the KKT system of the least-norm problem in exact arithmetic on 500 random problems.

Bounds

  • Cost. In the real RAM, lines L2 to L4 cost O(n3)O(n^3). The exponential in line L1 by scaling and squaring costs O(n3log⁡(∥A∥t1+2))O(n^3 \log(\|A\| t_1 + 2)) operations to a fixed accuracy. Each evaluation of u(t)u(t) costs one more exponential. On a time grid it is cheaper to integrate the adjoint system z˙=−ATz\dot z = -A^T z from z(0)=eATt1ηz(0) = e^{A^T t_1} \eta and set u=BTzu = B^T z, at O(n2+nm)O(n^2 + n m) per step. The discrete version costs O(Nn2m+n3)O(N n^2 m + n^3).
  • Energy bounds. ∣d∣2/λmax⁡(W)≤dTW−1d≤∣d∣2/λmin⁡(W)|d|^2 / \lambda_{\max}(W) \le d^T W^{-1} d \le |d|^2 / \lambda_{\min}(W). The eigenvectors of WW for small eigenvalues are the hard directions.
  • Short horizons. For the double integrator, the energy grows like t1−3t_1^{-3} for a change of position. In general, for a target that needs kk integrations of the input, the energy grows like t1−(2k−1)t_1^{-(2 k - 1)} as t1→0t_1 \to 0.
  • Exactness. In continuous time the answer involves eAt1e^{A t_1} and is not rational in general. In discrete time it is rational for rational data and the formula is exact.

Reductions

  • To least norm in a Hilbert space. The problem is the least-norm solution of the linear equation Lu=d\mathcal{L} u = d, from the space of square integrable inputs to Rn\mathbb{R}^n. The answer is the projection of 0 on an affine subspace, u∗=L∗(LL∗)−1du^* = \mathcal{L}^* (\mathcal{L} \mathcal{L}^*)^{-1} d, and LL∗=W\mathcal{L} \mathcal{L}^* = W. The discrete version is the same with L=C\mathcal{L} = C.
  • To LQR. As a limit of LQR problems with a terminal weight, see Variants. Conversely, the minimum-energy input is the open-loop input of an LQR problem with a terminal constraint.
  • The reachable set. The states reachable from 0 at time t1t_1 with energy at most 1 form the ellipsoid {x:xTW(t1)−1x≤1}\{x : x^T W(t_1)^{-1} x \le 1\}. The dual statement for the observability Gramian gives the output energy of an initial state, and balanced truncation uses both ellipsoids to find the states that are hard to reach and hard to observe.

Applications

  • Proof of reachability: the formula gives an explicit input for every target when WW is invertible, so it is the usual proof that the Gramian test or the rank test of controllability is sufficient.
  • Open-loop transfers, such as moving a satellite or a flexible arm between two rest states, where the energy is a proxy for fuel or heating.
  • The energy dTW−1dd^T W^{-1} d as a measure of how hard a system is to control, for example to compare actuator placements, or the nodes of a network that receive the input.
  • Model reduction: the Gramian energy of a state is the input energy needed to reach it, which is how balanced truncation ranks states.
Proof: The Gramian formula gives the unique input of least energy, and Van Loan's block exponential gives the Gramianfull

Let A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, x0,x1∈Rnx_0, x_1 \in \mathbb{R}^n and t1>0t_1 > 0. The inputs are the square integrable functions u:[0,t1]→Rmu : [0, t_1] \to \mathbb{R}^m, with the inner product ⟨u,v⟩=∫0t1u(t)Tv(t) dt\langle u, v \rangle = \int_0^{t_1} u(t)^T v(t)\, dt and the energy ∥u∥2=⟨u,u⟩\|u\|^2 = \langle u, u \rangle. The solution of x˙=Ax+Bu\dot x = A x + B u, x(0)=x0x(0) = x_0 at time t1t_1 is

x(t1)=eAt1x0+Lu,Lu=∫0t1eA(t1−s)Bu(s) ds.x(t_1) = e^{A t_1} x_0 + \mathcal{L} u, \qquad \mathcal{L} u = \int_0^{t_1} e^{A (t_1 - s)} B u(s)\, ds.

So x(t1)=x1x(t_1) = x_1 holds if and only if Lu=d\mathcal{L} u = d, with d=x1−eAt1x0d = x_1 - e^{A t_1} x_0. The controllability Gramian is

W=∫0t1eAsBBTeATs ds.W = \int_0^{t_1} e^{A s} B B^T e^{A^T s}\, ds.

Step 1: the adjoint and the Gramian

For η∈Rn\eta \in \mathbb{R}^n let (L∗η)(t)=BTeAT(t1−t)η(\mathcal{L}^* \eta)(t) = B^T e^{A^T (t_1 - t)} \eta. Then for every input uu,

ηTLu=∫0t1ηTeA(t1−s)Bu(s) ds=⟨L∗η,u⟩,\eta^T \mathcal{L} u = \int_0^{t_1} \eta^T e^{A (t_1 - s)} B u(s)\, ds = \langle \mathcal{L}^* \eta, u \rangle,

so L∗\mathcal{L}^* is the adjoint of L\mathcal{L}. Also LL∗η=∫0t1eA(t1−s)BBTeAT(t1−s)η ds=Wη\mathcal{L} \mathcal{L}^* \eta = \int_0^{t_1} e^{A (t_1 - s)} B B^T e^{A^T (t_1 - s)} \eta\, ds = W \eta, by the substitution σ=t1−s\sigma = t_1 - s.

Step 2: the formula is optimal when W is invertible

Assume WW is invertible and put η=W−1d\eta = W^{-1} d and u∗=L∗ηu^* = \mathcal{L}^* \eta, that is u∗(t)=BTeAT(t1−t)W−1du^*(t) = B^T e^{A^T (t_1 - t)} W^{-1} d. By Step 1, Lu∗=Wη=d\mathcal{L} u^* = W \eta = d, so u∗u^* reaches x1x_1.

Let uu be any input with Lu=d\mathcal{L} u = d, and let v=u−u∗v = u - u^*. Then Lv=0\mathcal{L} v = 0 and ⟨u∗,v⟩=⟨L∗η,v⟩=ηTLv=0\langle u^*, v \rangle = \langle \mathcal{L}^* \eta, v \rangle = \eta^T \mathcal{L} v = 0. Hence

∥u∥2=∥u∗+v∥2=∥u∗∥2+2⟨u∗,v⟩+∥v∥2=∥u∗∥2+∥v∥2≥∥u∗∥2,\|u\|^2 = \|u^* + v\|^2 = \|u^*\|^2 + 2 \langle u^*, v \rangle + \|v\|^2 = \|u^*\|^2 + \|v\|^2 \ge \|u^*\|^2,

with equality only if ∥v∥=0\|v\| = 0, that is, u=u∗u = u^* almost everywhere. So u∗u^* is the unique input of least energy. Its energy is ∥u∗∥2=⟨L∗η,L∗η⟩=ηTLL∗η=ηTWη=dTW−1d\|u^*\|^2 = \langle \mathcal{L}^* \eta, \mathcal{L}^* \eta \rangle = \eta^T \mathcal{L} \mathcal{L}^* \eta = \eta^T W \eta = d^T W^{-1} d.

Step 3: when W is singular

WW is symmetric and positive semidefinite, since ηTWη=∫0t1∣BTeATsη∣2 ds≥0\eta^T W \eta = \int_0^{t_1} |B^T e^{A^T s} \eta|^2\, ds \ge 0. If WW is singular, take η≠0\eta \ne 0 with Wη=0W \eta = 0. The integrand is continuous and nonnegative, so BTeATsη=0B^T e^{A^T s} \eta = 0 for all s∈[0,t1]s \in [0, t_1], which means L∗η=0\mathcal{L}^* \eta = 0 and ηTLu=⟨L∗η,u⟩=0\eta^T \mathcal{L} u = \langle \mathcal{L}^* \eta, u \rangle = 0 for every input. So every reachable dd lies in the hyperplane ηTd=0\eta^T d = 0, and a target x1x_1 with ηT(x1−eAt1x0)≠0\eta^T (x_1 - e^{A t_1} x_0) \ne 0 cannot be reached. This is why the code stops with an error when WW is not positive definite. (WW is singular exactly when (A,B)(A, B) is not controllable, but this proof does not need that fact.)

Step 4: Van Loan's block exponential

Let M=[−ABBT0AT]M = \begin{bmatrix} -A & B B^T \\ 0 & A^T \end{bmatrix} and write eMt=[E(t)G(t)0F(t)]e^{M t} = \begin{bmatrix} E(t) & G(t) \\ 0 & F(t) \end{bmatrix}; the lower left block is 0 because MM is block upper triangular. From ddteMt=MeMt\frac{d}{dt} e^{M t} = M e^{M t} and eM0=Ie^{M 0} = I, the blocks satisfy F˙=ATF\dot F = A^T F with F(0)=IF(0) = I, so F(t)=eATtF(t) = e^{A^T t}; E˙=−AE\dot E = -A E with E(0)=IE(0) = I, so E(t)=e−AtE(t) = e^{-A t}; and

G˙=−AG+BBTF=−AG+BBTeATt,G(0)=0.\dot G = -A G + B B^T F = -A G + B B^T e^{A^T t}, \qquad G(0) = 0.

By variation of constants, G(t)=∫0te−A(t−s)BBTeATs dsG(t) = \int_0^t e^{-A (t - s)} B B^T e^{A^T s}\, ds. Multiply by eAt=F(t)Te^{A t} = F(t)^T:

F(t)TG(t)=∫0teAsBBTeATs ds=W(t).F(t)^T G(t) = \int_0^t e^{A s} B B^T e^{A^T s}\, ds = W(t).

So the code computes W(t1)=FTGW(t_1) = F^T G from one exponential of Mt1M t_1, as in line L1. It then makes the result exactly symmetric by averaging with its transpose, which changes nothing in exact arithmetic.

Theorem

Let t1>0t_1 > 0 and let WW be the Gramian. If WW is invertible, then the input u∗(t)=BTeAT(t1−t)W−1(x1−eAt1x0)u^*(t) = B^T e^{A^T (t_1 - t)} W^{-1} (x_1 - e^{A t_1} x_0) steers x0x_0 to x1x_1 at time t1t_1, every other input that does so has larger energy, and the least energy is dTW−1dd^T W^{-1} d. If WW is singular, some target cannot be reached. The lines L1 to L6 of the page compute exactly these quantities, in exact arithmetic.

Proof. Line L1 computes WW by Step 4. Line L2 stops when WW is singular, which is right by Step 3. Lines L3 and L4 compute dd and η=W−1d\eta = W^{-1} d. Line L5 is the input u∗=L∗ηu^* = \mathcal{L}^* \eta and line L6 the energy dTηd^T \eta, both optimal by Step 2. ■\blacksquare

The discrete-time version

For xk+1=Axk+Bukx_{k+1} = A x_k + B u_k, the state after NN steps is xN=ANx0+Cux_N = A^N x_0 + C u with C=[AN−1B⋯ABB]C = \begin{bmatrix} A^{N-1} B & \cdots & A B & B \end{bmatrix} and u=(u0,…,uN−1)u = (u_0, \dots, u_{N-1}) stacked. The same argument with the Euclidean inner product on RNm\mathbb{R}^{N m}, L=C\mathcal{L} = C and L∗=CT\mathcal{L}^* = C^T gives: if WN=CCT=∑j=0N−1AjBBT(AT)jW_N = C C^T = \sum_{j=0}^{N-1} A^j B B^T (A^T)^j is invertible, the unique input of least ∑k∣uk∣2\sum_k |u_k|^2 is u=CTWN−1du = C^T W_N^{-1} d with d=x1−ANx0d = x_1 - A^N x_0, that is uk=BT(AT)N−1−kWN−1du_k = B^T (A^T)^{N-1-k} W_N^{-1} d, and the least energy is dTWN−1dd^T W_N^{-1} d. All quantities are rational for rational data, so the function minimum_energy_discrete computes them exactly.

Floating point

The continuous-time code is in floating point. The relative error of the Gramian is that of the exponential of Mt1M t_1, near 10−1410^{-14} when Mt1M t_1 is not far from normal and has small norm. The solve with WW multiplies the error by about the condition number of WW, which is large when the target is hard to reach (a short horizon t1t_1, or a direction that BB excites weakly). The code refuses WW when W−ϵIW - \epsilon I is not positive definite, with ϵ\epsilon equal to 10−1210^{-12} times the largest entry of WW.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Fixed step simulation for the control pages.

Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
  flat list. x is a flat list. u is whatever the control returns (a flat
  list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
  step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
  round(hold / dt) must match the real ratios within 1e-9 (relative), or
  ValueError is raised.

This file holds no controller or observer of a control page.
"""

__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]


def _axpy(a, x, y):
    return [yi + a * xi for xi, yi in zip(x, y)]


def rk4_step(f, t, x, u, dt):
    """Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
    k1 = f(t, x, u)
    k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
    k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
    k4 = f(t + dt, _axpy(dt, k3, x), u)
    return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]


def _ratio(num, den, what):
    r = round(num / den)
    if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
        raise ValueError(what + " is not an integer multiple of dt")
    return r


def simulate(f, x0, t0, t1, dt, control=None, hold=None):
    """Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.

    control(t, x) gives the input. It is called at each sampling instant
    t0 + j hold, and its value is held (zero-order hold) until the next
    instant. hold must be an integer multiple of dt; hold = None means
    hold = dt. With control = None the input is None.

    Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
    N inputs, where us[k] acts on [ts[k], ts[k + 1]].
    """
    if dt <= 0:
        raise ValueError("dt must be positive")
    n_steps = _ratio(t1 - t0, dt, "t1 - t0")
    if n_steps < 0:
        raise ValueError("t1 is before t0")
    r = 1 if hold is None else _ratio(hold, dt, "hold")
    if r < 1:
        raise ValueError("hold must be at least dt")
    x = list(x0)
    ts = [t0]
    xs = [list(x)]
    us = []
    u = None
    for k in range(n_steps):
        t = t0 + k * dt
        if control is not None and k % r == 0:
            u = control(t, list(x))
        x = rk4_step(f, t, x, u, dt)
        ts.append(t0 + (k + 1) * dt)
        xs.append(x)
        us.append(u)
    return ts, xs, us


def simulate_discrete(F, x0, N, control=None):
    """Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.

    u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
    N + 1 states and N inputs. Exact if F and control are exact.
    """
    x = list(x0)
    xs = [list(x)]
    us = []
    for k in range(N):
        u = control(k, list(x)) if control is not None else None
        x = list(F(k, x, u))
        xs.append(x)
        us.append(u)
    return xs, us


def lti(A, B=None):
    """Return f(t, x, u) = A x + B u for the system x' = A x + B u.

    u may be a flat list, a scalar (one input) or None (zero input). B may
    be None for a system with no input.
    """
    def f(t, x, u):
        dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
        if B is None or u is None:
            return dx
        uu = u if isinstance(u, (list, tuple)) else [u]
        return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
    return f


def _self_test():
    import math
    f = lti([[-1.0]])
    _, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
    assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
minimum_energy_control.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-energy-control/. The authors are listed in prov/H8NC6E.jsonl.

"""Minimum-energy control of a linear system, in continuous and discrete time.

Continuous time: steer x' = A x + B u from x(0) = x0 to x(t1) = x1 with the
least energy, the integral of |u(t)|^2 over [0, t1]. The answer is

    u(t) = B^T e^(A^T (t1 - t)) W^(-1) d,   d = x1 - e^(A t1) x0,

with the controllability Gramian W = int_0^t1 e^(A s) B B^T e^(A^T s) ds,
and the least energy is d^T W^(-1) d. The Gramian comes from one matrix
exponential of size 2n (Van Loan's block method). Floating point.

Discrete time: steer x_(k+1) = A x_k + B u_k from x0 to x_N = x1 with the
least sum of |u_k|^2. The answer uses the N-step Gramian
W_N = sum_j A^j B B^T (A^T)^j. Exact with int and Fraction data.
"""

from fractions import Fraction
from typing import Callable, List, Sequence, Tuple, Union

import ctlmat as cm

Num = Union[int, float, Fraction]
Matrix = List[List[Num]]


def gramian(A: Sequence[Sequence[Num]], B: Sequence[Sequence[Num]], t1: float) -> List[List[float]]:
    """Return W(t1) = int_0^t1 e^(A s) B B^T e^(A^T s) ds.

    Van Loan: the exponential of [[-A, B B^T], [0, A^T]] t1 is
    [[., G], [0, F]] with F = e^(A^T t1) and G = e^(-A t1) W(t1), so
    W(t1) = F^T G. Cost: one exponential of a 2n by 2n matrix, O(n^3 log(|A| t1)).
    """
    n = len(A)
    a = [[float(v) for v in row] for row in A]
    b = [[float(v) for v in row] for row in B]
    bbt = cm.mul(b, cm.transpose(b))
    m = cm.block([[cm.scale(-1.0, a), bbt], [0, cm.transpose(a)]])
    e = cm.expm(cm.scale(float(t1), m))
    g = [row[n:] for row in e[:n]]
    f = [row[n:] for row in e[n:]]
    w = cm.mul(cm.transpose(f), g)
    return [[(w[i][j] + w[j][i]) / 2 for j in range(n)] for i in range(n)]


def minimum_energy_control(
    A: Sequence[Sequence[Num]],
    B: Sequence[Sequence[Num]],
    x0: Sequence[Num],
    x1: Sequence[Num],
    t1: float,
    rel_tol: float = 1e-12,
) -> Tuple[Callable[[float], List[float]], float, List[float]]:
    """Return (u, energy, eta) for the transfer from x0 at time 0 to x1 at time t1.

    u(t) is the optimal input as a list of m floats, energy is the least value
    of int_0^t1 |u|^2 dt, and eta = W^(-1) d. Precondition: t1 > 0. Raises
    ValueError if the Gramian is not positive definite within rel_tol times its
    largest entry, that is, if (A, B) is not controllable in the precision used.
    Cost: O(n^3 log(|A| t1)) once, then O(n^3 log(|A| t1)) per call of u.
    """
    if not t1 > 0:
        raise ValueError("t1 must be positive")
    a = [[float(v) for v in row] for row in A]
    b = [[float(v) for v in row] for row in B]
    w = gramian(a, b, t1)  # @line L1
    big = max(abs(v) for row in w for v in row)
    if big == 0.0 or not cm.is_pos_def(w, rel_tol * big):  # @line L2
        raise ValueError("the Gramian is singular: x1 cannot be reached from every x0")
    phi = cm.expm(cm.scale(float(t1), a))
    d = [float(v) - s for v, s in zip(x1, cm.matvec(phi, [float(v) for v in x0]))]  # @line L3
    eta = cm.solve(w, d)  # @line L4
    bt, at = cm.transpose(b), cm.transpose(a)

    def u(t: float) -> List[float]:
        return cm.matvec(bt, cm.matvec(cm.expm(cm.scale(t1 - t, at)), eta))  # @line L5

    energy = cm.dot(d, eta)  # @line L6
    return u, energy, eta


def reach_matrix(A: Sequence[Sequence[Num]], B: Sequence[Sequence[Num]], N: int) -> Matrix:
    """Return [A^(N-1) B, A^(N-2) B, ..., B], so that x_N = A^N x0 + C u for u = (u_0, ..., u_(N-1))."""
    blocks = []
    p = [list(row) for row in B]
    for _ in range(N):
        blocks.append(p)
        p = cm.mul(A, p)
    blocks.reverse()
    return [sum((blk[i] for blk in blocks), []) for i in range(len(A))]


def minimum_energy_discrete(
    A: Sequence[Sequence[Num]],
    B: Sequence[Sequence[Num]],
    x0: Sequence[Num],
    x1: Sequence[Num],
    N: int,
) -> Tuple[List[List[Num]], Num]:
    """Return (us, energy): the inputs u_0, ..., u_(N-1) of least sum |u_k|^2 with x_N = x1.

    us[k] = B^T (A^T)^(N-1-k) W_N^(-1) d with d = x1 - A^N x0 and
    W_N = C C^T for C = reach_matrix(A, B, N); energy = d^T W_N^(-1) d.
    Exact (Fraction) with int and Fraction data. Raises ValueError if W_N is
    singular. Cost: O(N n^2 m + n^3).
    """
    if N < 1:
        raise ValueError("N must be at least 1")
    c = reach_matrix(A, B, N)
    w = cm.mul(c, cm.transpose(c))
    d = [v - s for v, s in zip(x1, cm.matvec(cm.mat_power(A, N), list(x0)))]
    eta = cm.solve(w, d)
    flat = cm.matvec(cm.transpose(c), eta)
    m = len(B[0])
    us = [flat[k * m:(k + 1) * m] for k in range(N)]
    return us, cm.dot(d, eta)
test_minimum_energy_control.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-energy-control/. The authors are listed in prov/H8NC6E.jsonl.

import math
import random
from fractions import Fraction

import pytest

import ctlmat as cm
import ctlsim
from minimum_energy_control import gramian, minimum_energy_control, minimum_energy_discrete, reach_matrix


def maxabs(a):
    return max(abs(v) for row in a for v in row)


def rand_mat(rng, n, m, lo=-1.5, hi=1.5):
    return [[rng.uniform(lo, hi) for _ in range(m)] for _ in range(n)]


def simulate_optimal(A, B, x0, eta, t1, dt):
    """RK4 on x' = A x + B B^T z, z' = -A^T z, e' = |B^T z|^2, so u = B^T z."""
    n, m = len(A), len(B[0])
    at = cm.transpose(A)
    z0 = cm.matvec(cm.expm(cm.scale(t1, at)), eta)

    def f(t, s, u):
        x, z = s[:n], s[n:2 * n]
        v = [sum(B[i][j] * z[i] for i in range(n)) for j in range(m)]
        dx = [sum(A[i][k] * x[k] for k in range(n)) + sum(B[i][j] * v[j] for j in range(m)) for i in range(n)]
        dz = [-sum(at[i][k] * z[k] for k in range(n)) for i in range(n)]
        return dx + dz + [sum(vj * vj for vj in v)]

    steps = round(t1 / dt)
    assert abs(steps * dt - t1) <= 1e-12 * t1
    _, xs, _ = ctlsim.simulate(f, list(x0) + z0 + [0.0], 0.0, t1, dt)
    return xs[-1][:n], xs[-1][-1]


def lyapunov_gramian(A, B, t1):
    """Independent oracle: A W + W A^T + B B^T - e^(A t1) B B^T e^(A^T t1) = 0, by Kronecker form."""
    n = len(A)
    phi = cm.expm(cm.scale(t1, A))
    bbt = cm.mul(B, cm.transpose(B))
    rhs = cm.sub(cm.mul(phi, cm.mul(bbt, cm.transpose(phi))), bbt)
    op = cm.add(cm.kron(cm.eye(n), A), cm.kron(A, cm.eye(n)))
    return cm.unvec(cm.solve(op, cm.vec(rhs)), n, n)


def test_double_integrator():
    A, B = [[0, 1], [0, 0]], [[0], [1]]
    W = gramian(A, B, 1.0)
    want = [[1 / 3, 1 / 2], [1 / 2, 1.0]]
    assert maxabs(cm.sub(W, want)) <= 1e-14
    u, energy, eta = minimum_energy_control(A, B, [0, 0], [1, 0], 1.0)
    assert abs(energy - 12.0) <= 1e-12
    assert abs(eta[0] - 12.0) <= 1e-11 and abs(eta[1] + 6.0) <= 1e-11
    for t in [0.0, 0.25, 0.5, 0.75, 1.0]:
        assert abs(u(t)[0] - (6.0 - 12.0 * t)) <= 1e-11


def test_scalar_closed_form():
    for a in [-1.0, 0.5, 2.0]:
        for t1 in [0.3, 1.0, 2.0]:
            W = gramian([[a]], [[1.0]], t1)[0][0]
            want = (math.exp(2 * a * t1) - 1) / (2 * a)
            assert abs(W - want) <= 1e-13 * want
            _, energy, _ = minimum_energy_control([[a]], [[1.0]], [0.0], [1.0], t1)
            assert abs(energy - 1 / want) <= 1e-12 / want
    W = gramian([[-1.0]], [[1.0]], 1.0)[0][0]
    assert abs(W - (1 - math.exp(-2.0)) / 2) <= 1e-15


def test_gramian_against_lyapunov_oracle():
    rng = random.Random(11)
    count = 0
    while count < 500:
        n, m = rng.randint(1, 3), rng.randint(1, 2)
        A, B = rand_mat(rng, n, n), rand_mat(rng, n, m)
        sums = [r1 + r2 for r1 in cm.polyroots(cm.charpoly(A)) for r2 in cm.polyroots(cm.charpoly(A))]
        if min(abs(s) for s in sums) < 0.05:
            continue
        t1 = rng.uniform(0.2, 1.5)
        W = gramian(A, B, t1)
        ref = lyapunov_gramian(A, B, t1)
        assert maxabs(cm.sub(W, ref)) <= 1e-9 * (1 + maxabs(ref))
        assert cm.is_symmetric(W, 0)
        count += 1


def test_simulation_reaches_target_with_stated_energy():
    rng = random.Random(5)
    done = 0
    while done < 60:
        n, m = rng.randint(1, 3), rng.randint(1, 2)
        A, B = rand_mat(rng, n, n), rand_mat(rng, n, m)
        W = gramian(A, B, 1.0)
        if min(cm._sym_eigvals(W)) < 1e-3:
            continue
        x0 = [rng.uniform(-1, 1) for _ in range(n)]
        x1 = [rng.uniform(-1, 1) for _ in range(n)]
        u, energy, eta = minimum_energy_control(A, B, x0, x1, 1.0)
        # RK4 with dt = 0.01 over [0, 1]; the global error is O(dt^4).
        xT, eT = simulate_optimal(A, B, x0, eta, 1.0, 0.01)
        scale = 1 + max(abs(v) for v in eta)
        assert max(abs(p - q) for p, q in zip(xT, x1)) <= 1e-6 * scale
        assert abs(eT - energy) <= 1e-6 * (1 + energy)
        z = u(0.5)
        assert len(z) == m
        done += 1


def test_zoh_inputs_cost_more():
    """Least-norm piecewise constant inputs reach x1 too, with energy at least the optimum, tending to it."""
    A, B = [[0.0, 1.0], [-2.0, -0.3]], [[0.0], [1.0]]
    x0, x1, t1 = [1.0, 0.0], [0.0, 0.5], 2.0
    _, best, _ = minimum_energy_control(A, B, x0, x1, t1)
    prev = None
    for N in [5, 10, 20, 40]:
        h = t1 / N
        aug = cm.block([[A, B], [cm.zeros(1, 2), cm.zeros(1, 1)]])
        e = cm.expm(cm.scale(h, aug))
        Ad = [row[:2] for row in e[:2]]
        Bd = [row[2:] for row in e[:2]]
        us, en = minimum_energy_discrete(Ad, Bd, x0, x1, N)
        zoh = h * en
        assert zoh >= best * (1 - 1e-12)
        if prev is not None:
            assert zoh <= prev + 1e-12
        prev = zoh
    assert prev - best <= 0.01 * best


def kkt_oracle(C, d):
    """Least-norm solution of C u = d from the KKT system [[I, C^T], [C, 0]] [u; lam] = [0; d]."""
    n, k = len(C), len(C[0])
    K = cm.block([[cm.eye(k), cm.transpose(C)], [C, cm.zeros(n, n)]])
    sol = cm.solve(K, [0] * k + list(d))
    return sol[:k]


def test_discrete_exact_against_kkt():
    rng = random.Random(23)
    count = 0
    while count < 500:
        n, m, N = rng.randint(1, 3), rng.randint(1, 2), rng.randint(1, 4)
        A = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
        B = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
        C = reach_matrix(A, B, N)
        if cm.det(cm.mul(C, cm.transpose(C))) == 0:
            with pytest.raises(ValueError):
                minimum_energy_discrete(A, B, [0] * n, [1] * n, N)
            continue
        x0 = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
        x1 = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
        us, energy = minimum_energy_discrete(A, B, x0, x1, N)
        x = list(x0)
        for uk in us:
            x = [p + q for p, q in zip(cm.matvec(A, x), cm.matvec(B, uk))]
        assert x == x1
        flat = [v for uk in us for v in uk]
        d = [p - q for p, q in zip(x1, cm.matvec(cm.mat_power(A, N), x0))]
        assert flat == kkt_oracle(C, d)
        assert energy == sum(v * v for v in flat)
        count += 1


def test_discrete_scalar_example():
    us, energy = minimum_energy_discrete([[2]], [[1]], [0], [21], 3)
    assert us == [[Fraction(4)], [Fraction(2)], [Fraction(1)]]
    assert energy == 21


def test_uncontrollable_and_bad_input():
    with pytest.raises(ValueError):
        minimum_energy_control([[1.0, 0.0], [0.0, 1.0]], [[1.0], [1.0]], [0.0, 0.0], [1.0, 0.0], 1.0)
    with pytest.raises(ValueError):
        minimum_energy_control([[0.0]], [[1.0]], [0.0], [1.0], 0.0)
    with pytest.raises(ValueError):
        minimum_energy_control([[0.0]], [[0.0]], [0.0], [1.0], 1.0)
    with pytest.raises(ValueError):
        minimum_energy_discrete([[1]], [[1]], [0], [1], 0)

References

  1. Roger W. Brockett, Finite Dimensional Linear Systems, Wiley, 1970 (SIAM Classics in Applied Mathematics 74, 2015), the treatment of controllability and of inputs of least norm
  2. Charles F. Van Loan, Computing integrals involving the matrix exponential, IEEE Transactions on Automatic Control 23(3), 395-404, 1978, integrals such as the Gramian computed from the exponential of one block triangular matrix

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/H8NC6E/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a known algorithm
  • a contract.yaml