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
- Model
- Word RAM
- Properties
- randomizedexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 over 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 , and one sample costs 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 ; this is the generator of Yuan, Shultz, Pixley, Miller and Aziz (1999). The price is the BDD itself, which can be exponential in .
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 of a constraint under the order ; a source of uniform random integers.
Output. A model of drawn with for every model , or "no solution" when . In the weighted variant, biases are given, and with .
Notation. is the level of node , the index of its variable, and the terminals 0 and 1 have level . and are the children for and . An edge from to skips the variables between them.
The algorithm
The count is the number of assignments of that satisfy the function of . A branch of toward a child has such assignments, since the skipped variables are free, and the two branches together have . The walk takes each branch with probability equal to its share.
- 1
for 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
if N(root) = 0 then return "no solution" - 3
u ← root; draw x_i as a fair bit for every i < ℓ(root) - 4
while u is not a terminal: - 5
c1 ← 2^(ℓ(hi(u))−ℓ(u)−1) N(hi(u)) - 6
draw r uniformly from {0, 1, ..., N(u) − 1} - 7
if r < c1 then x_ℓ(u) ← 1, next ← hi(u) else x_ℓ(u) ← 0, next ← lo(u) - 8
draw x_i as a fair bit for every i with ℓ(u) < i < ℓ(next) - 9
u ← next - 10
return x
Line L1 runs once per constraint, and lines L3 to L10 once per sample. The number of models is . Line L6 draws an integer, not a real number: the branch probability is then exact.
Example
Take over four variables. The variable does not occur, and the BDD has three nodes: the root at level 0 with and ; the node at level 1 with and ; and the node at level 3 with and .
| node | level | branch 0 | branch 1 | |
|---|---|---|---|---|
| 3 | 1 | |||
| 1 | to , skips : | to 1, skips : | 6 | |
| 0 | to , skips : | to : | 10 |
So : eight models with , and two with , . Take the model . The walk goes to with probability , then to with probability , fills with probability , and at goes to 1 with probability . The product is . The model has , with the factor for the two skipped variables, and has .
With biases. Let and the other biases be . The weights are , and , which is the probability of under the biases. Each of the eight models with has weight and probability ; each of the two with has weight and probability . Under the constraint, has probability , not : a bias is a weight before conditioning, not the final marginal.
Correctness
The proof is in proofs/correctness.md. It shows four facts.
- counts the satisfying assignments of the variables from the level of down, skipped variables included, so .
- The walk never enters the terminal 0, so every output is a model.
- For a model , the probability of the walk along its path is after the factors for the skipped variables cancel, and the product telescopes to . 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 by the same telescoping with in place of , and rejection sampling from uniform assignments is also exact, with a geometric number of tries of mean .
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 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. is a reduced ordered BDD over the variables in this order. Each nonterminal node has a level , the index of its variable, and children and with and . The terminals and have level . Node represents a function that depends only on the variables at levels , with . The constraint is and is its number of models among the assignments. The gap of an edge from to a child is , the number of variables that the edge skips. We assume that each call randrange(m) returns each of with probability exactly , independently of all other calls; for a pseudo-random generator this is a modeling assumption.
is computed at line L1 by , and
Lemma 1 (counts). For every node , is the number of assignments of that satisfy . Hence .
Proof. Induction on . 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 at level , split the satisfying assignments by the value of . Those with satisfy , which does not depend on the variables at levels ; these are free, and the remaining variables give choices by the induction hypothesis. So there are of them. The case is the same with . For the root, the variables above it are free.
The counting page states the same recurrence. In particular for every nonterminal of a reduced BDD with , and only for the terminal 0.
Lemma 2 (the walk ends at 1). If , every run of lines L3 to L10 ends at the terminal 1, and the returned satisfies .
Proof. At a node with , line L7 moves to with probability and to with probability , where and by the recurrence. A child with has branch probability 0, so the walk only visits nodes with , and it never reaches the terminal 0. The level grows at each step, so the walk stops after at most steps, at the terminal 1. The values of at the levels of the visited nodes are the branches taken, so evaluating at follows the same path and gives 1.
Theorem 1 (exact uniformity). If , the sampler returns every model of with probability exactly and returns no other assignment. If , it returns "no solution".
Proof. The last sentence is line L2. Let be a model, and let be the path that selects in : if and otherwise. It ends at 1 because is a model, so each by Lemma 1. The sampler returns exactly when the following independent events all happen.
- Line L3 draws for each : probability .
- For each , line L7 takes the branch to : probability , because is uniform on and the branch is decided by .
- For each , line L8 draws at the skipped levels: probability .
Different runs that return 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:
by Lemma 1. Every output is a model by Lemma 2, and the models have total probability 1, so no other assignment has positive probability.
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 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 be biases, let and , and let . Define , and . Draw the variables above the root and the skipped variables with their own biases, and at node go to with probability . Then each model is returned with probability , where .
Proof. As in Lemma 1, is the sum of over the assignments of the variables at levels that satisfy : a skipped variable is free, and summing over its two values multiplies by . The variables above the root contribute the factor 1 in the same way, so . All biases are positive, so whenever , and the walk stays on nodes with as in Lemma 2. For a model with path , the probability of returning is the product of over the variables above the root and over the skipped variables, times, for each , . The factors together cover every variable once and give , and the ratios telescope to .
With every , , , and Theorem 2 gives Theorem 1.
Theorem 3 (rejection sampling). Let and . Draw uniformly from until , and return the last and the number of draws. Then the returned is each model with probability exactly , independently of , and has the geometric distribution , with mean .
Proof. The draws are independent, and each is a model with probability . The process returns at draw exactly when the first draws are not models and draw equals , which has probability . Summing over gives , a product of a function of and the constant . So and are independent, is uniform on the models, and is geometric with success probability . Its mean is .
If , 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 .
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 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 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 , so word operations and words of storage. With a fixed BDD, the counts serve every later sample.
- One sample. At most iterations, each with a comparison and a random integer below , plus fair bits in all: word operations, or if the counts fit in a word.
- Weighted. The weights are rationals whose size grows with the denominators of the biases; with biases that are multiples of , they are integers of bits after scaling. A change of the biases needs a new bottom-up pass.
- Rejection. per try and 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 steps, with no retries, unlike rejection.
Variants and improvements
- Biases on inputs (Yuan et al.). Each input has a bias , and the generator draws from the bias law conditioned on the constraint, by the weights with and ; skipped variables add the factor and are drawn with their own bias. The engineer sets biases to make rare cases likely.
- State variables. In a simulation the constraint depends on the state . Placing the state variables above the inputs in the order lets the walk follow the current values of 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 uses auxiliary variables , path counting over all variables is uniform over pairs , not over stimuli . Quantify out first with BDD quantification, and sample .
- 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 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 the probability and the probability , against for both.
- Forgetting the skipped variables. Counting with treats a branch that skips variables as having fewer solutions than it has. In the example, the root would split in place of .
- Floating-point counts. Counts above 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 .
- Biases are not marginals. A bias of on gave the probability 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.
# 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
- 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0PZ387 Edit this page History Report an error Markdown