def get_pos_SR(min_variable_number, max_variable_number, clause_number): variable_number = random.randint(min_variable_number, max_variable_number) clauses = [] solver = Minisat22() while solver.solve(): clause = get_SR(variable_number) solver.add_clause(clause) clauses.append(clause) if len(clauses) > clause_number: clauses = [] solver.delete() solver = Minisat22() clauses = clauses[:-1] return CNF(clauses)
def _optimize(epeg, constraints, top_id, lower_bound, upper_bound, model): if lower_bound <= upper_bound: cost = int((2 * lower_bound + upper_bound) / 3) lits = [] weights = [] for key, value in epeg.nodes.items(): lits.append(key) weights.append(value.cost) object_function = PBEnc.leq(lits=lits, weights=weights, bound=cost, top_id=top_id) cnf = CNF(from_clauses=constraints.clauses + object_function.clauses) solver = Minisat22() solver.append_formula(cnf.clauses) if solver.solve(): model = solver.get_model() return _optimize(epeg, constraints, top_id, lower_bound, cost - 1, model) else: return _optimize(epeg, constraints, top_id, cost + 1, upper_bound, model) return model, lower_bound
def solve_problem(problem): n_police = problem['police'] n_medics = problem['medics'] observations = problem['observations'] queries = problem['queries'] n_rows = len(observations[0]) n_cols = len(observations[0][0]) n_time = len(observations) + 1 + 3 # All the information we could have var_pool, formula = make_formula(n_police, n_medics, n_rows, n_cols, n_time) assumptions = [ var_pool.id(f'({r}, {c}), {t}, {s}') for t, obs in enumerate(observations) for r, row in enumerate(obs) for c, s in enumerate(row) if s != '?' ] results = {query: '?' for query in queries} with Minisat22(bootstrap_with=formula) as solver: for query in results: (r, c), t, s = query with_query = solver.solve(assumptions + [var_pool.id(f'({r}, {c}), {t}, {s}')]) with_not_query = solver.solve( assumptions + [-var_pool.id(f'({r}, {c}), {t}, {s}')]) if with_query and not with_not_query: results[query] = 'T' elif with_not_query and not with_query: results[query] = 'F' return results
def SATSolver(clauses): m = Minisat22() # m.conf_budget(1000) m.prop_budget(2000) # adding limit on solver for clause in clauses: m.add_clause(clause) return m.solve_limited()
def main(): variable_size_list = [ 10, 100, 1000 ] # each item in this list is used to generate a horn variable of that size avg_time_for_variable_size_set = [ ] # this list is maintained to compare the time increase per formula size for numb_of_variables in variable_size_list: linear_horn = horn_variable_generator(numb_of_variables) # instance of horn_formula = linear_horn.build_using_pysat( ) # generate a horn variable of size numb_of_variables avg_time = 0 numb_runs = 10 # average the time to solve over numb_run runs of the sat solver. for i in range(1, numb_runs): with Minisat22(bootstrap_with=horn_formula, use_timer=True) as m: m.solve() # solve using minisat avg_time += m.time() # accumulate the time used in the solver avg_time = avg_time / numb_runs # find the real average over numb_run minisat calls avg_time_for_variable_size_set.append( avg_time) # maintain a list of average times for# [a, b, c] # this loop prints the time increase per formula for index, time in enumerate(avg_time_for_variable_size_set[:-1]): time_diff = avg_time_for_variable_size_set[index + 1] / time print "\n" "It takes ", time_diff, " times longer to compute", variable_size_list[ index + 1], " variables than ", variable_size_list[index], " variables"
def satisfiable(self): solver = Minisat22() for clause in self.clauses: solver.add_clause(clause) result = solver.solve() solver.delete() return result
def solve_CNF_core(clauses): global calls calls += 1 solver = Minisat22(bootstrap_with=clauses) res = solver.solve() core = solver.get_core() solver.delete() return (res, core)
def sol_4C(): s = Minisat22() # Link Symbols link_symbols(s, varmap2) # Make sure that no two students walk out twice in a group across the seven days for (i, j) in itertools.combinations(range(n_student), 2): clauses = [] for d in range(n_day): for g in range(n_group): clauses.append(varmap2[(d, g, (i, j))]) for (c1, c2) in itertools.combinations(clauses, 2): s.add_clause([-c1, -c2]) # Make sure that every student is assigned and only assigned one group every day for i in range(n_day): for j in range(n_student): groups = [varmap2[(i, g, j)] for g in range(n_group)] for (g1, g2) in itertools.combinations(groups, 2): s.add_clause([-g1, -g2]) s.add_clause(groups) # Make sure that every group has three students every day for i in range(n_day): for j in range(n_group): for (s1, s2, s3) in itertools.combinations(range(n_student), 3): c1 = varmap2[(i, j, (s1, s2))] c2 = varmap2[(i, j, (s1, s3))] c3 = varmap2[(i, j, (s2, s3))] s.add_clause([-c1, -c2, c3]) s.add_clause([-c1, -c3, c2]) s.add_clause([-c2, -c3, c1]) s.solve() res = [s.get_model()] for _ in range(9): curr = res[-1] clause = [] for i in range(len(curr)): clause.append(-curr[i]) s.add_clause(clause) s.solve() res.append(s.get_model()) return res
def minisat22_satisfiable(expr, all_models=False, minimal=False): if not isinstance(expr, EncodedCNF): exprs = EncodedCNF() exprs.add_prop(expr) expr = exprs from pysat.solvers import Minisat22 # Return UNSAT when False (encoded as 0) is present in the CNF if {0} in expr.data: if all_models: return (f for f in [False]) return False r = Minisat22(expr.data) if minimal: r.set_phases([-(i + 1) for i in range(r.nof_vars())]) if not r.solve(): return False if not all_models: return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r.get_model()} else: # Make solutions sympy compatible by creating a generator def _gen(results): satisfiable = False while results.solve(): sol = results.get_model() yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol} if minimal: results.add_clause([-i for i in sol if i > 0]) else: results.add_clause([-i for i in sol]) satisfiable = True if not satisfiable: yield False raise StopIteration return _gen(r)
def compute_unsat_core(clauses, start_index): # attach selector literal # print("clauses:", clauses) clauses_with_indices = [] index = start_index refs = [] for cl in clauses: clauses_with_indices.append(cl + [-index]) refs.append(index) index += 1 # solve with minisat with Minisat22(bootstrap_with=clauses_with_indices) as m: status = m.solve(assumptions=refs) # print("status:", status) unsat_core = m.get_core() if unsat_core is None: model = m.get_model() # print("start_index:", start_index) # print("sat model size:", len(model) ) # print("model:", model) return True, [x for x in model if abs(x) < start_index] else: return False, sorted([x - start_index for x in unsat_core])
s1.add_clause([-2, 3]) s1.add_clause([-3, 4]) if s1.solve() == True: print(s1.get_model()) print('blocking models:') m = s1.get_model() s1.add_clause([-l for l in m]) # actual blocking if s1.solve() == True: print(s1.get_model()) # should compute another model s1.delete() # this is needed if used not within the 'with' context print('model enumeration + bootstrapping the solver:') s2 = Minisat22(bootstrap_with=[[-1, 2], [-2, 3], [-3, 4] ]) # also working with MiniSat22 directly for m in s2.enum_models(): # implemented as a generator print(m) s2.delete() print('\'with\' constructor + assumptions:') with Solver(name='mgh', bootstrap_with=[[-1, 2], [-2, 3], [-3, 4]]) as s3: for m in s3.enum_models(assumptions=[5]): print(m) # no s3.delete() is needed -- it is called automatically if used in the 'with' environment print('appending formula and extracting an unsat core:') with Glucose3(bootstrap_with=[[-1, 2], [-2, 3]]) as s4: s4.append_formula([[-3, 4], [-4, 5]])
def get_solution(pysat_list, assumptions, vpool): solution_dict = {} g = Minisat22 # print(pysat_list) area_type = ['H', 'S', 'U'] for assumption in assumptions: s_b = '{}_{}_{}_{}'.format(assumption[2], assumption[0][0], assumption[0][1], assumption[1]) # n_s = '~{}_{}_{}_{}'.format(assumption[2], assumption[0][0], assumption[0][1], assumption[1]) s = generate_clause(s_b, vpool) # n_s = generate_clause(n_s, vpool) #sub_s = [] #sub_s.append(s) sub_s = [ '{}_{}_{}_{}'.format(area, assumption[0][0], assumption[0][1], assumption[1]) for area in area_type if area is not assumption[2] ] sub_s.append(s_b) #print(sub_s) #print(s, n_s) ###print("clause:", s[0]) solution_list = [] for sub_assumption in sub_s: sub_assumption = generate_clause(sub_assumption, vpool) with Minisat22(bootstrap_with=pysat_list) as m: #print(m.solve(assumptions=s[0])) #result = m.solve(assumptions=s[0]) solution_list.append(m.solve(assumptions=sub_assumption[0])) m.delete() if solution_list.count(1) > 1: solution_dict[assumption] = '?' elif solution_list[2]: solution_dict[assumption] = "T" else: solution_dict[assumption] = "F" # if result: # solution_dict[assumption] = "T" # else: # solution_dict[assumption] = "F" #solution_dict = {} return solution_dict # def get_general_assumptions(true_assumptions, input, areas, vpool): # matrix = input["observations"] # shape = np.shape(matrix) # t, i , j # # print(shape) # dimentions = [shape[1], shape[2]] # epoch = shape[0] # type1 = ['H', 'S', 'U'] # type2 = ['S', 'U', 'H'] # type3 = ['U', 'H', 'S'] # for area in areas["?"]: # for i in range(len(type1)): # cl_str = "~{3}_{0}_{1}_{2} | ~{4}_{0}_{1}_{2}".format(area[0], area[1], area[2], type1[i], type2[i]) # true_assumptions.append(str(cl_str)) # cl_str = "~{3}_{0}_{1}_{2} | ~{4}_{0}_{1}_{2}".format(area[0], area[1], area[2], type1[i], type3[i]) # true_assumptions.append(str(cl_str)) # for area_type in ['S', '?']: # for area in areas[area_type]: # if area[2] > 0: # neighbours_list = find_neighbours(dimentions, area[0], area[1], area[2] - 1) # #neighbours_list = [] # find_neighbours(dimentions, area[0], area[1], area[2] - 1) # cl_str = "~H_{0}_{1}_{2} | ~S_{0}_{1}_{3}".format(area[0], area[1], area[2] - 1, area[2]) # for n in neighbours_list: # cl_str += " | " + "S_{0}_{1}_{2} & ~H_{0}_{1}_{2}".format(n[0], n[1], n[2]) # #print(cl_str) # #print(to_cnf("A & B ==> ((C & ~D) | (E & ~F))")) # cl_str = str(to_cnf(cl_str)) # #print("from gen_list: ", cl_str) # x = cl_str.split('&') # for clause in x: # #print("clause: ", clause) # true_assumptions.append(clause) # #true_assumptions.append(str(cl_str)) # # # print("n_list of area: ", area, neighbours_list) # # for n in neighbours_list: # # # if area[2] < epoch - 1: # # if matrix[n[2]][n[0]][n[1]] == 'H' or matrix[n[2]][n[0]][n[1]] == '?': # # a=> a or a=> b # # s = '{}_{}_{}_{} & {}_{}_{}_{} & {}_{}_{}_{}' # return
def solve_problem(input): police = input['police'] actions_police = [] i = 1 for p in range(police): actions_police.append('P' + str(i)) i += 1 medics = input['medics'] actions_medics = [] j = 1 for m in range(medics): actions_medics.append('M' + str(j)) j += 1 states = {} for turn in range(len(input['observations'])): states[turn] = input['observations'][turn] KB = [] r = len(states[0]) c = len(states[0][0]) state_p = ['U', 'H', 'S', '?', 'Q', 'I'] max_turns = len(input['observations']) p = {} inital_state = [] max_index = 1 dict_p_to_int = {} all_p_a = {} for turn in range(max_turns): p_0 = [] for i in range(r): for j in range(c): inital_state.append( tuple([tuple([i, j]), turn, states[turn][i][j]])) for state in state_p: p_0.append(tuple([tuple([i, j]), turn, state])) dict_p_to_int[tuple([tuple([i, j]), turn, state])] = max_index all_p_a[tuple([tuple([i, j]), turn, state])] = max_index if tuple([tuple([i, j]), turn, state]) in inital_state: KB.append([max_index]) else: if tuple([tuple([i, j]), turn, '?']) not in inital_state: KB.append([-1 * max_index]) max_index += 1 p[turn] = p_0 all_actions = {} # add actions to dict_p_to_int for turn in range(max_turns): for i in range(r): for j in range(c): for ac1 in actions_police: max_index = max_index + 1 dict_p_to_int[tuple([tuple([i, j]), turn, ac1])] = max_index all_p_a[tuple([tuple([i, j]), turn, ac1])] = max_index all_actions[tuple([tuple([i, j]), turn, ac1])] = max_index for ac2 in actions_medics: max_index = max_index + 1 dict_p_to_int[tuple([tuple([i, j]), turn, ac2])] = max_index all_p_a[tuple([tuple([i, j]), turn, ac2])] = max_index all_actions[tuple([tuple([i, j]), turn, ac2])] = max_index # S -> ~H,~I,~Q,~U for turn in range(max_turns): for i in range(r): for j in range(c): x1 = dict_p_to_int[tuple([tuple([i, j]), turn, 'Q'])] x2 = dict_p_to_int[tuple([tuple([i, j]), turn, 'H'])] x3 = dict_p_to_int[tuple([tuple([i, j]), turn, 'I'])] x4 = dict_p_to_int[tuple([tuple([i, j]), turn, 'S'])] x5 = dict_p_to_int[tuple([tuple([i, j]), turn, 'U'])] x6 = dict_p_to_int[tuple([tuple([i, j]), turn, '?'])] for s in state_p: if s == 'Q': KB.extend([[-1 * x1, -1 * x2], [-1 * x1, -1 * x3], [-1 * x1, -1 * x4], [-1 * x1, -1 * x5]]) if s == 'H': KB.extend([[-1 * x2, -1 * x1], [-1 * x2, -1 * x3], [-1 * x2, -1 * x4], [-1 * x2, -1 * x5]]) if s == 'I': KB.extend([[-1 * x3, -1 * x1], [-1 * x3, -1 * x2], [-1 * x3, -1 * x4], [-1 * x3, -1 * x5]]) if s == 'S': KB.extend([[-1 * x4, -1 * x1], [-1 * x4, -1 * x2], [-1 * x4, -1 * x3], [-1 * x4, -1 * x5]]) if s == 'U': KB.extend([[-1 * x5, -1 * x1], [-1 * x5, -1 * x2], [-1 * x5, -1 * x3], [-1 * x5, -1 * x4]]) if s == '?': KB.append([-1 * x6, x1, x2, x3, x4, x5]) # KB.append(["S -> ~H,~I,~Q,~U Done"]) goals = input['queries'] add_effect_all_actions = {} for action in actions_police: for turn in range(max_turns): for i in range(r): for j in range(c): add = [] if turn + 1 < max_turns: Q1 = dict_p_to_int[tuple( [tuple([i, j]), turn + 1, 'Q'])] add.append(Q1) elif turn + 2 <= max_turns: Q2 = dict_p_to_int[tuple( [tuple([i, j]), turn + 2, 'Q'])] add.append(Q2) elif turn + 3 <= max_turns: H3 = dict_p_to_int[tuple( [tuple([i, j]), turn + 3, 'H'])] add.append(H3) add_effect_all_actions[max_index] = add # {~a_t,p_t} a_t = dict_p_to_int[tuple([tuple([i, j]), turn, action])] p_t = dict_p_to_int[tuple([tuple([i, j]), turn, 'S'])] KB.append([-1 * a_t, p_t]) #KB.append(["-1 * a_t, p_t police Done"]) for action in actions_medics: for turn in range(max_turns): for i in range(r): for j in range(c): if turn + 1 <= max_turns: add_effect_all_actions[max_index] = [ tuple([tuple([i, j]), turn + 1, 'I']) ] # {~a_t,p_t} a_t = dict_p_to_int[tuple([tuple([i, j]), turn, action])] p_t = dict_p_to_int[tuple([tuple([i, j]), turn, 'H'])] KB.append([-1 * a_t, p_t]) #KB.append(["-1 * a_t, p_t med Done"]) # don't apply interfering actions at the same time # {~a_t,a_t'} # apply one action once each turn for ac in actions_medics: for turn in range(max_turns): for i in range(r): for j in range(c): x1 = dict_p_to_int[tuple([tuple([i, j]), turn, ac])] for i_1 in range(r): for j_1 in range(c): if i != i_1 and j != j_1: x2 = dict_p_to_int[tuple( [tuple([i_1, j_1]), turn, ac])] KB.append([-1 * x1, -1 * x2]) for ac in actions_police: for turn in range(max_turns): for i in range(r): for j in range(c): x1 = dict_p_to_int[tuple([tuple([i, j]), turn, ac])] for i_1 in range(r): for j_1 in range(c): if i != i_1 and j != j_1: x2 = dict_p_to_int[tuple( [tuple([i_1, j_1]), turn, ac])] KB.append([-1 * x1, -1 * x2]) # apply action if can for ac in actions_medics: for turn in range(max_turns): l1 = [] for i in range(r): for j in range(c): l1.append(dict_p_to_int[tuple([tuple([i, j]), turn, ac])]) KB.append(l1) for ac in actions_police: for turn in range(max_turns): l1 = [] for i in range(r): for j in range(c): l1.append(dict_p_to_int[tuple([tuple([i, j]), turn, ac])]) KB.append(l1) # fact implies disjunction of its achevers # {~p_t} or {a_(t-1)|p in add(a)} if len(all_actions) != 0: for p, v1 in dict_p_to_int.items(): l = [-1 * v1] for action, v2 in add_effect_all_actions.items(): if v1 in v2: l.append(action) if len(l) > 1: KB.append(l) for turn in range(1, max_turns): for key, v in dict_p_to_int.items(): ######### U ########### if turn != key[1]: continue if key[2] == 'U': KB.append([ -1 * v, dict_p_to_int[tuple([key[0], key[1] - 1, key[2]])] ]) ######### I ########### if key[2] == 'I': l2 = [v * -1] if len(actions_medics) > 0: if turn + 1 < max_turns: KB.append([ -1 * v, dict_p_to_int[tuple([key[0], key[1] + 1, key[2]])] ]) for i in range(turn): for ac in actions_medics: l2.append(dict_p_to_int[tuple([key[0], i, ac])]) KB.append(l2) ######### ? ########### if key[2] == '?': x1 = v x2 = dict_p_to_int[tuple([key[0], key[1], 'H'])] x3 = dict_p_to_int[tuple([key[0], key[1], 'U'])] x4 = dict_p_to_int[tuple([key[0], key[1], 'S'])] x5 = dict_p_to_int[tuple([key[0], key[1], 'I'])] x6 = dict_p_to_int[tuple([key[0], key[1], 'Q'])] KB.append([-1 * x1, x2, x3, x4, x5, x6]) ######### H ########### if key[2] == 'H': x1 = v x2 = dict_p_to_int[tuple([key[0], key[1] - 1, key[2]])] # H in i-1 N = neighbors(key[0][0], key[0][1], r, c) ############# turn < 3 ############ if turn < 3: if len(N) == 1: x3 = dict_p_to_int[tuple( [N[0], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor1 was S # (x2 | ~x1) & (~x1 | ~x3) KB.extend([[x2, -1 * x1], [-1 * x1, -1 * x3]]) # x1-> x2 & ~x3 elif len(N) == 2: x3 = dict_p_to_int[tuple( [N[0], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple( [N[1], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor2 was S # (x2 | ~x1) & (~x1 | ~x3) & (~x1 | ~x4) KB.extend([[x2, -1 * x1], [-1 * x1, -1 * x3], [-1 * x1, -1 * x4]]) # x1-> x2 & ~x3 & ~x4 elif len(N) == 3: x3 = dict_p_to_int[tuple( [N[0], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple( [N[1], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor2 was S x5 = dict_p_to_int[tuple( [N[2], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor2 was S # (x2 | ~x1) & (~x1 | ~x3) & (~x1 | ~x4) & (~x1 | ~x5) KB.extend([[x2, -1 * x1], [-1 * x1, -1 * x3], [-1 * x1, -1 * x4], [-1 * x1, -1 * x5]]) # x1-> x2 & ~x3 & ~x4 & ~x5 else: x3 = dict_p_to_int[tuple( [N[0], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple( [N[1], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor2 was S x5 = dict_p_to_int[tuple( [N[2], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor3 was S x6 = dict_p_to_int[tuple( [N[3], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor4 was S # (x2 | ~x1) & (~x1 | ~x3) & (~x1 | ~x4) & (~x1 | ~x5) & (~x1 | ~x6) KB.extend([[x2, -1 * x1], [-1 * x1, -1 * x3], [-1 * x1, -1 * x4], [-1 * x1, -1 * x5], [-1 * x1, -1 * x6]]) # x1-> x2 & ~x3 & ~x4 & ~x5 ########## turn >= 3 ########## else: # i was sick for 3 turns x7 = dict_p_to_int[tuple([key[0], key[1] - 1, 'S'])] x8 = dict_p_to_int[tuple([key[0], key[1] - 2, 'S'])] x9 = dict_p_to_int[tuple([key[0], key[1] - 3, 'S'])] if police > 0: # i was in quarantine for 2 turns x10 = dict_p_to_int[tuple([key[0], key[1] - 1, 'Q'])] x11 = dict_p_to_int[tuple([key[0], key[1] - 2, 'Q'])] if len(N) == 1: x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S # x1-> (x2 & ~x3) or (x7 & x8 & x9) or (x10 & x11) KB.extend([[x10, x2, x7, -1 * x1], [x10, x2, x8, -1 * x1], [x10, x2, x9, -1 * x1], [x11, x2, x7, -1 * x1], [x11, x2, x8, ~x1], [x11, x2, x9, -1 * x1], [x10, x7, -1 * x1, -1 * x3], [x10, x8, -1 * x1, -1 * x3], [x10, x9, -1 * x1, -1 * x3], [x11, x7, -1 * x1, -1 * x3], [x11, x8, ~x1, -1 * x3], [x11, x9, -1 * x1, -1 * x3]]) elif len(N) == 2: x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple([ N[1], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S # x1-> (x2 & ~x3 & ~x4 )or (x7 & x8 & x9) or (x10 & x11) KB.extend([[x10, x2, x7, -1 * x1], [x10, x2, x8, -1 * x1], [x10, x2, x9, -1 * x1], [x11, x2, x7, -1 * x1], [x11, x2, x8, -1 * x1], [x11, x2, x9, -1 * x1], [x10, x7, -1 * x1, -1 * x3], [x10, x7, -1 * x1, -1 * x4], [x10, x8, -1 * x1, -1 * x3], [x10, x8, -1 * x1, -1 * x4], [x10, x9, -1 * x1, -1 * x3], [x10, x9, -1 * x1, -1 * x4], [x11, x7, -1 * x1, -1 * x3], [x11, x7, -1 * x1, -1 * x4], [x11, x8, -1 * x1, -1 * x3], [x11, x8, -1 * x1, -1 * x4], [x11, x9, -1 * x1, -1 * x3], [x11, x9, ~x1, -1 * x4]]) elif len(N) == 3: x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple([ N[1], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S x5 = dict_p_to_int[tuple([ N[2], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S # x1-> (x2 & ~x3 & ~x4 & ~x5 )or (x7 & x8 & x9) or (x10 & x11) KB.extend([[x10, x2, x7, -1 * x1], [x10, x2, x8, -1 * x1], [x10, x2, x9, -1 * x1], [x11, x2, x7, -1 * x1], [x11, x2, x8, -1 * x1], [x11, x2, x9, -1 * x1], [x10, x7, -1 * x1, ~x3], [x10, x7, -1 * x1, -1 * x4], [x10, x7, -1 * x1, -1 * x5], [x10, x8, -1 * x1, -1 * x3], [x10, x8, -1 * x1, -1 * x4], [x10, x8, -1 * x1, -1 * x5], [x10, x9, -1 * x1, -1 * x3], [x10, x9, -1 * x1, -1 * x4], [x10, x9, -1 * x1, -1 * x5], [x11, x7, -1 * x1, -1 * x3], [x11, x7, -1 * x1, -1 * x4], [x11, x7, -1 * x1, -1 * x5], [x11, x8, -1 * x1, -1 * x3], [x11, x8, -1 * x1, -1 * x4], [x11, x8, -1 * x1, -1 * x5], [x11, x9, -1 * x1, -1 * x3], [x11, x9, -1 * x1, -1 * x4], [x11, x9, -1 * x1, -1 * x5]]) else: # x1-> (x2 & ~x3 & ~x4 & ~x5 & ~x6 )or (x7 & x8 & x9) or (x10 & x11) x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple([ N[1], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S x5 = dict_p_to_int[tuple([ N[2], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor3 was S x6 = dict_p_to_int[tuple([ N[3], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor4 was S KB.extend([[x10, x2, x7, -1 * x1], [x10, x2, x8, -1 * x1], [x10, x2, x9, -1 * x1], [x11, x2, x7, -1 * x1], [x11, x2, x8, -1 * x1], [x11, x2, x9, -1 * x1], [x10, x7, -1 * x1, -1 * x3], [x10, x7, -1 * x1, -1 * x4], [x10, x7, -1 * x1, -1 * x5], [x10, x7, ~x1, -1 * x6], [x10, x8, -1 * x1, -1 * x3], [x10, x8, -1 * x1, -1 * x4], [x10, x8, -1 * x1, -1 * x5], [x10, x8, -1 * x1, -1 * x6], [x10, x9, -1 * x1, -1 * x3], [x10, x9, -1 * x1, -1 * x4], [x10, x9, -1 * x1, -1 * x5], [x10, x9, -1 * x1, -1 * x6], [x11, x7, -1 * x1, -1 * x3], [x11, x7, -1 * x1, -1 * x4], [x11, x7, -1 * x1, -1 * x5], [x11, x7, -1 * x1, -1 * x6], [x11, x8, -1 * x1, -1 * x3], [x11, x8, -1 * x1, -1 * x4], [x11, x8, -1 * x1, -1 * x5], [x11, x8, -1 * x1, -1 * x6], [x11, x9, -1 * x1, -1 * x3], [x11, x9, -1 * x1, -1 * x4], [x11, x9, -1 * x1, -1 * x5], [x11, x9, -1 * x1, -1 * x6]]) else: if len(N) == 1: x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S # x1-> (x2 & ~x3) or (x7 & x8 & x9) KB.extend([[x2, x7, -1 * x1], [x2, x8, -1 * x1], [x2, x9, -1 * x1], [x7, -1 * x1, ~x3], [x8, -1 * x1, -1 * x3], [x9, -1 * x1, -1 * x3]]) elif len(N) == 2: x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple([ N[1], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S # x1-> (x2 & ~x3 & ~x4 )or (x7 & x8 & x9) KB.extend([[x2, x7, -1 * x1], [x2, x8, -1 * x1], [x2, x9, -1 * x1], [x7, -1 * x1, -1 * x3], [x7, -1 * x1, -1 * x4], [x8, -1 * x1, -1 * x3], [x8, -1 * x1, -1 * x4], [x9, -1 * x1, -1 * x3], [x9, -1 * x1, -1 * x4]]) elif len(N) == 3: x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple([ N[1], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S x5 = dict_p_to_int[tuple([ N[2], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S # x1-> (x2 & ~x3 & ~x4 & ~x5 )or (x7 & x8 & x9) KB.extend([[x2, x7, -1 * x1], [x2, x8, -1 * x1], [x2, x9, -1 * x1], [x7, -1 * x1, -1 * x3], [x7, -1 * x1, -1 * x4], [x7, -1 * x1, -1 * x5], [x8, -1 * x1, -1 * x3], [x8, -1 * x1, -1 * x4], [x8, -1 * x1, -1 * x5], [x9, -1 * x1, -1 * x3], [x9, -1 * x1, -1 * x4], [x9, -1 * x1, -1 * x5]]) else: # x1-> (x2 & ~x3 & ~x4 & ~x5 & ~x6 )or (x7 & x8 & x9) x3 = dict_p_to_int[tuple([ N[0], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor1 was S x4 = dict_p_to_int[tuple([ N[1], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor2 was S x5 = dict_p_to_int[tuple([ N[2], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor3 was S x6 = dict_p_to_int[tuple([ N[3], key[1] - 1, 'S' ])] # in i-1 :i was H , my neighbor4 was S KB.extend([[x2, x7, -1 * x1], [x2, x8, -1 * x1], [x2, x9, -1 * x1], [x7, -1 * x1, -1 * x3], [x7, -1 * x1, -1 * x4], [x7, -1 * x1, -1 * x5], [x7, -1 * x1, -1 * x6], [x8, -1 * x1, -1 * x3], [x8, -1 * x1, -1 * x4], [x8, -1 * x1, -1 * x5], [x8, -1 * x1, -1 * x6], [x9, -1 * x1, -1 * x3], [x9, -1 * x1, -1 * x4], [x9, -1 * x1, -1 * x5], [x9, -1 * x1, -1 * x6]]) #KB.append(["H Done"]) ######### S ########### if key[2] == 'S': x1 = v x2 = dict_p_to_int[tuple([key[0], key[1] - 1, key[2] ])] # i was S in the last turn (i-1) x3 = dict_p_to_int[tuple([key[0], key[1] - 1, 'H' ])] # i was H in the last turn (i-1) N = neighbors(key[0][0], key[0][1], r, c) ###### turn < 3 ##### if len(N) == 1: # x1 -> (x2) or (x3 and x4) x4 = dict_p_to_int[tuple( [N[0], key[1] - 1, 'S'])] # in i-1 :i was H , my neighbor1 was S KB.extend([[x2, x3, -1 * x1], [x2, x4, -1 * x1]]) elif (len(N) == 2): # x1 -> (x2) or ((x3 and x4) or (x3 and x5)) x4 = dict_p_to_int[tuple( [N[0], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor1 was S x5 = dict_p_to_int[tuple( [N[1], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor2 was S KB.extend([[x2, x3, -1 * x1], [x2, x3, x4, -1 * x1], [x2, x3, x5, -1 * x1], [x2, x4, x5, -1 * x1]]) elif (len(N) == 3): # x1 -> (x2) or ((x3 and x4) or (x3 and x5) or (x3 and x6) x4 = dict_p_to_int[tuple( [N[0], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor1 was S x5 = dict_p_to_int[tuple( [N[1], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor2 was S x6 = dict_p_to_int[tuple( [N[2], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor3 was S KB.extend([[x2, x3, -1 * x1], [x2, x3, x4, -1 * x1], [x2, x3, x5, -1 * x1], [x2, x3, x6, -1 * x1], [x2, x3, x4, x5, -1 * x1], [x2, x3, x4, x6, -1 * x1], [x2, x3, x5, x6, -1 * x1], [x2, x4, x5, x6, -1 * x1]]) else: # x1 -> (x2) or ((x3 and x4) or (x3 and x4) or (x3 and x5) or (x3 and x6) x4 = dict_p_to_int[tuple( [N[0], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor1 was S x5 = dict_p_to_int[tuple( [N[1], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor2 was S x6 = dict_p_to_int[tuple( [N[2], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor3 was S x7 = dict_p_to_int[tuple( [N[3], key[1] - 1, key[2]])] # in i-1 :i was H , my neighbor4 was S KB.extend([[x2, x3, -1 * x1], [x2, x3, x4, -1 * x1], [x2, x3, x5, -1 * x1], [x2, x3, x6, -1 * x1], [x2, x3, x7, -1 * x1], [x2, x3, x4, x5, -1 * x1], [x2, x3, x4, x6, -1 * x1], [x2, x3, x4, x7, -1 * x1], [x2, x3, x5, x6, -1 * x1], [x2, x3, x5, x7, -1 * x1], [x2, x3, x6, x7, -1 * x1], [x2, x3, x4, x5, x6, -1 * x1], [x2, x3, x4, x5, x7, -1 * x1], [x2, x3, x4, x6, x7, -1 * x1], [x2, x3, x5, x6, x7, -1 * x1], [x2, x4, x5, x6, x7, -1 * x1]]) if turn > 2 and turn + 1 < max_turns: x1 = v x2 = dict_p_to_int[tuple([key[0], key[1] - 1, key[2]])] x3 = dict_p_to_int[tuple([key[0], key[1] - 2, key[2]])] x4 = dict_p_to_int[tuple([key[0], key[1] + 1, "H"])] KB.append([x4, -1 * x1, -1 * x2, -1 * x3]) ######### Q ########### if key[2] == 'Q': l2 = [v * -1] if len(actions_police) > 0: for action in actions_police: l2.append(dict_p_to_int[tuple( [key[0], key[1] - 1, action])]) if turn > 2: l2.append(dict_p_to_int[tuple( [key[0], key[1] - 2, action])]) KB.append(l2) result = {} with Minisat22(bootstrap_with=KB) as m: for q in goals: r1 = m.solve(assumptions=[dict_p_to_int[q]]) r2 = m.solve(assumptions=[-1 * dict_p_to_int[q]]) if r1 == False: result[q] = 'F' elif r1 == r2: result[q] = '?' else: result[q] = 'T' return result
def hads_to_graphs(all_columns=True, transpose=True): if DEBUGGING: start_time = datetime.datetime.now() translate = { '0': [-1, -1, -1, -1], '1': [-1, -1, -1, 1], '2': [-1, -1, 1, -1], '3': [-1, -1, 1, 1], '4': [-1, 1, -1, -1], '5': [-1, 1, -1, 1], '6': [-1, 1, 1, -1], '7': [-1, 1, 1, 1], '8': [1, -1, -1, -1], '9': [1, -1, -1, 1], 'A': [1, -1, 1, -1], 'B': [1, -1, 1, 1], 'C': [1, 1, -1, -1], 'D': [1, 1, -1, 1], 'E': [1, 1, 1, -1], 'F': [1, 1, 1, 1] } #tracks the number of graphs and hadamard matrices hctr = 0 gctr = 0 mults_to_clauses = dict() emap = dict() ectr = 0 for a in range(K): for b in range(a + 1, K): ectr += 1 emap[ectr] = (a, b) emap[(a, b)] = ectr re_emap = dict() ectr = 0 for b in range(K): for a in range(b): ectr += 1 #re_emap[(a,b)] = ectr re_emap[emap[(a, b)]] = ectr print('relabeled index of', (a, b), 'from', emap[(a, b)], 'to', ectr, file=sys.stderr) #return if all_columns: max_col = K - 1 else: max_col = 0 for curr_line in fileinput.input(): myh = [] #print('curr line is:') #print(curr_line) #print('just did it') #print('currline[:-1] is:') #print(curr_line[:-1]) #print('just did it') #print() if DEBUGGING: print('the entries of curr line are:', file=sys.stderr) for s in curr_line: print(s) for s in curr_line[:-1]: if DEBUGGING: print(s, file=sys.stderr) print(translate[s], file=sys.stderr) myh.extend(translate[s]) myh = matrix([myh[i * K:(i + 1) * K] for i in range(K)]) #for line in chunk.splitlines(): # myh = [] # for s in line: # myh.extend(translate[s]) #myh = matrix([myh[i*K:(i+1)*K] for i in range(K)]]) if VERBOSE: print('trying matrix', hctr, '...', file=sys.stderr) for col in range(max_col + 1): hh = swap_cols(myh, 0, col) dd = diagonal_matrix([hh[j, 0] for j in range(K)]) hh = dd * hh dd = diagonal_matrix([hh[0, j] for j in range(K)]) hh = hh * dd if transpose: newhh = [] for i in range(K): newhh.append([hh[j, i] for j in range(K)]) hh = matrix(newhh) nclauses = 0 nvars = K * (K - 1) / 2 if SOLVER_NUM == 0: g = Glucose3() if SOLVER_NUM == 1: g = Glucose4() if SOLVER_NUM == 2: g = Lingeling() if SOLVER_NUM == 3: g = MapleChrono() if SOLVER_NUM == 4: g = MapleCM() if SOLVER_NUM == 5: g = Maplesat() if SOLVER_NUM == 6: g = Minicard() if SOLVER_NUM == 7: g = Minisat22() if SOLVER_NUM == 8: g = MinisatGH() matchings = dict() ectr = 0 for b in range(K - 1): ectr += 1 my_row = [0 for i in range(K - 1)] my_row[b] = K my_row = tuple(my_row) matchings[my_row] = [(ectr, 0, b)] for a in range(1, K): for b in range(a + 1, K): if DEBUGGING: print('trying', (a, b), file=sys.stderr) ectr += 1 hab = tuple([hh[a, j] * hh[b, j] for j in range(K)]) my_row = [] for j in range(1, K): dot = 0 for k in range(K): dot += hab[k] * hh[j, k] my_row.append(dot) my_row = tuple(my_row) if my_row in matchings: matchings[my_row].append((ectr, a, b)) old_ectr = matchings[my_row][0][0] if DEBUGGING: print('the old ectr,ectr=', old_ectr, ectr, file=sys.stderr) g.add_clause((re_emap[old_ectr], -re_emap[ectr])) g.add_clause((-re_emap[old_ectr], re_emap[ectr])) nclauses += 2 else: matchings[my_row] = [(ectr, a, b)] coes_to_inds = dict() mults = [] for i in range(K - 1): coe = my_row[i] if coe in coes_to_inds: coes_to_inds[coe].append(i) else: coes_to_inds[coe] = [i] mults = [(coe, len(coes_to_inds[coe])) for coe in coes_to_inds if coe] mults.sort() mults = tuple(mults) if mults in mults_to_clauses: old_ectr, num_new_vars, old_coes_to_inds, old_clauses = mults_to_clauses[ mults] #must relabel the old indices to match the new ones #for each coefficient c relab = dict() for coe in old_coes_to_inds: coe_ctr = 0 for old_index in old_coes_to_inds[coe]: relab[1 + old_index] = re_emap[ 1 + coes_to_inds[coe][coe_ctr]] relab[-1 - old_index] = -re_emap[ 1 + coes_to_inds[coe][coe_ctr]] coe_ctr += 1 relab[old_ectr] = re_emap[ectr] relab[-old_ectr] = -re_emap[ectr] for i in range(1, 1 + num_new_vars): relab[old_ectr + i] = i + nvars relab[-old_ectr - i] = -i - nvars for curr_clause in old_clauses: g.add_clause([relab[k] for k in curr_clause]) nclauses += len(old_clauses) nvars += num_new_vars else: if DEBUGGING: print('dealing with', mults, 'for the first time...', file=sys.stderr) cnf = PBEnc.equals(lits=range(1, K) + [ectr], weights=list(my_row) + [-K], bound=0, encoding=4) curr_clauses, maxvar = simplify_clause_list( cnf.clauses, ectr + 1) num_new_vars = maxvar - ectr if DEBUGGING: print("", file=sys.stderr) print("", file=sys.stderr) print('adding new clauses; there are', nvars, 'vars', file=sys.stderr) for curr_clause in curr_clauses: if DEBUGGING: print('relabeling clause', c, 'with ectr=', ectr, 'and', nvars, 'vars', file=sys.stderr) new_clause = [] for k in curr_clause: if abs(k) <= ectr: if k > 0: new_clause.append(re_emap[k]) else: new_clause.append(-re_emap[-k]) else: if k > 0: if DEBUGGING: print(k, 'is the', k - ectr, 'th dummy...', 'shift it up by', nvars, file=sys.stderr) new_clause.append(k - ectr + nvars) else: new_clause.append(k + ectr - nvars) if DEBUGGING: print(k, 'is the', k + ectr, 'th dummy...', 'shift it down by', nvars, file=sys.stderr) if DEBUGGING: print(' adding', new_clause, file=sys.stderr) g.add_clause(new_clause) nvars += num_new_vars nclauses += len(curr_clauses) mults_to_clauses[mults] = (ectr, num_new_vars, coes_to_inds, curr_clauses) if DEBUGGING: print('now there are', (nvars, nclauses), 'vars,clauses', file=sys.stderr) sol_ctr = 0 if VERBOSE: print('there are', nvars, 'variables and', nclauses, 'clauses', file=sys.stderr) print('trying to find all solutions!', file=sys.stderr) if True: #nvars >= 2000: while g.solve(): new_sol = g.get_model() sol_ctr += 1 if sol_ctr % 1000 == 0: print(' ', sol_ctr, 'found so far...', file=sys.stderr) gctr += 1 #nx.write_graph6(nx.Graph([emap[k] for k in new_sol[:K*(K-1)/2] if k > 0]), sys.stdout, nodes = range(K)) #print( str([emap[k] for k in new_sol[:K*(K-1)/2] if k > 0]), file = sys.stdout ) g.add_clause( [-new_sol[1 + j * (j + 1) / 2] for j in range(K - 1)]) #print([k for k in new_sol[:K*(K-1)/2] if k > 0], file = sys.stderr) #print('which is really:', file = sys.stderr) #print([re_emap[emap[k]] for k in new_sol[:K*(K-1)/2] if k > 0], file = sys.stderr) #print('got written as\n', file = sys.stderr) print(sol_to_g6(new_sol[:K * (K - 1) / 2]), file=sys.stdout) #g.add_clause( [-new_sol[j] for j in range(K-1)] ) if VERBOSE: print(sol_ctr, 'solutions found!', file=sys.stderr) if DEBUGGING: end_time = datetime.datetime.now() elapsed_time = end_time - start_time print('total time elapsed:', elapsed_time.seconds, ":", elapsed_time.microseconds, 'matrices solved:', hctr, file=sys.stderr) else: if VERBOSE: print('too hard for now!', file=sys.stderr) hctr += 1 return
def qbf(v_forall, F): ''' Implementation of the CEGAR 2-QBF algorithm forall x, exists y, F For efficiency reason, x and y would better be sets ''' syn_man = [] ver_man = F max_id = 1 + max( [ max( [abs(x) for x in cnf] ) for cnf in F ] ) universal_clauses = [] for dnf in F: for x in dnf: if abs(x) in v_forall: universal_clauses.append(dnf) break # print("universal clauses:", universal_clauses) gas = 16 i = 0 while i < gas: sol_x = None sol_y = None # find solution for synMan if syn_man == []: sol_x = v_forall else: with Minisat22(bootstrap_with= syn_man) as m: if m.solve(): sol_x = m.get_model() if sol_x is None: return True sol_x = list( filter(lambda x: abs(x) in v_forall, sol_x) ) # print("sol_x", sol_x) # find solution for VerMan with Minisat22(bootstrap_with= ver_man) as m: if m.solve(assumptions=sol_x): sol_y = m.get_model() if sol_y is None: return False # print("sol_y", sol_y) sol_y = set( filter(lambda x: abs(x) not in v_forall, sol_y) ) # update synMan # 1. fill in values in sol_y and reduce universal_clauses cl = fill_in_simplify(universal_clauses, sol_y) # print("cl:", cl) # 2. tseitin transform "not cl" res, max_id = negate_clauses(cl, max_id) # print("res:", res) if res == []: # no more cases for x need to be considered, done return True for dnf in res: syn_man.append(dnf) # print("syn_man:", syn_man) syn_man = deduplicate(syn_man) # print("syn_man:", syn_man) i += 1 # print("run out of gas!!") return True
from pysat.solvers import Minisat22 from pysat.formula import CNF import math ################ using minisat to solve n-queens ############# #file1= open("queen2sat.cnf","a"); formula = CNF(from_file='queen2sat.cnf') #print(formula.clauses) m = Minisat22(bootstrap_with=formula.clauses, use_timer=True) #m.solve() control = False while (m.solve() == True): s = (m.get_model()) int_list = [i * -1 for i in s] #print(s) #print('{0:.2f}s'.format(s.time())) print('{0:.5f}s'.format(m.time_accum())) with open('require_input', 'r') as fr: read_data = fr.read() rd = read_data.split(' ') #print(read_data) rd = [int(i) for i in rd] #print(rd) rd_set = set(rd) ans = set(s) result = rd_set.intersection(ans) #print(result) if rd[0] == 0: print("No given queen's position") break elif len(result) == len(rd):
def analyse_sat_solvers(games: [GameEncoder], show_png=False): from timeit import default_timer as timer from pysat.solvers import Cadical, Glucose4, Lingeling, Minisat22, Maplesat df = pd.DataFrame(columns=["Solver", "Execution time [sec]", "Algorithm"]) for g in games: cnf_ = CNF(from_string=as_DIMACS_CNF(g.get_cnf_solution())) solvers = { "Cadical": Cadical(cnf_), "Glucose4": Glucose4(cnf_), "Lingeling": Lingeling(cnf_), "Minisat22": Minisat22(cnf_), "Maplesat": Maplesat(cnf_) } for name, solver in solvers.items(): start = timer() solved = solver.solve() end = timer() delta_t = end - start print(name, "\tSolved:", solved, "\tTime:", delta_t) df = df.append( { "Solver": name, "Execution time [sec]": delta_t, "Algorithm": g.algo_name }, ignore_index=True) df.to_csv("data\\solver_analysis.csv", index=False) print("Saved data-frame as csv.") plt.yscale('log') sns.barplot(x="Solver", y="Execution time [sec]", hue="Algorithm", data=df) plt.savefig("data\\solver_performance_analysis.png") if show_png: print("Plotting graph...") plt.show() class EncodingPerformanceAnalysis: def __init__(self, efficient=True): print( f"EFFICIENT={efficient}: Creating and solving multiple games, this might take a while..." ) paths = glob.glob("tent-inputs\\*.txt") self.efficient = efficient self.games = [ GameEncoderBinomial.from_text_file(path, efficient=self.efficient, verbose=False) for path in paths ] self.games_cnf = [g.get_cnf_solution() for g in self.games] def store_metrics(self): df = pd.DataFrame(columns=[ "Field-size", "Literals", "Variables", "Clauses", "Algorithm" ]) for index, cnf in enumerate(self.games_cnf): game_size = self.games[index].capacity clauses_n = len(cnf) literals = list(chain(*cnf)) variables = set(abs(x) for x in literals) df = df.append( { "Algorithm": "Efficient" if self.efficient else "Simple", "Clauses": clauses_n, "Field-size": game_size, "Literals": len(literals), "Variables": len(variables) }, ignore_index=True) df.Capacity = df.Capacity.astype(int) df.Literals = df.Literals.astype(int) df.Variables = df.Variables.astype(int) time_id = datetime.datetime.now().strftime('%m-%d_%H-%M-%S') df.to_csv(f"data\\encoding_performance_analysis_{time_id}.csv", index=False) print("Saved data-frame as csv.")
# encode(i,j,k) # i represent the vertical line - 1 # j represent the horizontal line - 1 # j represent the value on a specific position - 1 phi6 = [[encode(0, 4, 1)], [encode(0, 7, 0)], [encode(0, 8, 6)], [encode(1, 1, 2)], [encode(1, 5, 6)], [encode(1, 8, 7)], [encode(2, 4, 8)], [encode(2, 6, 5)], [encode(3, 1, 7)], [encode(3, 3, 8)], [encode(3, 5, 1)], [encode(3, 7, 5)], [encode(4, 0, 3)], [encode(4, 2, 5)], [encode(4, 6, 2)], [encode(4, 8, 1)], [encode(5, 1, 1)], [encode(5, 3, 5)], [encode(5, 5, 2)], [encode(5, 7, 6)], [encode(6, 2, 6)], [encode(6, 4, 5)], [encode(7, 0, 7)], [encode(7, 3, 6)], [encode(7, 7, 4)], [encode(8, 0, 1)], [encode(8, 1, 4)], [encode(8, 4, 2)]] # This part of the program launches the SAT solver with the conjunction of the constraints, # ie the concatenation of the lists representing them. with Minisat22(bootstrap_with=phi1 + phi2 + phi3 + phi4 + phi5 + phi6) as m: if m.solve(): model = [decode(v) for v in m.get_model() if v > 0] r = [[0 for i in l] for j in l] for (i, j, k) in model: r[i][j] += k + 1 print("\n") for ligne in r: print(ligne) else: print("There's no solution")
# Zephaniah Hill # The University of Michigan -- EECS 598 # July 2, 2018 from pysat.solvers import Solver, Minisat22 # import the needed libraries # The formula we solve using minisat is: # (x+y+z)*(!x+!y+!z) # to encode these we define an integer for each variable # {x = 1, y = 2, z = 3} # The structure is a list of lists, where each sublist is a subformula which is ANDed to the other items in the superlist. # (x+y+z) = [1, 2, 3] # (!x+!y+!z) = [-1, -2, -3] the negation operator is signified by a negative integer. CNF_formula = [[1, 2, 3], [1, 2, 3]] with Minisat22(bootstrap_with=CNF_formula, use_timer=True) as m: print(m.solve()) # solve using minisat print(m.time())
for p in problems_all: if str(p) in seen_set: continue else: seen_set.add(str(p)) if len(p) > 1000: # print("passed") continue sat = False # print(len(p)) with Minisat22(bootstrap_with=p) as m: # g = Glucose3() # for l in p: # g.add_clause(l) # # # print("loaded") if m.solve(): sat = True solved += 1 total += 1 tagged_data.append((p, sat)) # if total % 1 == 0: print(solved,total,solved/total) np.save(str(i) + "_tagged_data.npy", tagged_data) print(solved, total, solved / total)
clauses = [] for row in rows: nums = row.split() clauses.append([int(num) for num in nums[:len(nums)-1]]) clauses_2 = [] clauses_3 = [] solver_calls = 0 i = 0 M = [] while len(clauses) > 0: clauses_2 = clauses[:i] clauses_3 = clauses_2 + M with Minisat22(bootstrap_with=clauses_3) as m: solver_calls += 1 if m.solve(): i+=1 model = m.get_model() else: clauses = clauses_2[:i-1] # if i is 0 it means that M is already unsatisfiable if i == 0: break M.append(clauses_2[i-1]) i = 0 print 'solver calls', solver_calls print 'MUS length', len(M)