Part 7. SymPy: symbolic once, numeric many times#

SymPy excels at exact computation: it expands, simplifies, differentiates, sums, and proves identities. Each of its operations, however, builds and traverses an expression tree made of Python objects. In Lecture 3 we built such a system ourselves (MiniCAS), so we know how much work hides behind a single substitution. That is why SymPy is very slow when we use it as a calculator in a loop. The rule of this part is: we do the symbolic computation once and turn its result into a fast numerical function, which we then call many times. The second rule: when we know what we want, we choose specialized tools instead of general ones (simplify, Rational in a loop). The examples come from Lectures 3 and 5.

Hide code cell source

# Narzędzia pomiaru czasu — opisane w części 1 tego rozdziału.
import platform
import statistics
import subprocess
import sys
import textwrap
import timeit
from importlib.metadata import version

import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter

INDYGO, BURSZTYN, ZIELEN = "#4f46e5", "#d97706", "#059669"
SZARY, TUSZ, SIATKA = "#94a3b8", "#334155", "#e2e8f0"
JEDNOSTKI = (("s", 1.0), ("ms", 1e-3), ("µs", 1e-6), ("ns", 1e-9))


def zmierz(f, *args, cel=0.02, proby=7):
    """Mediana czasu jednego wywołania f(*args), w sekundach.

    Szybką funkcję wywołujemy w seriach trwających około `cel` sekund, bo
    zegar nie zauważy pojedynczego wywołania trwającego ułamek mikrosekundy.
    Z `proby` serii bierzemy medianę, odporną na serie zakłócone przez inne
    programy.
    """
    zegar = timeit.Timer(lambda: f(*args))
    t = zegar.timeit(number=1)          # rozgrzewka i pierwsza ocena
    if t > cel:                         # wolna funkcja: trzy wywołania
        return statistics.median(zegar.repeat(repeat=3, number=1))
    n = 1
    while t < cel / 10:                 # zbyt krótka seria: wydłużamy ją
        n *= 10
        t = zegar.timeit(number=n)
    n = max(1, round(n * cel / t))      # seria trwa teraz około `cel` s
    return statistics.median(zegar.repeat(repeat=proby, number=n)) / n


def czas(s):
    """Czas w sekundach jako napis z jednostką, np. 1.23 ms."""
    for jednostka, skala in JEDNOSTKI:
        if s >= 0.9995 * skala or jednostka == "ns":
            v = s / skala
            if v >= 99.95:
                return f"{v:.0f} {jednostka}"
            return f"{v:#.3g} {jednostka}"


def krotnosc(r):
    """Iloraz czasów jako napis: 340×, 2.5×, 0.81×."""
    if r >= 10:
        return f"{r:.0f}×"
    return f"{r:.1f}×" if r >= 1 else f"{r:.2f}×"


def porownaj(warianty, *args, zgodne=None):
    """Mierzy warianty (nazwa → funkcja) na tych samych danych.

    Najpierw sprawdza, że wszystkie warianty dają ten sam wynik (operatorem
    == albo funkcją `zgodne`): porównujemy tylko programy, które liczą to
    samo. Przyspieszenie to czas pierwszego wariantu podzielony przez czas
    danego. Zwraca słownik czasów.
    """
    wyniki = {nazwa: f(*args) for nazwa, f in warianty.items()}
    wzorzec = next(iter(wyniki.values()))
    for nazwa, w in wyniki.items():
        if not (zgodne(w, wzorzec) if zgodne else w == wzorzec):
            raise AssertionError(f"wariant „{nazwa}” daje inny wynik")
    czasy = {nazwa: zmierz(f, *args) for nazwa, f in warianty.items()}
    baza = next(iter(czasy.values()))
    szer = max(len(nazwa) for nazwa in czasy)
    wiersze = [f"{'wariant':{szer}}  {'czas':>9}  {'przyspieszenie':>14}"]
    for nazwa, t in czasy.items():
        wiersze.append(f"{nazwa:{szer}}  {czas(t):>9}"
                       f"  {krotnosc(baza / t):>14}")
    print("\n".join(wiersze))
    return czasy


def srodowisko(*biblioteki):
    """Wypisuje, na czym mierzymy: procesor, system, Python, biblioteki."""
    if sys.platform == "darwin":
        procesor = subprocess.run(
            ["sysctl", "-n", "machdep.cpu.brand_string"],
            capture_output=True, text=True).stdout.strip()
        system = f"macOS {platform.mac_ver()[0]}"
    else:
        procesor = platform.processor()
        system = f"{platform.system()} {platform.release()}"
    opis = [procesor or platform.machine(), system,
            f"Python {platform.python_version()}"]
    opis += [f"{b} {version(b)}" for b in biblioteki]
    print(textwrap.fill("Pomiary: " + ", ".join(opis), width=79,
                        subsequent_indent="  "))


def upewnij(warunek, tresc):
    """Pilnuje zdań z tekstu rozdziału.

    Gdy pomiar przeczy zdaniu, budowa książki się zatrzymuje.
    """
    if not warunek:
        raise AssertionError(f"Tekst rozdziału twierdzi: {tresc}. "
                             "Pomiar temu przeczy.")


def _os_czasu(v, _):
    for jednostka, skala in JEDNOSTKI:
        if v >= 0.9995 * skala:
            return f"{v / skala:.0f} {jednostka}"
    return f"{v / 1e-9:g} ns"


def wykres_czasow(czasy, tytul):
    """Czasy wariantów na osi logarytmicznej; najszybszy jest wyróżniony."""
    nazwy = list(czasy)[::-1]           # pierwszy wariant na górze
    t = [czasy[nazwa] for nazwa in nazwy]
    fig, ax = plt.subplots(figsize=(8, 0.42 * len(nazwy) + 1.2))
    ax.scatter(t, range(len(nazwy)), s=70, zorder=3, edgecolors="white",
               linewidths=2, c=[INDYGO if v == min(t) else SZARY for v in t])
    for i, v in enumerate(t):
        ax.annotate(czas(v), (v, i), xytext=(9, 0), va="center",
                    textcoords="offset points", fontsize=9, color=TUSZ)
    ax.set_yticks(range(len(nazwy)), nazwy)
    ax.set_xscale("log")
    ax.set_xlim(min(t) / 3, max(t) * 8)  # miejsce na etykiety
    ax.xaxis.set_major_locator(LogLocator(base=10))
    ax.xaxis.set_major_formatter(FuncFormatter(_os_czasu))
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.grid(axis="x", color=SIATKA, lw=1)
    ax.set_axisbelow(True)
    for bok in ("top", "right", "left"):
        ax.spines[bok].set_visible(False)
    ax.tick_params(axis="y", length=0)
    ax.set_title(tytul, loc="left", fontsize=11)
    plt.tight_layout()
    plt.show()


def wykres_skalowania(rozmiary, serie, tytul, opis_x="n"):
    """Czas w zależności od rozmiaru danych, obie osie logarytmiczne."""
    fig, ax = plt.subplots(figsize=(8, 4))
    style = zip(serie.items(), (INDYGO, BURSZTYN, ZIELEN), "osD")
    for (nazwa, czasy_serii), kolor, znak in style:
        ax.loglog(rozmiary, czasy_serii, "-", marker=znak, color=kolor,
                  lw=2, ms=6, label=nazwa)
    ax.set_xticks(rozmiary, [str(n) for n in rozmiary])
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.yaxis.set_major_formatter(FuncFormatter(_os_czasu))
    ax.yaxis.set_minor_formatter(NullFormatter())
    ax.set_xlabel(opis_x)
    ax.grid(color=SIATKA, lw=1)
    ax.set_axisbelow(True)
    for bok in ("top", "right"):
        ax.spines[bok].set_visible(False)
    ax.legend(loc="best", frameon=False, fontsize=9)
    ax.set_title(tytul, loc="left", fontsize=11)
    plt.tight_layout()
    plt.show()
import inspect
import math
import random
from fractions import Fraction

import numpy as np
import sympy as sp
from sympy.core.cache import clear_cache

import minicas

srodowisko("numpy", "sympy")
Pomiary: Apple M4, macOS 26.6.2, Python 3.12.11, numpy 2.5.3, sympy 1.14.0

Values of an expression at many points#

In Lecture 3 (§3.4) we evaluated the expression \(\sin(x+1)+\cos(x+1)\) at a thousand random points in two ways: with the MiniCAS interpreter, which traverses the expression tree at every point, and with a virtual machine, for which the MiniCAS compiler translates the tree once. Let us add SymPy to the comparison: substitution with subs followed by evalf, the value evalf(subs=...), and the function sp.lambdify, which turns an expression into an ordinary Python function. The functions that use SymPy clear SymPy’s cache before each call (see part 1), because otherwise we would be measuring the retrieval of stored results.

x = sp.symbols("x")
w = sp.sin(x + 1) + sp.cos(x + 1)
w_minicas = minicas.parse("sin(x+1) + cos(x+1)")
program = minicas.compile_expr(w_minicas)
f_math = sp.lambdify(x, w, "math")
f_numpy = sp.lambdify(x, w, "numpy")

random.seed(20261025)                       # te same punkty co na wykładzie 3
punkty = [random.uniform(-10, 10) for _ in range(1000)]
punkty_tablica = np.array(punkty)


def sympy_subs(ts):
    clear_cache()
    return [float(w.subs(x, t).evalf()) for t in ts]


def sympy_evalf(ts):
    clear_cache()
    return [float(w.evalf(subs={x: t})) for t in ts]


czasy_wartosci = porownaj({
    "SymPy: subs i evalf": lambda: sympy_subs(punkty),
    "SymPy: evalf(subs=...)": lambda: sympy_evalf(punkty),
    "MiniCAS: interpreter drzewa":
        lambda: [minicas.numeric(w_minicas, {"x": t}) for t in punkty],
    "MiniCAS: maszyna wirtualna":
        lambda: [program.run({"x": t}, exact=False) for t in punkty],
    "lambdify(..., 'math')": lambda: [f_math(t) for t in punkty],
    "lambdify(..., 'numpy')": lambda: f_numpy(punkty_tablica),
}, zgodne=lambda a, b: np.allclose(np.asarray(a, dtype=float),
                                   np.asarray(b, dtype=float),
                                   rtol=1e-12, atol=1e-12))
wykres_czasow(czasy_wartosci, "sin(x+1) + cos(x+1) w 1000 punktów")
wariant                           czas  przyspieszenie
SymPy: subs i evalf             177 ms            1.0×
SymPy: evalf(subs=...)         22.7 ms            7.8×
MiniCAS: interpreter drzewa    5.01 ms             35×
MiniCAS: maszyna wirtualna     1.28 ms            138×
lambdify(..., 'math')          64.5 µs           2753×
lambdify(..., 'numpy')         7.35 µs          24157×
../_images/f4c1088e3e727c7670ae92d47c0e9bdb5130543acecf49ca3a1d389792fb4072.png

The difference between the first and the last row is four orders of magnitude. Substitution in SymPy builds a new tree at every point, simplifies it, and only then computes the value. The MiniCAS interpreter is faster, because it only traverses the tree, without building a new one. The MiniCAS virtual machine traverses the tree once, at compile time. The function lambdify goes one step further: it writes Python source code and compiles it with the built-in compiler. This can be seen in the code it generated:

print(inspect.getsource(f_math))
def _lambdifygenerated(x):
    return sin(x + 1) + cos(x + 1)

It is the same idea as the compiler from Lecture 3: we turn the expression tree into a program once. Here, however, the program is a Python function executed by the CPython interpreter, and in the "numpy" version the loop over the points runs in C. SymPy can also translate expressions into code in C and other languages (sp.ccode, the sympy.utilities.codegen module) or, for high precision, into functions of the mpmath library (lambdify(..., "mpmath")).

Let us return to the profiler example from part 1. The trapezoidal rule with values computed by subs spent almost all of its time in SymPy. After replacing subs with lambdify:

f_calka = sp.exp(-x**2)
g_math = sp.lambdify(x, f_calka, "math")
g_numpy = sp.lambdify(x, f_calka, "numpy")


def trapezy_subs(n):
    clear_cache()
    h = sp.Rational(1, n)
    ys = [float(f_calka.subs(x, k * h)) for k in range(n + 1)]
    return (sum(ys) - (ys[0] + ys[-1]) / 2) / n


def trapezy_lambdify(n):
    ys = [g_math(k / n) for k in range(n + 1)]
    return (sum(ys) - (ys[0] + ys[-1]) / 2) / n


def trapezy_numpy(n):
    ys = g_numpy(np.linspace(0, 1, n + 1))
    return (ys.sum() - (ys[0] + ys[-1]) / 2) / n


czasy_trapezy = porownaj({"subs (część 1)": trapezy_subs,
                          "lambdify, math": trapezy_lambdify,
                          "lambdify, numpy": trapezy_numpy}, 200,
                         zgodne=lambda a, b: abs(a - b) < 1e-14)
wariant               czas  przyspieszenie
subs (część 1)     20.9 ms            1.0×
lambdify, math     13.4 µs           1558×
lambdify, numpy    3.90 µs           5347×

The same computation is now thousands of times faster. We announced this in part 1 after reading the profile: it pays to speed up the part of the program where the time really goes.

Polynomials: Poly instead of expressions#

A SymPy expression is a general tree: a sum of products of powers. For polynomials, SymPy has a separate representation, the class Poly. It stores only the exponents and the coefficients, and it multiplies polynomials with algorithms for polynomials over a specific ring, here over \(\mathbb Z\). This is the same choice that MiniCAS made in Lecture 3 (§3.3): a polynomial is a set of monomials, that is, of exponent tuples with coefficients, not a tree. Let us multiply two polynomials of degree \(8\) in three variables:

y, z = sp.symbols("y z")
e1, e2 = (x + y + z + 1)**8, (x - y + 2*z - 1)**8
P1, P2 = sp.Poly(e1, x, y, z), sp.Poly(e2, x, y, z)


def iloczyn_expand():
    clear_cache()
    return sp.expand(e1 * e2)


def iloczyn_poly():
    clear_cache()
    return P1 * P2


def iloczyn_poly_z_zamiana():
    clear_cache()
    return (sp.Poly(e1, x, y, z) * sp.Poly(e2, x, y, z)).as_expr()


wynik = iloczyn_expand()
assert sp.Poly(wynik, x, y, z) == iloczyn_poly()
print("jednomianów w iloczynie:", len(iloczyn_poly().terms()))
czasy_poly = porownaj({
    "expand(e1 * e2)": iloczyn_expand,
    "Poly * Poly": iloczyn_poly,
    "Poly z zamianą tam i z powrotem": iloczyn_poly_z_zamiana},
    zgodne=lambda a, b: True)
jednomianów w iloczynie: 897
wariant                               czas  przyspieszenie
expand(e1 * e2)                     443 ms            1.0×
Poly * Poly                        3.99 ms            111×
Poly z zamianą tam i z powrotem    48.4 ms            9.1×

We checked that the results agree before the measurement (assert). Multiplication in Poly is tens to hundreds of times faster, and even with the conversion of the expression to Poly and back, it beats expand many times over. When a computation consists of many operations on polynomials (division with remainder, GCD, Gröbner bases), we convert the expression to Poly once, at the beginning.

simplify or a specific operation#

The function sp.simplify tries many simplification strategies and picks the shortest result. It is convenient but slow, and the form of the result is hard to predict. When we know what we want, we call a specific operation: cancel (reducing a fraction), factor, expand, together, trigsimp.

r = (x**6 - 1) / (x**2 - 1)


def przez_simplify():
    clear_cache()
    return sp.simplify(r)


def przez_cancel():
    clear_cache()
    return sp.cancel(r)


def przez_factor():
    clear_cache()
    return sp.factor(r)


for f in (przez_simplify, przez_cancel, przez_factor):
    print(f"{f.__name__:15} {f()}")
czasy_upraszczanie = porownaj({"simplify": przez_simplify,
                               "cancel": przez_cancel,
                               "factor": przez_factor},
                              zgodne=lambda a, b: sp.cancel(a - b) == 0)
przez_simplify  x**4 + x**2 + 1
przez_cancel    x**4 + x**2 + 1
przez_factor    (x**2 - x + 1)*(x**2 + x + 1)
wariant        czas  przyspieszenie
simplify    3.45 ms            1.0×
cancel       768 µs            4.5×
factor       527 µs            6.5×

Even more important than time is the certainty of the result. In Lecture 5 (§5.3) we proved formulas for sums of powers by checking that \(S(n)-S(n-1)-n^p\) is the zero polynomial. The function udowodnij did this with sp.expand(...) == 0, not with sp.simplify(...) == 0. For polynomials, expand is a decision procedure: a polynomial is zero if and only if nothing is left after expanding and collecting like terms. The function simplify is a heuristic. When it does not return zero, we do not know whether the expression is nonzero or simplify merely failed to find a way. For expressions with elementary functions, one cannot do better. Richardson’s theorem (deep dive) says that already for expressions with the sine and the absolute value, there is no algorithm that decides whether an expression is identically zero.

n, k = sp.symbols("n k", integer=True, positive=True)
S = sp.expand(sp.summation(k**10, (k, 1, n)))
tozsamosc = S - S.subs(n, n - 1) - n**10


def zero_przez_expand():
    clear_cache()
    return sp.expand(tozsamosc) == 0


def zero_przez_simplify():
    clear_cache()
    return sp.simplify(tozsamosc) == 0


czasy_zero = porownaj({"simplify(...) == 0": zero_przez_simplify,
                       "expand(...) == 0": zero_przez_expand})
wariant                  czas  przyspieszenie
simplify(...) == 0    10.8 ms            1.0×
expand(...) == 0      2.70 ms            4.0×

Here both functions answer correctly, but expand does so faster and with a guarantee.

Rational numbers: Rational, Fraction, and a better algorithm#

SymPy numbers (sp.Rational, sp.Integer) are expression objects. Every operation goes through SymPy’s machinery: type checking, ordering of arguments, the cache. In a loop with thousands of operations on numbers, fractions.Fraction works better. Better still is to change the algorithm. Let us compute the harmonic number \(H_{2000}=1+\tfrac12+\dots+\tfrac1{2000}\) exactly. Summing the fractions one after another reduces the result after every addition, and reduction requires the GCD of ever longer numbers. Binary splitting divides the summation range into halves, sums each half recursively as a pair of integers (numerator, denominator) without reducing, and reduces only once, at the end:

\[ \sum_{a\le k<b}\frac1k=\frac{P}{Q},\qquad P=P_1Q_2+P_2Q_1,\quad Q=Q_1Q_2, \]

where \(P_1/Q_1\) and \(P_2/Q_2\) are the sums over the two halves. At every step, the numbers being multiplied have similar lengths, and it is on such multiplications that fast big-integer arithmetic gains the most.

def h_rational(n):
    clear_cache()
    return sum(sp.Rational(1, k) for k in range(1, n + 1))


def h_fraction(n):
    return sum(Fraction(1, k) for k in range(1, n + 1))


def dzielenie_binarne(a, b):
    """Suma 1/k dla a <= k < b jako para (licznik, mianownik)."""
    if b - a == 1:
        return 1, a
    s = (a + b) // 2
    p1, q1 = dzielenie_binarne(a, s)
    p2, q2 = dzielenie_binarne(s, b)
    return p1 * q2 + p2 * q1, q1 * q2


def h_binarnie(n):
    return Fraction(*dzielenie_binarne(1, n + 1))     # Fraction skraca raz


def h_harmonic_od_zera(n):
    sp.harmonic.harmonic_cache.clear()     # tego clear_cache nie czyści
    clear_cache()
    return sp.harmonic(n)


def jako_fraction(q):
    return Fraction(int(sp.numer(q)), int(sp.denom(q)))


czasy_h = porownaj({"suma sp.Rational": h_rational,
                    "suma Fraction": h_fraction,
                    "dzielenie binarne": h_binarnie,
                    "sp.harmonic od zera": h_harmonic_od_zera,
                    "sp.harmonic z pamięcią": sp.harmonic}, 2000,
                   zgodne=lambda a, b: jako_fraction(a) == jako_fraction(b))
H = h_binarnie(2000)
print(f"H_2000: licznik ma {len(str(H.numerator))} cyfr,",
      f"mianownik {len(str(H.denominator))}")
wariant                      czas  przyspieszenie
suma sp.Rational          15.6 ms            1.0×
suma Fraction             2.22 ms            7.0×
dzielenie binarne          671 µs             23×
sp.harmonic od zera       18.6 ms           0.84×
sp.harmonic z pamięcią     103 ns         151738×
H_2000: licznik ma 867 cyfr, mianownik 866

The sum of Fraction numbers is several times faster than the sum of sp.Rational numbers, and binary splitting is faster still. The advantage of binary splitting grows with \(n\) (exercise 3). The same technique is used to compute constants such as \(\pi\) or \(e\) to millions of digits (B. Haible, T. Papanikolaou, Fast multiprecision evaluation of series of rational numbers, 1998).

The last two rows are a cautionary tale about measurement. Computed from scratch, sp.harmonic adds up sp.Rational numbers one after another, so it is as slow as our sum. The second time, however, it takes a fraction of a microsecond. SymPy remembers all the computed \(H_k\) in its own dictionary sp.harmonic.harmonic_cache, which clear_cache does not clear. Had we not noticed this, we would have declared sp.harmonic the fastest algorithm, while measuring nothing but a dictionary lookup.

Summary#

  • We do the symbolic computation once and turn the result into a numerical function with sp.lambdify. This speeds up the evaluation thousands of times: subs in a loop is the slowest way to compute values.

  • lambdify is a compiler like the one from Lecture 3: it turns the expression tree into Python code, and with the "numpy" module it computes on whole arrays.

  • For polynomials, we use Poly, not general expressions.

  • Instead of simplify, we choose a specific operation (cancel, factor, expand). For polynomial identities, expand(...) == 0 is faster and gives a certain answer.

  • In loops over rational numbers, we use Fraction, and a better algorithm (binary splitting) gives even more.

  • When timing SymPy, we clear SymPy’s cache (clear_cache) and remember that some functions have caches of their own (sp.harmonic).

Exercises#

  1. ★ Plot the interpolating polynomial from Lecture 5 at \(10^4\) points, computing the values with subs and with lambdify. Measure both running times.

  2. ★ Compare sp.diff with expand and with simplify for the derivative of order \(10\) of the function \(e^{x}\sin x\). Which form of the result is shorter?

  3. ★★ Compare the Fraction sum with binary splitting for \(H_n\), \(n=10^3, 10^4, 10^5\). How does the ratio of the running times grow?

  4. ★★ Time sp.factor for \(x^n-1\) and \(n=60, 120, 240\). Explain the number of factors (cyclotomic polynomials) and compare it with the number of divisors of \(n\).

  5. ★★ Use sp.lambdify(x, w, "mpmath") to compute \(\sin(x+1)+\cos(x+1)\) to \(50\) digits at the point \(x=10^{20}\). Compare with the "math" version. Which one is correct, and why?