Algorithm Search⌘K

Algorithmadvanced

BDD-based constrained random generation

Also called weighted BDD stimulus generation, Yuan constraint solver.

Yuan and coauthors' generator that builds a BDD of the constraints, weights each node by the count of solutions below it and walks down to draw solutions with set biases.

Time
O(n^2 / w) queryO(B n / w) setup
Space
O(B n / w) extra
Where
B = the number of nodes of the BDD of the constraint; n = the number of Boolean variables; w = the word size
Properties
randomizedexactofflineiterative
Origin
Jun Yuan, Kurt Shultz, Carl Pixley, Hillel Miller, Adnan Aziz, 1999

BDD-based constrained random generation solves the constrained random stimulus generation problem when the constraint fits in a binary decision diagram. Build the reduced ordered BDD of the constraint CC over nn Boolean variables. Store at each node the number of solutions of the function below it, by the recurrence of satisfy-count with factors of 2 for the variables that an edge skips. Then walk from the root to the terminal 1, taking each branch with probability proportional to the count of solutions under it, and fill the skipped variables with fair bits. Each solution comes out with probability exactly 1/#C1/\#C, and one sample costs O(n)O(n) steps. With weights on the nodes in place of counts, the same walk draws from the law in which each variable has its own bias, conditioned on CC; this is the generator of Yuan, Shultz, Pixley, Miller and Aziz (1999). The price is the BDD itself, which can be exponential in nn.

In plain words

The rules for legal inputs are first turned into a decision diagram: a chart in which each step asks about one input bit and goes left for 0 and right for 1, and every route that ends at "yes" is a legal input.

Each point of the chart is labeled with the number of legal inputs that can still be finished from there. To draw an input, start at the top and at each point go left or right with chances in proportion to the labels on the two sides. Bits that the chart never asks about on the chosen route can be anything, so they are flipped like fair coins.

Every legal input is drawn equally often. To favor some inputs, the labels count weighted inputs instead of plain ones, and the same walk follows the weights.

The problem

Input. A reduced ordered BDD with root root\mathrm{root} of a constraint C:{0,1}n→{0,1}C : \{0, 1\}^n \to \{0, 1\} under the order x0<x1<⋯<xn−1x_0 < x_1 < \cdots < x_{n-1}; a source of uniform random integers.

Output. A model xx of CC drawn with Pr⁡[x=s]=1/#C\Pr[x = s] = 1/\#C for every model ss, or "no solution" when #C=0\#C = 0. In the weighted variant, biases p0,…,pn−1∈(0,1)p_0, \ldots, p_{n-1} \in (0, 1) are given, and Pr⁡[x=s]=w(s)/∑t⊨Cw(t)\Pr[x = s] = w(s) / \sum_{t \models C} w(t) with w(s)=∏ipisi(1−pi)1−siw(s) = \prod_i p_i^{s_i} (1 - p_i)^{1 - s_i}.

Notation. ℓ(u)\ell(u) is the level of node uu, the index of its variable, and the terminals 0 and 1 have level nn. lo(u)\mathrm{lo}(u) and hi(u)\mathrm{hi}(u) are the children for xℓ(u)=0x_{\ell(u)} = 0 and 11. An edge from uu to vv skips the ℓ(v)−ℓ(u)−1\ell(v) - \ell(u) - 1 variables between them.

The algorithm

The count N(u)N(u) is the number of assignments of xℓ(u),…,xn−1x_{\ell(u)}, \ldots, x_{n-1} that satisfy the function of uu. A branch of uu toward a child vv has 2ℓ(v)−ℓ(u)−1N(v)2^{\ell(v) - \ell(u) - 1} N(v) such assignments, since the skipped variables are free, and the two branches together have N(u)N(u). The walk takes each branch with probability equal to its share.

  1. 1for each node u below root, children first: N(0) ← 0, N(1) ← 1, N(u) ← 2^(ℓ(lo(u))−ℓ(u)−1) N(lo(u)) + 2^(ℓ(hi(u))−ℓ(u)−1) N(hi(u))
  2. 2if N(root) = 0 then return "no solution"
  3. 3u ← root; draw x_i as a fair bit for every i < ℓ(root)
  4. 4while u is not a terminal:
  5. 5c1 ← 2^(ℓ(hi(u))−ℓ(u)−1) N(hi(u))
  6. 6draw r uniformly from {0, 1, ..., N(u) − 1}
  7. 7if r < c1 then x_ℓ(u) ← 1, next ← hi(u) else x_ℓ(u) ← 0, next ← lo(u)
  8. 8draw x_i as a fair bit for every i with ℓ(u) < i < ℓ(next)
  9. 9u ← next
  10. 10return x

Line L1 runs once per constraint, and lines L3 to L10 once per sample. The number of models is #C=2ℓ(root)N(root)\#C = 2^{\ell(\mathrm{root})} N(\mathrm{root}). Line L6 draws an integer, not a real number: the branch probability c1/N(u)c_1 / N(u) is then exact.

Example

Take C=x0x1+x3C = x_0 x_1 + x_3 over four variables. The variable x2x_2 does not occur, and the BDD has three nodes: the root aa at level 0 with lo(a)=c\mathrm{lo}(a) = c and hi(a)=b\mathrm{hi}(a) = b; the node bb at level 1 with lo(b)=c\mathrm{lo}(b) = c and hi(b)=1\mathrm{hi}(b) = 1; and the node cc at level 3 with lo(c)=0\mathrm{lo}(c) = 0 and hi(c)=1\mathrm{hi}(c) = 1.

node level branch 0 branch 1 NN
cc 3 20⋅0=02^0 \cdot 0 = 0 20⋅1=12^0 \cdot 1 = 1 1
bb 1 to cc, skips x2x_2: 21⋅1=22^1 \cdot 1 = 2 to 1, skips x2,x3x_2, x_3: 22⋅1=42^2 \cdot 1 = 4 6
aa 0 to cc, skips x1,x2x_1, x_2: 22⋅1=42^2 \cdot 1 = 4 to bb: 20⋅6=62^0 \cdot 6 = 6 10

So #C=10\#C = 10: eight models with x3=1x_3 = 1, and two with x0=x1=1x_0 = x_1 = 1, x3=0x_3 = 0. Take the model s=(1,0,1,1)s = (1, 0, 1, 1). The walk goes to bb with probability 6/106/10, then to cc with probability 2/62/6, fills x2=1x_2 = 1 with probability 1/21/2, and at cc goes to 1 with probability 1/11/1. The product is 610⋅26⋅12⋅1=110\frac{6}{10} \cdot \frac{2}{6} \cdot \frac{1}{2} \cdot 1 = \frac{1}{10}. The model (0,1,0,1)(0, 1, 0, 1) has 410⋅14⋅1=110\frac{4}{10} \cdot \frac{1}{4} \cdot 1 = \frac{1}{10}, with the factor 14\frac{1}{4} for the two skipped variables, and (1,1,0,0)(1, 1, 0, 0) has 610⋅46⋅14=110\frac{6}{10} \cdot \frac{4}{6} \cdot \frac{1}{4} = \frac{1}{10}.

With biases. Let p3=1/4p_3 = 1/4 and the other biases be 1/21/2. The weights are W(c)=14W(c) = \frac{1}{4}, W(b)=12⋅14+12⋅1=58W(b) = \frac{1}{2} \cdot \frac{1}{4} + \frac{1}{2} \cdot 1 = \frac{5}{8} and W(a)=12⋅14+12⋅58=716W(a) = \frac{1}{2} \cdot \frac{1}{4} + \frac{1}{2} \cdot \frac{5}{8} = \frac{7}{16}, which is the probability of CC under the biases. Each of the eight models with x3=1x_3 = 1 has weight 18⋅14=132\frac{1}{8} \cdot \frac{1}{4} = \frac{1}{32} and probability 132/716=114\frac{1}{32} / \frac{7}{16} = \frac{1}{14}; each of the two with x3=0x_3 = 0 has weight 18⋅34=332\frac{1}{8} \cdot \frac{3}{4} = \frac{3}{32} and probability 314\frac{3}{14}. Under the constraint, x3=1x_3 = 1 has probability 814=47\frac{8}{14} = \frac{4}{7}, not 14\frac{1}{4}: a bias is a weight before conditioning, not the final marginal.

Correctness

The proof is in proofs/correctness.md. It shows four facts.

  • N(u)N(u) counts the satisfying assignments of the variables from the level of uu down, skipped variables included, so #C=2ℓ(root)N(root)\#C = 2^{\ell(\mathrm{root})} N(\mathrm{root}).
  • The walk never enters the terminal 0, so every output is a model.
  • For a model ss, the probability of the walk along its path is 2−ℓ(root)∏jN(uj+1)/N(uj)2^{-\ell(\mathrm{root})} \prod_j N(u_{j+1}) / N(u_j) after the factors for the skipped variables cancel, and the product telescopes to 1/#C1/\#C. This is exact for every model, with the don't-care variables above the root and on the edges filled by fair bits.
  • The weighted walk gives w(s)/Zw(s) / Z by the same telescoping with WW in place of NN, and rejection sampling from uniform assignments is also exact, with a geometric number of tries of mean 2n/#C2^n / \#C.

The tests check the exact law in Fractions by running the sampler on every outcome of its random draws, against the models found by evaluating the constraint on all 2n2^n assignments. The chi-square statistic and the total variation distance of a fixed-seed sample, and the mean number of rejection tries, are measured, not proved.

Proof: Path-count sampling on a BDD is exactly uniform, its weighted form is exact, and rejection sampling is exact with 2^n/#models expected triesfull

Setting. BB is a reduced ordered BDD over the variables x0,…,xn−1x_0, \ldots, x_{n-1} in this order. Each nonterminal node uu has a level ℓ(u)∈{0,…,n−1}\ell(u) \in \{0, \ldots, n-1\}, the index of its variable, and children lo(u)\mathrm{lo}(u) and hi(u)\mathrm{hi}(u) with ℓ(lo(u))>ℓ(u)\ell(\mathrm{lo}(u)) > \ell(u) and ℓ(hi(u))>ℓ(u)\ell(\mathrm{hi}(u)) > \ell(u). The terminals 00 and 11 have level nn. Node uu represents a function fuf_u that depends only on the variables at levels ℓ(u),…,n−1\ell(u), \ldots, n-1, with fu=xˉℓ(u)flo(u)+xℓ(u)fhi(u)f_u = \bar x_{\ell(u)} f_{\mathrm{lo}(u)} + x_{\ell(u)} f_{\mathrm{hi}(u)}. The constraint is C=frootC = f_{\mathrm{root}} and #C\#C is its number of models among the 2n2^n assignments. The gap of an edge from uu to a child vv is g(u,v)=ℓ(v)−ℓ(u)−1g(u, v) = \ell(v) - \ell(u) - 1, the number of variables that the edge skips. We assume that each call randrange(m) returns each of 0,…,m−10, \ldots, m-1 with probability exactly 1/m1/m, independently of all other calls; for a pseudo-random generator this is a modeling assumption.

NN is computed at line L1 by N(0)=0N(0) = 0, N(1)=1N(1) = 1 and

N(u)=2g(u,lo)N(lo(u))+2g(u,hi)N(hi(u)).N(u) = 2^{g(u, \mathrm{lo})} N(\mathrm{lo}(u)) + 2^{g(u, \mathrm{hi})} N(\mathrm{hi}(u)).

Lemma 1 (counts). For every node uu, N(u)N(u) is the number of assignments of xℓ(u),…,xn−1x_{\ell(u)}, \ldots, x_{n-1} that satisfy fuf_u. Hence #C=2ℓ(root)N(root)\#C = 2^{\ell(\mathrm{root})} N(\mathrm{root}).

Proof. Induction on n−ℓ(u)n - \ell(u). For the terminals the set of variables is empty and the count is 0 for the constant 0 and 1 for the constant 1. For a nonterminal uu at level ii, split the satisfying assignments by the value of xix_i. Those with xi=1x_i = 1 satisfy fhi(u)f_{\mathrm{hi}(u)}, which does not depend on the g(u,hi)g(u, \mathrm{hi}) variables at levels i+1,…,ℓ(hi(u))−1i+1, \ldots, \ell(\mathrm{hi}(u)) - 1; these are free, and the remaining variables give N(hi(u))N(\mathrm{hi}(u)) choices by the induction hypothesis. So there are 2g(u,hi)N(hi(u))2^{g(u, \mathrm{hi})} N(\mathrm{hi}(u)) of them. The case xi=0x_i = 0 is the same with lo\mathrm{lo}. For the root, the ℓ(root)\ell(\mathrm{root}) variables above it are free. □\square

The counting page states the same recurrence. In particular N(u)>0N(u) > 0 for every nonterminal uu of a reduced BDD with fu≠0f_u \ne 0, and N(u)=0N(u) = 0 only for the terminal 0.

Lemma 2 (the walk ends at 1). If N(root)>0N(\mathrm{root}) > 0, every run of lines L3 to L10 ends at the terminal 1, and the returned xx satisfies CC.

Proof. At a node uu with N(u)>0N(u) > 0, line L7 moves to hi(u)\mathrm{hi}(u) with probability c1/N(u)c_1 / N(u) and to lo(u)\mathrm{lo}(u) with probability c0/N(u)c_0 / N(u), where c1=2g(u,hi)N(hi(u))c_1 = 2^{g(u, \mathrm{hi})} N(\mathrm{hi}(u)) and c0=N(u)−c1=2g(u,lo)N(lo(u))c_0 = N(u) - c_1 = 2^{g(u, \mathrm{lo})} N(\mathrm{lo}(u)) by the recurrence. A child vv with N(v)=0N(v) = 0 has branch probability 0, so the walk only visits nodes with N>0N > 0, and it never reaches the terminal 0. The level grows at each step, so the walk stops after at most nn steps, at the terminal 1. The values of xx at the levels of the visited nodes are the branches taken, so evaluating CC at xx follows the same path and gives 1. □\square

Theorem 1 (exact uniformity). If #C>0\#C > 0, the sampler returns every model ss of CC with probability exactly 1/#C1/\#C and returns no other assignment. If #C=0\#C = 0, it returns "no solution".

Proof. The last sentence is line L2. Let ss be a model, and let root=u0,u1,…,uk=1\mathrm{root} = u_0, u_1, \ldots, u_k = 1 be the path that ss selects in BB: uj+1=hi(uj)u_{j+1} = \mathrm{hi}(u_j) if sℓ(uj)=1s_{\ell(u_j)} = 1 and lo(uj)\mathrm{lo}(u_j) otherwise. It ends at 1 because ss is a model, so each N(uj)>0N(u_j) > 0 by Lemma 1. The sampler returns ss exactly when the following independent events all happen.

  • Line L3 draws sis_i for each i<ℓ(root)i < \ell(\mathrm{root}): probability 2−ℓ(root)2^{-\ell(\mathrm{root})}.
  • For each j<kj < k, line L7 takes the branch to uj+1u_{j+1}: probability 2g(uj,uj+1)N(uj+1)/N(uj)2^{g(u_j, u_{j+1})} N(u_{j+1}) / N(u_j), because rr is uniform on {0,…,N(uj)−1}\{0, \ldots, N(u_j) - 1\} and the branch is decided by r<c1r < c_1.
  • For each j<kj < k, line L8 draws sis_i at the g(uj,uj+1)g(u_j, u_{j+1}) skipped levels: probability 2−g(uj,uj+1)2^{-g(u_j, u_{j+1})}.

Different runs that return ss must take this path, since the path is fixed by the values at the visited levels. Multiplying, the powers of 2 of the last two items cancel, and the product telescopes:

Pr⁡[output=s]=2−ℓ(root)∏j=0k−1N(uj+1)N(uj)=2−ℓ(root)N(1)N(root)=12ℓ(root)N(root)=1#C,\Pr[\text{output} = s] = 2^{-\ell(\mathrm{root})} \prod_{j=0}^{k-1} \frac{N(u_{j+1})}{N(u_j)} = \frac{2^{-\ell(\mathrm{root})} N(1)}{N(\mathrm{root})} = \frac{1}{2^{\ell(\mathrm{root})} N(\mathrm{root})} = \frac{1}{\#C},

by Lemma 1. Every output is a model by Lemma 2, and the #C\#C models have total probability 1, so no other assignment has positive probability. ■\blacksquare

The don't-care variables enter in two places, both handled: the variables above the root (line L3), and the variables skipped by an edge (line L8). Each is filled by a fair bit, and the factor 2g2^{g} in the recurrence weighs the branch by the number of completions of the skipped variables. Without that factor, a branch that skips many variables would be chosen too rarely.

Theorem 2 (weighted generation). Let p0,…,pn−1∈(0,1)p_0, \ldots, p_{n-1} \in (0, 1) be biases, let bi(1)=pib_i(1) = p_i and bi(0)=1−pib_i(0) = 1 - p_i, and let w(s)=∏ibi(si)w(s) = \prod_i b_i(s_i). Define W(0)=0W(0) = 0, W(1)=1W(1) = 1 and W(u)=(1−pℓ(u))W(lo(u))+pℓ(u)W(hi(u))W(u) = (1 - p_{\ell(u)}) W(\mathrm{lo}(u)) + p_{\ell(u)} W(\mathrm{hi}(u)). Draw the variables above the root and the skipped variables with their own biases, and at node uu go to hi(u)\mathrm{hi}(u) with probability pℓ(u)W(hi(u))/W(u)p_{\ell(u)} W(\mathrm{hi}(u)) / W(u). Then each model ss is returned with probability w(s)/Zw(s) / Z, where Z=∑t⊨Cw(t)=W(root)Z = \sum_{t \models C} w(t) = W(\mathrm{root}).

Proof. As in Lemma 1, W(u)W(u) is the sum of ∏i≥ℓ(u)bi(ti)\prod_{i \ge \ell(u)} b_i(t_i) over the assignments tt of the variables at levels ℓ(u),…,n−1\ell(u), \ldots, n-1 that satisfy fuf_u: a skipped variable xix_i is free, and summing over its two values multiplies by bi(0)+bi(1)=1b_i(0) + b_i(1) = 1. The variables above the root contribute the factor 1 in the same way, so Z=W(root)Z = W(\mathrm{root}). All biases are positive, so W(u)>0W(u) > 0 whenever fu≠0f_u \ne 0, and the walk stays on nodes with W>0W > 0 as in Lemma 2. For a model ss with path u0,…,uku_0, \ldots, u_k, the probability of returning ss is the product of bi(si)b_i(s_i) over the variables above the root and over the skipped variables, times, for each jj, bℓ(uj)(sℓ(uj))W(uj+1)/W(uj)b_{\ell(u_j)}(s_{\ell(u_j)}) W(u_{j+1}) / W(u_j). The factors bi(si)b_i(s_i) together cover every variable once and give w(s)w(s), and the ratios telescope to W(1)/W(root)=1/ZW(1) / W(\mathrm{root}) = 1/Z. ■\blacksquare

With every pi=1/2p_i = 1/2, w(s)=2−nw(s) = 2^{-n}, W(u)=2−(n−ℓ(u))N(u)W(u) = 2^{-(n - \ell(u))} N(u), and Theorem 2 gives Theorem 1.

Theorem 3 (rejection sampling). Let #C>0\#C > 0 and q=#C/2nq = \#C / 2^n. Draw xx uniformly from {0,1}n\{0, 1\}^n until C(x)=1C(x) = 1, and return the last xx and the number TT of draws. Then the returned xx is each model with probability exactly 1/#C1/\#C, independently of TT, and TT has the geometric distribution Pr⁡[T=k]=(1−q)k−1q\Pr[T = k] = (1 - q)^{k-1} q, with mean E[T]=1/q=2n/#C\mathrm{E}[T] = 1/q = 2^n / \#C.

Proof. The draws are independent, and each is a model with probability qq. The process returns ss at draw kk exactly when the first k−1k - 1 draws are not models and draw kk equals ss, which has probability (1−q)k−12−n(1 - q)^{k-1} 2^{-n}. Summing over kk gives Pr⁡[x=s,T=k]=(1−q)k−1q⋅1#C\Pr[x = s, T = k] = (1 - q)^{k-1} q \cdot \frac{1}{\#C}, a product of a function of kk and the constant 1/#C1/\#C. So xx and TT are independent, xx is uniform on the models, and TT is geometric with success probability qq. Its mean is ∑k≥1k(1−q)k−1q=1/q\sum_{k \ge 1} k (1 - q)^{k-1} q = 1/q. ■\blacksquare

If #C=0\#C = 0, rejection sampling never stops, which is why the implementation takes a bound on the tries. The bound changes the law only by the event that the bound is reached, which has probability (1−q)bound(1 - q)^{\text{bound}}.

What is measured. The tests check Theorems 1 and 2 exactly, by running the sampler on every outcome of its calls to randrange and summing the probabilities in Fractions, and compare with the models found by evaluating each constraint on all 2n2^n assignments. For the pseudo-random generator of Python, the chi-square and total variation tests on a fixed-seed sample, and the mean number of rejection tries, are measurements, not proofs.

Complexity

  • Building the BDD. Not part of this algorithm, and the dominant cost. The size BB depends on the constraint and the variable order; it is linear for many control constraints, and exponential under every order for a constraint on the middle output bit of a multiplier.
  • Counts. Line L1 does one shift and one addition per node, on integers below 2n+12^{n+1}, so O(Bn/w)O(B n / w) word operations and O(Bn/w)O(B n / w) words of storage. With a fixed BDD, the counts serve every later sample.
  • One sample. At most nn iterations, each with a comparison and a random integer below 2n2^n, plus nn fair bits in all: O(n2/w)O(n^2 / w) word operations, or O(n)O(n) if the counts fit in a word.
  • Weighted. The weights W(u)W(u) are rationals whose size grows with the denominators of the biases; with biases that are multiples of 2−k2^{-k}, they are integers of O(nk)O(n k) bits after scaling. A change of the biases needs a new bottom-up pass.
  • Rejection. O(n)O(n) per try and 2n/#C2^n / \#C tries on average, which is far worse when the constraint is tight.

Properties

  • Exact. The law is exactly uniform, or exactly the conditioned bias law, given exact random integers.
  • Independent samples. Each walk uses fresh randomness, so samples are independent and can repeat; unlike randc, the generator does not cycle through the solutions.
  • Order independent law. Every variable order gives the same law; the order changes only the size of the BDD.
  • Bounded time. Each sample takes at most nn steps, with no retries, unlike rejection.

Variants and improvements

  • Biases on inputs (Yuan et al.). Each input has a bias pip_i, and the generator draws from the bias law conditioned on the constraint, by the weights W(u)=(1−pℓ(u))W(lo(u))+pℓ(u)W(hi(u))W(u) = (1 - p_{\ell(u)}) W(\mathrm{lo}(u)) + p_{\ell(u)} W(\mathrm{hi}(u)) with W(0)=0W(0) = 0 and W(1)=1W(1) = 1; skipped variables add the factor 11 and are drawn with their own bias. The engineer sets biases to make rare cases likely.
  • State variables. In a simulation the constraint C(q,x)C(q, x) depends on the state qq. Placing the state variables above the inputs in the order lets the walk follow the current values of qq and sample only the inputs. The counts of the input part are then the counts of the inputs for that state, so the law is uniform over the legal inputs of the current state.
  • Auxiliary variables. If C(x,y)C(x, y) uses auxiliary variables yy, path counting over all variables is uniform over pairs (x,y)(x, y), not over stimuli xx. Quantify yy out first with BDD quantification, and sample ∃y C\exists y\, C.
  • Many constraints. Constraints that share no variables have separate BDDs, and a sample is the union of independent samples; the BDD of their conjunction is never built.
  • Other compiled forms. The same bottom-up count and top-down walk work on any decision diagram or circuit form that supports linear-time model counting, and fail on forms that do not.

When to use it

  • The constraint has a BDD of manageable size, and many samples are drawn from it, as in a simulation that draws one transaction per cycle.
  • The law must be exact, for example to make functional coverage results comparable between runs, or to give rare legal inputs their fair share.
  • Not when the constraint holds wide arithmetic, such as a product of two 32-bit words, whose BDD is too large; use a SAT-based or hashing-based generator from the problem page.
  • Not needed when the constraint is loose: if #C/2n\#C / 2^n is large, rejection sampling is exact and simpler.

Pitfalls

  • A fair coin at each node. Walking down by a fair coin wherever both children are nonzero is not uniform. In the example it gives (0,0,0,1)(0, 0, 0, 1) the probability 12⋅14=18\frac{1}{2} \cdot \frac{1}{4} = \frac{1}{8} and (1,1,0,0)(1, 1, 0, 0) the probability 12⋅12⋅14=116\frac{1}{2} \cdot \frac{1}{2} \cdot \frac{1}{4} = \frac{1}{16}, against 110\frac{1}{10} for both.
  • Forgetting the skipped variables. Counting with N(u)=N(lo)+N(hi)N(u) = N(\mathrm{lo}) + N(\mathrm{hi}) treats a branch that skips variables as having fewer solutions than it has. In the example, the root would split 1:21 : 2 in place of 4:64 : 6.
  • Floating-point counts. Counts above 2532^{53} lose bits in a double, and a probability computed as a quotient of floats is not exact. Keep integer counts and draw an integer below N(u)N(u).
  • Biases are not marginals. A bias of 1/41/4 on x3x_3 gave x3=1x_3 = 1 the probability 4/74/7 in the example. To get a target marginal, the biases must be tuned against the constraint.
  • Pseudo-random numbers. The theorems assume ideal random integers. A poor generator, or one reseeded in the same way for each test, repeats the same stimuli.

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.

bdd.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the hv3 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""A small reduced ordered BDD package with a unique table.

Variables are 0 .. n-1, and variable i is at level i, so the order is fixed.
Node 0 is the constant 0 and node 1 the constant 1; both are at level n.
Every other node is a triple (var, lo, hi) with lo != hi, stored once.
"""


class BDD:
    def __init__(self, n):
        if n < 0:
            raise ValueError("the number of variables must be nonnegative")
        self.n = n
        self._var = [n, n]      # level of each node
        self._lo = [0, 1]
        self._hi = [0, 1]
        self._unique = {}
        self._cache = {}

    # structure

    def level(self, u):
        return self._var[u]

    def low(self, u):
        return self._lo[u]

    def high(self, u):
        return self._hi[u]

    def is_terminal(self, u):
        return u <= 1

    def mk(self, i, lo, hi):
        """The node for (if x_i then hi else lo), reduced and shared."""
        if not 0 <= i < self.n:
            raise ValueError("no variable %r" % (i,))
        if lo == hi:
            return lo
        if self._var[lo] <= i or self._var[hi] <= i:
            raise ValueError("children must be below the variable")
        key = (i, lo, hi)
        u = self._unique.get(key)
        if u is None:
            u = len(self._var)
            self._var.append(i)
            self._lo.append(lo)
            self._hi.append(hi)
            self._unique[key] = u
        return u

    def var(self, i):
        return self.mk(i, 0, 1)

    def nvar(self, i):
        return self.mk(i, 1, 0)

    # operations

    def ite(self, f, g, h):
        """If f then g else h, by Shannon expansion on the top variable."""
        if f == 1:
            return g
        if f == 0:
            return h
        if g == h:
            return g
        if g == 1 and h == 0:
            return f
        key = (f, g, h)
        r = self._cache.get(key)
        if r is not None:
            return r
        i = min(self._var[f], self._var[g], self._var[h])
        f0, f1 = self._cof(f, i)
        g0, g1 = self._cof(g, i)
        h0, h1 = self._cof(h, i)
        r = self.mk(i, self.ite(f0, g0, h0), self.ite(f1, g1, h1))
        self._cache[key] = r
        return r

    def _cof(self, u, i):
        if self._var[u] == i:
            return self._lo[u], self._hi[u]
        return u, u

    def NOT(self, f):
        return self.ite(f, 0, 1)

    def AND(self, f, g):
        return self.ite(f, g, 0)

    def OR(self, f, g):
        return self.ite(f, 1, g)

    def XOR(self, f, g):
        return self.ite(f, self.NOT(g), g)

    # inspection

    def evaluate(self, u, x):
        """The value of the function of node u at the assignment x (a sequence of bits)."""
        while u > 1:
            u = self._hi[u] if x[self._var[u]] else self._lo[u]
        return u

    def nodes(self, u):
        """The nodes reachable from u, children before parents."""
        order, seen, stack = [], set(), [(u, False)]
        while stack:
            v, done = stack.pop()
            if done:
                order.append(v)
                continue
            if v in seen:
                continue
            seen.add(v)
            stack.append((v, True))
            if v > 1:
                stack.append((self._hi[v], False))
                stack.append((self._lo[v], False))
        return order
bdd_constrained_random_generation.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bdd-constrained-random-generation/. The authors are listed in prov/0PZ387.jsonl.

"""Uniform and weighted random solutions of a constraint given as a reduced ordered BDD.

The constraint is a node `root` of a bdd.BDD over the variables 0 .. n-1.
Counts are exact integers and weights exact Fractions, and every random choice
is made with randrange, so the law of a sample is exactly the stated one.
"""

from fractions import Fraction

from bdd import BDD


def path_counts(bdd, root):
    """N[u] = number of assignments of the variables at levels level(u) .. n-1 that satisfy u."""
    N = {0: 0, 1: 1}
    lev = bdd.level
    for u in bdd.nodes(root):
        if u > 1:
            lo, hi = bdd.low(u), bdd.high(u)
            N[u] = (N[lo] << (lev(lo) - lev(u) - 1)) + (N[hi] << (lev(hi) - lev(u) - 1))
    return N


def model_count(bdd, root, N=None):
    """The number of models of root over all n variables."""
    if N is None:
        N = path_counts(bdd, root)
    return N[root] << bdd.level(root)


def _fill(x, start, stop, rng):
    for i in range(start, stop):
        x[i] = rng.randrange(2)


def sample(bdd, root, rng, N=None):
    """One model of root, each with probability exactly 1/#models; None if there is none."""
    if N is None:
        N = path_counts(bdd, root)  # @line L1
    if N[root] == 0:  # @line L2
        return None
    lev = bdd.level
    x = [0] * bdd.n
    u = root
    _fill(x, 0, lev(u), rng)  # @line L3
    while u > 1:  # @line L4
        lo, hi = bdd.low(u), bdd.high(u)
        c1 = N[hi] << (lev(hi) - lev(u) - 1)  # @line L5
        r = rng.randrange(N[u])  # @line L6
        if r < c1:  # @line L7
            x[lev(u)], nxt = 1, hi
        else:
            x[lev(u)], nxt = 0, lo
        _fill(x, lev(u) + 1, lev(nxt), rng)  # @line L8
        u = nxt  # @line L9
    return x  # @line L10


def probability_of(bdd, root, x, N=None):
    """The exact probability, as a Fraction, that sample returns the assignment x."""
    if N is None:
        N = path_counts(bdd, root)
    if N[root] == 0 or bdd.evaluate(root, x) == 0:
        return Fraction(0)
    lev = bdd.level
    u = root
    p = Fraction(1, 2 ** lev(u))
    while u > 1:
        nxt = bdd.high(u) if x[lev(u)] else bdd.low(u)
        p *= Fraction(N[nxt] << (lev(nxt) - lev(u) - 1), N[u])
        p /= 2 ** (lev(nxt) - lev(u) - 1)
        u = nxt
    return p


# weighted generation: variable i is 1 with bias p[i], conditioned on the constraint

def _bernoulli(q, rng):
    """1 with probability q exactly, for a Fraction q in [0, 1]."""
    return 1 if rng.randrange(q.denominator) < q.numerator else 0


def path_weights(bdd, root, p):
    """W[u] = probability under the biases that the variables at levels level(u) .. n-1 satisfy u."""
    W = {0: Fraction(0), 1: Fraction(1)}
    for u in bdd.nodes(root):
        if u > 1:
            i = bdd.level(u)
            W[u] = (1 - p[i]) * W[bdd.low(u)] + p[i] * W[bdd.high(u)]
    return W


def weighted_sample(bdd, root, p, rng, W=None):
    """A model s of root with probability w(s) / Z, where w(s) = prod p_i^s_i (1 - p_i)^(1 - s_i)."""
    p = [Fraction(q) for q in p]
    if any(not 0 < q < 1 for q in p):
        raise ValueError("each bias must lie strictly between 0 and 1")
    if W is None:
        W = path_weights(bdd, root, p)
    if W[root] == 0:
        return None
    x = [0] * bdd.n
    u = root
    for i in range(bdd.level(u)):
        x[i] = _bernoulli(p[i], rng)
    while u > 1:
        i, lo, hi = bdd.level(u), bdd.low(u), bdd.high(u)
        x[i] = _bernoulli(p[i] * W[hi] / W[u], rng)
        nxt = hi if x[i] else lo
        for k in range(i + 1, bdd.level(nxt)):
            x[k] = _bernoulli(p[k], rng)
        u = nxt
    return x


def weighted_probability_of(bdd, root, p, x, W=None):
    """The exact probability, as a Fraction, that weighted_sample returns x."""
    p = [Fraction(q) for q in p]
    if W is None:
        W = path_weights(bdd, root, p)
    if W[root] == 0 or bdd.evaluate(root, x) == 0:
        return Fraction(0)
    prob = Fraction(1)
    u = root
    for i in range(bdd.level(u)):
        prob *= p[i] if x[i] else 1 - p[i]
    while u > 1:
        i, lo, hi = bdd.level(u), bdd.low(u), bdd.high(u)
        q = p[i] * W[hi] / W[u]
        prob *= q if x[i] else 1 - q
        nxt = hi if x[i] else lo
        for k in range(i + 1, bdd.level(nxt)):
            prob *= p[k] if x[k] else 1 - p[k]
        u = nxt
    return prob


# the baseline

def rejection_sample(n, constraint, rng, max_tries=None):
    """Draw uniform assignments of n bits until constraint(x) holds; return (x, tries)."""
    tries = 0
    while max_tries is None or tries < max_tries:
        tries += 1
        x = [rng.randrange(2) for _ in range(n)]
        if constraint(x):
            return x, tries
    return None, tries


def example():
    """The constraint (x0 and x1) or x3 over four variables, the example of the page."""
    b = BDD(4)
    root = b.OR(b.AND(b.var(0), b.var(1)), b.var(3))
    return b, root


if __name__ == "__main__":
    import random

    b, root = example()
    N = path_counts(b, root)
    print("models:", model_count(b, root, N))
    rng = random.Random(1)
    print("samples:", [sample(b, root, rng, N) for _ in range(5)])
    p = [Fraction(1, 2)] * 3 + [Fraction(1, 4)]
    print("weighted:", [weighted_sample(b, root, p, rng) for _ in range(5)])
test_bdd_constrained_random_generation.py 284 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bdd-constrained-random-generation/. The authors are listed in prov/0PZ387.jsonl.

import itertools
import random
from collections import Counter
from fractions import Fraction

import pytest

from bdd import BDD
from bdd_constrained_random_generation import (
    example, model_count, path_counts, path_weights, probability_of,
    rejection_sample, sample, weighted_probability_of, weighted_sample)


# constraints as expression trees, evaluated without any BDD

def random_expr(rng, n, depth):
    if depth == 0 or rng.random() < 0.25:
        return ("var", rng.randrange(n))
    op = rng.choice(("not", "and", "and", "or", "or", "xor"))
    if op == "not":
        return ("not", random_expr(rng, n, depth - 1))
    return (op, random_expr(rng, n, depth - 1), random_expr(rng, n, depth - 1))


def eval_expr(e, x):
    op = e[0]
    if op == "var":
        return x[e[1]]
    if op == "not":
        return 1 - eval_expr(e[1], x)
    a, b = eval_expr(e[1], x), eval_expr(e[2], x)
    if op == "and":
        return a & b
    if op == "or":
        return a | b
    return a ^ b


def build(bdd, e):
    op = e[0]
    if op == "var":
        return bdd.var(e[1])
    if op == "not":
        return bdd.NOT(build(bdd, e[1]))
    f = {"and": bdd.AND, "or": bdd.OR, "xor": bdd.XOR}[op]
    return f(build(bdd, e[1]), build(bdd, e[2]))


def assignments(n):
    for bits in itertools.product((0, 1), repeat=n):
        yield list(bits)


def brute_models(n, e):
    return [tuple(x) for x in assignments(n) if eval_expr(e, x)]


def random_constraint(rng, n):
    e = random_expr(rng, n, rng.randint(1, 4))
    b = BDD(n)
    return e, b, build(b, e)


# the exact law of a sampler, by enumerating every outcome of every randrange call

class _Need(Exception):
    pass


class _ScriptRng:
    def __init__(self, script):
        self.script = script
        self.pos = 0
        self.ranges = []

    def randrange(self, m):
        if self.pos == len(self.script):
            raise _Need(m)
        r = self.script[self.pos]
        self.pos += 1
        self.ranges.append(m)
        return r


def exact_law(run):
    law = Counter()
    stack = [[]]
    while stack:
        script = stack.pop()
        rng = _ScriptRng(script)
        try:
            out = run(rng)
        except _Need as need:
            for r in range(need.args[0]):
                stack.append(script + [r])
            continue
        prob = Fraction(1)
        for m in rng.ranges:
            prob /= m
        law[None if out is None else tuple(out)] += prob
    return law


# tests

def test_example_of_the_page():
    b, root = example()
    N = path_counts(b, root)
    assert model_count(b, root, N) == 10
    assert N[root] == 10 and b.level(root) == 0
    models = [tuple(x) for x in assignments(4) if (x[0] and x[1]) or x[3]]
    law = exact_law(lambda rng: sample(b, root, rng, N))
    assert set(law) == set(models)
    assert all(law[m] == Fraction(1, 10) for m in models)
    p = [Fraction(1, 2)] * 3 + [Fraction(1, 4)]
    assert path_weights(b, root, p)[root] == Fraction(7, 16)
    wlaw = exact_law(lambda rng: weighted_sample(b, root, p, rng))
    for m in models:
        assert wlaw[m] == (Fraction(1, 14) if m[3] else Fraction(3, 14))


def test_sampler_law_is_uniform_by_enumeration():
    """The sampler itself, run on every outcome of its random draws, against the models of the expression."""
    rng = random.Random(5)
    for trial in range(150):
        n = rng.randint(1, 5)
        e, b, root = random_constraint(rng, n)
        models = brute_models(n, e)
        law = exact_law(lambda r: sample(b, root, r))
        if not models:
            assert law == {None: 1}
            continue
        assert set(law) == set(models)
        assert all(q == Fraction(1, len(models)) for q in law.values())


def test_count_and_probability_of_against_enumeration():
    rng = random.Random(17)
    for trial in range(120):
        n = rng.randint(1, 9)
        e, b, root = random_constraint(rng, n)
        models = set(brute_models(n, e))
        N = path_counts(b, root)
        assert model_count(b, root, N) == len(models)
        total = Fraction(0)
        for x in assignments(n):
            q = probability_of(b, root, x, N)
            assert q == (Fraction(1, len(models)) if tuple(x) in models else 0)
            total += q
        assert total == (1 if models else 0)


def test_weighted_law_is_the_conditioned_product_law():
    rng = random.Random(23)
    for trial in range(80):
        n = rng.randint(1, 4)
        e, b, root = random_constraint(rng, n)
        p = [Fraction(rng.randint(1, 3), 4) for _ in range(n)]
        w = {}
        for x in assignments(n):
            if eval_expr(e, x):
                wx = Fraction(1)
                for i in range(n):
                    wx *= p[i] if x[i] else 1 - p[i]
                w[tuple(x)] = wx
        Z = sum(w.values())
        law = exact_law(lambda r: weighted_sample(b, root, p, r))
        if not w:
            assert law == {None: 1}
            continue
        assert dict(law) == {s: ws / Z for s, ws in w.items()}
        for s, ws in w.items():
            assert weighted_probability_of(b, root, p, list(s)) == ws / Z


def test_chi_square_and_total_variation_on_a_sample():
    """Measured, not proved: a fixed-seed sample of a 7-variable constraint."""
    b = BDD(7)
    v = b.var
    # (x0 xor x2) and (x1 or x4) and not (x3 and x5 and x6)
    root = b.AND(b.AND(b.XOR(v(0), v(2)), b.OR(v(1), v(4))),
                 b.NOT(b.AND(b.AND(v(3), v(5)), v(6))))
    N = path_counts(b, root)
    m = model_count(b, root, N)
    assert m == 2 * 3 * 7  # x0,x2: 2 of 4; x1,x4: 3 of 4; x3,x5,x6: 7 of 8
    rng = random.Random(2026)
    draws = 21000
    hits = Counter(tuple(sample(b, root, rng, N)) for _ in range(draws))
    assert len(hits) == m
    expected = draws / m
    chi2 = sum((hits[s] - expected) ** 2 / expected for s in hits)
    # 41 degrees of freedom; the 0.999 quantile of chi-square(41) is about 74.7
    assert chi2 < 74.7
    tv = sum(abs(hits[s] / draws - 1 / m) for s in hits) / 2
    assert tv < 0.05


def naive_walk(b, root, rng):
    """The wrong sampler of the pitfall: a fair coin at every node with two live children."""
    x = [rng.randrange(2) for _ in range(b.n)]
    u = root
    while u > 1:
        lo, hi = b.low(u), b.high(u)
        if lo == 0:
            bit = 1
        elif hi == 0:
            bit = 0
        else:
            bit = rng.randrange(2)
        x[b.level(u)] = bit
        u = hi if bit else lo
    return x


def test_naive_walk_is_not_uniform():
    b, root = example()
    law = exact_law(lambda rng: naive_walk(b, root, rng))
    assert law[(0, 0, 0, 1)] == Fraction(1, 8)
    assert law[(1, 1, 0, 0)] == Fraction(1, 16)
    assert law[(1, 0, 0, 1)] == Fraction(1, 8)
    assert sum(law.values()) == 1


def test_rejection_tries_match_two_to_the_n_over_models():
    b, root = example()
    constraint = lambda x: b.evaluate(root, x) == 1
    rng = random.Random(31)
    runs = 4000
    total = 0
    hits = Counter()
    for _ in range(runs):
        x, tries = rejection_sample(4, constraint, rng)
        total += tries
        hits[tuple(x)] += 1
    mean = total / runs
    # geometric with p = 10/16: mean 1.6, standard deviation of the mean about 0.0158
    assert abs(mean - 16 / 10) < 0.07
    assert len(hits) == 10
    tv = sum(abs(c / runs - 1 / 10) for c in hits.values()) / 2
    assert tv < 0.05


def test_rejection_on_sparse_constraint():
    b = BDD(8)
    root = b.AND(b.AND(b.var(0), b.var(1)), b.AND(b.var(2), b.XOR(b.var(3), b.var(4))))
    constraint = lambda x: b.evaluate(root, x) == 1
    assert model_count(b, root) == 16  # 2^8 / 16 = 16 tries on average
    rng = random.Random(8)
    runs = 3000
    mean = sum(rejection_sample(8, constraint, rng)[1] for _ in range(runs)) / runs
    # standard deviation of the mean: sqrt(240) / sqrt(3000), about 0.28
    assert abs(mean - 16) < 1.2


def test_unsatisfiable_and_errors():
    b = BDD(3)
    root = b.AND(b.var(0), b.NOT(b.var(0)))
    assert root == 0
    assert sample(b, root, random.Random(0)) is None
    assert model_count(b, root) == 0
    assert weighted_sample(b, root, [Fraction(1, 2)] * 3, random.Random(0)) is None
    assert rejection_sample(3, lambda x: False, random.Random(0), max_tries=5) == (None, 5)
    assert sample(b, 1, random.Random(0)) is not None and model_count(b, 1) == 8
    with pytest.raises(ValueError):
        weighted_sample(b, 1, [Fraction(0)] * 3, random.Random(0))
    with pytest.raises(ValueError):
        b.mk(3, 0, 1)


def test_bdd_helper_is_canonical():
    rng = random.Random(41)
    for trial in range(60):
        n = rng.randint(1, 5)
        e1 = random_expr(rng, n, 3)
        e2 = random_expr(rng, n, 3)
        b = BDD(n)
        f, g = build(b, e1), build(b, e2)
        same = all(eval_expr(e1, x) == eval_expr(e2, x) for x in assignments(n))
        assert (f == g) == same
        for x in assignments(n):
            assert b.evaluate(f, x) == eval_expr(e1, x)

History

Bryant (1986) introduced reduced ordered BDDs and counted their satisfying assignments in time linear in their size. Yuan, Shultz, Pixley, Miller and Aziz (ICCAD 1999) used BDDs of the input constraints of a simulation environment to generate random input vectors, with biases on the inputs, by weights computed bottom-up on the BDD and a top-down walk; the journal version appeared in 2000. Yuan, Pixley and Aziz describe the method, with its treatment of state variables, in their book of 2006. SystemVerilog later made constrained random generation part of the language, in Clause 18 of IEEE Std 1800, and leaves the solver to the tool.

References

  1. Jun Yuan, Kurt Shultz, Carl Pixley, Hillel Miller and Adnan Aziz, Modeling design constraints and biasing in simulation using BDDs, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design (ICCAD), 1999, the BDD of the constraints over inputs and state, the weights computed bottom-up on the nodes, and the top-down walk that draws biased solutions
  2. J. Yuan, K. Shultz, C. Pixley, H. Miller and A. Aziz, Automatic vector generation using constraints and biasing, Journal of Electronic Testing, Theory and Applications 16, 107 to 120, 2000, the journal version of the BDD-based generator (general locator)
  3. Jun Yuan, Carl Pixley and Adnan Aziz, Constraint-Based Verification, Springer, 2006, the chapters on constraint BDDs, on random generation from them with input biases, and on the treatment of state variables (general locator)
  4. Randal E. Bryant, Graph-based algorithms for Boolean function manipulation, IEEE Transactions on Computers C-35(8), 677 to 691, 1986, Section 4.6 (Satisfy-count, the count of the satisfying assignments of a BDD)

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.query
  • a full proof of time.setup
  • 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