def revise(clausein, sortedStates, bb): isInBB = False unknowVars = False unknowVarsList = [] isNeg = False clausein = str(clausein).split('&') for clause in clausein: for x in str(clause): if x == "~": isNeg = True if x in symbol: if x in operands: isInBB = True isNeg = False else: unknowVars = True if isNeg: unknowVarsList.append("~" + x) isNeg = False else: unknowVarsList.append(x) if unknowVars: for x in unknowVarsList: addOperands(str(x), True) if isInBB: for i in range(0, len(sortedStates)): values = sortedStates.__getitem__(i) value1 = values.strip(" ") value2 = value1.split(" ") items = [] for x in value2: items.append(x) setOP(items) a = recursive(str(clause)) if a: break global operandsAssigned operandsAssigned = [] pointer = len(bb) i = 0 while i < pointer: values = bb.__getitem__(i) use = to_cnf(values) b = recursive(str(use)) if not b: bb.pop(i) pointer = pointer - 1 else: i = i + 1 bb.append(to_cnf(clause)) return bb
def handle_input(bb): print('Select action:') action = input(PROMPT) action = action.lower() if action == 'r': print('--- Revision ---') print('Enter a formula:') frm = input(PROMPT) try: frm = to_cnf(frm) print('Select order (real number from 0 to 1):') order = input(PROMPT) bb.revise(frm, float(order)) except SympifyError: print('Invalid formula') except ValueError: print('Order has to be a real number from 0 to 1') print() elif action == 'd': print('--- Calculate degree ---') print('Enter a formula:') frm = input(PROMPT) try: frm = to_cnf(frm) print(bb.degree(frm)) except SympifyError: print('Invalid formula') print() elif action == 'e': bb.clear() print('--- Emptied belief base ---') print() elif action == 'p': print('--- Printing belief base ---') print(bb) print() elif action == 'h': print_help() elif action == 'q': exit() else: print('Sorry, the command was not recognized. Type \'h\' for help.') print() handle_input(bb)
def cnf_conditions(self): cnf = sp.to_cnf(self.conditions) cnf_expressions = self.get_expressions(cnf, self.expression_symbols) if not isinstance(cnf_expressions, AndList): cnf_expressions = AndList([cnf_expressions]) return cnf_expressions
def get_gene_association_list(ga): gene_association = ga.replace('and', '&').replace('or', '|').replace('OR', '|') if not gene_association: return "" try: res = to_cnf(gene_association, False) gene_association = [[str(it) for it in disjuncts(cjs)] for cjs in conjuncts(res)] result = '''<table class="p_table" border="0" width="100%%"> <tr class="centre"><th colspan="%d" class="centre">Gene association</th></tr> <tr>''' % (2 * len(gene_association) - 1) first = True for genes in gene_association: if first: first = False else: result += '<td class="centre"><i>and</i></td>' result += '<td><table border="0">' if len(genes) > 1: result += "<tr><td class='centre'><i>(or)</i></td></tr>" for gene in genes: result += "<tr><td class='main'><a href=\'http://www.ncbi.nlm.nih.gov/gene/?term=%s[sym]\' target=\'_blank\'>%s</a></td></tr>" % ( gene, gene) result += '</table></td>' result += '</tr></table>' return result except: return ""
def existence(expression): cnf = to_cnf(sympify(expression), True) symbols = cnf.atoms() symbols.remove(F) for interpretation in get_all_interpretations(symbols): if not cnf.subs(interpretation): return False return True
def build_knowledge_base(rule_file_name, fact_file_name): rules = parse_rule_file(rule_file_name) facts = parse_fact_file(fact_file_name) kb = rules + facts kb_sentence = kb[0] for k in kb[1:]: kb_sentence = kb_sentence & k kb_cnf_sentence = sp.to_cnf(kb_sentence) return kb_cnf_sentence
def __init__(self, sentence): self.model = {x: True, y: False, z: True, a: False, c: False} self.expr = sentence self.expr = self.make_simple() print("Given Sentence:") print(self.expr) self.expr = sympy.to_cnf(self.expr) # print('in CNF:') # print(self.expr) self.result = self.logic_solver(self.expr) print("Result") print self.result
def build_knowledge_base_interactive(rule_file_name): rules = parse_rule_file(rule_file_name) (mushroom_properties, patient_properties) = define_properties() fact_list = [] ### First iterate through list of mushroom properties and get user responses print "Please answer the following questions about the mushroom the patient ingested." print "If you do not know the answer, please enter \"?\"" for p in mushroom_properties: if p == "stem has ring" or p == "stem has volva": response = raw_input("Does the mushroom's " + p.replace("has", "have a") + "? ") if response == "yes": fact_list.append(p) else: continue else: response = raw_input("What is the mushroom's " + p + "? ") if response == "?" or response == "\n": continue else: fact = p + " is " + response fact_list.append(fact) ### Next iterate through list of patient properties and get user responses print "Please answer the following questions about the patient." for p in patient_properties: response = raw_input("Does the patient have " + p + "? ") if response == "yes": fact_list.append(p) else: continue ### Format facts for conversion to SymPy symbols facts = [] for f in fact_list: facts.append(custom_replace(f)) ### Convert facts to SymPy symbols facts = [sp.sympify(x) for x in facts] ### Assemble KB kb = rules + facts kb_sentence = kb[0] for k in kb[1:]: kb_sentence = kb_sentence & k kb_cnf_sentence = sp.to_cnf(kb_sentence) return kb_cnf_sentence
def find_all_solutions(expression): cnf = to_cnf(sympify(expression), True) symbols = cnf.atoms() symbols.remove(F) print(cnf) truth_table = [] for interpretation in get_all_interpretations(symbols): formula = cnf.subs(interpretation) if not formula: return False elif formula == F: truth_table.append((interpretation, True)) elif formula == ~F: truth_table.append((interpretation, False)) else: truth_table.append((interpretation, None)) return get_all_full_dnf(truth_table, symbols)
def encode_sum(k: int): # print(k, end=':') overall_addition = [] se = set() for symbol in syms: se.add(str(symbol)) overall_addition_course = None for i in range(1, k+1): x = list(combinations(se, i)) clause_string = '' for part_clause in x: clause_string += '&'.join(part_clause) negated = se - set(part_clause) if len(negated) != 0: clause_string += '&~'+'&~'.join(negated) clause_string += '|' clause_string.replace('||', '|') clause_string = clause_string[:-1] overall_addition.append(clause_string) overall_addition_course = parse_expr('|'.join(overall_addition)) overall_addition_course = sp.to_cnf(overall_addition_course, True) return overall_addition_course
def at_least(lits: list, bound): lits_to_str_dict = {} str_to_lits_dict = {} for idx, lit in enumerate(lits): lits_to_str_dict[lit] = "A" * (idx + 1) str_to_lits_dict["A" * (idx + 1)] = lit lits = list(str_to_lits_dict.keys()) k_groups = list(combinations(lits, bound)) not_cnf_strings = [] for group in k_groups: group = [str(item) for item in group] cur_str = "( " + " & ".join(group) + " )" not_cnf_strings.append(cur_str) not_cnf_strings = " | ".join(not_cnf_strings) cnf_string = to_cnf(not_cnf_strings) cnf_string = str(cnf_string) cnf_string = cnf_string.split("&") clauses = [] for clause in cnf_string: clause = clause.replace("(", "").replace(")", "").split("|") clause = [lit.strip() for lit in clause if lit != ""] clause = [str_to_lits_dict[lit] for lit in clause] clauses.append(clause) return clauses
print "PartA is satisfiable with the assignment:" print str(satisfiable(part_a)) + "\n\n\n" # Build part B. part_b = False for hole in xrange(1, 4): part_b = Or(part_b, And(P[1][hole], P[2][hole])) part_b = Or(part_b, And(P[1][hole], P[3][hole])) part_b = Or(part_b, And(P[1][hole], P[4][hole])) part_b = Or(part_b, And(P[2][hole], P[3][hole])) part_b = Or(part_b, And(P[2][hole], P[4][hole])) part_b = Or(part_b, And(P[3][hole], P[4][hole])) print "PartB is satisfiable with the assignment:" print str(satisfiable(part_b)) + "\n\n\n" # Pigeon Hole Principle php = And(part_a, part_b) if(not satisfiable(php)): print "PHP is not satisfiable with the assignment.\n\n\n" else: print "PHP is satisfiable with assignment: ", print str(satisfiable(php)) + "\n\n\n" # Build the not PHP problem. not_php = Not(php) print "Not PHP is in CNF is: ", print pretty_print_CNF(str(to_cnf(not_php))) + "\n\n\n" print "It is satisfiable with the assignment: " print str(satisfiable(not_php)) + "\n\n\n"
X[i], '&', Y[i], ')')) carries = bp.wequal(C, carries) results = [''] * wl results[0] = ''.join(('Xor(', X[0], ',', Y[0], ')')) for i in range(1, wl): results[i] = ''.join(('Xor(', X[i], ',', Y[i], ',', C[i - 1], ')')) results = bp.wequal(Z, results) bp.store_string('./models/equations/addition.txt',\ '\n'.join(carries + results)) # Addition modulo 2 ^ wl with the first part of the K constant K = bp.get_words('K.txt') K_additions = [''] * len(K) for i in range(len(K)): new_addition = '\n'.join(carries + results) for j in range(wl): new_addition = new_addition.replace(bp.bit('y', j),\ str(bool(K[i] >> j & 1)).lower()) new_addition = new_addition.split('\n') for j in range(wl - 1): new_addition[j] = ''.join((new_addition[j][0: 4],\ str(sympy.to_cnf(new_addition[j][4:], True)))) for j in range(wl - 1, 2 * wl - 1): new_addition[j] = ''.join((new_addition[j][0: 4],\ bp.reduce_xor(new_addition[j][4:], r'~?[xyc][0-9]{2}'))) K_additions[i] = '\n'.join(new_addition).replace(' ', '') for i in range(len(K)): bp.store_string('./models/equations/addition_K' + str(i) + '.txt',\ K_additions[i])
def simp(f): return to_cnf(f, simplify=True)
def solve_problem(problem): # Get all the problem parameters # The code below is a patchwork based on faulty logic, but it kinda works police_teams = problem["police"] medical_teams = problem["medics"] observations = problem["observations"] queries = problem["queries"] num_of_time_steps = len(observations) num_of_rows = len(observations[0]) num_of_columns = len(observations[0][0]) var_to_data = {} # Map all possible assignments to either true/false or a variable P = defaultdict(lambda: defaultdict(dict)) current_variable_name = 1 for code in ['U', 'H', 'S', 'Q', 'I']: for t in range(num_of_time_steps): for l in range(num_of_rows * num_of_columns): i = floor(l / num_of_rows) j = l - i * num_of_rows if observations[t][i][j] == '?': P[code][t][l] = symbols(str(current_variable_name)) var_to_data[current_variable_name] = (code, t, l) current_variable_name += 1 else: P[code][t][ l] = true if observations[t][i][j] == code else false expression = true # U # Check if the tile hasn't ever been a wall for t1 in range(num_of_time_steps): for l in range(num_of_rows * num_of_columns): was_ever = false for t2 in range(num_of_time_steps): was_ever = was_ever | P['U'][t2][l] if was_ever == true: for t2 in range(num_of_time_steps): expression = expression & P['U'][t2][l] & ( P['U'][t2][l] >> (~P['S'][t2][l] & ~P['H'][t2][l] & ~P['Q'][t2][l] & ~P['I'][t2][l])) continue # Can be nothing else expression = expression & (P['U'][t1][l] >> (~P['S'][t1][l] & ~P['H'][t1][l] & ~P['Q'][t1][l] & ~P['I'][t1][l])) # Check if the tile has ever been anything but wall for t1 in range(num_of_time_steps): for l in range(num_of_rows * num_of_columns): for code in ['H', 'S', 'Q', 'I']: if P[code][t1][l] == true: for t2 in range(num_of_time_steps): expression = expression & ~P['U'][t2][l] # If the tile is ever going to be a wall, he cant be anything else, ever for t1 in range(num_of_time_steps): for l in range(num_of_rows * num_of_columns): right_hand = true for t2 in range(num_of_time_steps): for code in ['H', 'S', 'Q', 'I']: right_hand = right_hand & ~P[code][t2][l] expression = expression & (P['U'][t1][l] >> right_hand) & ( P['U'][t1][l] << right_hand) # H for t in range(1, num_of_time_steps): for l in range(num_of_rows * num_of_columns): was_previously_healthy = P['H'][t - 1][l] # Create a list of all valid neighbors i = floor(l / num_of_columns) j = l - i * num_of_rows above_pos = l - num_of_columns if i != 0 else None left_pos = l - 1 if j != 0 else None right_pos = l + 1 if j != (num_of_columns - 1) else None below_pos = l + num_of_columns if i != (num_of_rows - 1) else None neighbors = [above_pos, left_pos, right_pos, below_pos] neighbors = set(neighbors) neighbors.discard(None) no_sick_neighbors = true # Check if any neighbor is sick for neighbor in neighbors: no_sick_neighbors = no_sick_neighbors & ~P['S'][t - 1][neighbor] # The only way to be an H tile at time t without recovery or quarantine # Also make sure you didn't just get vaccinated non_recovery_option = no_sick_neighbors & was_previously_healthy & ~P[ 'I'][t][l] # Apply different cluases based on the possibility of recovery or quarantine if t >= 3: recovery = P['S'][t - 1][l] & P['S'][t - 2][l] & P['S'][t - 3][l] finished_qurantine = P['Q'][t - 2][l] & P['Q'][t - 1][l] expression = expression & ( P['H'][t][l] >> (recovery | non_recovery_option | finished_qurantine)) & ( P['H'][t][l] << (recovery | non_recovery_option | finished_qurantine)) if t == 2: finished_qurantine = P['Q'][t - 2][l] & P['Q'][t - 1][l] expression = expression & ( P['H'][t][l] >> (non_recovery_option | finished_qurantine)) & ( P['H'][t][l] << (non_recovery_option | finished_qurantine)) if t == 1: expression = expression & ( P['H'][t][l] >> non_recovery_option) & ( P['H'][t][l] << non_recovery_option) # Can be nothing else expression = expression & (P['H'][t][l] >> (~P['S'][t][l] & ~P['U'][t][l] & ~P['Q'][t][l] & ~P['I'][t][l])) # S for t in range(1, num_of_time_steps): for l in range(num_of_rows * num_of_columns): was_previously_sick = P['S'][t - 1][l] # Create a list of all valid neighbors i = floor(l / num_of_columns) j = l - i * num_of_rows above_pos = l - num_of_columns if i != 0 else None left_pos = l - 1 if j != 0 else None right_pos = l + 1 if j != (num_of_columns - 1) else None below_pos = l + num_of_columns if i != (num_of_rows - 1) else None neighbors = [above_pos, left_pos, right_pos, below_pos] neighbors = set(neighbors) neighbors.discard(None) sick_neighbors = false # Check if any neighbor is sick for neighbor in neighbors: sick_neighbors = sick_neighbors | P['S'][t - 1][neighbor] # The only way to be an S tile at time t # Also make sure you aren't another tile expression = expression & (P['S'][t][l] >> ( (sick_neighbors | was_previously_sick) & ~P['Q'][t][l] & ~P['U'][t][l] & ~P['I'][t][l] & ~P['H'][t][l])) & ( P['S'][t][l] << ((sick_neighbors | was_previously_sick) & ~P['Q'][t][l] & ~P['U'][t][l] & ~P['I'][t][l] & ~P['H'][t][l])) # Can be nothing else expression = expression & (P['S'][t][l] >> (~P['H'][t][l] & ~P['U'][t][l] & ~P['Q'][t][l] & ~P['I'][t][l])) # Q # Probably will have difficulties with teams with size over 1 if police_teams != 0: # Cannot be present at the start for l in range(num_of_rows * num_of_columns): expression = expression & ~P['Q'][0][l] for t in range(1, num_of_time_steps): # Go over every possible way to choose tiles for quarantine # Im not going to even try to explain whats below, I'm not sure myself for comb in combinations(range(num_of_rows * num_of_columns), police_teams): right_hand = true left_hand = true for l1 in comb: left_hand = left_hand & P['Q'][t][l1] if t >= 2: was_quarantiend = P['Q'][t - 1][l1] & ~P['Q'][t - 2][l1] else: was_quarantiend = P['Q'][t - 1][l1] was_sick = P['S'][t - 1][l1] right_hand = right_hand & (was_quarantiend | was_sick) choose_k = (left_hand >> right_hand) choose_no_one_else = true for l in range(num_of_rows * num_of_columns): if l in comb: continue choose_no_one_else = choose_no_one_else & ~P['Q'][t][l] expression = expression & choose_k & ( left_hand >> choose_no_one_else) # Can be nothing else for l1 in comb: expression = expression & ( P['Q'][t][l1] >> (~P['H'][t][l1] & ~P['U'][t][l1] & ~P['S'][t][l1] & ~P['I'][t][l1])) # No teams means no possible Q tiles else: for t in range(num_of_time_steps): for l in range(num_of_rows * num_of_columns): expression = expression & ~P['Q'][t][l] # I # Probably doesnt work if medical_teams != 0: # Cannot be present at the start for l in range(num_of_rows * num_of_columns): expression = expression & ~P['I'][0][l] for t in range(1, num_of_time_steps): # Go over every possible way to choose tiles for quarantine # Im not going to even try to explain whats below, I'm not sure myself for comb in combinations(range(num_of_rows * num_of_columns), medical_teams): right_hand = true left_hand = true for l1 in comb: left_hand = left_hand & P['I'][t][l1] was_vaccinated = P['I'][t - 1][l1] was_healthy = P['H'][t - 1][l1] right_hand = right_hand & (was_vaccinated | was_healthy) choose_k = (left_hand >> right_hand) choose_no_one_else = true for l in range(num_of_rows * num_of_columns): if l in comb: continue choose_no_one_else = choose_no_one_else & ~P['I'][t][l] expression = expression & (choose_k & (left_hand >> choose_no_one_else)) # Can be nothing else for l1 in comb: expression = expression & ( P['I'][t][l1] >> (~P['H'][t][l1] & ~P['U'][t][l1] & ~P['S'][t][l1] & ~P['Q'][t][l1])) # No teams means no possible I tiles else: for t in range(num_of_time_steps): for l in range(num_of_rows * num_of_columns): expression = expression & ~P['I'][t][l] # Make sure every tile at a point in time can only have a single assignment for t in range(num_of_time_steps): for l in range(num_of_rows * num_of_columns): for code1 in ['U', 'H', 'S', 'Q', 'I']: right_hand = true for code2 in ['U', 'H', 'S', 'Q', 'I']: if code1 == code2: continue right_hand = right_hand & ~P[code2][t][l] expression = expression & (P[code1][t][l] >> right_hand) & ( P[code1][t][l] << right_hand) # Convert to CNF cnf = to_cnf(expression) return_dict = {} # Go over queries for query in queries: # A catch all in case of a logical mishap if cnf == true: return_dict[query] = '?' continue if not cnf: return_dict[query] = 'F' continue (i, j) = query[0] time_step = query[1] code = query[2] # Check if the query is true pos_query_cnf = cnf & P[code][time_step][i * num_of_columns + j] # Check if the query is false neg_query_cnf = cnf & ~P[code][time_step][i * num_of_columns + j] pos_input_cnf = [] neg_input_cnf = [] # Parse the cnf from the sympolab equation object for clause in str(pos_query_cnf).replace('~', '-').replace( '(', '[').replace(')', ']').replace('|', ',').split('&'): try: res = int(clause) pos_input_cnf.append([res]) except ValueError: res = loads(clause) pos_input_cnf.append(res) for clause in str(neg_query_cnf).replace('~', '-').replace( '(', '[').replace(')', ']').replace('|', ',').split('&'): try: res = int(clause) neg_input_cnf.append([res]) except ValueError: res = loads(clause) neg_input_cnf.append(res) # Start solving g_pos = Glucose3() for clause in pos_input_cnf: g_pos.add_clause(clause) g_neg = Glucose3() for clause in neg_input_cnf: g_neg.add_clause(clause) pos_found_sol = g_pos.solve() neg_found_sol = g_neg.solve() return_symbol = '' if pos_found_sol: return_symbol = "T" else: return_symbol = "F" if pos_found_sol and neg_found_sol: return_symbol = '?' return_dict[query] = return_symbol return return_dict
def gen_ex_del_bad_s(n_soft_const, Q_UBA, delta_template_UBA, delta_bad_all_UBA, Q_UCBA, delta_template_UCBA, I, io_vars, T): """Generate the extended delta and bad transitions for soft constraints specific to the problem""" # delta is initially in DNF # ' ' --> and # , --> or delta_UBA = [{} for n in range(n_soft_const)] for n in range(n_soft_const): for t in T: for q in Q_UBA[n]: for i in I: for qq in Q_UBA[n]: k = 'del_' + t + '_' + q + '_' + i + '_' + qq + '_' + str( n + 1) trs_temp = [ tr for tr in delta_template_UBA[n] if tr[0] == q and tr[2] == qq ] if not trs_temp: v = ['F'] elif len(trs_temp) == 1: v = rep_label(trs_temp[0][1], t, i, io_vars) else: raise Exception( "More than 1 transition between states") delta_UBA[n][k] = v # bad_tra is in CNF and represents the whole equivalency formula # ' ' --> or # , --> and bad_tra_template_UBA = [[] for n in range(n_soft_const)] for n in range(n_soft_const): for tr in delta_bad_all_UBA[n]: eq_formula = '( bad_t_q_i_qq_n >> ( ' + tr[1] + ' ) )' + ' & '+\ '( bad_t_q_i_qq_n << ( ' + tr[1] + ' ) )' eq_formula = str(sp.to_cnf(eq_formula, True)) bad_tra_template_UBA[n].append((tr[0], eq_formula, tr[2])) bad_tra_UBA = [{} for n in range(n_soft_const)] for n in range(n_soft_const): for t in T: for q in Q_UBA[n]: for i in I: for qq in Q_UBA[n]: k = 'bad_' + t + '_' + q + '_' + i + '_' + qq + '_' + str( n + 1) trs_temp = [ tr for tr in bad_tra_template_UBA[n] if tr[0] == q and tr[2] == qq ] if not trs_temp: v = ['~' + k] elif len(trs_temp) == 1: v_str = rep_label([trs_temp[0][1]], t, i, io_vars)[0] v_str = v_str.replace('bad_t_q_i_qq_n', k) v_str = v_str.split(' & ') v = [] for cl in v_str: if cl[0] == '(': v.append(' '.join(cl[1:-1].split(' | '))) else: v.append(' '.join(cl.split(' | '))) else: raise Exception( "More than 1 bad transition between states") bad_tra_UBA[n][k] = v # delta is initially in DNF # ' ' --> and # , --> or delta_UCBA = [{} for n in range(n_soft_const)] for n in range(n_soft_const): for t in T: for q in Q_UCBA[n]: for i in I: for qq in Q_UCBA[n]: k = 'del_' + t + '_' + q + '_' + i + '_' + qq + '_' + str( n + 1) trs_temp = [ tr for tr in delta_template_UCBA[n] if tr[0] == q and tr[2] == qq ] if not trs_temp: v = ['F'] elif len(trs_temp) == 1: v = rep_label(trs_temp[0][1], t, i, io_vars) else: raise Exception( "More than 1 transition between states") delta_UCBA[n][k] = v return (delta_UBA, bad_tra_UBA, delta_UCBA)
def solve_problem_with_teams(kb, kb_symbols, data_q, undefined, queries, num_of_observations, row_num, col_num, medic_num, police_num, possible_states, symb_dict, kb_list): answer = {} change = True res = False while change: # global check kb_symbols = spreader(kb_symbols, undefined, kb, row_num, col_num, data_q, possible_states, police_num) kb_symbols = not_H(kb, kb_symbols, data_q, undefined) kb_symbols = not_S(kb, kb_symbols, data_q, undefined) if medic_num > 0: kb_symbols = not_I(kb, kb_symbols, data_q, undefined) kb_symbols, undefined = update_I(kb, kb_symbols, data_q, undefined, possible_states) kb_symbols = vaccine(kb, kb_symbols, data_q, undefined, medic_num, num_of_observations, possible_states) if police_num > 0: kb_symbols = not_Q(kb, kb_symbols, data_q, undefined, police_num, num_of_observations) kb_symbols = quarantine(kb, kb_symbols, data_q, undefined, police_num, num_of_observations, possible_states) undefined_copy = undefined.copy() undefined_copy.reverse() for und in undefined_copy: ex_list = exclusive(und,possible_states,symb_dict) data_q_list = to_sat_cnf(data_q, symb_dict) data_q_list.extend(kb_list) data_q_list.extend(ex_list) if police_num > 0: isS = is_S_with_police(und, row_num, col_num, num_of_observations) else: isS = is_S(und, row_num, col_num, num_of_observations) if not isS: S_cnf_list = data_q_list.copy() else: S_cnf = sympy.to_cnf(~isS, simplify=True, force=True) S_cnf_list = is_to_sat_cnf(S_cnf, symb_dict, data_q_list.copy()) solver = pysat.solvers.Solver(name='g3', bootstrap_with=S_cnf_list, with_proof=True) res = solver.solve() solver.delete() if not res: new_S = und + '_S' data_q.append(new_S) kb.append(new_S) undefined.remove(und) new_S = sympy.symbols(new_S) kb_symbols = sympy.And(kb_symbols, new_S) for p in possible_states: if p != 'S': not_symbol = und + '_' + p if '~' + not_symbol not in data_q: data_q.append('~' + not_symbol) not_symbol = sympy.symbols(not_symbol) kb_symbols = sympy.And(kb_symbols, ~not_symbol) else: isH = is_H(und, row_num, col_num, police_num, medic_num, num_of_observations) if not isH: H_cnf_list = data_q_list.copy() else: H_cnf = sympy.to_cnf(~isH, simplify=True, force=True) H_cnf_list = is_to_sat_cnf(H_cnf, symb_dict, data_q_list.copy()) solver = pysat.solvers.Solver(name='g3', bootstrap_with=H_cnf_list) res = solver.solve() solver.delete() if not res: new_H = und + '_H' data_q.append(new_H) kb.append(new_H) undefined.remove(und) new_H = sympy.symbols(new_H) kb_symbols = sympy.And(kb_symbols, new_H) for p in possible_states: if p != 'H': not_symbol = und + '_' + p if '~' + not_symbol not in data_q: data_q.append('~' + not_symbol) not_symbol = sympy.symbols(not_symbol) kb_symbols = sympy.And(kb_symbols, ~not_symbol) elif police_num > 0: isQ = is_Q(und, num_of_observations, row_num, col_num) if not isQ: Q_cnf_list = data_q_list.copy() else: Q_cnf = sympy.to_cnf(~isQ, simplify=True, force=True) Q_cnf_list = is_to_sat_cnf(Q_cnf, symb_dict, data_q_list.copy()) solver = pysat.solvers.Solver(name='g3', bootstrap_with=Q_cnf_list) res = solver.solve() solver.delete() if not res: new_Q = und + '_Q' data_q.append(new_Q) kb.append(new_Q) undefined.remove(und) new_Q = sympy.symbols(new_Q) kb_symbols = sympy.And(kb_symbols, new_Q) for p in possible_states: if p != 'Q': not_symbol = und + '_' + p if '~' + not_symbol not in data_q: data_q.append('~' + not_symbol) not_symbol = sympy.symbols(not_symbol) kb_symbols = sympy.And(kb_symbols, ~not_symbol) else: possible_not_s = len(possible_states) - 1 i, j, number = und.split('_') for s in possible_states: find_not_s = [] for option in [p for p in possible_states if p != s]: if '~{}_{}_{}_{}'.format(int(i), int(j), int(number), option) in data_q: find_not_s.append(option) find_not_s = set(find_not_s) if possible_not_s == len(find_not_s): new_state = '{}_{}_{}_{}'.format(int(i), int(j), int(number),s) data_q.append(new_state) kb.append(new_state) new_state = sympy.symbols(new_state) kb_symbols = sympy.And(kb_symbols, new_state) if s == 'U': kb_symbols, undefined = update_U(kb_symbols, undefined, [(int(i),int(j))], possible_states, kb, data_q) else: undefined.remove(und) else: possible_not_s = len(possible_states) - 1 i, j, number = und.split('_') for s in possible_states: find_not_s = [] for option in [p for p in possible_states if p != s]: if '~{}_{}_{}_{}'.format(int(i), int(j), int(number), option) in data_q: find_not_s.append(option) find_not_s = set(find_not_s) if possible_not_s == len(find_not_s): new_state = '{}_{}_{}_{}'.format(int(i), int(j), int(number), s) data_q.append(new_state) kb.append(new_state) new_state = sympy.symbols(new_state) kb_symbols = sympy.And(kb_symbols, new_state) if s == 'U': kb_symbols, undefined = update_U(kb_symbols, undefined, [(int(i), int(j))], possible_states, kb, data_q) else: undefined.remove(und) if set(undefined_copy) == set(undefined): change = False for quer in queries: place, number, s = quer i, j = place q = '{}_{}_{}_{}'.format(i, j, number, s) if q in data_q: answer[quer] = 'T' elif '~' + q in data_q: answer[quer] = 'F' else: answer[quer] = '?' return answer
def solve_problem_no_teams(kb, kb_symbols, data_q, undefined, queries, num_of_observations, row_num, col_num, possible_states): answer = {} change = True police_num, medic_num= 0, 0 kb_symbols = spreader(kb_symbols, undefined, kb, row_num, col_num, data_q, possible_states, police_num) while change: undefined_copy = undefined.copy() undefined_copy.reverse() for und in undefined_copy: isS = is_S(und, row_num, col_num, num_of_observations) kb_S = sympy.And(~isS, kb_symbols) kb_S_cnf = sympy.to_cnf(kb_S) res = sympy.satisfiable(kb_S_cnf) if not res: new_S = und + '_S' data_q.append(new_S) kb.append(new_S) undefined.remove(und) new_S = sympy.symbols(new_S) kb_symbols = sympy.And(kb_symbols, new_S) no_H = und + '_H' data_q.append('~' + no_H) no_H = sympy.symbols(no_H) kb_symbols = sympy.And(kb_symbols, ~no_H) no_U = und + '_U' if '~' + no_U not in data_q: data_q.append('~' + no_U) no_U = sympy.symbols(no_U) kb_symbols = sympy.And(kb_symbols, ~no_U) else: isH = is_H(und, row_num, col_num, police_num, medic_num, num_of_observations) kb_H = sympy.And(~isH, kb_symbols) kb_H_cnf = sympy.to_cnf(kb_H) res = sympy.satisfiable(kb_H_cnf) if not res: new_H = und + '_H' data_q.append(new_H) kb.append(new_H) undefined.remove(und) new_H = sympy.symbols(new_H) kb_symbols = sympy.And(kb_symbols, new_H) no_S = und + '_S' data_q.append('~' + no_S) no_S = sympy.symbols(no_S) kb_symbols = sympy.And(kb_symbols, ~no_S) no_U = und + '_U' if '~' + no_U not in data_q: data_q.append('~' + no_U) no_U = sympy.symbols(no_U) kb_symbols = sympy.And(kb_symbols, ~no_U) kb_symbols = spreader(kb_symbols, undefined, kb, row_num, col_num, data_q, possible_states, police_num) if set(undefined_copy) == set(undefined): change = False for quer in queries: place, number, s = quer i, j = place q = '{}_{}_{}_{}'.format(i, j, number, s) if q in data_q: answer[quer] = 'T' elif '~' + q in data_q: answer[quer] = 'F' else: answer[quer] = '?' return answer
file_and_console_print("Done") # Print the expression for move 1 in level 1 (i.e. bits V1,b). # This is NOT in CNF form. for b in xrange(0, 3): file_and_console_print("\n\n\n\nPrinting V1,%d in non-CNF Form" % (b + 1)) non_cnf_string = pretty_print_CNF(str(level1[0][b])) file_and_console_print("\nV1,%d=" % (b + 1)) file_and_console_print(non_cnf_string) file_and_console_print("Printing V1,%d in non-CNF Form...Done" % (b + 1)) # Print the CNF for move 1 in level 1 (i.e. bits V1,b). for b in xrange(0, 3): file_and_console_print("\n\n\n\nConverting to CNF for V1,%d" % (b + 1)) temp_expression = to_cnf(level1[0][b], False) # Uncomment the line below to simplify the expression # temp_expression = to_cnf(temp_expression, True) cnf_string = pretty_print_CNF(str(temp_expression)) file_and_console_print("\nV1,%d=" % (b + 1)) file_and_console_print(cnf_string) file_and_console_print("Converting to CNF for V1,%d...Done" % (b + 1)) # This will print the statements all the way to the tree root. if solve_to_tree_root: # Print the expression for move 1 in level 1 (i.e. bits V1,b). # This is NOT in CNF form. for b in xrange(0, 3): file_and_console_print("\n\n\n\nPrinting V%d in non-CNF Form" % (b + 1)) non_cnf_string = pretty_print_CNF(str(level0_root[b])) file_and_console_print("\nV%d=" % (b + 1))
sortedList = checkPermutations(list, bb) return sortedList if __name__ == '__main__': print("Enter belief state, seperated by comma") print("Valid operands: '|', '&', '>>', '<->'") bb = input() list = bb.split(",") bbtocnf = [] inverted = [] for elements in list: if "<->" in elements: word = recursiveBiConditional(elements, 0) bbtocnf.append(to_cnf(word)) else: bbtocnf.append(to_cnf(elements)) sortedList = endOperations(bbtocnf, operands) print(sortedList) while True: printRevise() line = input() opp = [] if line == "EXIT": break else: if "<->" in line:
for i in range(1, k+1): x = list(combinations(se, i)) clause_string = '' for part_clause in x: clause_string += '&'.join(part_clause) negated = se - set(part_clause) if len(negated) != 0: clause_string += '&~'+'&~'.join(negated) clause_string += '|' clause_string.replace('||', '|') clause_string = clause_string[:-1] overall_addition.append(clause_string) exec('overall_addition_course = ' + '|'.join(overall_addition)) sp.to_cnf(overall_addition_course, True) # In[16]: # se # In[17]: overall_addition_course_cnf = sp.to_cnf(overall_addition_course, True) # In[18]:
from sympy import symbols, Equivalent, to_cnf, dotprint from graphviz import Source if __name__ == "__main__": # Define expression B1, P1, P2 = symbols('B1,P1,P2') p_1 = Equivalent(B1, (P1 | P2)) & ~B1 # ( B1 <-> (P1 & P2)) & ~B1 p_1_cnf = to_cnf(p_1) # Create the graphviz content expression_tree = dotprint(p_1) # Using the graphviz module write tree to file and generate .svg with result src = Source(expression_tree) src.render('expr_tree', view=True, format='pdf')
# In[26]: NNF_STRING # In[ ]: # In[27]: sp.to_cnf(tseitin1(NNF_STRING)) == make_cnf(NNF_STRING) # In[28]: for i in range(1, 40): NNF_FILE_NAME = f'nnf/test_case{i}.nnf' CNF_FILE_NAME = f'cnf/test_case{i}.cnf' NNF_STRING = read_NNF_from_file(NNF_FILE_NAME) detect_incorrect_brackets(NNF_STRING) detect_operator_errors(NNF_STRING) max_num:int = max_no(NNF_STRING) syms: sp.Symbol = define_variables(max_num+1) for j in range(max_num+1): exec(f'x{j} = syms[{j}]')
def to_cnf_sympy(self, boolean_fmla_sympy, sympy_symbol_list=[]): if len(sympy_symbol_list) > 0: self.set_symbols(sympy_symbol_list) return sympy.to_cnf(boolean_fmla_sympy)