alkahest

Finite Expression Method (alkahest.fex)

Experimental. alkahest.fex may change between minor releases.

Requires NumPy. alkahest.fex imports NumPy when it is imported, and plain pip install alkahest does not install it. Install the fex extra: pip install "alkahest[fex]". Without NumPy, import alkahest.fex raises ImportError: alkahest.fex requires NumPy: pip install 'alkahest[fex]'. fex.TorchEvaluator additionally needs PyTorch.

The Finite Expression Method (FEX) looks for a closed-form solution of a PDE inside a fixed binary tree of operator slots. A candidate is an opcode vector e (one operator per slot) plus parameters θ. Leaves are Σᵢ αᵢ φ(xᵢ) + β over all d coordinates. Search and fitting run at a concrete dimension, and finalize turns a fitted candidate into an exact closed form, lifts it to a symbolic dimension d, and proves it.

Origin and credit

The Finite Expression Method was created by Senwei Liang and Haizhao Yang:

  • S. Liang and H. Yang, Finite Expression Method for Solving High-Dimensional Partial Differential Equations. arXiv:2206.10121 (first version June 2022); published in the Journal of Machine Learning Research 26(138):1–31, 2025 (JMLR page). This is the method itself: the operator tree, the risk-seeking policy-gradient search, the coarse-then-fine parameter fit and the paper's benchmark problems, which alkahest.fex reproduces.
  • The authors' reference implementation is github.com/LeungSamWai/Finite-expression-method.

Two later papers from the same line of work are also implemented here:

  • Z. Song, M. K. Cameron and H. Yang, A Finite Expression Method for Solving High-Dimensional Committor Problems, arXiv:2306.12268 (2023): the committor formulation with the variational (Ritz) loss, Problem.dirichlet, and the variable-dependence test in analyze.
  • G. Hardwick, S. Liang and H. Yang, Solving High-Dimensional Partial Integral Differential Equations: The Finite Expression Method, arXiv:2410.00835 (2024): FEX-PG and its Taylor-moment treatment of the jump integral, Problem.pide.

Alkahest provides an independent implementation of FEX and a symbolic backend for it: the compiled exact evaluator, symbolic pruning, and finalize's exact closed forms and proofs for symbolic d. The method and its benchmark problems are the authors' work; nothing here implies that they endorse Alkahest. If you use alkahest.fex in published work, please cite the original paper:

@article{liang2025fex,
  author  = {Senwei Liang and Haizhao Yang},
  title   = {Finite Expression Method for Solving High-Dimensional Partial
             Differential Equations},
  journal = {Journal of Machine Learning Research},
  year    = {2025},
  volume  = {26},
  number  = {138},
  pages   = {1--31},
  url     = {http://jmlr.org/papers/v26/23-1290.html},
  note    = {arXiv:2206.10121}
}

and the committor or PIDE paper when you use Problem.dirichlet or Problem.pide.

The pieces

name what it does
Template the tree shape, the operator tables (0 1 id sq cube quartic exp sin cos tanh log abs, + * - /) and the dimension, or a particle layout with the many-body leaves R, R2, P, P2 (below); Template.instantiate(e, θ) gives an ordinary Expr
Problem the PDE: poisson, the linear conservation law, cubic Schrödinger, the Rayleigh-quotient eigenproblem, dirichlet (Ritz energy), pide (integro-differential equations with Gaussian jumps), or any operator written in Jet symbols (Problem.from_operator)
Evaluator computes u, ∇u, Δu, the residuals and the full Jacobian in θ for a batch of candidates and points in one parallel float64 pass (a fused Forward-Laplacian, O(d) per node); scoring a new candidate never compiles anything
fit Levenberg–Marquardt on the exact Jacobian, or Adam / BFGS
search, solve a reference controller (risk-seeking policy gradient), and a driver that searches the restricted proposals of analyze in turn
analyze, transform_problem, reduce_problem symbolic pruning: the data's operator vocabulary, separability, radial symmetry, dispersion relations, and the substitutions u = e^v / u = log w
finalize exact closed form, symbolic-d lift and proof (below)
TorchEvaluator a PyTorch (CUDA) evaluator for the same problems

Candidates that overflow, divide by zero or take log of a non-positive number score +inf, never NaN. Malformed input raises FexError (E-FEX-001 … E-FEX-015).

Fit, then finalize

Python
import numpy as np
from alkahest import fex

d = 5
tpl = fex.Template("depth2_sub", dim=d)
prob = fex.Problem.poisson(d, rhs=-d, bc=lambda x: 0.5 * sum(xi**2 for xi in x))
rng = np.random.default_rng(0)
pts = fex.sample_box(500, d, rng=rng)
bd = fex.sample_box_boundary(200, d, rng=rng)

ev = fex.Evaluator(tpl, prob, pts, bd)
res = fex.fit(ev, [3, 0, 0, 2], rng=rng)   # id(L[sq] + L[0]) = a·Σxᵢ² + b
res.loss < 1e-20                            # True

out = fex.finalize(res, prob, template=tpl, points=pts, boundary=bd)
out["exact"]                                # True
out["expr_symbolic_d"]                      # 1/2 * Sum(Indexed(x, i)^2, i, 1, d)
out["verification"]["symbolic_d"]["status"] # 'exactly_verified'
out["certificate"]["path"]                  # 'kernel'

finalize pins redundant parameters, filters small coefficients, ties equal leaf weights, and snaps each value to an exact constant (a rational, a rational multiple of π, √2, √3, e, log 2, log 3, or a relation found by PSLQ or LLL). A constant is accepted only within a tolerance that shrinks with its description cost, and each step is kept only if a refit keeps the loss inside the gate. Tied leaves then lift to Sum(φ(Indexed(x, i)), i, 1, d).

What "proved" means here

out["verification"] has three parts, in the statuses of verify_pde_solution:

  • concrete: the PDE residual and every boundary face at the fitted d, checked exactly;
  • symbolic_d: the PDE residual and the boundary condition on every face of [lo, hi]^d for every d. A zero is a proof; a nonzero is never reported as a refutation;
  • interval: Arb-ball enclosures of the residual at the sample points when no exact form exists. These are evidence, not a proof.

For Poisson, the cubic Schrödinger equation, the eigenproblem and linear transport, out["certificate"] carries a Lean 4 theorem about the PDE residual at every point of ℝ^d (at the fitted d), checked by proof by reflection through Alkahest.Kernel.Pde, with a tactic HasDerivAt fallback for Poisson and transport. Boundary conditions are not part of the theorem. See PDE residuals.

On the FEX paper's problems (from the 3.15.0 CHANGELOG): Poisson at d = 10, 20, 50 and the conservation law at d = 5, 20 are recovered by search and proved for every d; with symbolic pruning (u = e^v), the cubic Schrödinger equation is solved at every d from 6 to 48 (24 of 24 runs, 7 of 24 without pruning) and proved for every d; the harmonic eigenproblem at d = 10 … 18 gives λ = d exactly. Benchmarks are in benchmarks/fex/.

Integro-differential equations

fex.Problem.pide(dim, time=, drift=, diffusion=, jump=, rhs=, terminal=, T=) builds u_t + b·∇u + ½Tr(σσᵀ∇²u) + λ∫(u(x+G) − u − G·∇u)φ(z)dz = rhs with Gaussian jumps (fex.GaussianJump), following Hardwick–Liang–Yang (arXiv 2410.00835). The search uses the Taylor-moment replacement of the integral, but finalize verifies a solution against the exact integral (fex.gaussian_expectation), and reports whether the replacement was exact on it. On the paper's two high-dimensional examples u = |x|²/d is recovered at every d from 2 to 100 (eq. 32) and from 25 to 100 (eq. 33), and proved for every d.

Many-body leaves

For N particles in D dimensions (d = N·D coordinates, particle-major: x[m·D + a] is coordinate a of particle m), a template built with particles=(N, D) may also use four pooled leaves. One weight is shared by every particle or pair, so each leaf is invariant under permutations of the particles and under rotations and reflections:

token leaf parameters
R α Σ_m φ(|x_m|) + β α, β
R2 α Σ_m φ(|x_m|²) + β α, β
P α Σ_{i<j} φ(r_ij) + β, r_ij = |x_i − x_j| α, β
P2 α Σ_{i<j} φ(r_ij²) + β α, β

Trees combine them as usual: B(P,R2) with + under u = e^v is the Jastrow form ψ = exp(Σ_{i<j} u(r_ij) + Σ_m w(|x_m|)), B(U(P),U(R2)) with * is a product of two such factors, and L leaves can sit beside them. The evaluator tabulates the jet (S, ∇S, ΔS) of each pooled invariant once per operator and point set, with ΔΣ_{i<j} φ(r_ij) = Σ_{i<j} 2(φ''(r_ij) + (D−1)φ'(r_ij)/r_ij). The O(N²·D) pair sum is therefore paid once, and scoring a candidate costs O(N·D) per point, as for a coordinate leaf. A coincidence r_ij = 0 makes the P and R jets non-finite, so the candidate scores +inf. P2 and R2 have no such division. fex.TorchEvaluator supports these leaves too.

fex.Problem.many_body(N, D, one_body=, pair=) is H = −½ Σ_m Δ_m + Σ_m V₁(|x_m|) + Σ_{i<j} V₂(r_ij), with V₁ and V₂ given as functions of the distance. With form="log" (the default) it is the equation for v = log ψ, −½(Δv + |∇v|²) + V = E, under the centred least-squares loss. With form="rayleigh" it is the Rayleigh quotient of 2H.

That equation is also solved by growing or singular functions. For example, Calogero–Moser with λ → 1 − λ gives a solution that is singular at coincidences. fex.solve_many_body therefore refits the best skeleton from sign-flipped starts and keeps the lowest-energy solution that decays outwards and is not singular at coincidences. That choice is a heuristic on sample points, not a proof of normalisability.

fex.finalize_many_body snaps the parameters to exact constants (rationals, the constants of snap_candidates, and quadratic surds p + q√m found by LLL). It then derives the energy exactly: it proves that −½(Δv + |∇v|²) + V reduces to a constant at the fitted N. The residual is assembled summand by summand, expanded, grouped by the particles each term involves and simplified group by group, so the cost grows like N³. This is an exact proof at the fitted N; nothing is sampled.

Python
import numpy as np
from alkahest import fex

# Calogero–Moser: H = −½Σ∂ᵢ² + ½Σxᵢ² + λ(λ−1)Σ_{i<j}(xᵢ−xⱼ)⁻², λ = 2
n = 5
prob = fex.Problem.many_body(n, 1, one_body=lambda r: r**2 / 2, pair=lambda r: 2 / r**2)
tpl = fex.Template.many_body("B(P,R2)", n, 1)
rng = np.random.default_rng(0)
pts = fex.sample_particles(400, n, 1, min_distance=0.05, rng=rng)
res = fex.solve_many_body(tpl, prob, pts, epochs=30, batch=32, rng=rng)
out = fex.finalize_many_body(res, prob, template=tpl, points=pts)
out["energy"]                     # 45/2  (= ωN/2 + ωλN(N−1)/2)
out["verification"]["status"]     # 'exactly_verified'

The pair-leaf Jastrow form and the energy formula are those of F. Calogero, Solution of the one-dimensional N-body problems with quadratic and/or inversely quadratic pair potentials, J. Math. Phys. 12, 419 (1971). For N coupled oscillators (V₂ = k r²/2, the Moshinsky model generalised) the same pipeline recovers log ψ = −ω/2 Σ|x_m|² − (Ω−ω)/(2N) Σ r_ij² with Ω = √(ω² + kN) and E₀ = D/2 (ω + (N−1)Ω), an exact quadratic surd, at every N from 2 to 10 (benchmarks/fex/bench_many_body.py).

For a sampler, Evaluator.value_jacobian(e, θ, points) gives ∂u/∂θ at arbitrary points. Evaluator.jet_vjp(e, θ, points, seeds) gives Σ_p seeds_p · ∂(u, Δu, ∇u)_p/∂θ, for example the gradient of a mean local energy.

For every particle number N

fex.lift_many_body takes results of one skeleton at several N, each from finalize_many_body, and proves the solution for every N.

  1. Families. Each leaf weight and the energy becomes an exact family (P(N) + σ√S(N))/N^k. The family is found by exact interpolation and checked on more N than it has unknowns, so it is never just an interpolation of every point. It is a hypothesis until step 3.
  2. Wave function. A P[log] leaf with weight λ becomes the Jastrow product ∏_{i<j} r_ij^λ. Every other pooled leaf becomes exp(α Σ φ).
  3. Proof. The wave function, the lifted potential and the energy family go to alkahest.experimental.verify_many_body, the symbolic-N pair-sum verifier (many-body systems). Only a symbolic identity in N is reported as exactly_verified.
Python
import numpy as np
from alkahest import fex

def calogero(n):
    return fex.Problem.many_body(n, 1, one_body=lambda r: r**2 / 2, pair=lambda r: 2 / r**2)

results = []
for n in range(3, 7):
    prob, tpl = calogero(n), fex.Template.many_body("B(P,R2)", n, 1)
    rng = np.random.default_rng(100 + n)
    pts = fex.sample_particles(300, n, 1, min_distance=0.05, rng=rng)
    res = fex.solve_many_body(tpl, prob, pts, epochs=30, batch=32, rng=rng)
    results.append((prob, fex.finalize_many_body(res, prob, template=tpl, points=pts)))
lifted = fex.lift_many_body(results)
lifted["status"]     # 'exactly_verified': Hψ = Eψ for every N
lifted["energy"]     # N^2 − N/2

For N coupled oscillators the pair weight lifts to (1 − √(N+1))/(2N) and the energy to 3/2 + 3/2 (N−1)√(N+1). Both are proved for every N in the same way.

For Monte Carlo fitting and scoring of many-body candidates (sampling |ψ|², energy and variance losses, stochastic reconfiguration, error bars) and the Kato cusp conditions, see Variational Monte Carlo.

alkahest 3.15.1