def read_kb(filename): """ Creates a knowledge base from file in DIMACS format. :param filename: File's relative address. :return: Sentence instance. """ if not os.path.isfile(filename): print('ERROR: iofiles read_kb -> ' + filename + ' not found') exit() f = open(filename, 'r') # consume comments in the preamble. comment lines start with a 'c' for line in f: if line[0] != 'c': break # the next line in the file contains info on the number of clauses and # variables. the line begins with a 'p' and the format (cnf). # example line: 'p cnf 5 3' --> 5 variables and 3 clauses (nbvar, nclauses)= [int(i) for i in line.split()[2:]] new_kb = Sentence(nbvar) # each of the next lines in the file represents a clause. each line ends # with a '0'. example line: ' 1 -5 4 0' # save the clauses into an object for line in f: while line[0] == ' ': line = line[1:len(line)] if line[0] == '%': break aux_list = list() for variable in line.split()[:-1]: # discard the ending '0' variable = int(variable) aux_list.append(variable) new_kb.add_clause(tuple(aux_list)) f.close() return new_kb
import copy from sentence import Sentence from wsat import WSat import iofiles from gsat import GSat import time kb3 = Sentence(14) kb3.add_clause((-3, -14)) kb3.add_clause((14,)) kb3.add_clause((9,)) kb3.add_clause((14, -5)) kb3.add_clause((5, 3, -9)) kb3.add_clause((3,)) print(kb3.pure_symbols()) """ kb3 = iofiles.read_kb('problems/uf50-01.cnf') print(kb3) walk = WSat(kb3, 0.5, 1000) greedy = GSat(kb3, 5, 200) start = time.time() print(walk.solve())