Algorithm Search⌘K

Data structureadvanced

Taylor expansion diagram

Also called TED.

Ciesielski, Kalla and Askar's canonical graph of a polynomial over word-level variables built by Taylor expansion, used to verify arithmetic datapaths.

Time
O(f g D) expected addO(f D) evaluateO(D) expected mk
Space
O(f D) nodes
Where
D = the largest degree of one variable; f = the number of nodes of the first argument; g = the number of nodes of the second argument
Properties
not concurrentnot externalpersistent
Origin
Maciej Ciesielski, Priyank Kalla, 2001

A Taylor expansion diagram (TED) is a canonical graph of a multivariate polynomial. Ciesielski, Kalla and their coauthors introduced it in 2001 to compare arithmetic datapaths at the word level. Each variable stands for a whole data word and takes integer or real values, not bits. For the top variable xx in a fixed order, a node expands its polynomial ff in the Taylor series at x=0x = 0:

f=f(0)+x f′(0)+12x2f′′(0)+⋯+1d!xdf(d)(0),f = f(0) + x \, f'(0) + \tfrac{1}{2} x^2 f''(0) + \cdots + \tfrac{1}{d!} x^d f^{(d)}(0),

where the derivatives are by xx and the coefficients are polynomials in the later variables. A polynomial has a finite series, so the node has one child per power x0,…,xdx^0, \ldots, x^d. With the rules "drop a node that does not depend on its variable" and "merge equal nodes", the diagram is canonical: two expressions, such as A⋅B+A⋅CA \cdot B + A \cdot C and A⋅(B+C)A \cdot (B + C), give the same node exactly when they are the same polynomial. A TED of a 0-1 variable needs only the powers 0 and 1, since x2=xx^2 = x, and then the node is the moment node of a binary moment diagram. The TED carries that idea to word variables.

In plain words

Write a polynomial in a fixed order of its variables. Take the first variable, say aa, and group the terms by the power of aa: the terms without aa, the terms with aa, those with a2a^2, and so on. Each group, with its power of aa taken out, is a smaller polynomial in the other variables. Do the same for each of them with the next variable, and so on until only numbers are left.

Draw this as a graph. A node for aa has an arrow to each group. Equal groups are stored only once, and a variable that does not occur is skipped. Then every polynomial has exactly one graph. To test whether two circuits compute the same polynomial, build both graphs and compare the two top nodes.

The abstract type

The variables are x1,…,xnx_1, \ldots, x_n in this order, and the coefficients are rational numbers. A node uu stands for a polynomial fu∈Q[x1,…,xn]f_u \in \mathbb{Q}[x_1, \ldots, x_n].

operation result
CONST(q)(q) the constant polynomial qq
MK(v,c0,…,cd)(v, c_0, \ldots, c_d) the polynomial ∑k=0dxvkfck\sum_{k=0}^{d} x_v^k f_{c_k}
ADD(f,g)(f, g) f+gf + g
MUL(f,g)(f, g) f⋅gf \cdot g
EVALUATE(f,p)(f, p) the value of ff at the point pp
BUILD(e)(e) the node of an expression ee made of variables, numbers, ++, −-, ×\times and powers
EQUAL(f,g)(f, g) whether f=gf = g, by comparing ids

For a polynomial ff in xv,…,xnx_v, \ldots, x_n there are unique polynomials f0,…,fdf_0, \ldots, f_d in xv+1,…,xnx_{v+1}, \ldots, x_n, with fd≠0f_d \ne 0 unless d=0d = 0, such that f=∑kxvkfkf = \sum_k x_v^k f_k. They are the Taylor coefficients: fk=1k!∂kf/∂xvkf_k = \frac{1}{k!} \partial^k f / \partial x_v^k at xv=0x_v = 0. Division by k!k! needs a field of characteristic 0, such as Q\mathbb{Q} or R\mathbb{R}.

Representation

A sink (n+1,q)(n + 1, q) stores one rational number qq. An inner node (v,c0,…,cd)(v, c_0, \ldots, c_d) stores the level vv and d+1d + 1 children on later levels, where ckc_k is the node of the kk-th Taylor coefficient. A unique table maps each key to its node, and MK keeps three rules:

  • Trailing zeros. A last child that is the sink 0 is dropped, since xvd⋅0x_v^d \cdot 0 adds nothing.
  • No dependence. If only c0c_0 is left, MK returns c0c_0, since f=f0f = f_0 does not depend on xvx_v.
  • Merging. If the key is stored, MK returns the stored node.

So every inner node has at least two children and a nonzero last child. Unfolded, a TED lists the monomials of ff: the path that takes child kvk_v at each tested variable ends at the coefficient of ∏vxvkv\prod_v x_v^{k_v}, and a skipped variable has power 0.

Operations

For a node uu and a level vv at most the level of uu, let coef(u,v)\mathrm{coef}(u, v) be (c0,…,cd)(c_0, \ldots, c_d) if u=(v,c0,…,cd)u = (v, c_0, \ldots, c_d), and (u)(u) if uu is on a later level.

  1. MK(v, c_0, ..., c_d)
  2. 1while d ≥ 1 and c_d is the sink 0 do d ← d − 1 ▷ trailing zeros
  3. 2if d = 0 then return c_0 ▷ no dependence on x_v
  4. 3if U holds (v, c_0, ..., c_d) then return it ▷ merging
  5. 4otherwise make a new node u, store U[v, c_0, ..., c_d] ← u, and return u
  6. ADD(f, g) ▷ ADD(0, g) = g, ADD(f, 0) = f; results are cached under {f, g}
  7. 5if f and g are sinks then return CONST(q_f + q_g)
  8. 6v ← min(level(f), level(g)); a ← coef(f, v); b ← coef(g, v); pad the shorter with 0; return MK(v, ADD(a_k, b_k) for each k)
  9. MUL(f, g) ▷ 0 and 1 are shortcuts; results are cached under {f, g}
  10. 7if f and g are sinks then return CONST(q_f · q_g)
  11. 8v, a, b as in ADD; for k ← 0 to d_a + d_b do c_k ← the ADD of MUL(a_i, b_j) over all i + j = k
  12. 9return MK(v, c_0, ..., c_{d_a + d_b})
  13. EVALUATE(u, p) ▷ one pass over the nodes reachable from u, children first
  14. 10val[w] ← q for a sink (n + 1, q); val[w] ← Σ_k val[c_k] · p_v^k by Horner's rule for w = (v, c_0, ..., c_d); return val[u]
  15. BUILD(e)
  16. 11a variable x gives MK(x, 0, 1), a number q gives CONST(q); +, −, × and powers recurse with ADD, ADD and MUL by −1, and MUL

ADD uses that the Taylor coefficients of a sum are the sums of the coefficients. MUL multiplies two polynomials in xvx_v whose coefficients are polynomials in the later variables:

(∑ixviai)(∑jxvjbj)=∑kxvk∑i+j=kaibj.\Bigl(\sum_i x_v^i a_i\Bigr)\Bigl(\sum_j x_v^j b_j\Bigr) = \sum_k x_v^k \sum_{i + j = k} a_i b_j.

Example

The square of a sum. Take the order a,ba, b and f=(a+b)2f = (a + b)^2. BUILD gives the node of a+ba + b, namely (a,(b,0,1),1)(a, (b, 0, 1), 1), and MUL of it with itself. Line L8 takes v=av = a, coef=((b,0,1),1)\mathrm{coef} = ((b, 0, 1), 1) for both, and computes

kk ∑i+j=kaibj\sum_{i + j = k} a_i b_j Taylor coefficient of ff by aa node
0 b⋅bb \cdot b f(0,b)=b2f(0, b) = b^2 (b,0,0,1)(b, 0, 0, 1)
1 b⋅1+1⋅bb \cdot 1 + 1 \cdot b ∂f/∂a\partial f / \partial a at a=0a = 0: 2b2b (b,0,2)(b, 0, 2)
2 1⋅11 \cdot 1 12∂2f/∂a2=1\frac{1}{2} \partial^2 f / \partial a^2 = 1 the sink 1

The root is (a,(b,0,0,1),(b,0,2),1)(a, (b, 0, 0, 1), (b, 0, 2), 1): 3 inner nodes and the sinks 0, 1 and 2, so 6 nodes. BUILD of the other form a⋅a+2⋅a⋅b+b⋅ba \cdot a + 2 \cdot a \cdot b + b \cdot b goes through other calls and returns the same root id.

Rational coefficients. With one variable, (x+12)(x−13)(x + \frac{1}{2})(x - \frac{1}{3}) and x2+16x−16x^2 + \frac{1}{6} x - \frac{1}{6} both give the node (x,−16,16,1)(x, -\frac{1}{6}, \frac{1}{6}, 1). The children are f(0)=−16f(0) = -\frac{1}{6}, f′(0)=16f'(0) = \frac{1}{6} and 12f′′(0)=1\frac{1}{2} f''(0) = 1.

A datapath rewrite. With the order A,B,CA, B, C, the designs A⋅B+A⋅CA \cdot B + A \cdot C and A⋅(B+C)A \cdot (B + C) give the same node (A,0,(B,C,1))(A, 0, (B, C, 1)), where (B,C,1)(B, C, 1) is B+CB + C. A bit-level check of the two would compare circuits with different multipliers.

Measured sizes, with the code of this page:

polynomial inner nodes all nodes monomials
(a+b)k(a + b)^k, k=1,…,6k = 1, \ldots, 6 k+1k + 1 4, 6, 7, 9, 10, 12 k+1k + 1
(x1+⋯+xn)2(x_1 + \cdots + x_n)^2, n=2,…,6n = 2, \ldots, 6 2n−12n - 1 2n+22n + 2 n(n+1)/2n(n + 1)/2

The square of a sum of nn words has a linear number of nodes, while it has a quadratic number of monomials.

Correctness

Canonicity. The Taylor coefficients of a polynomial by xvx_v are unique, because Q[xv,…,xn]\mathbb{Q}[x_v, \ldots, x_n] is the ring of polynomials in xvx_v over Q[xv+1,…,xn]\mathbb{Q}[x_{v+1}, \ldots, x_n]. And ff does not depend on xvx_v exactly when all coefficients after the 0-th are zero. With these two facts, the induction of BDD canonicity goes through. Every inner node depends on its variable, by the trailing-zeros rule. Two nodes with the same polynomial on the same level have the same coefficients, hence by induction the same children, and the merging rule makes them one node. So over Q\mathbb{Q}, two polynomials are equal exactly when their nodes are the same. Since Q\mathbb{Q} is infinite, this is also equality as functions. ADD and MUL are correct by the identities above, and EVALUATE by Horner's rule. The full proofs are in the proof file.

The tests check canonicity on 300 random expressions with fixed seeds: each expression and a second form of the same polynomial, with the monomials and factors in random order, give the same node, and a changed coefficient gives another node. On 400 more expressions, two nodes are equal exactly when the polynomials, expanded independently, are equal. The tests also check that the kk-th child of the root is 1k!∂kf/∂xvk\frac{1}{k!} \partial^k f / \partial x_v^k at xv=0x_v = 0, that EVALUATE agrees with the expanded polynomial at random rational points, and that the store stays reduced.

Proof: Reduced ordered TEDs are canonical, and ADD, MUL and EVALUATE are correctfull

The variables are x1,…,xnx_1, \ldots, x_n in this order, and all polynomials have rational coefficients. Write Rv=Q[xv,…,xn]R_v = \mathbb{Q}[x_v, \ldots, x_n], so Rn+1=QR_{n+1} = \mathbb{Q}. A sink (n+1,q)(n + 1, q) has the level n+1n + 1 and the polynomial f≡qf \equiv q. An inner node u=(v,c0,…,cd)u = (v, c_0, \ldots, c_d) has the level vv, its children have larger levels, and fu=∑k=0dxvkfckf_u = \sum_{k=0}^{d} x_v^k f_{c_k}. By induction from the sinks, fu∈Rvf_u \in R_v. The store is reduced if every inner node has d≥1d \ge 1 and cdc_d not the sink 0, no two sinks hold the same number, and no two inner nodes have the same key (v,c0,…,cd)(v, c_0, \ldots, c_d). Lines L1 to L4 of MK keep it reduced, and CONST keeps the sinks distinct.

Lemma 1 (Taylor coefficients). Let f∈Rvf \in R_v. (a) There are unique d≥0d \ge 0 and f0,…,fd∈Rv+1f_0, \ldots, f_d \in R_{v+1} with fd≠0f_d \ne 0 or d=0d = 0, such that f=∑k=0dxvkfkf = \sum_{k=0}^{d} x_v^k f_k. (b) fk=1k!∂kf∂xvk∣xv=0f_k = \frac{1}{k!} \frac{\partial^k f}{\partial x_v^k}\big|_{x_v = 0}. (c) f∈Rv+1f \in R_{v+1} if and only if d=0d = 0.

Proof. (a) RvR_v is the ring Rv+1[xv]R_{v+1}[x_v] of polynomials in xvx_v with coefficients in Rv+1R_{v+1}: group the monomials of ff by their power of xvx_v. A polynomial in xvx_v has unique coefficients, so the fkf_k are unique, and dd is the degree, or 0 for f=0f = 0. (b) For j≥kj \ge k, ∂kxvj/∂xvk=j!(j−k)!xvj−k\partial^k x_v^j / \partial x_v^k = \frac{j!}{(j-k)!} x_v^{j-k}, and for j<kj < k it is 0. At xv=0x_v = 0 only j=kj = k is left, which gives k! fkk! \, f_k. The field Q\mathbb{Q} has characteristic 0, so we may divide by k!k!. (c) By uniqueness in (a). □\square

So a node is exactly the Taylor expansion of its polynomial at xv=0x_v = 0, cut after the last nonzero term. Equality here is equality of polynomials. Over the infinite field Q\mathbb{Q} a polynomial that is 0 at every point is the zero polynomial, so it is also equality of functions on Qn\mathbb{Q}^n.

Theorem 2 (canonicity). In a reduced store, (a) the polynomial of every inner node on level vv is not in Rv+1R_{v+1}, and (b) two distinct nodes have distinct polynomials.

Proof. By induction on kk from n+1n + 1 down to 1, for the nodes on levels kk and above. For k=n+1k = n + 1 the nodes are sinks with distinct numbers, so (b) holds, and (a) has no cases.

Let u=(k,c0,…,cd)u = (k, c_0, \ldots, c_d). Its children are on levels above kk. The child cdc_d is not the sink 0, and the sink 0 has the polynomial 0, so by (b) for those levels fcd≠0f_{c_d} \ne 0. With d≥1d \ge 1, Lemma 1(a) says that dd is the degree of fuf_u in xkx_k, and Lemma 1(c) gives fu∉Rk+1f_u \notin R_{k+1}. This is (a).

For (b), let u≠wu \ne w be nodes on levels kk and above with fu=fwf_u = f_w. If both are above level kk, (b) for those levels gives a contradiction. If uu is on level kk and ww above it, then fw∈Rk+1f_w \in R_{k+1} and fu∉Rk+1f_u \notin R_{k+1} by (a), a contradiction. If u=(k,c0,…,cd)u = (k, c_0, \ldots, c_d) and w=(k,c0′,…,cd′′)w = (k, c'_0, \ldots, c'_{d'}), then Lemma 1(a) gives d=d′d = d' and fci=fci′f_{c_i} = f_{c'_i} for all ii. By (b) for the higher levels ci=ci′c_i = c'_i, so uu and ww have the same key, and the merging of lines L3 and L4 gives u=wu = w. □\square

Corollary. A node whose polynomial lies in Rv+1R_{v+1} is on a level larger than vv: an inner node on level w≤vw \le v has a polynomial outside Rw+1⊇Rv+1R_{w+1} \supseteq R_{v+1}. And EQUAL by node ids is correct.

Lemma 3 (MK and coef). (a) MK(v,c0,…,cd)(v, c_0, \ldots, c_d), with all ckc_k on levels larger than vv, returns a node with the polynomial ∑kxvkfck\sum_k x_v^k f_{c_k}. (b) If vv is at most the level of uu and coef(u,v)=(c0,…,cd)\mathrm{coef}(u, v) = (c_0, \ldots, c_d), then fu=∑kxvkfckf_u = \sum_k x_v^k f_{c_k} and every ckc_k is on a level larger than vv.

Proof. (a) Line L1 drops children that are the sink 0, which add xvk⋅0x_v^k \cdot 0. If one child is left, line L2 returns it, and its polynomial is the sum. Otherwise lines L3 and L4 return the node with that key. (b) If uu is on level vv, this is the definition of fuf_u. If not, coef\mathrm{coef} returns (u)(u), and fu=xv0fuf_u = x_v^0 f_u. □\square

Theorem 4 (ADD). ADD(f,g)(f, g) returns the node of ff+fgf_f + f_g, and at most ∣f∣⋅∣g∣\lvert f \rvert \cdot \lvert g \rvert calls reach line L6.

Proof. By induction on the sum of the levels of the arguments. The shortcuts for the sink 0 and line L5 are correct. The cache returns only results of earlier calls with the same pair, in either order, which is correct because addition commutes. At line L6, Lemma 3(b) gives ff+fg=∑kxvk(fak+fbk)f_f + f_g = \sum_k x_v^k (f_{a_k} + f_{b_k}), with the shorter list padded by the sink 0. Each recursive call has both arguments on levels larger than vv, so the level sum grows, and by induction it returns the node of fak+fbk∈Rv+1f_{a_k} + f_{b_k} \in R_{v+1}. By the corollary that node is on a level larger than vv, so Lemma 3(a) applies and MK returns the node of the sum. The arguments of every call are nodes reachable from ff and from gg, or the sink 0, which the shortcut handles, and the cache lets each pair reach line L6 once. □\square

Theorem 5 (MUL). MUL(f,g)(f, g) returns the node of ff⋅fgf_f \cdot f_g.

Proof. By induction on the sum of the levels, as for ADD. The shortcuts for 0 and 1 and line L7 are correct, and so is the cache, since multiplication commutes. At line L8, with ff=∑ixvifaif_f = \sum_i x_v^i f_{a_i} and fg=∑jxvjfbjf_g = \sum_j x_v^j f_{b_j} from Lemma 3(b), the coefficients lie in Rv+1R_{v+1} and commute with xvx_v, so

ff⋅fg=∑kxvk∑i+j=kfaifbj.f_f \cdot f_g = \sum_{k} x_v^k \sum_{i + j = k} f_{a_i} f_{b_j}.

Each MUL(ai,bj)(a_i, b_j) has both arguments on levels larger than vv, so by induction it returns the node of faifbj∈Rv+1f_{a_i} f_{b_j} \in R_{v+1}, and ADD (Theorem 4) sums them in ckc_k, the node of the inner sum. By the corollary every ckc_k is on a level larger than vv, and Lemma 3(a) gives the result at line L9. □\square

EVALUATE and BUILD. Line L10 computes, children first, val(u)=∑kval(ck) xvk\mathit{val}(u) = \sum_k \mathit{val}(c_k) \, x_v^k by Horner's rule, so by induction val(u)=fu\mathit{val}(u) = f_u at the point. BUILD at line L11 is correct by induction on the expression: a variable xx is MK(x,0,1)(x, 0, 1), the polynomial 0+x⋅10 + x \cdot 1, a number is a sink, and ++, −- and ×\times are ADD, ADD with MUL by −1-1, and MUL. A power is repeated MUL. So two expressions of the same polynomial give the same node, by Theorem 2. ■\blacksquare

Complexity

operation time notes
MK, CONST O(D)O(D) expected one hash of up to D+1D + 1 children
ADD(f,g)(f, g) O(∣f∣⋅∣g∣⋅D)O(\lvert f \rvert \cdot \lvert g \rvert \cdot D) expected each pair of nodes once
MUL(f,g)(f, g) no general polynomial bound is given here each pair once, but each step runs ADD on intermediate results
EVALUATE O(∣f∣⋅D)O(\lvert f \rvert \cdot D) all reachable nodes
space O(∣f∣⋅D)O(\lvert f \rvert \cdot D) up to D+1D + 1 children per node

DD is the largest degree of one variable. The times count rational operations as O(1)O(1). Coefficients of products can grow large, so exact arithmetic costs more for high degrees and many factors.

Variants

  • Normalized weighted TEDs. Ciesielski, Kalla and Askar put multiplicative weights on the edges and normalize them, so that common factors such as the 2i2^i of a bit vector or a constant multiple move into the weights. The rules are chosen so that the normalized form stays canonical.
  • Bit-level variables. A variable that takes only 0 and 1 obeys x2=xx^2 = x, so its node has the children for x0x^0 and x1x^1 only. Such a node is a moment node of a BMD, so a TED over 0-1 variables is a BMD, and a word X=∑i2ixiX = \sum_i 2^i x_i links the word level to the bits.
  • Other bases. An ADD uses the Shannon expansion for functions of bits to numbers, and KFDDs choose an expansion per variable. TEDs are the polynomial case with a Taylor basis per word variable.
  • Polynomials modulo 2w2^w. A real datapath computes modulo 2w2^w, where different polynomials can give the same function. A TED over Q\mathbb{Q} then proves equivalence only when the two polynomials are equal. The canonical forms of polynomial functions modulo 2w2^w need extra rules.

When to use it

Use a TED to check that two arithmetic datapaths, given as expressions over words, compute the same polynomial: rewrites of a filter, a transform, a sum of products, or a high-level synthesis step. The cost depends on the number of words and their degrees, not on the width of the words. For control logic, comparisons and other bit-level functions, BDDs and SAT are the right tools. For a gate-level multiplier, the structure is not a word-level expression, and the algebraic method that rewrites the gate polynomials is the usual choice. For one-off identity tests, random evaluation at a few points is cheaper but gives no canonical form.

Pitfalls

  • Field of characteristic 0. The Taylor coefficients divide by k!k!, and canonicity uses unique coefficients over a field. Over the integers modulo 2w2^w the same diagram is still a correct representation of a polynomial, but equal functions need not have equal polynomials, so different nodes do not prove that two designs differ.
  • The variable order. The diagram is canonical only for a fixed order, and its size depends on the order. Both sides of a check must use the same manager and the same order.
  • Evaluation visits all nodes. As in a BMD, the value is a sum over many paths, not one path.
  • Big numbers. Coefficients are exact rationals. Fixed-width numbers overflow for large products.
  • Mixed bits and words. A variable that is really a bit must use x2=xx^2 = x. Treating it as a word variable makes x2x^2 and xx different nodes, and two equal bit-level designs look different.

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.

taylor_expansion_diagram.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/taylor-expansion-diagram/. The authors are listed in prov/B790DF.jsonl.
"""Reduced ordered Taylor expansion diagrams over the rationals.

A node (v, (c_0, ..., c_d)) stands for the polynomial sum_k x_v^k f_{c_k}, where
f_{c_k} = (1/k!) d^k f / dx_v^k at x_v = 0 is the k-th Taylor coefficient. The
children are on later levels. A sink holds one Fraction. MK keeps the diagram
reduced: no trailing zero child, no node with only the 0-th child, and no two
equal nodes. Then two polynomials are equal exactly when their node ids are.
"""

from __future__ import annotations

from fractions import Fraction
from typing import Mapping, Sequence, Union

Expr = Union[tuple, str, int, Fraction]


class TED:
    def __init__(self, order: Sequence[str]) -> None:
        self.order = list(order)
        self.level = {name: i for i, name in enumerate(self.order)}
        self.n = len(self.order)
        self.nodes: list[tuple] = []        # id -> ("c", q) or (level, children)
        self.unique: dict[tuple, int] = {}
        self.add_cache: dict[tuple[int, int], int] = {}
        self.mul_cache: dict[tuple[int, int], int] = {}
        self.zero = self.const(0)
        self.one = self.const(1)

    # ------------------------------------------------------------------ nodes

    def const(self, q) -> int:
        key = ("c", Fraction(q))
        u = self.unique.get(key)
        if u is None:
            u = len(self.nodes)
            self.nodes.append(key)
            self.unique[key] = u
        return u

    def is_const(self, u: int) -> bool:
        return self.nodes[u][0] == "c"

    def value(self, u: int) -> Fraction:
        return self.nodes[u][1]

    def var_level(self, u: int) -> int:
        return self.n if self.is_const(u) else self.nodes[u][0]

    def children(self, u: int) -> tuple[int, ...]:
        return self.nodes[u][1]

    def mk(self, v: int, children: Sequence[int]) -> int:
        ch = list(children)
        while len(ch) > 1 and ch[-1] == self.zero:                  # @line L1
            ch.pop()
        if len(ch) == 1:                                             # @line L2
            return ch[0]
        key = (v, tuple(ch))
        u = self.unique.get(key)                                     # @line L3
        if u is None:
            u = len(self.nodes)                                      # @line L4
            self.nodes.append(key)
            self.unique[key] = u
        return u

    def var(self, name: str) -> int:
        return self.mk(self.level[name], (self.zero, self.one))

    def coef(self, u: int, v: int) -> list[int]:
        """The Taylor coefficients of u by the variable of level v <= level of u."""
        return list(self.children(u)) if self.var_level(u) == v else [u]

    # ------------------------------------------------------------- operations

    def add(self, f: int, g: int) -> int:
        if f == self.zero:
            return g
        if g == self.zero:
            return f
        if self.is_const(f) and self.is_const(g):                    # @line L5
            return self.const(self.value(f) + self.value(g))
        key = (min(f, g), max(f, g))
        r = self.add_cache.get(key)
        if r is None:
            v = min(self.var_level(f), self.var_level(g))            # @line L6
            a, b = self.coef(f, v), self.coef(g, v)
            m = max(len(a), len(b))
            a += [self.zero] * (m - len(a))
            b += [self.zero] * (m - len(b))
            r = self.mk(v, [self.add(x, y) for x, y in zip(a, b)])
            self.add_cache[key] = r
        return r

    def mul(self, f: int, g: int) -> int:
        if f == self.zero or g == self.zero:
            return self.zero
        if f == self.one:
            return g
        if g == self.one:
            return f
        if self.is_const(f) and self.is_const(g):                    # @line L7
            return self.const(self.value(f) * self.value(g))
        key = (min(f, g), max(f, g))
        r = self.mul_cache.get(key)
        if r is None:
            v = min(self.var_level(f), self.var_level(g))            # @line L8
            a, b = self.coef(f, v), self.coef(g, v)
            c = [self.zero] * (len(a) + len(b) - 1)
            for i, x in enumerate(a):
                for j, y in enumerate(b):
                    c[i + j] = self.add(c[i + j], self.mul(x, y))
            r = self.mk(v, c)                                        # @line L9
            self.mul_cache[key] = r
        return r

    def neg(self, f: int) -> int:
        return self.mul(self.const(-1), f)

    def evaluate(self, u: int, point: Mapping[str, Fraction]) -> Fraction:
        val: dict[int, Fraction] = {}

        def go(w: int) -> Fraction:
            if w in val:
                return val[w]
            if self.is_const(w):
                r = self.value(w)
            else:                                                    # @line L10
                x = Fraction(point[self.order[self.var_level(w)]])
                r = Fraction(0)
                for c in reversed(self.children(w)):                 # Horner
                    r = r * x + go(c)
            val[w] = r
            return r

        return go(u)

    def build(self, e: Expr) -> int:
        """The node of an expression: a variable name, a number, or (op, a, b)
        with op in '+', '-', '*', or ('^', a, k) for a power k >= 0."""
        if isinstance(e, str):                                       # @line L11
            return self.var(e)
        if isinstance(e, (int, Fraction)):
            return self.const(e)
        op = e[0]
        if op == "^":
            r, base = self.one, self.build(e[1])
            for _ in range(e[2]):
                r = self.mul(r, base)
            return r
        a, b = self.build(e[1]), self.build(e[2])
        if op == "+":
            return self.add(a, b)
        if op == "-":
            return self.add(a, self.neg(b))
        return self.mul(a, b)

    # ---------------------------------------------------------------- reading

    def reachable(self, u: int) -> set[int]:
        seen, todo = set(), [u]
        while todo:
            w = todo.pop()
            if w not in seen:
                seen.add(w)
                if not self.is_const(w):
                    todo.extend(self.children(w))
        return seen

    def size(self, u: int) -> int:
        return len(self.reachable(u))

    def to_poly(self, u: int) -> dict[tuple[int, ...], Fraction]:
        """Unfold u into {exponent vector: coefficient}, with nonzero coefficients."""
        if self.is_const(u):
            q = self.value(u)
            return {(0,) * self.n: q} if q else {}
        v = self.var_level(u)
        out: dict[tuple[int, ...], Fraction] = {}
        for k, c in enumerate(self.children(u)):
            for mono, q in self.to_poly(c).items():
                m = list(mono)
                m[v] += k
                out[tuple(m)] = q
        return out
test_taylor_expansion_diagram.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/taylor-expansion-diagram/. The authors are listed in prov/B790DF.jsonl.

import random
from fractions import Fraction
from math import factorial

from taylor_expansion_diagram import TED

F = Fraction
VARS = ("a", "b", "c", "d")


# ------------------------------------------------- a reference: dicts of monomials

def p_add(p, q):
    out = dict(p)
    for m, c in q.items():
        out[m] = out.get(m, 0) + c
        if out[m] == 0:
            del out[m]
    return out


def p_mul(p, q):
    out = {}
    for m1, c1 in p.items():
        for m2, c2 in q.items():
            m = tuple(x + y for x, y in zip(m1, m2))
            out[m] = out.get(m, 0) + c1 * c2
            if out[m] == 0:
                del out[m]
    return out


def expand(e, names=VARS):
    n = len(names)
    if isinstance(e, str):
        m = [0] * n
        m[names.index(e)] = 1
        return {tuple(m): F(1)}
    if isinstance(e, (int, Fraction)):
        return {(0,) * n: F(e)} if e else {}
    if e[0] == "^":
        r, base = {(0,) * n: F(1)}, expand(e[1], names)
        for _ in range(e[2]):
            r = p_mul(r, base)
        return r
    a, b = expand(e[1], names), expand(e[2], names)
    if e[0] == "+":
        return p_add(a, b)
    if e[0] == "-":
        return p_add(a, {m: -c for m, c in b.items()})
    return p_mul(a, b)


def random_expr(rng, depth):
    if depth == 0 or rng.random() < 0.25:
        if rng.random() < 0.6:
            return rng.choice(VARS)
        return F(rng.randint(-3, 3), rng.randint(1, 3))
    op = rng.choice("++-**^")
    if op == "^":
        return ("^", random_expr(rng, depth - 1), rng.randint(0, 3))
    return (op, random_expr(rng, depth - 1), random_expr(rng, depth - 1))


def as_sum_of_monomials(p, rng, names=VARS):
    """Another expression of the same polynomial: shuffled monomials and factors."""
    terms = list(p.items())
    rng.shuffle(terms)
    e = 0
    for mono, c in terms:
        factors = [n for n, k in zip(names, mono) for _ in range(k)]
        rng.shuffle(factors)
        t = c
        for x in factors:
            t = ("*", x, t) if rng.random() < 0.5 else ("*", t, x)
        e = ("+", t, e) if rng.random() < 0.5 else ("+", e, t)
    return e


def check_reduced(t):
    seen = set()
    for u, node in enumerate(t.nodes):
        assert node not in seen
        seen.add(node)
        if node[0] != "c":
            v, ch = node
            assert len(ch) >= 2 and ch[-1] != t.zero
            assert all(t.var_level(c) > v for c in ch)


# ----------------------------------------------------------------------- tests

def test_example_of_the_page():
    t = TED(("a", "b"))
    square = t.build(("*", ("+", "a", "b"), ("+", "a", "b")))
    expanded = t.build(("+", ("+", ("*", "a", "a"), ("*", 2, ("*", "a", "b"))), ("*", "b", "b")))
    assert square == expanded
    assert t.size(square) == 6                     # 3 inner nodes, sinks 0, 1, 2
    root = t.nodes[square]
    assert root[0] == 0 and len(root[1]) == 3      # children for k = 0, 1, 2
    assert t.to_poly(root[1][0]) == {(0, 2): 1}    # f(0, b) = b^2
    assert t.to_poly(root[1][1]) == {(0, 1): 2}    # df/da at a = 0 is 2b
    assert root[1][2] == t.one                     # (1/2) d2f/da2 = 1


def test_rational_example():
    t = TED(("x",))
    f = t.build(("*", ("+", "x", F(1, 2)), ("-", "x", F(1, 3))))
    g = t.build(("+", ("+", ("^", "x", 2), ("*", F(1, 6), "x")), F(-1, 6)))
    assert f == g
    assert [t.value(c) for c in t.children(f)] == [F(-1, 6), F(1, 6), F(1)]


def test_datapath_rewrite():
    t = TED(("A", "B", "C"))
    assert t.build(("+", ("*", "A", "B"), ("*", "A", "C"))) == t.build(("*", "A", ("+", "B", "C")))
    assert t.build(("-", ("*", "A", "B"), ("*", "B", "A"))) == t.zero
    assert t.build(("*", "A", "B")) != t.build(("*", "A", "C"))


def test_canonicity_on_random_expressions():
    rng = random.Random(1806)
    for _ in range(300):
        t = TED(VARS)
        e = random_expr(rng, 4)
        p = expand(e)
        u = t.build(e)
        assert t.to_poly(u) == {m: c for m, c in p.items()}
        assert t.build(as_sum_of_monomials(p, rng)) == u
        # A changed coefficient gives another node.
        mono = (rng.randint(0, 2), rng.randint(0, 2), 0, 0)
        q = p_add(p, {mono: F(1, 7)})
        assert t.build(as_sum_of_monomials(q, rng)) != u
        check_reduced(t)


def test_equal_nodes_iff_equal_polynomials():
    rng = random.Random(77)
    t = TED(VARS)
    seen = {}
    for _ in range(400):
        e = random_expr(rng, 3)
        key = tuple(sorted(expand(e).items()))
        u = t.build(e)
        if key in seen:
            assert seen[key] == u
        else:
            assert u not in seen.values()
            seen[key] = u
    assert len(seen) > 100
    check_reduced(t)


def test_children_are_taylor_coefficients():
    rng = random.Random(5)
    for _ in range(100):
        t = TED(VARS)
        p = expand(random_expr(rng, 4))
        u = t.build(as_sum_of_monomials(p, rng))
        if t.is_const(u):
            continue
        v = t.var_level(u)
        for k, c in enumerate(t.children(u)):
            # (1/k!) d^k f / dx_v^k at x_v = 0
            deriv = {}
            for m, q in p.items():
                if m[v] >= k:
                    m2 = list(m)
                    m2[v] -= k
                    deriv[tuple(m2)] = q * factorial(m[v]) / factorial(m[v] - k)
            at_zero = {m: q / factorial(k) for m, q in deriv.items() if m[v] == 0}
            assert t.to_poly(c) == at_zero


def test_evaluate_matches_the_expression():
    rng = random.Random(9)
    for _ in range(200):
        t = TED(VARS)
        e = random_expr(rng, 4)
        u = t.build(e)
        point = {x: F(rng.randint(-5, 5), rng.randint(1, 4)) for x in VARS}
        want = sum((c * prod_pow(point, m) for m, c in expand(e).items()), F(0))
        assert t.evaluate(u, point) == want


def prod_pow(point, mono):
    r = F(1)
    for x, k in zip(VARS, mono):
        r *= point[x] ** k
    return r

History

Ciesielski, Kalla, Zeng and Rouzeyre presented TEDs for register-transfer level verification at the High-Level Design Validation and Test Workshop in 2001 and at DATE 2002. Ciesielski, Kalla and Askar gave the journal paper in the IEEE Transactions on Computers in 2006, with normalized weights and the use for data flow designs. TEDs extend the word-level line of decision diagrams that started with the BMDs of Bryant and Chen (1995), which handle words through their bits.

References

  1. M. Ciesielski, P. Kalla and S. Askar, Taylor expansion diagrams, a canonical representation for verification of data flow designs, IEEE Transactions on Computers 55(9), 1188 to 1201, 2006, the decomposition of a polynomial by the Taylor series in one variable at a time, the reduction and normalization rules, canonicity for a fixed variable order, the operations, and the use for equivalence of data flow designs
  2. M. J. Ciesielski, P. Kalla, Z. Zeng and B. Rouzeyre, Taylor expansion diagrams, a compact, canonical representation with applications to symbolic verification, Design, Automation and Test in Europe (DATE 2002), 285 to 289, 2002, TEDs as a compact canonical form of polynomials and their use in symbolic verification
  3. M. Ciesielski, P. Kalla, Z. Zeng and B. Rouzeyre, Taylor expansion diagrams, a new representation for RTL verification, IEEE International High-Level Design Validation and Test Workshop (HLDVT 2001), 70 to 75, 2001, the first presentation of TEDs for register-transfer level verification

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.add
  • a full proof of time.evaluate
  • a full proof of time.mk
  • a full proof of space.nodes
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)
WritingW4 complete
  • a review of the text: no review record reviews/B790DF/text.yaml