Algorithm Search⌘K

Algorithmresearch

Proper generalized decomposition

Builds a separated representation of the solution as sums of products of functions of each variable by greedy alternating enrichment.

Time
O(M (M + s) (M + s + I) N) total
Space
O((M + s) N) extra
Where
I = the largest number of alternating steps per mode; M = the number of modes; N = the sum nx + ny of the grid sizes; s = the number of terms of the right side
Properties
deterministicnot exactiterativemonotone-energy
Origin
Amine Ammar, Béchir Mokdad, Francisco Chinesta, Roland Keunings, 2006

The proper generalized decomposition (PGD) computes the solution of a partial differential equation in many variables as a sum of products of functions of one variable each, u(x,y)≈∑m=1MXm(x)Ym(y)u(x, y) \approx \sum_{m=1}^M X_m(x) Y_m(y). It does not need the solution first. It adds one product at a time: for the current approximation it finds a new product that lowers the energy of the error, by solving in turn a small problem for XX with YY fixed and a small problem for YY with XX fixed. Each small problem is a one-dimensional Galerkin problem. So the cost grows with the sum of the grid sizes, not with their product, and this is the reason to use it in high dimensions, where a grid in all variables is too large.

The POD-Galerkin model and the reduced basis method are a posteriori: they first compute full solutions, then compress them. PGD is a priori: it builds the separated form from the operator and the right side, and it never forms a full solution. The truncated SVD of the exact solution gives the best sum of MM products in the Frobenius norm, but it needs the exact solution. PGD is greedy, so at a given MM it is usually less accurate than the SVD, but it costs much less. Alternating least squares also fixes one factor and solves for the other, but it fits a known matrix; PGD solves an equation whose solution is unknown.

In plain words

You want the temperature on a square, but you write it as a short list of "a curve in xx times a curve in yy". Start with nothing. Look at what the equation still misses, and find the one product that helps the most: guess the yy curve, find the best xx curve for it, then the best yy curve for that xx curve, and repeat a few times. Add the product and look again. Each step only solves problems on a line, never on the whole square.

The problem

The model problem is −auxx−buyy=f-a u_{xx} - b u_{yy} = f on (0,1)2(0, 1)^2 with u=0u = 0 on the boundary, with central finite differences on nx×nyn_x \times n_y interior points. With Uij=u(xi,yj)U_{ij} = u(x_i, y_j), the discrete system is the Sylvester equation

KxU+UKy=F,Kx=ahx2tridiag⁡(−1,2,−1),Ky=bhy2tridiag⁡(−1,2,−1),K_x U + U K_y = F, \qquad K_x = \frac{a}{h_x^2} \operatorname{tridiag}(-1, 2, -1), \quad K_y = \frac{b}{h_y^2} \operatorname{tridiag}(-1, 2, -1),

or (Kx⊗I+I⊗Ky)vec⁡(U)=vec⁡(F)(K_x \otimes I + I \otimes K_y) \operatorname{vec}(U) = \operatorname{vec}(F) with the Kronecker product. The right side is given in separated form F=∑t=1sftx(fty)TF = \sum_{t=1}^s f^x_t (f^y_t)^T. The output is a list of modes (Xm,Ym)(X_m, Y_m) with UM=∑m=1MXmYmTU_M = \sum_{m=1}^M X_m Y_m^T. The operator A(V)=KxV+VKy\mathcal{A}(V) = K_x V + V K_y is symmetric positive definite for the inner product ⟨V,W⟩=∑ijVijWij\langle V, W \rangle = \sum_{ij} V_{ij} W_{ij}, so UU minimizes the energy

J(V)=12⟨V,AV⟩−⟨F,V⟩,∥U−V∥A2=2(J(V)−J(U)).J(V) = \tfrac12 \langle V, \mathcal{A} V \rangle - \langle F, V \rangle, \qquad \|U - V\|_{\mathcal{A}}^2 = 2 (J(V) - J(U)).

The algorithm

  1. PGD(K_x, K_y, separated F, M, tol)
  2. 1U ← 0, the empty sum of products
  3. 2for m = 1 to M
  4. 3R ← F - K_x U - U K_y, kept as a sum of products
  5. 4if ‖R‖_F ≤ tol ‖F‖_F then stop
  6. 5Y ← R^T w for a fixed w with R^T w ≠ 0
  7. 6repeat until X Y^T stops changing, at most I times
  8. 7X ← the solution of (‖Y‖² K_x + (Y^T K_y Y) I) X = R Y
  9. 8Y ← the solution of ((X^T K_x X) I + ‖X‖² K_y) Y = R^T X
  10. 9U ← U + X Y^T
  11. 10return the modes of U

Line L3 never forms RR as an nx×nyn_x \times n_y matrix. It is the list of the ss terms of FF and the 2(m−1)2(m-1) terms −(KxXk)YkT-(K_x X_k) Y_k^T and −Xk(KyYk)T-X_k (K_y Y_k)^T. Then RY=∑tpt(qtTY)R Y = \sum_t p_t (q_t^T Y) and RTXR^T X cost O((s+m)N)O((s + m) N), and line L4 uses ∥R∥F2=∑t,t′(ptTpt′)(qtTqt′)\|R\|_F^2 = \sum_{t, t'} (p_t^T p_{t'}) (q_t^T q_{t'}). Lines L7 and L8 are the conditions that the derivative of J(U+XYT)J(U + X Y^T) with respect to XX, and then YY, is 0. Each matrix is a positive combination of a tridiagonal matrix and the identity, so the Thomas algorithm solves it in O(N)O(N). Line L5 picks w=(1,…,1)w = (1, \ldots, 1), or a unit vector if that gives 0, so that RY≠0R Y \ne 0.

Example

By hand. Let F=skslTF = s_k s_l^T be a product of eigenvectors, Kxsk=λkskK_x s_k = \lambda_k s_k and Kysl=μlslK_y s_l = \mu_l s_l. Then R=FR = F and line L5 gives Y=(skTw)sl=c slY = (s_k^T w) s_l = c\, s_l. Line L7 reads c2∥sl∥2(Kx+μlI)X=c∥sl∥2skc^2 \|s_l\|^2 (K_x + \mu_l I) X = c \|s_l\|^2 s_k, so X=sk/(c(λk+μl))X = s_k / (c (\lambda_k + \mu_l)), and XYT=skslT/(λk+μl)X Y^T = s_k s_l^T / (\lambda_k + \mu_l). This is the exact solution, so the next residual is 0 and the method stops after one mode. The test file checks this on a 10×710 \times 7 grid.

The unit load. Take a=b=1a = b = 1, f=1f = 1 (one term, s=1s = 1) and a 30×3030 \times 30 grid. The reference is the exact discrete solution by the discrete sine transform in each direction. The table compares PGD with the truncated SVD of the reference, which is the best possible in the Frobenius norm. These numbers come from the test file and a scratch run.

MM relative energy error of PGD relative Frobenius error of PGD relative Frobenius error of the SVD alternating steps
1 3.20×10−23.20 \times 10^{-2} 9.19×10−39.19 \times 10^{-3} 9.15×10−39.15 \times 10^{-3} 6
2 3.48×10−33.48 \times 10^{-3} 7.12×10−47.12 \times 10^{-4} 5.04×10−45.04 \times 10^{-4} 7
3 8.04×10−48.04 \times 10^{-4} 3.79×10−43.79 \times 10^{-4} 4.62×10−54.62 \times 10^{-5} 11
4 3.73×10−43.73 \times 10^{-4} 2.16×10−42.16 \times 10^{-4} 4.40×10−64.40 \times 10^{-6} 30
6 2.05×10−52.05 \times 10^{-5} 1.66×10−61.66 \times 10^{-6} 6
8 5.17×10−75.17 \times 10^{-7} 1.10×10−71.10 \times 10^{-7} 9

The energy error goes down at each mode, as the proof shows. One mode is almost as good as the best rank one, but later modes are far from the SVD: a greedy sum of the best single products is not the best sum. Eight modes store 8⋅60=4808 \cdot 60 = 480 numbers, against 900 for the grid; in dd dimensions with nn points each the ratio is MdnM d n against ndn^d.

Correctness

The proof file shows, in exact arithmetic, that lines L7 and L8 each give the unique minimizer of J(U+XYT)J(U + X Y^T) over one factor with the other fixed, so JJ does not increase inside the loop. The first step of line L7 lowers JJ by 12(RY)TG−1(RY)>0\tfrac12 (R Y)^T G^{-1} (R Y) > 0, where GG is its matrix. With the identity ∥U−V∥A2=2(J(V)−J(U))\|U - V\|_{\mathcal{A}}^2 = 2(J(V) - J(U)), the energy error goes down strictly at each mode while R≠0R \ne 0. It also shows that the method stops after one mode when FF is a product of eigenvectors. Convergence of the energy error to 0 as MM grows is proved by Le Bris, Lelièvre and Maday for the greedy method with the best rank-one product at each step. The alternating steps find a stationary point, not always the best product, so the page cites this result and does not claim it for the implementation.

Proof: Each PGD step is a one-factor energy minimizer, so the energy error does not grow, and the method stopsfull

We assume exact arithmetic. KxK_x and KyK_y are symmetric positive definite, A(V)=KxV+VKy\mathcal{A}(V) = K_x V + V K_y, ⟨V,W⟩=∑ijVijWij\langle V, W \rangle = \sum_{ij} V_{ij} W_{ij}, UU is the solution of A(U)=F\mathcal{A}(U) = F, and J(V)=12⟨V,AV⟩−⟨F,V⟩J(V) = \frac12 \langle V, \mathcal{A} V \rangle - \langle F, V \rangle.

Lemma 1 (the energy identity). A\mathcal{A} is symmetric positive definite for ⟨⋅,⋅⟩\langle \cdot, \cdot \rangle, and ∥U−V∥A2=⟨U−V,A(U−V)⟩=2(J(V)−J(U))\|U - V\|_{\mathcal{A}}^2 = \langle U - V, \mathcal{A}(U - V) \rangle = 2 (J(V) - J(U)) for every VV.

Proof. ⟨W,AV⟩=tr⁡(WTKxV)+tr⁡(WTVKy)\langle W, \mathcal{A} V \rangle = \operatorname{tr}(W^T K_x V) + \operatorname{tr}(W^T V K_y), which is symmetric in VV and WW because KxK_x and KyK_y are symmetric. With the eigendecompositions Kx=QΛQTK_x = Q \Lambda Q^T and Ky=PMPTK_y = P M P^T and V~=QTVP\tilde{V} = Q^T V P, ⟨V,AV⟩=∑kl(λk+μl)V~kl2>0\langle V, \mathcal{A} V \rangle = \sum_{kl} (\lambda_k + \mu_l) \tilde{V}_{kl}^2 > 0 for V≠0V \ne 0. Expand J(V)−J(U)J(V) - J(U) with F=AUF = \mathcal{A} U: it is 12⟨V,AV⟩−⟨U,AV⟩+12⟨U,AU⟩=12∥U−V∥A2\frac12 \langle V, \mathcal{A} V \rangle - \langle U, \mathcal{A} V \rangle + \frac12 \langle U, \mathcal{A} U \rangle = \frac12 \|U - V\|_{\mathcal{A}}^2. □\square

Fix the current sum Um−1U_{m-1} and its residual R=F−A(Um−1)R = F - \mathcal{A}(U_{m-1}). For a product XYTX Y^T,

ϕ(X,Y)=J(Um−1+XYT)−J(Um−1)=12⟨XYT,A(XYT)⟩−⟨R,XYT⟩.\phi(X, Y) = J(U_{m-1} + X Y^T) - J(U_{m-1}) = \tfrac12 \langle X Y^T, \mathcal{A}(X Y^T) \rangle - \langle R, X Y^T \rangle .

Lemma 2 (the half steps). For a fixed Y≠0Y \ne 0, ϕ(⋅,Y)\phi(\cdot, Y) is a strictly convex quadratic with the unique minimizer X∗X^* given by line L7, and ϕ(X∗,Y)=−12(RY)TG−1(RY)\phi(X^*, Y) = -\frac12 (R Y)^T G^{-1} (R Y) with G=∥Y∥2Kx+(YTKyY)IG = \|Y\|^2 K_x + (Y^T K_y Y) I. The same holds for line L8 with the roles of XX and YY exchanged.

Proof. ⟨XYT,KxXYT⟩=∥Y∥2XTKxX\langle X Y^T, K_x X Y^T \rangle = \|Y\|^2 X^T K_x X and ⟨XYT,XYTKy⟩=(YTKyY)∥X∥2\langle X Y^T, X Y^T K_y \rangle = (Y^T K_y Y) \|X\|^2, so ϕ(X,Y)=12XTGX−XT(RY)\phi(X, Y) = \frac12 X^T G X - X^T (R Y). GG is positive definite, since ∥Y∥2>0\|Y\|^2 > 0, KxK_x is positive definite and YTKyY>0Y^T K_y Y > 0. So the unique minimizer solves GX=RYG X = R Y, which is line L7, and the minimum value is −12(RY)TG−1(RY)-\frac12 (RY)^T G^{-1} (RY). The proof for YY uses ⟨XYT,A(XYT)⟩=(XTKxX)∥Y∥2+∥X∥2YTKyY\langle X Y^T, \mathcal{A}(X Y^T) \rangle = (X^T K_x X) \|Y\|^2 + \|X\|^2 Y^T K_y Y in the same way. □\square

Lemma 3 (the start vector). If R≠0R \ne 0, line L5 returns YY with RY≠0R Y \ne 0.

Proof. Some row ii of RR is not 0, so RTei≠0R^T e_i \ne 0, and the loop over w=(1,…,1),e1,e2,…w = (1, \ldots, 1), e_1, e_2, \ldots finds a ww with Y=RTw≠0Y = R^T w \ne 0. Then wTRY=∥RTw∥2>0w^T R Y = \|R^T w\|^2 > 0, so RY≠0R Y \ne 0. □\square

Theorem 1 (the energy error does not grow). Let R≠0R \ne 0 at line L4. Then the new sum Um=Um−1+XYTU_m = U_{m-1} + X Y^T of line L9 satisfies ∥U−Um∥A<∥U−Um−1∥A\|U - U_m\|_{\mathcal{A}} < \|U - U_{m-1}\|_{\mathcal{A}}.

Proof. Let Y0Y_0 be the vector of line L5 and X1,Y1,X2,…X_1, Y_1, X_2, \ldots the iterates of lines L7 and L8. By Lemma 2, each half step does not increase ϕ\phi: ϕ(X1,Y0)≥ϕ(X1,Y1)≥ϕ(X2,Y1)≥…\phi(X_1, Y_0) \ge \phi(X_1, Y_1) \ge \phi(X_2, Y_1) \ge \ldots. By Lemmas 2 and 3, ϕ(X1,Y0)=−12(RY0)TG−1(RY0)<0\phi(X_1, Y_0) = -\frac12 (R Y_0)^T G^{-1} (R Y_0) < 0, since G−1G^{-1} is positive definite and RY0≠0R Y_0 \ne 0. So the final product has ϕ(X,Y)<0\phi(X, Y) < 0, that is, J(Um)<J(Um−1)J(U_m) < J(U_{m-1}), and Lemma 1 turns this into the claim. ■\blacksquare

Theorem 2 (one mode for a product of eigenvectors). If F=skslTF = s_k s_l^T with Kxsk=λkskK_x s_k = \lambda_k s_k and Kysl=μlslK_y s_l = \mu_l s_l, then the first mode is XYT=U=skslT/(λk+μl)X Y^T = U = s_k s_l^T / (\lambda_k + \mu_l), and the method stops at the next line L4.

Proof. With U0=0U_0 = 0, R=FR = F, and line L5 gives Y0=c slY_0 = c\, s_l with c=skTw≠0c = s_k^T w \ne 0 by Lemma 3. Line L7 gives c2∥sl∥2(Kx+μlI)X=c∥sl∥2skc^2 \|s_l\|^2 (K_x + \mu_l I) X = c \|s_l\|^2 s_k, so X=sk/(c(λk+μl))X = s_k / (c(\lambda_k + \mu_l)). Line L8 then has XTKxX=λk∥X∥2X^T K_x X = \lambda_k \|X\|^2 and RTX=(skTX)slR^T X = (s_k^T X) s_l, so ∥X∥2(λkI+Ky)Y=(skTX)sl\|X\|^2 (\lambda_k I + K_y) Y = (s_k^T X) s_l and Y=c slY = c\, s_l again. The product does not change, so the loop stops, and XYT=skslT/(λk+μl)X Y^T = s_k s_l^T / (\lambda_k + \mu_l). It solves the equation, since A(skslT)=(λk+μl)skslT\mathcal{A}(s_k s_l^T) = (\lambda_k + \mu_l) s_k s_l^T. Then the next residual is 0. ■\blacksquare

Termination. Line L2 runs at most MM times and line L6 at most II times, and each of lines L3, L5, L7 and L8 does a finite amount of work. No division by 0 occurs: the tridiagonal matrices of lines L7 and L8 are positive definite by Lemma 2, so all pivots of the Thomas algorithm are positive. Line L5 only runs when R≠0R \ne 0, and then Lemma 3 gives a nonzero YY, so GG is positive definite at the first step; every later XX and YY is nonzero because it solves GX=RYG X = R Y with RY≠0R Y \ne 0, which follows by induction from ϕ<0\phi < 0 (a zero factor gives ϕ=0\phi = 0, and ϕ\phi does not increase).

What is not proved here. The energy error goes to 0 as M→∞M \to \infty when each mode is the best rank-one product; this is the result of Le Bris, Lelièvre and Maday, and it is cited, not proved. The alternating loop of lines L6 to L8 gives a product with ϕ<0\phi < 0 but not always the best one, so for this implementation only the monotone decrease is proved.

Complexity

In the real RAM model, with N=nx+nyN = n_x + n_y: at mode mm the residual has s+2ms + 2m terms. One alternating step costs O((s+m)N)O((s + m) N) for RYR Y or RTXR^T X and O(N)O(N) for the tridiagonal solves. The norm check costs O((s+m)2N)O((s + m)^2 N). Over MM modes with at most II steps each, the time is O(M(M+s)(M+s+I)N)O(M (M + s)(M + s + I) N). The memory is O((M+s)N)O((M + s) N) for the modes and the right side. A direct solve on the grid needs nxnyn_x n_y unknowns, and in dd dimensions ndn^d; PGD needs O(Mdn)O(M d n).

Properties

  • A priori. It needs the operator and the right side, not snapshots of the solution.
  • Monotone in energy. The energy error does not grow when a mode is added, for a symmetric positive definite operator.
  • Linear in the dimension. The cost per mode grows with ∑knk\sum_k n_k, not with ∏knk\prod_k n_k.
  • Not optimal. The sum of MM greedy modes is usually worse than the best rank-MM approximation.
  • Separated input. The right side and the operator must have a separated form with few terms.

Variants and improvements

  • More than two variables. For u(x1,…,xd)u(x_1, \ldots, x_d), add products X(1)(x1)⋯X(d)(xd)X^{(1)}(x_1) \cdots X^{(d)}(x_d), and update each factor in turn with the others fixed. Parameters and time can be extra variables, which gives a solution for all parameter values at once.
  • Update of the earlier modes. After adding a mode, recompute the coefficients, or all factors in one direction, by a Galerkin projection on the current modes. This improves the accuracy per mode.
  • Non-symmetric problems. For an operator that is not symmetric, the Galerkin conditions no longer minimize an energy. Minimal residual or Petrov-Galerkin versions keep a monotone error.
  • Nonlinear problems. Linearize, for example by a fixed point or Newton iteration, and apply PGD at each step.
  • Other tensor formats. Tensor-train or hierarchical Tucker formats replace the sum of products when the canonical sum needs too many terms.

When to use it

Use PGD when the equation has many variables, or when you want the solution as an explicit function of parameters, and when the operator and the data have a separated form with few terms. It fits the forward problems of stochastic Galerkin type, where the random variables are extra coordinates. For a problem in two or three space variables only, a direct or multigrid solver on the grid is usually better. When you can afford full solutions at chosen parameters, the reduced basis method gives certified errors.

Pitfalls

  • Not separable data. A right side or a coefficient with no short separated form, such as a load on a disc, needs many terms, and the cost grows with ss.
  • Slow convergence. For rough data the modes decay slowly. For a random right side of rank 3 on an 8×68 \times 6 grid in the tests, the relative energy error after 10 modes is still 1.07×10−31.07 \times 10^{-3}, although the exact solution has rank at most 6.
  • Stagnation of the alternating steps. The loop can need many steps or stop at a poor product. Limit the steps, and do not expect the best product.
  • The residual floor. The Gram formula for ∥R∥F2\|R\|_F^2 computes a square, so cancellation limits the relative residual to about the square root of the machine precision, near 10−810^{-8}. Do not set the tolerance below that.
  • Scaling of the factors. XYTX Y^T does not change when XX is multiplied by cc and YY by 1/c1/c. Compare products, not factors, when you test for a fixed point.

Implementations

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.

proper_generalized_decomposition.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/proper-generalized-decomposition/. The authors are listed in prov/TWTF98.jsonl.
"""Proper generalized decomposition (PGD) by greedy rank-one enrichment with alternating directions.

The model problem is -a u_xx - b u_yy = f on the unit square with u = 0 on the boundary, with
central differences on nx by ny interior points. With U[i][j] = u(x_i, y_j), the discrete system is
    Kx U + U Ky = F,
where Kx = (a / hx^2) tridiag(-1, 2, -1) and Ky = (b / hy^2) tridiag(-1, 2, -1). This is the
Kronecker system (Kx (x) I + I (x) Ky) vec(U) = vec(F). PGD writes U as a sum of products
X_1 Y_1^T + ... + X_M Y_M^T and never forms a matrix of size nx * ny: F is given in the
separated form F = sum_s fx_s fy_s^T, and every residual is kept as a list of products.
"""

import math

Vector = list[float]
Terms = list[tuple[Vector, Vector]]  # a matrix sum_t p_t q_t^T


def dot(u: Vector, v: Vector) -> float:
    return sum(a * b for a, b in zip(u, v))


def tri_apply(d: float, o: float, v: Vector) -> Vector:
    """(d on the diagonal, o off the diagonal) times v."""
    n = len(v)
    return [d * v[i] + o * ((v[i - 1] if i > 0 else 0.0) + (v[i + 1] if i < n - 1 else 0.0)) for i in range(n)]


def tri_solve(d: float, o: float, rhs: Vector) -> Vector:
    """Solve the constant tridiagonal system (d, o) z = rhs by the Thomas algorithm."""
    n = len(rhs)
    c = [0.0] * n
    g = [0.0] * n
    m = d
    c[0], g[0] = o / m, rhs[0] / m
    for i in range(1, n):
        m = d - o * c[i - 1]
        c[i] = o / m
        g[i] = (rhs[i] - o * g[i - 1]) / m
    z = [0.0] * n
    z[-1] = g[-1]
    for i in range(n - 2, -1, -1):
        z[i] = g[i] - c[i] * z[i + 1]
    return z


class Laplace2D:
    def __init__(self, nx: int, ny: int, a: float = 1.0, b: float = 1.0):
        self.nx, self.ny = nx, ny
        hx, hy = 1.0 / (nx + 1), 1.0 / (ny + 1)
        self.kx = (2.0 * a / hx ** 2, -a / hx ** 2)
        self.ky = (2.0 * b / hy ** 2, -b / hy ** 2)

    def kx_apply(self, v: Vector) -> Vector:
        return tri_apply(self.kx[0], self.kx[1], v)

    def ky_apply(self, v: Vector) -> Vector:
        return tri_apply(self.ky[0], self.ky[1], v)


def residual_terms(op: Laplace2D, f: Terms, modes: Terms) -> Terms:
    """R = F - Kx U - U Ky for U = sum X_m Y_m^T, as a list of products."""
    out = list(f)
    for x, y in modes:
        out.append(([-t for t in op.kx_apply(x)], y))
        out.append(([-t for t in x], op.ky_apply(y)))
    return out


def norm2(terms: Terms) -> float:
    """Squared Frobenius norm of sum p_t q_t^T, by the Gram identity."""
    total = 0.0
    for i, (p, q) in enumerate(terms):
        total += dot(p, p) * dot(q, q)
        for p2, q2 in terms[i + 1:]:
            total += 2.0 * dot(p, p2) * dot(q, q2)
    return max(total, 0.0)


def times_right(terms: Terms, y: Vector) -> Vector:
    """R y."""
    out = [0.0] * len(terms[0][0])
    for p, q in terms:
        c = dot(q, y)
        out = [a + c * b for a, b in zip(out, p)]
    return out


def times_left(terms: Terms, x: Vector) -> Vector:
    """R^T x."""
    out = [0.0] * len(terms[0][1])
    for p, q in terms:
        c = dot(p, x)
        out = [a + c * b for a, b in zip(out, q)]
    return out


def start_vector(terms: Terms, nx: int) -> Vector:
    """A Y with R Y != 0 when R != 0: Y = R^T w for w = (1, ..., 1), then w = e_1, e_2, ..."""
    for w in [[1.0] * nx] + [[1.0 if i == j else 0.0 for i in range(nx)] for j in range(nx)]:
        y = times_left(terms, w)
        if any(t != 0.0 for t in y):
            return y
    raise ValueError("the residual is zero")


def solve_x(op: Laplace2D, terms: Terms, y: Vector) -> Vector:
    """The minimizer over X of the energy for a fixed Y: (|Y|^2 Kx + (Y^T Ky Y) I) X = R Y."""
    yy, yky = dot(y, y), dot(y, op.ky_apply(y))
    return tri_solve(yy * op.kx[0] + yky, yy * op.kx[1], times_right(terms, y))


def solve_y(op: Laplace2D, terms: Terms, x: Vector) -> Vector:
    """The minimizer over Y for a fixed X: ((X^T Kx X) I + |X|^2 Ky) Y = R^T X."""
    xx, xkx = dot(x, x), dot(x, op.kx_apply(x))
    return tri_solve(xx * op.ky[0] + xkx, xx * op.ky[1], times_left(terms, x))


def pgd(op: Laplace2D, f: Terms, m_max: int, tol: float = 1e-8, inner_tol: float = 1e-10, inner_max: int = 50) -> tuple[Terms, list[float], list[int]]:
    """Return the modes (X_m, Y_m), the relative residuals before each step, and the inner counts."""
    modes: Terms = []  # @line L1: U <- 0
    fnorm = math.sqrt(norm2(f))
    res: list[float] = []
    inner: list[int] = []
    for _ in range(m_max):  # @line L2
        terms = residual_terms(op, f, modes)  # @line L3: R = F - Kx U - U Ky
        res.append(math.sqrt(norm2(terms)) / fnorm)
        if res[-1] <= tol:  # @line L4: stop when the residual is small
            break
        y = start_vector(terms, op.nx)  # @line L5
        it = 0
        for it in range(inner_max):  # @line L6: alternating directions
            x = solve_x(op, terms, y)  # @line L7
            y_new = solve_y(op, terms, x)  # @line L8
            # the change from X Y^T to X Y_new^T in the Frobenius norm, relative
            xx = dot(x, x)
            ch = xx * (dot(y_new, y_new) - 2.0 * dot(y, y_new) + dot(y, y))
            y = y_new
            if ch <= inner_tol ** 2 * xx * dot(y, y):
                break
        inner.append(it + 1)
        modes.append((x, y))  # @line L9: U <- U + X Y^T
    return modes, res, inner  # @line L10


def to_dense(modes: Terms, nx: int, ny: int) -> list[Vector]:
    u = [[0.0] * ny for _ in range(nx)]
    for x, y in modes:
        for i in range(nx):
            for j in range(ny):
                u[i][j] += x[i] * y[j]
    return u
test_proper_generalized_decomposition.py 212 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/proper-generalized-decomposition/. The authors are listed in prov/TWTF98.jsonl.
import math
import random

import pytest

from proper_generalized_decomposition import (
    Laplace2D,
    dot,
    norm2,
    pgd,
    residual_terms,
    times_left,
    times_right,
    to_dense,
    tri_apply,
    tri_solve,
)


def dense(terms, nx, ny):
    return to_dense(terms, nx, ny)


def apply_a(op, v):
    """Kx V + V Ky for a dense nx by ny matrix V."""
    nx, ny = op.nx, op.ny
    out = [[0.0] * ny for _ in range(nx)]
    for j in range(ny):
        col = op.kx_apply([v[i][j] for i in range(nx)])
        for i in range(nx):
            out[i][j] += col[i]
    for i in range(nx):
        row = op.ky_apply(v[i])
        for j in range(ny):
            out[i][j] += row[j]
    return out


def inner(p, q):
    return sum(a * b for ra, rb in zip(p, q) for a, b in zip(ra, rb))


def energy_functional(op, fd, v):
    """J(V) = 1/2 <V, A V> - <F, V>."""
    return 0.5 * inner(v, apply_a(op, v)) - inner(fd, v)


def sine_solve(op, fd):
    """Reference solution of Kx U + U Ky = F by the discrete sine transform in each direction."""
    nx, ny = op.nx, op.ny
    sx = [[math.sqrt(2.0 / (nx + 1)) * math.sin((i + 1) * (k + 1) * math.pi / (nx + 1)) for k in range(nx)] for i in range(nx)]
    sy = [[math.sqrt(2.0 / (ny + 1)) * math.sin((i + 1) * (k + 1) * math.pi / (ny + 1)) for k in range(ny)] for i in range(ny)]
    lx = [op.kx[0] + 2 * op.kx[1] * math.cos((k + 1) * math.pi / (nx + 1)) for k in range(nx)]
    ly = [op.ky[0] + 2 * op.ky[1] * math.cos((k + 1) * math.pi / (ny + 1)) for k in range(ny)]
    t = [[sum(sx[i][k] * fd[i][j] for i in range(nx)) for j in range(ny)] for k in range(nx)]
    g = [[sum(t[k][j] * sy[j][l] for j in range(ny)) / (lx[k] + ly[l]) for l in range(ny)] for k in range(nx)]
    t2 = [[sum(sx[i][k] * g[k][l] for k in range(nx)) for l in range(ny)] for i in range(nx)]
    return [[sum(t2[i][l] * sy[j][l] for l in range(ny)) for j in range(ny)] for i in range(nx)]


def gauss_solve(m, b):
    n = len(b)
    a = [list(row) + [bi] for row, bi in zip(m, b)]
    for k in range(n):
        piv = max(range(k, n), key=lambda i: abs(a[i][k]))
        a[k], a[piv] = a[piv], a[k]
        for i in range(k + 1, n):
            c = a[i][k] / a[k][k]
            for j in range(k, n + 1):
                a[i][j] -= c * a[k][j]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (a[i][n] - sum(a[i][j] * x[j] for j in range(i + 1, n))) / a[i][i]
    return x


def jacobi_eigenvalues(a, sweeps=60):
    n = len(a)
    a = [list(r) for r in a]
    for _ in range(sweeps):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off <= 1e-30 * sum(a[i][i] ** 2 for i in range(n)):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                th = (a[q][q] - a[p][p]) / (2 * a[p][q])
                t = (1.0 if th >= 0 else -1.0) / (abs(th) + math.sqrt(th * th + 1))
                c = 1 / math.sqrt(t * t + 1)
                s = t * c
                for k in range(n):
                    a[k][p], a[k][q] = c * a[k][p] - s * a[k][q], s * a[k][p] + c * a[k][q]
                for k in range(n):
                    a[p][k], a[q][k] = c * a[p][k] - s * a[q][k], s * a[p][k] + c * a[q][k]
    return sorted((a[i][i] for i in range(n)), reverse=True)


def rel_errors(op, u, modes):
    """Relative energy and Frobenius errors of the first m modes, m = 1..len(modes)."""
    eu, fu = inner(u, apply_a(op, u)), inner(u, u)
    out = []
    for m in range(1, len(modes) + 1):
        um = dense(modes[:m], op.nx, op.ny)
        e = [[p - q for p, q in zip(ra, rb)] for ra, rb in zip(u, um)]
        out.append((math.sqrt(max(inner(e, apply_a(op, e)), 0.0) / eu), math.sqrt(inner(e, e) / fu)))
    return out


def random_rhs(rng, nx, ny, s):
    return [([rng.gauss(0, 1) for _ in range(nx)], [rng.gauss(0, 1) for _ in range(ny)]) for _ in range(s)]


def test_tridiagonal_solve():
    rng = random.Random(1)
    rhs = [rng.gauss(0, 1) for _ in range(9)]
    z = tri_solve(5.0, -2.0, rhs)
    assert tri_apply(5.0, -2.0, z) == pytest.approx(rhs, abs=1e-12)
    assert tri_solve(3.0, -1.0, [6.0]) == [2.0]


def test_sine_reference_against_the_kronecker_system():
    rng = random.Random(2)
    op = Laplace2D(4, 3, 1.0, 0.3)
    nx, ny = 4, 3
    fd = [[rng.gauss(0, 1) for _ in range(ny)] for _ in range(nx)]
    cols = []
    for c in range(nx * ny):
        e = [[1.0 if i * ny + j == c else 0.0 for j in range(ny)] for i in range(nx)]
        ae = apply_a(op, e)
        cols.append([ae[i][j] for i in range(nx) for j in range(ny)])
    mat = [[cols[c][r] for c in range(nx * ny)] for r in range(nx * ny)]
    x = gauss_solve(mat, [fd[i][j] for i in range(nx) for j in range(ny)])
    u = sine_solve(op, fd)
    assert [u[i][j] for i in range(nx) for j in range(ny)] == pytest.approx(x, rel=1e-10, abs=1e-12)


def test_separated_operations_against_dense():
    rng = random.Random(3)
    op = Laplace2D(6, 5, 1.0, 2.0)
    f = random_rhs(rng, 6, 5, 2)
    modes = random_rhs(rng, 6, 5, 3)
    terms = residual_terms(op, f, modes)
    rd = dense(terms, 6, 5)
    ad = apply_a(op, dense(modes, 6, 5))
    fd = dense(f, 6, 5)
    assert max(abs(rd[i][j] - fd[i][j] + ad[i][j]) for i in range(6) for j in range(5)) < 1e-9
    assert norm2(terms) == pytest.approx(inner(rd, rd), rel=1e-10)
    x, y = [rng.gauss(0, 1) for _ in range(6)], [rng.gauss(0, 1) for _ in range(5)]
    assert times_right(terms, y) == pytest.approx([dot(row, y) for row in rd], rel=1e-10, abs=1e-9)
    assert times_left(terms, x) == pytest.approx([sum(x[i] * rd[i][j] for i in range(6)) for j in range(5)], rel=1e-10, abs=1e-9)


def test_one_mode_for_a_product_of_eigenvectors():
    nx, ny = 10, 7
    op = Laplace2D(nx, ny, 1.0, 1.0)
    sx = [math.sin(2 * (i + 1) * math.pi / (nx + 1)) for i in range(nx)]
    sy = [math.sin(3 * (j + 1) * math.pi / (ny + 1)) for j in range(ny)]
    modes, res, _ = pgd(op, [(sx, sy)], 5, tol=1e-9)
    assert len(modes) == 1 and res[-1] <= 1e-9
    u = sine_solve(op, dense([(sx, sy)], nx, ny))
    um = dense(modes, nx, ny)
    assert max(abs(a - b) for ra, rb in zip(u, um) for a, b in zip(ra, rb)) < 1e-12


def test_half_steps_minimize_and_the_energy_error_does_not_grow():
    rng = random.Random(4)
    nx, ny = 8, 6
    op = Laplace2D(nx, ny, 1.0, 2.0)
    f = random_rhs(rng, nx, ny, 3)
    fd = dense(f, nx, ny)
    u = sine_solve(op, fd)
    modes, _, _ = pgd(op, f, 30, tol=1e-14)
    errs = [e for e, _ in rel_errors(op, u, modes)]
    assert all(b <= a * (1 + 1e-12) for a, b in zip([1.0] + errs, errs))
    assert errs[9] == pytest.approx(1.074e-3, rel=1e-2) and errs[-1] < 1e-5
    # the energy identity |U - V|_A^2 = 2 (J(V) - J(U))
    v = dense(modes[:3], nx, ny)
    e = [[p - q for p, q in zip(ra, rb)] for ra, rb in zip(u, v)]
    assert inner(e, apply_a(op, e)) == pytest.approx(2 * (energy_functional(op, fd, v) - energy_functional(op, fd, u)), rel=1e-8)
    # the X step is the exact minimizer for its Y: random changes of X raise J
    from proper_generalized_decomposition import solve_x

    base = modes[:2]
    terms = residual_terms(op, f, base)
    y = [rng.gauss(0, 1) for _ in range(ny)]
    x = solve_x(op, terms, y)
    j0 = energy_functional(op, fd, dense(base + [(x, y)], nx, ny))
    assert j0 < energy_functional(op, fd, dense(base, nx, ny))
    for _ in range(10):
        dx = [t + 1e-3 * rng.gauss(0, 1) for t in x]
        assert energy_functional(op, fd, dense(base + [(dx, y)], nx, ny)) > j0


def test_example_numbers():
    n = 30
    op = Laplace2D(n, n, 1.0, 1.0)
    f = [([1.0] * n, [1.0] * n)]
    u = sine_solve(op, dense(f, n, n))
    modes, res, _ = pgd(op, f, 8, tol=1e-12)
    errs = rel_errors(op, u, modes)
    assert [e for e, _ in errs[:3]] == pytest.approx([3.199e-2, 3.482e-3, 8.037e-4], rel=1e-3)
    assert errs[5][0] == pytest.approx(2.052e-5, rel=1e-2) and errs[7][0] == pytest.approx(5.166e-7, rel=1e-2)
    assert [fr for _, fr in errs[:3]] == pytest.approx([9.193e-3, 7.118e-4, 3.793e-4], rel=1e-3)
    assert res[1] == pytest.approx(0.1226, rel=1e-3)
    # the SVD of the exact solution is better in the Frobenius norm at the same rank
    lam = jacobi_eigenvalues([[sum(u[k][i] * u[k][j] for k in range(n)) for j in range(n)] for i in range(n)])
    tail = [math.sqrt(sum(lam[m:]) / sum(lam)) for m in (1, 2, 3)]
    assert tail == pytest.approx([9.146e-3, 5.040e-4, 4.624e-5], rel=1e-2)
    assert all(t <= fr for t, (_, fr) in zip(tail, errs))

History

Ammar, Mokdad, Chinesta and Keunings introduced the method in 2006 to solve high-dimensional equations of the kinetic theory of complex fluids, where a grid in all configuration variables is too large. In 2009 Le Bris, Lelièvre and Maday analysed the greedy rank-one algorithm for the Poisson problem in separated form and proved its convergence. Chinesta, Keunings and Leygue wrote a primer on the method in 2014.

References

  1. Amine Ammar, Béchir Mokdad, Francisco Chinesta and Roland Keunings, A new family of solvers for some classes of multidimensional partial differential equations encountered in kinetic theory modeling of complex fluids, Journal of Non-Newtonian Fluid Mechanics 139(3), 2006, 153-176, the separated representation and the enrichment by alternating directions
  2. Claude Le Bris, Tony Lelièvre and Yvon Maday, Results and questions on a nonlinear approximation approach for solving high-dimensional partial differential equations, Constructive Approximation 30(3), 2009, 621-651, the greedy algorithm for the Poisson problem in separated form and its convergence
  3. Francisco Chinesta, Roland Keunings and Adrien Leygue, The Proper Generalized Decomposition for Advanced Numerical Simulations, A Primer, SpringerBriefs in Applied Sciences and Technology, Springer, 2014, the construction of the separated representation for the Poisson problem and the alternating directions

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 proofH1 sketch
  • a full proof of time.total
  • a full proof of space.extra
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 scene preset for the example