Ejemplo n.º 1
0
    def construct_buchi_graph(self):
        """
        parse the output of the program ltl2ba and build the buchi automaton
        """
        # directory of the program ltl2ba
        dirname = os.path.dirname(__file__)
        # output of the program ltl2ba
        output = subprocess.check_output(dirname + "/./ltl2ba -f \"" +
                                         self.formula + "\"",
                                         shell=True).decode("utf-8")

        # find all states/nodes in the buchi automaton
        state_re = re.compile(r'\n(\w+):\n\t')
        state_group = re.findall(state_re, output)

        # find initial and accepting states
        init = [s for s in state_group if 'init' in s]
        # treat the node accept_init as init node
        accept = [s for s in state_group if 'accept' in s]
        # finish the inilization of the graph of the buchi automaton
        self.buchi_graph.graph['init'] = init
        self.buchi_graph.graph['accept'] = accept

        # for each state/node, find it transition relations
        for state in state_group:
            # add node
            self.buchi_graph.add_node(state, label='', formula='')
            # loop over all transitions starting from current state
            state_if_fi = re.findall(state + r':\n\tif(.*?)fi', output,
                                     re.DOTALL)
            if state_if_fi:
                relation_group = re.findall(r':: (\(.*?\)) -> goto (\w+)\n\t',
                                            state_if_fi[0])
                for symbol, next_state in relation_group:
                    symbol = symbol.replace('||', '|').replace('&&', '&')
                    edge_label = self.merge_check_feasible(symbol)
                    if edge_label:
                        # update node, no edges for selfloop
                        if state == next_state:
                            self.buchi_graph.nodes[state]['label'] = edge_label
                            self.buchi_graph.nodes[state]['formula'] = to_dnf(
                                symbol)
                            # if 'accept' in state:
                            #     print(edge_label)
                            continue
                        # add edge
                        self.buchi_graph.add_edge(state,
                                                  next_state,
                                                  label=edge_label,
                                                  formula=to_dnf(symbol))

            else:
                state_skip = re.findall(state + r':\n\tskip\n', output,
                                        re.DOTALL)
                if state_skip:
                    self.buchi_graph.nodes[state]['label'] = 'skip'
                    self.buchi_graph.nodes[state]['formula'] = 'skip'

        self.delete_node_no_selfloop_except_init_accept()
Ejemplo n.º 2
0
def hoftask(init, buchi_graph, regions):
    h_task = DiGraph(type='subtask')
    try:
        label = to_dnf(
            buchi_graph.edges[(buchi_graph.graph['init'][0],
                               buchi_graph.graph['init'][0])]['label'], True)
    except KeyError:
        # no self loop
        label = to_dnf('0')
    init_node = State((init, buchi_graph.graph['init'][0]), label)
    h_task.add_node(init_node)
    open_set = list()
    open_set.append(init_node)
    explore_set = list()

    while open_set:
        curr = open_set.pop(0)

        # assume co-safe
        # if curr.q in buchi_graph.graph['accept']:
        #     continue
        # print(curr)
        for q_b in buchi_graph.succ[curr.q]:

            try:
                label = to_dnf(buchi_graph.edges[(q_b, q_b)]['label'], True)
            except KeyError:
                # no self loop
                label = to_dnf('0')
            if q_b != curr.q:  # and q_b not in buchi_graph.graph['accept']:
                # region corresponding to the label/word
                edge_label = (buchi_graph.edges[(curr.q, q_b)]['label'])
                if edge_label == '(1)':
                    x_set = [curr.x]
                else:
                    x_set = target(to_dnf(edge_label), regions)
                if x_set:
                    for x in x_set:
                        cand = State((x, q_b), label)
                        # print(cand)
                        if cand not in open_set and cand not in explore_set:
                            open_set.append(cand)
                            # check the match with each subtask in h_task
                            if not match(h_task, curr, cand):
                                # print(cand)
                                h_task.add_node(cand)
                                h_task.add_edge(curr, cand)
                                # continue
                            # roots for accepting states
                            # if q_b in buchi_graph.graph['accept']:
                            #     h_task.add_edge(curr, cand)

        explore_set.append(curr)
    # for x in h_task.nodes:
    #     print(x)
    return h_task
def parse_definition(definitions):
    """Convert a definitions set to its disjunctive normal form

        Keyword arguments:
            definition -- str, indicating AND and OR relationship between gene
                            annotations (e.g. (A,B) C -> (A OR B) AND C).
    """
    symbol_dict = get_symbol_dict(definitions)

    expr_text = definitions.replace(" ",
                                    " & ").replace(",",
                                                   " | ").replace('+', ' & ')
    if expr_text.endswith('& ') or expr_text.endswith('| '):
        expr_text = expr_text[:-3]
        print(expr_text)
    try:
        expr = parse_expr(expr_text, local_dict=symbol_dict)
    except SyntaxError:
        print(definitions)
        print(expr_text)
        return

    dnf = to_dnf(expr)
    combinations = [
        d.strip("() ").replace(" ", "") for d in str(dnf).split("|")
    ]

    combinations = [x.split("&") for x in combinations]

    return combinations
Ejemplo n.º 4
0
def inclusion(subtask_lib, subtask_new, tree, end2path):
    """
    whether subtask_lib is included in subtask_new
    :param subtask_lib:
    :param subtask_new:
    :return:
    """
    # trick
    # no need to build subtree for those who doesn't have self-loop and edge label != 1   []<> ( <>)
    if subtask_new[1].label == to_dnf(
            '0') and subtask_new[0].x != subtask_new[1].x:
        return 'zero'
    condition = not satisfiable(
        And(subtask_lib[1].label, Not(subtask_new[1].label)))
    if subtask_lib[0].x == subtask_new[0].x and subtask_lib[
            1].x == subtask_new[1].x:
        condition = condition or good_execution(
            end2path[(subtask_lib[0], subtask_lib[1])], subtask_new[1].label,
            tree)
        if condition:
            return 'forward'
    elif subtask_lib[0].x == subtask_new[1].x and subtask_lib[
            1].x == subtask_new[0].x:
        condition = condition or good_execution(
            end2path[(subtask_lib[0], subtask_lib[1])], subtask_new[1].label,
            tree)
        if condition:
            return 'backward'

    return ''
Ejemplo n.º 5
0
 def pred(self, process = None):
     if process != None:
         return self._process_to_pred[process].pred()
     else:
         conjs = [self._process_to_pred[p].pred() for p in self._process_set]
         conj = And(*conjs)
         return to_dnf(conj)
Ejemplo n.º 6
0
def simplify_iconditions(iconditions, ignore_ne_isets=set()):
    ne_symbols = get_iconditions_ne_isets_logic_symbols(
        iconditions, ignore_ne_isets)
    dnf = convert_iconditions_2_disjunctive_formula(iconditions, ne_symbols)
    simplified_dnf = simplify(dnf)
    sim_dnf = to_dnf(dnf)
    return simplified_dnf, sim_dnf
Ejemplo n.º 7
0
 def rank_Cdnf(self, Query, d_index):
     Q_t = self.get_terms(Query)
     Q = str(to_dnf(Query, simplify=True))
     Q = Q.split("|")
     product = 1
     for cc in Q:
         product *= self.rank_cc(cc, Q_t, d_index)
     return 1 - product
 def select_group(self, formulas):
     selected =  min(self.select_max_contains(formulas),
                key=lambda block: sum(len(to_dnf(formula).args) for formula in block))
     print "selected"
     for j in selected:
          print j
     print '\n'
     return selected
Ejemplo n.º 9
0
Archivo: utils.py Proyecto: lwa19/dsc
def bool_symexpand(expr_string):
    from sympy.parsing.sympy_parser import parse_expr
    from sympy.logic.boolalg import to_dnf
    parsed_expr = parse_expr(expr_string, evaluate=False)
    new_locals = {
        sym.name: sympy.Symbol(sym.name)
        for sym in parsed_expr.atoms(sympy.Symbol)
    }
    return to_dnf(eval(expr_string, {}, new_locals), simplify=True)
 def select_group(self, formulas):
     selected = min(
         self.select_max_contains(formulas), key=lambda block: sum(len(to_dnf(formula).args) for formula in block)
     )
     print "selected"
     for j in selected:
         print j
     print "\n"
     return selected
Ejemplo n.º 11
0
def isp_simplify(file, ignore_isets=set()):
    formula = get_dnf_from_iconditions(file, ignore_isets)
    print(formula)
    simplified = simplify(formula)
    print("simplified: ", simplified)
    # print(to_dnf(left, simplify=True))
    # msg.send_message(str(simplified))
    print("dnf ", to_dnf(simplified))
    return formula
Ejemplo n.º 12
0
def test_to_dnf():
    assert to_dnf(~(B | C)) == And(Not(B), Not(C))
    assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C))
    assert to_dnf(A >> B) == (~A) | B
    assert to_dnf(A >> (B & C)) == (~A) | (B & C)
    assert to_dnf(A | B) == A | B

    assert to_dnf(Equivalent(A, B), True) == \
        Or(And(A, B), And(Not(A), Not(B)))
    assert to_dnf(Equivalent(A, B & C), True) == \
        Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C)))
    assert to_dnf(A + 1) == A + 1
Ejemplo n.º 13
0
def test_to_dnf():
    assert to_dnf(~(B | C)) == And(Not(B), Not(C))
    assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C))
    assert to_dnf(A >> B) == (~A) | B
    assert to_dnf(A >> (B & C)) == (~A) | (B & C)
    assert to_dnf(A | B) == A | B

    assert to_dnf(Equivalent(A, B), True) == \
        Or(And(A, B), And(Not(A), Not(B)))
    assert to_dnf(Equivalent(A, B & C), True) == \
        Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C)))
    assert to_dnf(A + 1) == A + 1
Ejemplo n.º 14
0
def hoftask_no_simplified(init, buchi_graph, regions):
    try:
        label = to_dnf(buchi_graph.edges[(buchi_graph.graph['init'][0], buchi_graph.graph['init'][0])]['label'], True)
    except KeyError:
        # no self loop
        label = to_dnf('0')
    init_node = State((init, buchi_graph.graph['init'][0]), label)
    h_task = DiGraph(type='subtask', init=init_node)
    h_task.add_node(init_node)
    open_set = list()
    open_set.append(init_node)
    explore_set = list()

    while open_set:
        curr = open_set.pop(0)
        for q_b in buchi_graph.succ[curr.q]:
            try:
                label = to_dnf(buchi_graph.edges[(q_b, q_b)]['label'], True)
            except KeyError:
                # no self loop
                label = to_dnf('0')
            if q_b != curr.q:
                # region corresponding to the label/word
                edge_label = (buchi_graph.edges[(curr.q, q_b)]['label'])
                if edge_label == '(1)':
                    x_set = [curr.x]
                else:
                    x_set = target(to_dnf(edge_label), regions)
                if x_set:
                    for x in x_set:
                        cand = State((x, q_b), label)
                        #  whether cand is already in the h_task
                        # cand = find_node(cand, h_task)
                        h_task.add_edge(curr, cand)
                        if cand not in open_set and cand not in explore_set:
                            open_set.append(cand)

        explore_set.append(curr)
    return h_task
def convert_to_dnf(frml):
    # frml = to_dnf(frml, force=True).replace(" ","")
    frml = frml.replace("^", "~")
    sub_frml = get_sub_formulas(frml, P="P", add_prefix="Q")
    for single_sub_frml_index in range(len(sub_frml)):
        sub_frml[single_sub_frml_index] = remove_iff_single_frml(
            sub_frml[single_sub_frml_index][1:-1])
        print(sub_frml[single_sub_frml_index])
        sub_frml[single_sub_frml_index] = str(
            to_dnf(sub_frml[single_sub_frml_index],
                   force=True)).replace(" ", "")
    for i in range(len(sub_frml)):
        current_index = sub_frml[i].find("P", 0)
        while current_index != -1:
            end_index = sub_frml[i].find("Q", current_index + 1)
            to_switch_index = int(sub_frml[i][current_index + 1:end_index]) - 1
            sub_frml[i] = sub_frml[i].replace(
                "P" + str(to_switch_index + 1) + "Q",
                sub_frml[to_switch_index])
            current_index = sub_frml[i].find("P", current_index + 1)
    return simplify_logic(str(to_dnf(sub_frml[-1],
                                     force=True)).replace(" ", ""),
                          force=True)
Ejemplo n.º 16
0
def stringToDNF(ps):
    
    # Replace ands and ors so that sympify parses correctly
    ps = ps.replace("and", "&")
    ps = ps.replace("or", "|")

    # Need to remove dashes and add a letter before each course number
    while "-" in ps:
        i = ps.find("-")
        ps = ps[:(i-2)] + "c" + ps[(i-2):i] + ps[(i+1):]

    try:
        psSympified = sympify(ps)
    except SympifyError:
        return ""

    return str(to_dnf(psSympified))
    def _create_symbolic_representation(self):
        """Creates a symbolic representation of the query to enable, among
        other things, manipulation with sympy so we can get to disjunctive
        normal form (DNF).
        """
        # Find all the expressions and replace them with symbols.
        self.symbol_to_expression_map = {}

        symbolified_string = self.filter_string
        for regex in [SAMPLE_SCOPE_REGEX, EXPRESSION_REGEX, SET_REGEX,
                GENE_REGEX]:
            symbolified_string = self._symbolify_string_for_regex(
                    symbolified_string, regex)

        symbolified_string = re.sub('AND|and', '&', symbolified_string)
        symbolified_string = re.sub('OR|or', '|', symbolified_string)

        self.sympy_representation = boolalg.to_dnf(symbolified_string)
Ejemplo n.º 18
0
def target(exp, regions):
    """
    find the target location
    :param label: word
    :return: target location/region
    """

    target = []

    if exp != to_dnf('1'):
        # a set of target points
        for dnf in exp.args or [exp]:
            truth_table = satisfiable(dnf, algorithm="dpll")
            # find the target point with true value
            for key, value in truth_table.items():
                if value:
                    des = key.name.split('_')[0]
                    target.append(regions[des])
        return target
    def _create_symbolic_representation(self):
        """Creates a symbolic representation of the query to enable, among
        other things, manipulation with sympy so we can get to disjunctive
        normal form (DNF).
        """
        # Find all the expressions and replace them with symbols.
        self.symbol_to_expression_map = {}

        symbolified_string = self.filter_string
        for regex in [
                SAMPLE_SCOPE_REGEX, EXPRESSION_REGEX, SET_REGEX, GENE_REGEX
        ]:
            symbolified_string = self._symbolify_string_for_regex(
                symbolified_string, regex)

        symbolified_string = re.sub('AND|and', '&', symbolified_string)
        symbolified_string = re.sub('OR|or', '|', symbolified_string)

        self.sympy_representation = boolalg.to_dnf(symbolified_string)
Ejemplo n.º 20
0
def to_dnf(association):

    # A and B and (C or D) or E
    association = association.replace(' AND ',' & ').replace(' OR ',' | ').replace(' and ',' & ').replace(' or ',' | ')
    # -> A & B & (C | D) | E
    association = str(boolalg.to_dnf(association))
    # -> Or(And(A, B, C), And(A, B, D), E)
    for and_old in re.findall(r'And\([^)]+\)',association):
        and_new = and_old
        and_new = and_new.replace('And(','(')
        and_new = and_new.replace(', ',' and ')
        association = association.replace(and_old, and_new)
    # -> Or((A and B and C), (A and B and D), E)
    association = association.replace(', ', ' or ')
    if association[:3] == 'Or(':
        association = association[3:-1]
    # .. -> (A and B) or (A and C) or D

    if association == 'False':
        association = ''
    return association
Ejemplo n.º 21
0
 def get_truth_assignment(self, symbol):
     """
     get one set of truth assignment that makes the symbol true
     :param symbol: logical expression which controls the transition
     :return: a set of truth assignment enables the symbol
     """
     # empty symbol
     if symbol == '(1)':
         return '1'
     # non-empty symbol
     else:
         exp = symbol.replace('||', '|').replace('&&',
                                                 '&').replace('!', '~')
         exp_dnf = to_dnf(exp).__str__()
         # loop over each clause
         for clause in exp_dnf.split(' | '):
             truth_table = dict()
             clause = clause.strip('(').strip(')')
             literals = clause.split(' & ')
             # loop over each literal
             for literal in literals:
                 if '~' not in literal:
                     truth_table[literal] = True
                 else:
                     truth_table[literal[1:]] = False
             # whether exist a literal with positive and negative version
             if len(literals) != len(truth_table):
                 continue
             else:
                 # exist a robot with two positive literals
                 true_key = [
                     truth.split('_')[1] for truth in truth_table.keys()
                     if truth_table[truth]
                 ]
                 if len(true_key) != len(set(true_key)):
                     continue
                 else:
                     # print(clause, truth_table)
                     return truth_table
         return dict()
Ejemplo n.º 22
0
def to_dnf(association):

    # A and B and (C or D) or E
    association = association.replace(' AND ', ' & ').replace(
        ' OR ', ' | ').replace(' and ', ' & ').replace(' or ', ' | ')
    # -> A & B & (C | D) | E
    association = str(boolalg.to_dnf(association))
    # -> Or(And(A, B, C), And(A, B, D), E)
    for and_old in re.findall(r'And\([^)]+\)', association):
        and_new = and_old
        and_new = and_new.replace('And(', '(')
        and_new = and_new.replace(', ', ' and ')
        association = association.replace(and_old, and_new)
    # -> Or((A and B and C), (A and B and D), E)
    association = association.replace(', ', ' or ')
    if association[:3] == 'Or(':
        association = association[3:-1]
    # .. -> (A and B) or (A and C) or D

    if association == 'False':
        association = ''
    return association
Ejemplo n.º 23
0
    def __init__(self, formulae):
        def parse_cnfdnf(f, t):
            if t == "cnf":
                t = (And, Or)
            elif t == "dnf":
                t = (Or, And)
            if not isinstance(f, t[0]):
                if isinstance(f, Symbol):
                    return [(f, )]
                else:
                    return [tuple(f.args)]
            ret = []
            for a in f.args:
                if not isinstance(a, t[1]):
                    ret.append((a, ))
                else:
                    ret.append(tuple(a.args))
            return ret

        self.formulae = formulae
        self.cnf = to_cnf(formulae, simplify=False)
        self.cnf_parsed = parse_cnfdnf(self.cnf, "cnf")
        self.dnf = to_dnf(formulae, simplify=False)
        self.dnf_parsed = parse_cnfdnf(self.dnf, "dnf")
Ejemplo n.º 24
0
def rule_manipulation(bw_rules, percentages, simulations):
    n = len(bw_rules)
    rulefilelist = [''] * simulations

    for sim in range(simulations):

        bw_rulelist = copy.deepcopy(bw_rules)
        transition_states = []
        states_count = []
        rule_length = [0] * n

        for i in range(n):
            rule_length[i] = len(bw_rulelist[i])

        new_rule_length = [
            math.ceil(a * b) for a, b in zip(rule_length, percentages)
        ]

        # keep track how many times the transition state is still left
        # it must not be totally eliminated from the system, otherwise
        # it would create an additional steady state
        for k in range(n):
            for i in bw_rulelist[k]:
                #print(i)
                if i not in transition_states:
                    transition_states.append(i)
                    states_count.append(1)

                else:
                    states_count[transition_states.index(
                        i)] = states_count[transition_states.index(i)] + 1

        # as long as not every rule is shortened to the according length, continue eliminating states
        while lst_or(rule_length, new_rule_length):
            choose_rule = random.choice(range(n))
            if len(bw_rulelist[choose_rule]) == 0:
                continue

            choose_transition = random.choice(bw_rulelist[choose_rule])
            idx = transition_states.index(choose_transition)
            if states_count[idx] > 1:
                bw_rulelist[choose_rule].remove(choose_transition)
                states_count[idx] = states_count[idx] - 1
                rule_length[choose_rule] = rule_length[choose_rule] - 1

        # translate rules to string
        rules = ['' for i in range(n)]
        for k in range(n):
            ruletext = []
            for j in range(len(bw_rulelist[k])):
                ruletext.append(' & '.join([
                    '{}{}'.format('' if bw_rulelist[k][j][i] == 1 else ' ~',
                                  symbols[i]) for i in range(n)
                ]))
                ruletext[j] = "(" + ruletext[j] + ")"
            if ruletext != []:
                rules[k] = ' | '.join(ruletext)
                rules[k] = "Xor((" + rules[k] + "), " + symbols[k] + ")"
                rules[k] = parse_expr(rules[k])
                rules[k] = to_dnf(rules[k], True)
                rules[k] = str(rules[k]).replace('&', 'and').replace(
                    '|', 'or').replace('~', 'not ')
            else:
                rules[k] = symbols[k]
            rulefilelist[sim] = rulefilelist[sim] + '1: {}* = {}'.format(
                symbols[k], rules[k]) + '\n'

    with open("rule_sets.json", "w") as fs:
        fs.write(json.dumps(rulefilelist, indent=2))
    fs.close()
Ejemplo n.º 25
0
# generate graph
w = 12
h = 9
d = 100
plt.figure(figsize=(w, h), dpi=d)
G = networkx.Graph()
G.add_edges_from(edges)
G.add_nodes_from(nodes)

start_time = time.time()
# compute number of MISs

E = parse_expr(edges[0][0] + "|" + edges[0][1])
for i in range(1, len(edges)):
    E = E & (parse_expr(edges[i][0] + "|" + edges[i][1]))
E = to_dnf(E, simplify=True, force=True)
expr = (' ' + str(E) + ' ').split("|")
print("\nnumber of MISs in this graph: ", len(expr))

# find MISs
temp = ""
temp1 = []
MIS = []
for i in range(len(expr)):
    temp2 = [' ' + j + ' ' for j in nodes]
    temp = expr[i][1] if len(expr[i]) == 3 else expr[i][2:len(expr[i]) - 2]
    temp1 = (' ' + temp + ' ').split("&")
    temp2 = [item for item in temp2 if item not in temp1]
    temp1 = []
    MIS.append(temp2)
print("MISs in this graph: ")
Ejemplo n.º 26
0
            for v,b in zip(dependent, conj):
                if b == '0':
                    rules_np[i][j][0] |= 1 << v
                elif b == '1':
                    rules_np[i][j][1] |= 1 << v
    return rules_np







interpret_logicalP = partial(interpret_logical,P)

rules_sym = {head : to_dnf(body, simplify=True) for head,body in paper_rules.items()}
rules_logical = [r[1] for r in sorted(paper_rules.items(), key=lambda x: int(P[str(x[0])]))]
rules_logical2 = [to_dnf(r) for r in rules_logical]
rules = rules_rep(P, rules_sym, same_k = True)
max_k = max(dnf_len(dnf) for dnf in rules_sym.values())

def all_clauses(n_vars):
    return (
            (x,y)
            for (x,y)
            in product(np.arange(2**n_vars, dtype=np.uint32), repeat=2)
            if x & y == Z and x | y)

def all_dnfs(n_vars, k):
    return map(np.array, product(all_clauses(n_vars), repeat=k))
Ejemplo n.º 27
0
def test_issue_19114():
    expr = (B & C) | (A & ~C) | (~A & ~B)
    # Expression is minimal, but there are multiple minimal forms possible
    res1 = (A & B) | (C & ~A) | (~B & ~C)
    result = to_dnf(expr, simplify=True)
    assert result in (expr, res1)
Ejemplo n.º 28
0
def parse_query(query: str) -> Any:
    return to_dnf(sympify(query))
Ejemplo n.º 29
0
 def dnf():
     from sympy.logic.boolalg import to_dnf
     from sympy.abc import A, B, C
     expr = input(("Enter a logic expression to perform DNF operation"))
     print(to_dnf(expr))
Ejemplo n.º 30
0
    reb = input("Введите введите выражение целиком: ")

    reb = reb.replace('1', 'A')
    reb = reb.replace('2', 'B')
    reb = reb.replace('3', 'C')
    reb = reb.replace('4', 'D')
    reb = reb.replace('5', 'F')
    reb = reb.replace('6', 'G')
    reb = reb.replace('7', 'H')
    reb = reb.replace('v', '|')
    reb = reb.replace(')(', ')&(')
    reb = reb.replace('-', '~')
    i = 0
    print(reb)
    print(restylec(to_dnf(reb, True)))

#TODO ЧТЕНИЕ С ФАЙЛА И ДОКИНУТЬ ВАРИАНТЫ ПЕРЕМЕННЫХ НА ВХОДЕ (х1,х2,х3...) или (у1,у2, у3...) или я хз еще как но надо добавить
if resh == "4":
    f = open("f.txt")
    for line in f:
        reb = line
        reb = reb.replace('1', 'A')
        reb = reb.replace('2', 'B')
        reb = reb.replace('3', 'C')
        reb = reb.replace('4', 'D')
        reb = reb.replace('5', 'F')
        reb = reb.replace('6', 'G')
        reb = reb.replace('7', 'H')
        reb = reb.replace('v', '|')
        reb = reb.replace(')(', ')&(')
from sympy.logic.boolalg import ITE, And, Xor, Or
from sympy.logic.boolalg import to_cnf, to_dnf
from sympy.logic.boolalg import is_cnf, is_dnf
from sympy.abc import A, B, C
from sympy.abc import X, Y, Z
from sympy.abc import a, b, c

ITE(True, False, True)
ITE(Or(True, False), And(True, True), Xor(True, True))
ITE(a, b, c)
ITE(True, a, b)
ITE(False, a, b)
ITE(a, b, c)

to_cnf(~(A | B) | C)
to_cnf((A | B) & (A | ~A), True)

to_dnf(Y & (X | Z))
to_dnf((X & Y) | (X & ~Y) | (Y & Z) | (~Y & Z), True)

is_cnf(X | Y | Z)
is_cnf(X & Y & Z)
is_cnf((X & Y) | Z)
is_cnf(X & (Y | Z))

is_dnf(X | Y | Z)
is_dnf(X & Y & Z)
is_dnf((X & Y) | Z)
is_dnf(X & (Y | Z))
Ejemplo n.º 32
0
print(Implies(False, False))
print(Implies(True, True))
print(Implies(False, True))

#cnf
from sympy.logic.boolalg import to_cnf
from sympy.abc import A, B, D

print(to_cnf(~(A | B) | D))
print(to_cnf((A | B) & (A | ~A), True))

#dnf
from sympy.logic.boolalg import to_dnf
from sympy.abc import A, B, C

print(to_dnf(B & (A | C)))
print(to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True))

#to check cnf and dnf
from sympy.logic.boolalg import is_cnf
from sympy.abc import A, B, C
from sympy.logic.boolalg import is_dnf
from sympy.abc import A, B, C

print(is_cnf(A | B | C))
print(is_cnf((A & B) | C))
print(is_dnf(A | B | C))
print(is_dnf(A & (B | C)))

#simplify logic
 def select_n_formulas(self, blocked_formulas, amount_of_formulas):
     return sorted(blocked_formulas, key=lambda formula: len(to_dnf(formula).args))[:amount_of_formulas]
Ejemplo n.º 34
0
def convert_symbolic_rules_to_dnf(nid_to_symbolic_rule, simplify=False):
    return {nid: boolalg.to_dnf(rule, simplify=simplify) for nid, rule in iteritems(nid_to_symbolic_rule)}
Ejemplo n.º 35
0
            stack.pop()
    return ltinlt

def delExtraNOT(str):
    coord = bracketsDestination(str)
    letterList = []
    for i in coord:
        letterList.append("".join(re.findall(" [A-Z] ", str[i[0] : i[1]] )))
    print(letterList)
    tmp = 1
    for j in range(0, len(letterList)-1):
        if letterList[j] == letterList[j+1]:
            letterList[j] = letterList[j+1] = ''
            #TODO: delete brackets here
            str = remove_character(str, coord[j][0])
            str = remove_character(str, coord[j][1])

            str = remove_character(str, coord[j+1][0])
            str = remove_character(str, coord[j+1][1])
    print(str)


# Simplification and calling the functions aka main
boolExpr = input("print some boolean expressions: ")
SimpleDNF = to_dnf(boolExpr, True).__str__()
print("Simplification is ",SimpleDNF)
print("Expression using NAND and NOT gates is ",disjParts(conjParts(partsOf(SimpleDNF))))
print(bracketsDestination('NOT ( NOT ( NOT ( D NAND C ) NAND B ) ) NAND NOT ( A )'))

delExtraNOT(disjParts(conjParts(partsOf(SimpleDNF))))
#TODO: mdy delete repeated NOT, mby no mby f**k you
Ejemplo n.º 36
0
def main(modeltext, desiredAttr):

    modeltext = modeltext.strip()

    # Split the modeltext by line
    modeltextLine = modeltext.splitlines()

    # Convert the desiredAttr to dictionary data type
    desiredAttrDic = {}
    s = 0
    for line in modeltextLine:
        IODic = line.split("=")
        desiredAttrDic[IODic[0].strip()] = str(bool(int(desiredAttr[s])))
        s = s + 1

    # Set logic symbols
    and_logic = ["and", "&&"]
    or_logic = ["or", "||"]
    negation_logic = ["not"]

    # Convert each logic expression to disjunctive normal form(DNF)
    formatTransformG = ""
    formatTransformAllPlus = ""
    formatFVS_ori = ""
    inputNodeList = []
    for line in modeltextLine:

        # Convert given logic symbols to official symbols
        and_rep = replaceMultiple(line, and_logic, "&")
        or_rep = replaceMultiple(and_rep, or_logic, "|")
        negation_rep = replaceMultiple(or_rep, negation_logic, "~")

        str1 = negation_rep.split("=")
        expression = str1[1].strip()

        # Extract nodes from each logic expression and create one list
        logicList = re.findall(r'\w+', negation_rep)

        logicOutput = logicList[0]
        logicInput = logicList[1:]

        # Remove duplicates in list
        logicInput = [x for i, x in enumerate(logicInput) if i == logicInput.index(x)]
        # print(logicOutput, logicInput[0])

        if logicInput[0] == "_INPUT_":
            inputNodeList.append(logicOutput)
            continue

        for node in logicInput:

            # Input negation
            if desiredAttrDic[node] == "False":
                # Exact replacement using regular expression
                expression = re.sub(r"\b" + node + r"\b", "( ~ " + node + ")", expression)

        # Output negation
        if desiredAttrDic[logicOutput] == "False":
            expression = expression.replace(expression, " ~ ( " + expression + ")")

        # print(expression)
        expressionDnf = to_dnf(expression, True)

        # Build all G network
        transformedLogicG = logicOutput + " = " + str(expressionDnf)
        formatTransformG = formatTransformG + transformedLogicG + "\n"

        # Build all plus products network
        plusProductSep = " | "
        x = str(expressionDnf).split("|")
        plusProductList = []
        for i in x:
            if not ("~") in i:
                plusProductList.append(i.strip())
        termSelected = plusProductSep.join(plusProductList)
        #print(termSelected)
        transformedLogicAllPlus = logicOutput + " = " + termSelected
        formatTransformAllPlus = formatTransformAllPlus + transformedLogicAllPlus + "\n"

        # Set formatFVS_ori
        for v in logicInput:
            formatFVS_ori = formatFVS_ori + logicOutput + ", " + v + "\n"

    return formatTransformG, formatTransformAllPlus, formatFVS_ori, inputNodeList
Ejemplo n.º 37
0
def hoftask(init, buchi_graph, regions, r):

    h_task = DiGraph(type='subtask')
    try:
        label = to_dnf(
            buchi_graph.edges[(buchi_graph.graph['init'][0],
                               buchi_graph.graph['init'][0])]['label'], True)
    except KeyError:
        # no self loop
        label = to_dnf('0')
    init_node = State((init, buchi_graph.graph['init'][0]), label)
    h_task.add_node(init_node)
    open_set = list()
    open_set.append((init_node, '0'))
    explore_set = list()
    # if  q1 --label--> q2, [target(label), q1]:q2
    succ_dict = dict()
    succ_dict[(init_node, '0')] = {buchi_graph.graph['init'][0]}

    task_group = dict()
    while open_set:
        curr = open_set.pop(0)
        # buchi state that curr corresponds to
        for q_target in succ_dict[curr]:
            try:
                label = to_dnf(
                    buchi_graph.edges[(q_target, q_target)]['label'], True)
            except KeyError:
                # no self loop
                label = to_dnf('0')
            for q_b in buchi_graph.succ[q_target]:

                if q_b != q_target:

                    # region corresponding to the label/word
                    edge_label = (buchi_graph.edges[(q_target, q_b)]['label'])
                    if edge_label == '(1)':
                        x_set = [curr[0].x]
                    elif '~' in edge_label and to_dnf(edge_label).nargs == {
                            1
                    }:  # ~l3_1
                        if curr[0].x == regions[to_dnf(
                                edge_label).args[0].name.split('_')[0]]:
                            x_set = [(curr[0].x[0], curr[0].x[1] - r)]
                        else:
                            x_set = [curr[0].x]
                    else:
                        x_set = target(to_dnf(edge_label), regions)
                    if x_set:
                        for x in x_set:
                            cand = State((x, q_target), label)
                            # seems no need to check
                            # if curr[0] != cand and not match(h_task, curr[0], cand):
                            if not match(h_task, curr[0], cand):
                                h_task.add_edge(curr[0], cand)
                                try:
                                    task_group[curr[0].x].add((curr[0], cand))
                                except KeyError:
                                    task_group[curr[0].x] = {(curr[0], cand)}
                            try:
                                succ_dict[(cand, edge_label)].add(q_b)
                            except KeyError:
                                succ_dict[(cand, edge_label)] = {q_b}

                            if (cand, edge_label) not in open_set and (
                                    cand, edge_label) not in explore_set:
                                open_set.append((cand, edge_label))
                                h_task.add_node(cand)

            explore_set.append(curr)

    return h_task, task_group