使用可以使用包管理器安装的 Python 包dd
,可以将布尔函数所在的变量赋值集转换为二元决策图。pip
pip install dd
TRUE
Python 中的以下示例假定函数的赋值是TRUE
作为一组字符串给出的。
from dd import autoref as _bdd
# assignments where the Boolean function is TRUE
data = {'0 0 0 0 0', '0 0 0 1 0', '1 1 1 1 0'}
# variable names
vrs = [f'x{i}' for i in range(1, 6)]
# convert the assignments to dictionaries
assignments = list()
for e in data:
tpl = e.split()
assignment = {k: bool(int(v)) for k, v in zip(vrs, tpl)}
assignments.append(assignment)
# initialize a BDD manager
bdd = _bdd.BDD()
# declare variables
bdd.declare(*vrs)
# create binary decision diagram
u = bdd.false
for assignment in assignments:
u |= bdd.cube(assignment)
# to confirm
satisfying_assignments = list(bdd.pick_iter(u))
print(satisfying_assignments)
为了更快地实现 BDD,以及使用 C 库CUDDdd.cudd
实现 ZDD ,Cython 模块扩展dd.cudd_zdd
可以按如下方式安装:
pip download dd --no-deps
tar xzf dd-*.tar.gz
cd dd-*
python setup.py install --fetch --cudd --cudd_zdd
dd.autoref
对于这个(小)示例,纯 Python 模块和 Cython 模块之间没有实际的速度差异dd.cudd
。
上面的二元决策图 (BDD)可以使用以下代码复制到零抑制二元决策图 (ZDD) :
from dd import _copy
from dd import cudd_zdd
# initialize a ZDD manager
zdd = cudd_zdd.ZDD()
# declare variables
zdd.declare(*vrs)
# copy the BDD to a ZDD
u_zdd = _copy.copy_bdd(u, zdd)
# confirm
satisfying_assignments = list(zdd.pick_iter(u_zdd))
print(satisfying_assignments)
该模块dd.cudd_zdd
已添加dd == 0.5.6
,因此上述安装需要dd >= 0.5.6
从PyPI或GitHub 存储库下载分发包。