Skip to content
lean-dojoPublic

About

A computer algebra system for Lean 4. It does symbolic computation (integrals, derivatives, limits, series, sums, ODEs, factoring, Gröbner bases) and numerical bounds, and every answer comes with a theorem Lean's kernel checks.

Topics

Resources

Contributing

Stars

11 stars

Watchers

0 watching

Forks

Repository files navigation

SymLean: A Verified Computer Algebra System in Lean

Computer algebra systems such as Mathematica, Maple and SymPy have long been part of how we do mathematics. Whether we are deriving an equation, working out an integral or simplifying a particularly unpleasant expression, it is often much easier to ask a computer to do the calculation. But when formalizing mathematics in Lean, we still need to prove that the resulting expression is correct. This can take considerably more effort than finding the answer itself. SymLean grew out of our interest in making these two processes work together. We wanted something that feels like a conventional computer algebra system but produces Lean theorems that we can use directly in our proofs.

The library covers symbolic algebra, differentiation, integration, series expansions, limits, equation solving, special functions and certified numerical computation. We can run a calculation interactively with #cas, or inside an existing Lean proof with the cas and cega tactics. The nice part is that the algorithms we use to find an answer don't have to be trusted. They can be heuristic, and we can even delegate computations to external computer algebra systems.

SymLean's own search and, optionally, SymPy, SageMath, Maxima, Giac, Singular, PARI/GP, FLINT and Gappa through CASOracle and DSLean propose answers; SymLean builds certificates and proofs with Mathlib and FloatLib, and Lean's kernel checks the theorem, here x^4 - 1 = (x - 1)(x + 1)(x^2 + 1).

Dashed arrows are proposals, which nobody has to trust. SymLean turns them into certificates and proofs with Mathlib and FloatLib, and Lean's kernel checks the result.

Documentation · Getting started · Why SymLean · Trust assumptions

Installation

From a checkout of this repository, fetch the Mathlib cache and build SymLean:

lake exe cache get
lake build

Use the Lean version in lean-toolchain (v4.36.0, with Mathlib v4.36.0). Dependency versions are pinned in lake-manifest.json.

In your own Lake project, add SymLean with require:

require SymLean from git "https://github.com/lean-dojo/SymLean.git" @ "main"

Then run lake update SymLean and lake exe cache get, and start a file with import CAS. A library that reads files into proofs with include_str or json_data% should add SymLean's facet SymLean.embeddedInputs to its needs, so that Lake rebuilds a module when such a file changes (see the library guide).

An example

If you have used Mathematica, Maple or SymPy, #cas will feel familiar: you give it a mode and an expression, and it answers. The difference is that every answer comes back as a theorem that Lean has checked. Here is a short session, with the answers SymLean prints:

import CAS

#cas [factor] (2*x^3 - 3*x^2 + 1)                 -- (x - 1)^2*(2*x + 1)
#cas [derive x] (x ^ 2 * sin x)                   -- x*(2*sin(x) + x*cos(x))
#cas [integrate x] (atan x)                       -- x*atan(x) - 1/2*log(1 + x^2)
#cas [integrate x in [0, 1]] (x * exp x)          -- 1
#cas [limit x → 0] (sin x / x)                    -- 1
#cas [series x 0 7] (sin x)                       -- x - 1/6*x^3 + 1/120*x^5 - 1/5040*x^7 + o(x^7)
#cas [sum k 1 n] (k^2)                            -- n*(n + 1)*(2*n + 1)/6
#cas [solve x] (x ^ 2 = 1)                        -- x = 1 ∨ x = -1
#cas [roots x] (x ^ 5 - x - 1 = 0)                -- 1.16730397826141868425, the only real root
#cas [dsolve y x] (y'' + 3*y' + 2*y = 0)          -- y(x) = c₁*exp(-x) + c₂*exp(-(2*x))
#cas [eigenvalues] !![2, 0, 0; 0, 3, 4; 0, 4, 9]  -- [1, 2, 11]
#cas (zeta 4)                                     -- pi^4/90
#cas [nintegrate x in [0, 1]] (exp (-x^2))        -- 0.746824 ± 10^-6
#cas [simplify] ((x ^ 4 - 1) / (x ^ 2 - 1))       -- x^2 + 1, when x^2 - 1 ≠ 0

Each line also prints the theorem behind its answer, with the conditions under which it holds: the simplification needs $x^2 - 1 \neq 0$, the root is enclosed in an interval of width $10^{-20}$, and the numerical integral comes with its error bound. Variables need no declaration.

In a proof, the tactics do the same work on your own goals:

theorem integral_x_exp : ∫ x in (0 : ℝ)..1, x * Real.exp x = 1 := by
  cas

example (x : ℝ) (hx : x ≠ 0) : x / x = 1 := by
  cas

example (x : ℝ) (h0 : 0 ≤ x) (h1 : x ≤ 1) : x * (1 - x) ≤ 1 / 4 := by
  cega

cas proves the definite integral in Mathlib's own terms. The second goal needs hx, because division in Lean is total: $x/0 = 0$, so at $x = 0$ the left side is $0/0 = 0$. Without hx the tactic fails and names the missing hypothesis x ≠ 0. cega proves the bound $x(1 - x) \le 1/4$ on $[0, 1]$. cas? and cega? suggest a tactic call to keep.

What you can work with

Every mode has a page with examples in the documentation.

Algebra and polynomials

  • Simplifying. simplify and fullSimplify rewrite an expression and prove that the result equals it under the conditions they print: cancelling $d$ adds $d \neq 0$. together, cancel and apart handle fractions. See the algebra guide.
  • Expanding and factoring. expand, factor, collect and trigExpand prove identities for all real values. factor finds rational roots and perfect powers, and doesn't claim that what's left is irreducible. See factor.
  • Polynomials. Coefficients, degrees, division with remainder, gcds with their Bézout cofactors and interpolation, all about Mathlib's ℚ[X]. See the polynomials guide.
  • Gröbner bases. groebner proves that its basis spans the same ideal and, by Buchberger's criterion, that it is a Gröbner basis. member proves ideal membership with explicit cofactors. See groebner.

Equations and linear algebra

  • Equations. solve and roots prove that no real solution is missing, and irrational roots come in intervals that hold exactly one root each. reduce proves where a polynomial inequality holds, and findRoot encloses a root of any equation. See the guide.
  • Matrices. det, inverse, matrixRank, rowReduce, linearSolve and nullSpace, each a theorem about Mathlib's definitions. linearSolve describes every solution. See the guide.
  • Eigenvalues. Exact eigenvalues with their multiplicities and a proof that there are no others, eigenvectors, characteristic polynomials, and positiveDefinite from an exact $L D L^T$ factorization. See the guide.

Calculus

  • Derivatives and extrema. derive and grad prove HasDerivAt and HasGradientAt theorems, with the conditions they need as hypotheses. minimize and maximize find the extrema of a polynomial, with a theorem that no value beats them. See the guide.
  • Integrals. integrate finds an antiderivative, checks it by differentiation and proves the definite integral, also over infinite intervals. It doesn't factor a general denominator, so 1 / (x ^ 3 - 1) is refused. See integrate.
  • Series and limits. Taylor and Laurent series with a little-o remainder, and limits at a point, from either side, or at $\pm\infty$, as Mathlib's Tendsto. See the guide.

Sums, recurrences and number theory

  • Sums. Closed forms of finite sums and products, proved by induction, including terms $c^k R(k)$ by Gosper's algorithm, and infinite sums such as $\sum 1/k^2 = \pi^2/6$ with a HasSum theorem. See the guide.
  • Recurrences. rsolve solves linear recurrences with constant coefficients and proves that every solution has the printed form. In a proof, cas gets the closed form from the recurrence and the initial values in your hypotheses. See rsolve.
  • Number theory. Divisors, totients, modular powers and inverses, the Chinese remainder theorem, Jacobi symbols, digits, continued fractions, binomials and Fibonacci numbers, each about Mathlib's definitions. #cas doesn't factor integers or test primality. See the guide.

Differential equations and special functions

  • Differential equations. dsolve solves linear equations and proves that the printed family is exactly the set of solutions, or with initial values the only one. ndsolve proves that a solution exists and is unique, and encloses it. See the guide.
  • Transforms. Laplace and inverse Laplace transforms, Fourier transforms of Gaussians, and Fourier coefficients as exact functions of $n$.
  • Special functions. Exact values of gamma, zeta and the Bernoulli numbers; the Chebyshev, Hermite, Legendre, Laguerre, Jacobi and Gegenbauer polynomials in monomials; and enclosures of erf and BesselJ. See the guide.

Certified numerics

  • Digits and enclosures. N d gives the first d digits of a real number with a theorem that each one is right, enclose bounds an expression on a box, and nintegrate gives an integral to 6 places with a proved error. See the numerics guide.
  • The cega tactic. In a proof, cega proves numerical bounds with a certificate that the kernel checks, such as Real.exp 1 ≤ 2.72 or ∫ x in (0 : ℝ)..1, Real.exp (-x ^ 2) ≤ 3 / 4. It computes with exact rationals, or with IEEE floats through FloatLib if you ask. See cega.
  • Big certificates. CAS.Cert checks a condition over tables and meshes of any size, in one module or spread over many. See the guide.

In a proof

  • cas. State the goal in Mathlib's terms and write cas: identities, derivatives, integrals, limits, sums, determinants, root counts and bounds. A condition it needs comes from your hypotheses, and a missing one is reported, never added. cas? and cega? tell you the call to keep. See the tactics guide.

Other systems and your own extensions

  • Other computer algebra systems. With the optional CASOracle, SymPy, SageMath, Maxima, Giac, Singular, PARI/GP, FLINT and Gappa propose answers, and SymLean proves each one or refuses it. See the oracle page.
  • Your own functions. @[cas_deriv] teaches cas a derivative and @[cas_route] adds a route. A registry only chooses which theorem to apply, so it adds no assumption. See the library guide.

Why a verified computer algebra system?

Computer algebra systems sometimes give wrong answers. One reason is that an answer only holds under a condition they don't print. Richard Fateman's review of Mathematica (J. Symbolic Computation 13(5), 1992) reports that Integrate[1/x^2, {x, -1, 1}] gave $-2$, which is what $-1/x$ gives at the endpoints, across the pole at $0$. The integral diverges. SymPy 1.14.0 gives $-1$ for integrate(sqrt(2 - x)*sqrt(1/(2 - x)), (x, 0, 1)), although the integrand is $1$ on $[0, 1]$ (sympy#29792). In Sage 10.2 to 10.9 the reduced echelon form of some sparse rational matrices was wrong (sagemath/sage#42411, fixed in Sage 10.10).

SymLean gives none of these wrong answers. Interestingly, on Fateman's integral our own search proposes $-2$ as well! The proof then needs $x \neq 0$ on all of $[-1, 1]$, so #cas [integrate x in [-1, 1]] (1 / x ^ 2) refuses:

error: `cas` did not prove the value -2 of the integral: it could not prove that the conditions of the primitive -(1/x) hold on the interval (x ≠ 0). The endpoint calculation needs a primitive valid throughout the interval.

On SymPy's integrand our search finds no antiderivative and says so. For the matrix from Sage's report, SymLean returns row operations $E$ with a theorem that $EA = R$, with $E$ invertible and $R$ in reduced echelon form, which determines $R$. Why SymLean has more cases.

Trust assumptions

A theorem from SymLean relies on:

  • its statement: the one you wrote, or the one the #cas report prints;
  • the Mathlib definitions it mentions, such as Real.arctan, and in a few answers SymLean's own short definitions, such as CAS.erf;
  • Lean's kernel, with the three standard axioms propext, Classical.choice and Quot.sound.

A report prints its statement through Lean's pretty printer, which writes a cast as ↑n without its target type, so two different statements can look the same. When that matters, I'd write the statement as an example in your own file and prove it there. set_option cas.suggest true offers that example, ready to paste.

One option, off by default, trusts more: with cega.nativeCertificates, cega [fast] and the certificate commands check large finite certificates with compiled code, and #print axioms then shows the native axioms involved. TRUST.md lists everything a proof trusts with the reason for each item, and the trust tutorial goes through both profiles.

Independent kernels (lake check --paranoid) accept SymLean proofs; TRUST.md says what to expect for large certificates.

Limitations

  • A refusal proves nothing. A search can miss an answer that exists, and SymLean does not compute everything Mathematica can.
  • An answer is correct, but complete only when the theorem says so, as with roots. findRoot proves one root and its uniqueness near the printed value.
  • A certified bound on a residual is not a bound on an error. It becomes one only through a stability theorem that your own proof supplies.
  • Every answer pays for a proof. Checking large finite tables in the kernel can be slow. The certificate guide explains how to split the work across modules or opt into compiled evaluation.

Contributing

We'd love help with SymLean, and CONTRIBUTING.md says where to start. Please follow Mathlib's conventions and keep every proof complete. lake exe cache get and then lake build check every proof, the examples included, with warnings as errors. The library guide lists the test scripts, scripts/dups.sh and the site build to run on a change.

Related work

Letting an untrusted search propose and the prover check is an old idea: Harrison and Théry combined HOL with Maple this way (J. Automated Reasoning 21, 1998). The closest project in Lean is Hex, the Lean FRO's really nice library of verified computational algebra, which proves factorization, determinants and primality in Lean. On Lean 4.35, SymLean called Hex for Berlekamp–Zassenhaus factoring, Bareiss determinants and primality certificates. That route comes back as soon as Hex is released for Lean 4.36, and we're in touch with its developers. We build on earlier work in HOL Light, Isabelle, Coq and Rocq, and Lean, and Why SymLean cites it.

Papers and algorithms we use

Here's what we use, and where it comes from :)

  • Hermite reduction, for the rational part of integrate: Hermite, Nouv. Ann. Math. 1872; Bronstein, 2005.
  • Gosper's algorithm, for hypergeometric sums in sum: Gosper, PNAS 1978.
  • C-finite recurrences, for the general solution of rsolve: Stanley, Enumerative Combinatorics 1 (2012).
  • Linear differential equations with constant coefficients, for dsolve: Teschl, Ordinary Differential Equations and Dynamical Systems (2012).
  • Buchberger's algorithm, for groebner and polynomial systems in solve: Buchberger, Aequationes Math. 1970.
  • Sturm sequences, for counting and isolating real roots: Sturm, Mém. Savans Étrangers 1835; Basu, Pollack and Roy, 2006.
  • The Faddeev–LeVerrier recursion, for characteristicPolynomial: Hou, SIAM Review 1998.
  • $L D L^T$ factorization, the certificate of positiveDefinite: Golub and Van Loan, Matrix Computations (2013).
  • Interval arithmetic with subdivision and the monotonicity test, for cega: Moore, Kearfott and Cloud (2009); Hansen, Numer. Math. 1980.
  • The Krawczyk operator, for enclosures of roots and of zeros of systems: Krawczyk, Computing 1969; Rump, Acta Numerica 2010.
  • Taylor models, for validated approximations of functions: Makino and Berz, Int. J. Pure Appl. Math. 2003.
  • Ball arithmetic and Kronecker substitution, which keep long computations cheap in the kernel: van der Hoeven 2010; Harvey, J. Symb. Comput. 2009.
  • Quadrature with Peano-kernel remainders, Simpson's rule in nintegrate and Gauss rules in the library: Gauss 1816; Peano 1913. The Gauss rules for any weight on any interval, Laguerre, Hermite and Jacobi among them, follow Gautschi, Orthogonal Polynomials (2004).
  • Validated initial value problems, for ndsolve: Nedialkov, Jackson and Corliss, Appl. Math. Comput. 1999.
  • Root enclosures start from Kerner's iteration, Numer. Math. 1966, and Mahler's separation bound, Michigan Math. J. 1964.
  • Sums of squares with rational coefficients, for the inequality certificates of the oracles: Parrilo, 2003; Peyrl and Parrilo, 2008.
  • Proof by reflection, for the normalizers that the kernel runs: Boutin, TACS 1997.

Credits

SymLean is written at Caltech by Robert Joseph George, Changhe Yang, Peicong Song, Thomas Y. Hou and Anima Anandkumar. Everything here is built on Mathlib (The mathlib Community, "The Lean Mathematical Library", CPP 2020, https://doi.org/10.1145/3372885.3373824). The certified numerics use FloatLib by Robert Joseph George, Will Adkisson and Anima Anandkumar. Many thanks to taterowney and the DSLean contributors for DSLean, which is under CC BY 4.0.

License

SymLean is released under the Apache License 2.0; see LICENSE.

About

A computer algebra system for Lean 4. It does symbolic computation (integrals, derivatives, limits, series, sums, ODEs, factoring, Gröbner bases) and numerical bounds, and every answer comes with a theorem Lean's kernel checks.

Topics

Resources

Contributing

Stars

11 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages