Exemple #1
0
 def _search_solver_helper(self, sent, symbols):    
     m = sent.implicit_model()
     unassigned_symbols = sorted(symbols - m.keys())  # TODO: different orders
     if len(unassigned_symbols) == 0:
         if sent.check_model(m):
             return m
         else:
             return None
     else:
         next_symbol = unassigned_symbols[0]
         negative_unit_clause = Clause([Literal(next_symbol, polarity=False)])
         closure = limited_unit_resolution_closure(negative_unit_clause,
                                                   sent.clauses)
         if cnf.c('FALSE') not in closure:
             sat_if_false = self._search_solver_helper(Cnf(closure), symbols) 
             if sat_if_false != None: # early termination if already satisfied
                 return sat_if_false
         positive_unit_clause = Clause([Literal(next_symbol, polarity=True)])
         closure = limited_unit_resolution_closure(positive_unit_clause,
                                                   sent.clauses)
         if cnf.c('FALSE') not in closure:                
             sat_if_true = self._search_solver_helper(Cnf(closure), symbols)
             return sat_if_true 
         else:
             return None
    def write(self, file_name, cnf: Cnf):

        file_path = path.join(
            path.join(self.this_file_path, self.output_folder_name), file_name)

        print('writing: ' + str(file_path))

        num_clause = cnf.get_number_of_clauses()
        num_literals = cnf.get_number_of_literals()

        title = 'c\nc start with comments\nc\np cnf %d %d\n' % (num_literals,
                                                                num_clause)

        open(file_path, 'w').write(title + cnf.get_cnf_string(with_zero=True))
 def cnf(self):
     num_symbols = self.box_width * self.box_width
     clause_strs = []
     for zone in self.zones():
         for digit in irange(1, num_symbols):
             clause_strs += exactly_one_clauses(zone, digit)
     clause_strs += nonempty_clauses(self.box_width)
     clauses = [cnf.c(clause) for clause in clause_strs]
     return Cnf(list(set(clauses)))
def unit_resolution(unit_clause, sent):
    clauses = sent.clauses
    processed = set(clauses)
    unprocessed = [unit_clause]
    result = general_resolution_solver(processed, unprocessed, lambda x: len(x) == 1)
    if result is not None:
        return Cnf(result)
    else:
        return None
Exemple #5
0
 def cnf(self):
     clauses = self.general_clauses()
     for row in range(len(self.matrix)):
         for col in range(len(self.matrix[row])):
             digit = self.matrix[row][col]
             if digit != 0:
                 clause = cnf.c(lit(digit, row+1, col+1))
                 clauses.append(clause)
     return Cnf(clauses)
Exemple #6
0
 def _search_solver_helper(self, sent, symbols):                       
     m = sent.implicit_model()
     unassigned_symbols = sorted(symbols - m.keys())
     if len(unassigned_symbols) == 0:
         if sent.check_model(m):
             return m, [m]
         else:
             return None, [m]
     else:
         next_symbol = unassigned_symbols[0]
         negative_unit_clause = Clause([Literal(next_symbol, polarity=False)])
         sent_if_false = Cnf(sent.clauses | { negative_unit_clause })            
         sat_if_false, models_if_false = self._search_solver_helper(sent_if_false, symbols)            
         if sat_if_false != None: # early termination if already satisfied
             return sat_if_false, models_if_false
         positive_unit_clause = Clause([Literal(next_symbol, polarity=True)])
         sent_if_true = Cnf(sent.clauses | { positive_unit_clause })
         sat_if_true, models_if_true = self._search_solver_helper(sent_if_true, symbols) 
         return sat_if_true, models_if_false + models_if_true  
Exemple #7
0
    def test(self, f):
        self.case += 1
        self.tested += 1
        print("CASE %d: %s" % (self.case, f.toString()))
        cnf = CnfClause()
        try:
            start = now()
            cnf = f.toCnf()
            duration = now() - start
        except KeyboardInterrupt:
            raise KeyboardInterrupt()
        except:
            printException()
            if stopOnError:
                raise FailedTestException()
            return

        deg = self.formulaDeg(f)
        size = self.cnfSize(cnf)

        print('CNF: time: %12.9f   f.deg: %3d   cnf.size: %3d' %
              (duration, deg, size))

        if not isinstance(cnf, Cnf):
            print('FAILED: not a Cnf: %s' % type(cnf))
            print()
            return

        start = now()
        equiSatisfiable = self.satisfiableFormula(f) == self.satisfiableCnf(
            cnf)
        equivalent = self.formulaVars(f).issubset(self.cnfVars(cnf)) and \
                all(self.formulaEval(f, i) == self.cnfEval(cnf, i) for i in self.interpretations(self.cnfVars(cnf)))
        duration = now() - start

        if equivalent:
            self.equiv += 1

        self.size += size
        self.time += duration

        if equiSatisfiable:
            self.passed += 1
            print('PASSED: testTime: %12.9f    equiSatisfiable %s' %
                  (duration, 'equivalent' if equivalent else ''))
        else:
            if len(cnf) < 20:
                print('FAILED: \n-----CNF-----\n%s%s' %
                      (cnf.toString(), '-' * 13))
            else:
                print('FAILED: \n-----CNF-----\n%s...\n%s' %
                      (Cnf(cnf[:20]).toString(), '-' * 13))
            if stopOnError:
                raise FailedTestException()
        print()
    def generate(self):
        num_of_var = self.num_of_var + self.get_variation(self.num_of_var)
        num_of_clause = self.num_of_clause + self.get_variation(
            self.num_of_clause)

        clause_list = list()
        for i in range(num_of_clause):
            num_of_var_per_clause = self.num_of_var_per_clause + self.get_variation(
                self.num_of_var_per_clause)
            var_list = list()
            for j in range(num_of_var_per_clause):
                signal = 1
                if rd() > 0.5:
                    signal = -1
                var_str = str(int(signal * round(num_of_var * rd() + 1)))
                var = Variable(var_str)
                var_list.append(var)
            clause = Clause(var_list)
            clause_list.append(clause)

        cnf = Cnf(clause_list)

        return cnf
Exemple #9
0
 def testCnfRead(self, dimacs, varMap, ecnf):
     iF = io.StringIO(dimacs)
     cnf = Cnf.readFromFile(iF, varMap)
     self.compare(cnf.toString(), ecnf.toString(),
                  'Cnf.readFromFile %s' % ecnf.toString())
Exemple #10
0
            'a': False
        }, False),
    ])

    t.testCnf(CnfClause([CnfLit('a'), CnfLit.Not('a')]), 'a -a', [
        ({
            'a': True
        }, True),
        ({
            'a': False
        }, True),
    ])

    t.testCnf(
        Cnf([
            CnfClause([CnfLit('a'), CnfLit.Not('b')]),
            CnfClause([CnfLit('b')]),
        ]), 'a -b\nb\n', [
            ({
                'a': True,
                'b': True
            }, True),
            ({
                'a': True,
                'b': False
            }, False),
            ({
                'a': False,
                'b': True
            }, False),
            ({
                'a': False,
Exemple #11
0
 def testCnfRead(self, dimacs, varMap, ecnf):
     iF = io.StringIO(dimacs)
     cnf = Cnf.readFromFile(iF, varMap)
     self.compare(cnf.toString(), ecnf.toString(), 'Cnf.readFromFile %s' % ecnf.toString())
Exemple #12
0
 def __call__(self, sent):
     symbols = sent.symbols()
     sent = Cnf(unit_resolution_closure(sent.clauses))
     result = self._search_solver_helper(sent, symbols)
     return result
Exemple #13
0
    def test(self, f: Formula) -> None:
        self.case += 1
        self.tested += 1
        print("CASE %d: %s" % (self.case, f.toString()))
        cnf = Cnf()
        try:
            start = now()
            cnf = f.toCnf()
            duration = now() - start
        except KeyboardInterrupt:
            raise KeyboardInterrupt()
        except:
            printException()
            if stopOnError:
                raise FailedTestException()
            return

        deg = self.formulaDeg(f)
        size = self.cnfSize(cnf)
        fVars = self.formulaVars(f)
        cnfVars = self.cnfVars(cnf)

        print(
            'CNF: time: %12.9f   fVars: %3d  f.deg: %3d    cnfVars: %3d  cnf.size: %3d'
            % (duration, len(fVars), deg, len(cnfVars), size))
        print('fVars:   %r' % (sorted(fVars), ))
        print('cnfVars: %r' % (sorted(cnfVars), ))

        if not isinstance(cnf, Cnf):
            print('FAILED: not a CNF (must be an instanse of Cnf): %s' %
                  type(cnf))
            print()
            return

        for i, cls in enumerate(cnf):
            if not isinstance(cls, Clause):
                print(
                    'FAILED: not a CNF, %d-th clause is not an instance of Clause: %s'
                    % (i, type(cnf)))
                print()
                return
            for j, lit in enumerate(cls):
                if not isinstance(lit, Literal):
                    print(
                        'FAILED: not a CNF, %d-th literal of %d-th clause is not a Literal: %s'
                        % (j, i, type(cnf)))
                    print()
                    return

        start = now()
        equiSatisfiable = self.satisfiableFormula(f) == self.satisfiableCnf(
            cnf)
        allVars = fVars.union(cnfVars)
        equivalent = all(
            self.formulaIsSatisfied(f, v) == self.cnfIsSatisfied(cnf, v)
            for v in self.valuations(allVars))
        durationTest = now() - start

        if equivalent:
            self.equiv += 1

        self.size += size
        self.time += duration

        if equiSatisfiable:
            self.passed += 1
            print('PASSED: testTime: %12.9f    equiSatisfiable %s' %
                  (durationTest, 'equivalent' if equivalent else ''))
        else:
            if len(cnf) < 20:
                print('FAILED: \n-----CNF-----\n%s%s' % (str(cnf), '-' * 13))
            else:
                print('FAILED: \n-----CNF-----\n%s...\n%s' %
                      (str(cnf[:20]), '-' * 13))
            if stopOnError:
                raise FailedTestException()
        print()