def load_cnf(s, varname='x'): """Parse an input string in DIMACS CNF format, and return an expression.""" m = _CNF_PREAMBLE_RE.match(s) if m: nvars = int(m.group(1)) ncls = int(m.group(2)) else: raise SyntaxError("incorrect preamble") ps, fs = s[:m.end()], s[m.end():] line = ps.count('\n') + 1 gtoks = _iter_tokens(fs, line) X = bitvec(varname, (1, nvars + 1)) clauses = [[]] try: while True: tok = _expect_token(gtoks, _CNF_FORMULA_TOKS) if tok.typ == 'ZERO': clauses.append([]) elif tok.typ == 'NOT': tok = _expect_token(gtoks, {'POSINT'}) assert tok.val <= len(X) clauses[-1].append(-X[tok.val]) elif tok.typ == 'POSINT': assert tok.val <= len(X) clauses[-1].append(X[tok.val]) except StopIteration: pass assert len(clauses) == ncls return And(*[Or(*clause) for clause in clauses])
def load_sat(s, varname='x'): """Parse an input string in DIMACS SAT format, and return an expression.""" m = _SAT_PREAMBLE_RE.match(s) if m: fmt = m.group(1) nvars = int(m.group(2)) else: raise SyntaxError("incorrect preamble") ps, fs = s[:m.end()], s[m.end():] line = ps.count('\n') + 1 gtoks = _iter_tokens(fs, line) types = {'POSINT', 'LPAREN'} | _SAT_OP_TOKS[fmt] X = bitvec(varname, (1, nvars + 1)) try: tok = _expect_token(gtoks, types) return _sat_formula(gtoks, tok, fmt, X) except StopIteration: raise SyntaxError("incomplete formula")
from pyeda.expr import ( factor, simplify, var, Or, And, Not, Xor, Xnor, Equal, Implies, ITE, Nor, Nand, OneHot0, OneHot, f_not, f_or, f_nor, f_and, f_nand, f_xor, f_xnor, f_equal, f_implies, f_ite ) from pyeda.vexpr import bitvec import nose MAJOR = sys.version_info.major MINOR = sys.version_info.minor a, b, c, d, e, p, q, s = map(var, 'abcdepqs') X = bitvec('x', 16) Y = bitvec('y', 16, 16, 16) def test_ops(): # __sub__, __rsub__ assert (a - 0) == 1 assert (0 - a) == -a assert (a - 1) == a assert (1 - a) == 1 assert (a - b).equivalent(a + -b) # xor, equal, ite assert a.xor(b, c).equivalent(-a * -b * c + -a * b * -c + a * -b * -c + a * b * c) assert a.equal(b, c).equivalent(-a * -b * -c + a * b * c) assert s.ite(a, b).equivalent(s * a + -s * b) def test_factor():
""" Test DIMACS load/dump methods """ from pyeda.vexpr import bitvec from pyeda.dimacs import load_cnf, dump_cnf, load_sat, dump_sat from pyeda.expr import Xor, Equal import nose X = bitvec('x', (1, 16)) F1 = (X[1] + -X[2] + X[3]) * (-X[4] + X[5]) * -X[6] F2 = (-X[1] * X[2] * -X[3]) + (X[4] * -X[5]) + X[6] F3 = X[1] + Xor(-X[2], X[3], -X[4] * X[5]) + -X[6] F4 = X[1] + Equal(-X[2], X[3], -X[4] * X[5]) + -X[6] F5 = X[1] + Xor(-X[2], X[3], Equal(-X[4], X[5])) + -X[6] CNF_NO_PREAMBLE = \ """c comment 1 -2 3 0 -4 5 0 -6 """ CNF_INCORRECT_PREAMBLE_1 = \ """c comment p 1 -2 3 0 -4 5 0 -6 """ CNF_INCORRECT_PREAMBLE_2 = \ """c comment