示例#1
0
文件: bdd_test.py 项目: swipswaps/dd
def test_count():
    g = x_and_y()
    assert g.count(4) == 1
    g = x_or_y()
    r = g.count(4)
    assert r == 3, r
    r = g.count(4, nvars=2)
    assert r == 3, r
    r = g.count(-4)
    assert r == 1, r
    r = g.count(-4, nvars=2)
    assert r == 1, r
    r = g.count(4, 3)
    assert r == 6, r
    r = g.count(-4, 3)
    assert r == 2, r
    with nt.assert_raises(Exception):
        g.count()
    r = g.count(4)
    assert r == 3, r
    g = _bdd.BDD()
    g.add_var('x')
    g.add_var('y')
    u = g.add_expr('x /\ y ')
    r = g.count(u)
    assert r == 1, r
示例#2
0
def consolidate_paths(automata, eliminate_goal_loop=False):
    transitions = defaultdict(list)
    final_trans = {}
    for trans in automata['transitions']:
        a, lbl = trans
        b = automata['transitions'][trans]

        if lbl == '':
            transitions[(a, b)].append(lbl)
        else:
            if ',' in lbl:
                if not eliminate_goal_loop:
                    final_trans[trans] = b
                elif a != b:
                    final_trans[trans] = b
            else:
                transitions[(a, b)].append(f'({lbl})')

    vocab = list(automata['alphabet'])
    for a, b in transitions:
        bdd = _BDD.BDD()
        bdd.declare(*vocab)
        formula = set(transitions[(a, b)])
        if '' in formula:
            formula.remove('')

        if len(formula) >= 1:
            formula = '|'.join(formula)
            formula2 = bdd_to_min_formula(bdd, bdd.add_expr(formula.upper()))
        else:
            formula2 = ''
        final_trans[(a, formula2)] = b

    automata['transitions'] = final_trans
    return automata
示例#3
0
def _init_bdd(use_cudd):
    if _bdd is None:
        raise ImportError('Failed to import `dd.bdd`.\n'
                          'Install package `dd`.')
    if not use_cudd:
        return _bdd.BDD()
    if cudd is None:
        raise ImportError('Failed to import module `dd.cudd`.\n'
                          'Compile the Cython bindings of `dd` to CUDD.')
    return cudd.BDD()
示例#4
0
文件: queens.py 项目: sysong13/dd
def solve_queens(n):
    """Return set of models for the `n`-queens problem.

    @rtype: `int`, `BDD`
    """
    vrs = [_var_str(i, j) for i in range(n) for j in range(n)]
    bdd = _bdd.BDD()
    bdd.declare(*vrs)
    s = queens_formula(n)
    u = bdd.add_expr(s)
    return u, bdd
示例#5
0
文件: queens.py 项目: maweki/dd
def solve_queens(n):
    """Return set of models for the `n`-queens problem.

    @rtype: `int`, `BDD`
    """
    v = [_var_str(i, j) for i in xrange(n) for j in xrange(n)]
    d = {xij: level for level, xij in enumerate(v)}
    bdd = _bdd.BDD(d)
    s = queens_formula(n)
    u = bdd.add_expr(s)
    return u, bdd
示例#6
0
 def __init__(self):
     # player 0 moves first (cox reverses this)
     self.players = dict()  # dict(str: int) maps: name -> turn
     self.vars = dict()
     # auto-populated
     self.prime = dict()
     self.unprime = dict()
     self.turns = list()
     # formulae
     self.init = dict()  # dict(key=list())
     self.action = dict()
     self.win = dict()
     # aux
     self.bdd = _bdd.BDD()
示例#7
0
def _evaluate_result(result, memory):
    """Return integer, given a result and memory w/o variables.

    @type result: `list`
    @type memory: `list`
    """
    bdd = _bdd.BDD({'x': 0})
    n = len(memory) + 1
    mem = ' '.join(memory)
    bits = list()
    for bit in result:
        s = '$ {n} {mem} {bit}'.format(n=n, mem=mem, bit=bit)
        u = bddizer.add_expr(s, bdd)
        bits.append(u)
    bits = [b == 1 for b in bits]
    # print([int(b) for b in bits])
    j = bv.twos_complement_to_int(bits)
    return j
示例#8
0
 def __init__(self, levels=None):
     manager = _bdd.BDD(levels)
     self._bdd = manager
     self.vars = manager.vars
示例#9
0
def dfa_intersection_to_rm(
    automata,
    reduce=False,
    set_reward=True,
    final_state=False
):  # from alberto and https://spot.lrde.epita.fr/ipynb/product.html
    # TODO consolidar caminos equivalentes

    result = {
        'alphabet': set().union(*[x["alphabet"] for x in automata]),
        'states': set(),
        'initial_state': "",
        'accepting_states': set(),
        'transitions': dict(),
        'reward': defaultdict(int)
    }
    sdict = {}
    todo = []
    new_state = get_new_state()

    def dst(state_numbers):
        state_numbers_tuple = tuple(state_numbers)
        p = sdict.get(state_numbers_tuple)
        if p is None:
            p = next(new_state)
            sdict[state_numbers_tuple] = p
            todo.append((state_numbers_tuple, p))
        return p

    result["initial_state"] = dst([aut['initial_state'] for aut in automata])

    #Create new alphabet in case some invalid characters are used
    alpha_dict = {}
    nvar = new_var()

    for a in result['alphabet']:
        alpha_dict[a] = next(nvar)

    bdd = None
    maxima = 0
    while todo:
        tuple_rc, osrc = todo.pop()
        lists_of_transitions = [
            automata[i]['out'][tuple_rc[i]] for i in range(len(automata))
        ]
        for elements in itertools.product(*lists_of_transitions):
            del bdd
            bdd = _BDD.BDD()
            #bdd.declare(*result["alphabet"])
            bdd.declare(*alpha_dict.values())

            cond = bdd.add_expr("TRUE")
            for ste, edge_cond in elements:
                edge_cond = edge_cond.upper()
                edge_cond = ''.join([
                    alpha_dict[x] if x in alpha_dict else x
                    for x in re.split('(TRUE|FALSE|!|&|\(|\)|\|)', edge_cond)
                ])
                ec = bdd.add_expr(edge_cond)
                cond = bdd.apply('&', cond, ec)

            if bdd.to_expr(cond) != "FALSE":
                reward = sum([
                    automata[i]["reward"][elements[i][0]]
                    for i in range(len(elements))
                    if elements[i][0] in automata[i]['reward']
                ])
                dest = dst([e[0] for e in elements])
                # TODO: check rm reduce if we want full reduce or to every subgoal
                #if reward > 0:
                #    result["accepting_states"].add(dest)
                if reward > maxima:
                    result["accepting_states"] = set([dest])
                    maxima = reward
                elif reward == maxima:
                    result["accepting_states"].add(dest)

                result["states"].add(osrc)
                result["states"].add(dest)
                # result["reward"][dest] = reward  // This is if you want the reward at the node instead of the edge
                if not set_reward:
                    reward = 0
                result["transitions"][(osrc, bdd_to_formula(bdd, cond))] = (
                    dest, reward
                )  # dest // This is if you want the reward at the node instead of the edge

    if reduce:
        full_transitions = deepcopy(result['transitions'])
        for k in result['transitions']:

            result['transitions'][k] = result['transitions'][k][0]
            """
            if k[0] not in result['accepting_states']:
                result['transitions'][k] = result['transitions'][k][0] # only the next state
            elif result['transitions'][k][0] != k[0]:
                result['transitions'][k] = result['transitions'][k][0] # only the next state
            """
        result = DFA.dfa_co_reachable(result)
        for k in result['transitions']:
            result['transitions'][k] = full_transitions[
                k]  # return the state and reward
    # rename with actual reward

    rm = {
        'alphabet': set(),
        'states': set(),
        'initial_state': "",
        'accepting_states': set(),
        'transitions': dict(),
    }

    rm["alphabet"] = alpha_dict.values()  #result["alphabet"]
    new_states = dict()

    for k in result[
            "states"]:  # result["reward"]: // This is if you want the reward at the node instead of the edge
        new_states[k] = f'''{k}'''  #  \n{"{"}{result["reward"][k]}{"}"}'''
        rm["states"].add(new_states[k])

    if result["initial_state"] not in new_states:
        new_states[result[
            "initial_state"]] = f"""{result["initial_state"]}\n{"{"}0{"}"}"""

    rm["initial_state"] = new_states[result["initial_state"]]

    if final_state:
        rm['accepting_states'] = result['accepting_states']

    beta_dict = {}
    for v, k in alpha_dict.items():
        beta_dict[k] = v

    new_transitions = dict()
    for ini in result["transitions"]:
        if final_state and new_states[ini[0]] in result['accepting_states']:
            continue
        end, reward = result["transitions"][ini]
        transition = ini[1]
        if transition == "":
            transition = "True"
        #ini = (new_states[ini[0]], ini[1]) // This is if you want the reward at the node instead of the edge
        ini = (new_states[ini[0]],
               str((transition, reward) if reward > 0 else transition))
        end = new_states[end]
        reward = result["reward"][end]
        new_transitions[ini] = end

    rm["transitions"] = new_transitions
    # ''.join([beta_dict[x] for x in re.split('\W', ini[1])])
    rm = consolidate_paths(rm)
    rm["alphabet"] = result["alphabet"]
    transitions = {}
    for s, k in rm['transitions']:
        r = rm['transitions'][(s, k)]
        if len(k) == 0:
            k = k
        elif k[0] + k[-1] == '()':
            t, v = eval(k)
            if len(t) > 0:
                t = ''.join([
                    f'{beta_dict[x]}' if x in beta_dict else x
                    for x in re.split('(TRUE|FALSE|!|&|\(|\)|\|)', t)
                ])
            k = (t, v)
        else:
            k = ''.join([
                f'{beta_dict[x]}' if x in beta_dict else x
                for x in re.split('(TRUE|FALSE|!|&|\(|\)|\|)', k)
            ])
        transitions[(s, str(k))] = r
    rm['transitions'] = transitions
    return rm
示例#10
0
 def __init__(self, ordering=None):
     bdd = _bdd.BDD(ordering)
     self.vars = bdd.vars
     self._bdd = bdd