Newer
Older
"""Representations and Inference for Logic (Chapters 7-9, 12)
Covers both Propositional and First-Order Logic. First we have four
important data types:
KB Abstract class holds a knowledge base of logical expressions
KB_Agent Abstract class subclasses agents.Agent
Expr A logical expression, imported from utils.py
substitution Implemented as a dictionary of var:value pairs, {x:1, y:x}
Be careful: some functions take an Expr as argument, and some take a KB.
Logical expressions can be created with Expr or expr, imported from utils, TODO
or with expr, which adds the capability to write a string that uses
the connectives ==>, <==, <=>, or <=/=>. But be careful: these have the
operator precedence of commas; you may need to add parens to make precedence work.
Then we implement various functions for doing logical inference:
pl_true Evaluate a propositional logical sentence in a model
tt_entails Say if a statement is entailed by a KB
pl_resolution Do resolution on propositional sentences
dpll_satisfiable See if a propositional sentence is satisfiable
And a few other functions:
to_cnf Convert to conjunctive normal form
unify Do unification of two FOL sentences
diff, simp Symbolic differentiation and simplification
Donato Meoli
a validé
import heapq
Donato Meoli
a validé
import itertools
import random
Donato Meoli
a validé
from collections import defaultdict, Counter
import networkx as nx
Donato Meoli
a validé
from agents import Agent, Glitter, Bump, Stench, Breeze, Scream
from csp import parse_neighbors, UniversalDict
Donato Meoli
a validé
from search import astar_search, PlanRoute
Donato Meoli
a validé
from utils import (remove_all, unique, first, argmax, probability, isnumber,
issequence, Expr, expr, subexpressions, extend)
# ______________________________________________________________________________
class KB:
"""A knowledge base to which you can tell and ask sentences.
To create a KB, first subclass this class and implement
tell, ask_generator, and retract. Why ask_generator instead of ask?
The book is a bit vague on what ask means --
For a Propositional Logic KB, ask(P & Q) returns True or False, but for an
FOL KB, something like ask(Brother(x, y)) might return many substitutions
such as {x: Cain, y: Abel}, {x: Abel, y: Cain}, {x: George, y: Jeb}, etc.
So ask_generator generates these one at a time, and ask either returns the
first one or returns False."""
def __init__(self, sentence=None):
def ask(self, query):
"""Return a substitution that makes the query true, or, failing that, return False."""
def ask_generator(self, query):
"""Yield all the substitutions that make query true."""
def retract(self, sentence):
class PropKB(KB):
"""A KB for propositional logic. Inefficient, with no indexing."""
def __init__(self, sentence=None):
self.clauses = []
if sentence:
self.tell(sentence)
"""Yield the empty substitution {} if KB entails query; else no results."""
if tt_entails(Expr('&', *self.clauses), query):
yield {}
def ask_if_true(self, query):
"""Return True if the KB entails query, else return False."""
Darius Bacon
a validé
for _ in self.ask_generator(query):
Darius Bacon
a validé
return False
def retract(self, sentence):
"""Remove the sentence's clauses from the KB."""
for c in conjuncts(to_cnf(sentence)):
if c in self.clauses:
self.clauses.remove(c)
# ______________________________________________________________________________
def KB_AgentProgram(KB):
"""A generic logical knowledge-based agent program. [Figure 7.1]"""
steps = itertools.count()
def program(percept):
KB.tell(make_percept_sentence(percept, t))
action = KB.ask(make_action_query(t))
KB.tell(make_action_sentence(action, t))
return action
return Expr("Percept")(percept, t)
return expr("ShouldDo(action, {})".format(t))
return Expr("Did")(action[expr('action')], t)
return program
def is_symbol(s):
"""A string s is a symbol if it starts with an alphabetic char.
>>> is_symbol('R2D2')
True
"""
return isinstance(s, str) and s[:1].isalpha()
def is_var_symbol(s):
"""A logic variable symbol is an initial-lowercase string.
>>> is_var_symbol('EXE')
False
"""
return is_symbol(s) and s[0].islower()
def is_prop_symbol(s):
"""A proposition logic symbol is an initial-uppercase string.
>>> is_prop_symbol('exe')
False
"""
return is_symbol(s) and s[0].isupper()
"""Return a set of the variables in expression s.
>>> variables(expr('F(x, x) & G(x, y) & H(y, z) & R(A, z, 2)')) == {x, y, z}
return {x for x in subexpressions(s) if is_variable(x)}
def is_definite_clause(s):
"""Returns True for exprs s of the form A & B & ... & C ==> D,
where all literals are positive. In clause form, this is
~A | ~B | ... | ~C | D, where exactly one clause is positive.
>>> is_definite_clause(expr('Farmer(Mac)'))
True
"""
if is_symbol(s.op):
return True
antecedent, consequent = s.args
all(is_symbol(arg.op) for arg in conjuncts(antecedent)))
withal
a validé
def parse_definite_clause(s):
"""Return the antecedents and the consequent of a definite clause."""
withal
a validé
assert is_definite_clause(s)
if is_symbol(s.op):
return [], s
else:
antecedent, consequent = s.args
return conjuncts(antecedent), consequent
withal
a validé
A, B, C, D, E, F, G, P, Q, a, x, y, z, u = map(Expr, 'ABCDEFGPQaxyzu')
Donato Meoli
a validé
# ______________________________________________________________________________
def tt_entails(kb, alpha):
"""Does kb entail the sentence alpha? Use truth tables. For propositional
kb's and sentences. [Figure 7.10]. Note that the 'kb' should be an
Expr which is a conjunction of clauses.
>>> tt_entails(expr('P & Q'), expr('Q'))
True
"""
assert not variables(alpha)
def tt_check_all(kb, alpha, symbols, model):
"""Auxiliary routine to implement tt_entails."""
if not symbols:
if pl_true(kb, model):
result = pl_true(alpha, model)
assert result in (True, False)
return result
else:
return True
else:
P, rest = symbols[0], symbols[1:]
return (tt_check_all(kb, alpha, rest, extend(model, P, True)) and
tt_check_all(kb, alpha, rest, extend(model, P, False)))
def prop_symbols(x):
if not isinstance(x, Expr):
elif is_prop_symbol(x.op):
return {symbol for arg in x.args for symbol in prop_symbols(arg)}
return {symbol for arg in x.args for symbol in constant_symbols(arg)}
def predicate_symbols(x):
"""Return a set of (symbol_name, arity) in x.
All symbols (even functional) with arity > 0 are considered."""
if not isinstance(x, Expr) or not x.args:
return set()
pred_set = {(x.op, len(x.args))} if is_prop_symbol(x.op) else set()
pred_set.update({symbol for arg in x.args for symbol in predicate_symbols(arg)})
return pred_set
def tt_true(s):
"""Is a propositional sentence a tautology?
>>> tt_true('P | ~P')
True
"""
def pl_true(exp, model={}):
"""Return True if the propositional logic expression is true in the model,
and False if it is false. If the model does not specify the value for
every proposition, this may return None to indicate 'not obvious';
this may happen even when the expression is tautological.
>>> pl_true(P, {}) is None
True
"""
op, args = exp.op, exp.args
return model.get(exp)
elif op == '~':
p = pl_true(args[0], model)
if p is None:
return None
else:
return not p
elif op == '|':
result = False
for arg in args:
p = pl_true(arg, model)
if p is True:
return True
if p is None:
result = None
return result
elif op == '&':
result = True
for arg in args:
p = pl_true(arg, model)
if p is False:
return False
if p is None:
result = None
return result
p, q = args
return pl_true(~p | q, model)
return pl_true(p | ~q, model)
pt = pl_true(p, model)
qt = pl_true(q, model)
if op == '<=>':
return pt == qt
elif op == '^': # xor or 'not equivalent'
return pt != qt
else:
raise ValueError("illegal operator in logic expression" + str(exp))
# ______________________________________________________________________________
def to_cnf(s):
"""Convert a propositional logical sentence to conjunctive normal form.
That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253]
(~B & ~C)
"""
if isinstance(s, str):
s = expr(s)
s = eliminate_implications(s) # Steps 1, 2 from p. 253
s = move_not_inwards(s) # Step 3
return distribute_and_over_or(s) # Step 4
def eliminate_implications(s):
"""Change implications into equivalent form with only &, |, and ~ as logical operators."""
a, b = args[0], args[-1]
return b | ~a
return a | ~b
elif s.op == '<=>':
return (a | ~b) & (b | ~a)
assert len(args) == 2 # TODO: relax this restriction
return Expr(s.op, *args)
def move_not_inwards(s):
"""Rewrite sentence s by moving negation sign inward.
>>> move_not_inwards(~(A | B))
if s.op == '~':
def NOT(b):
return move_not_inwards(~b)
a = s.args[0]
if a.op == '~':
return move_not_inwards(a.args[0]) # ~~A ==> A
if a.op == '&':
return associate('|', list(map(NOT, a.args)))
if a.op == '|':
return associate('&', list(map(NOT, a.args)))
return s
elif is_symbol(s.op) or not s.args:
return s
else:
return Expr(s.op, *list(map(move_not_inwards, s.args)))
def distribute_and_over_or(s):
"""Given a sentence s consisting of conjunctions and disjunctions
of literals, return an equivalent sentence in CNF.
>>> distribute_and_over_or((A & B) | C)
((A | C) & (B | C))
"""
if s.op == '|':
if s.op != '|':
return distribute_and_over_or(s)
return distribute_and_over_or(s.args[0])
conj = first(arg for arg in s.args if arg.op == '&')
if not conj:
others = [a for a in s.args if a is not conj]
rest = associate('|', others)
return associate('&', [distribute_and_over_or(c | rest)
for c in conj.args])
elif s.op == '&':
return associate('&', list(map(distribute_and_over_or, s.args)))
else:
return s
def associate(op, args):
"""Given an associative op, return an expression with the same
meaning as Expr(op, *args), but flattened -- that is, with nested
instances of the same op promoted to the top level.
>>> associate('&', [(A&B),(B|C),(B&C)])
(A & B & (B | C) & B & C)
>>> associate('|', [A|(B|(C|(A&B)))])
if len(args) == 0:
return _op_identity[op]
elif len(args) == 1:
return args[0]
else:
return Expr(op, *args)
_op_identity = {'&': True, '|': False, '+': 0, '*': 1}
"""Given an associative op, return a flattened list result such
that Expr(op, *result) means the same as Expr(op, *args).
>>> dissociate('&', [A & B])
[A, B]
"""
if arg.op == op:
collect(arg.args)
else:
result.append(arg)
def conjuncts(s):
"""Return a list of the conjuncts in the sentence s.
>>> conjuncts(A & B)
[A, B]
>>> conjuncts(A | B)
[(A | B)]
"""
def disjuncts(s):
"""Return a list of the disjuncts in the sentence s.
>>> disjuncts(A | B)
[A, B]
>>> disjuncts(A & B)
[(A & B)]
"""
# ______________________________________________________________________________
def pl_resolution(KB, alpha):
"""Propositional-logic resolution: say if alpha follows from KB. [Figure 7.12]
>>> pl_resolution(horn_clauses_KB, A)
True
"""
clauses = KB.clauses + conjuncts(to_cnf(~alpha))
new = set()
while True:
n = len(clauses)
pairs = [(clauses[i], clauses[j])
for i in range(n) for j in range(i + 1, n)]
for (ci, cj) in pairs:
resolvents = pl_resolve(ci, cj)
new = new.union(set(resolvents))
for c in new:
def pl_resolve(ci, cj):
"""Return all clauses that can be obtained by resolving clauses ci and cj."""
clauses = []
for di in disjuncts(ci):
for dj in disjuncts(cj):
if di == ~dj or ~di == dj:
Donato Meoli
a validé
clauses.append(associate('|', unique(remove_all(di, disjuncts(ci)) + remove_all(dj, disjuncts(cj)))))
return clauses
# ______________________________________________________________________________
"""A KB of propositional definite clauses."""
def tell(self, sentence):
assert is_definite_clause(sentence), "Must be definite clause"
self.clauses.append(sentence)
"""Yield the empty substitution if KB implies query; else nothing."""
if pl_fc_entails(self.clauses, query):
yield {}
def retract(self, sentence):
self.clauses.remove(sentence)
def clauses_with_premise(self, p):
"""Return a list of the clauses in KB that have p in their premise.
This could be cached away for O(1) speed, but we'll recompute it."""
if c.op == '==>' and p in conjuncts(c.args[0])]
def pl_fc_entails(KB, q):
"""Use forward chaining to see if a PropDefiniteKB entails symbol q.
[Figure 7.15]
Surya Teja Cheedella
a validé
>>> pl_fc_entails(horn_clauses_KB, expr('Q'))
True
"""
count = {c: len(conjuncts(c.args[0]))
for c in KB.clauses
if c.op == '==>'}
agenda = [s for s in KB.clauses if is_prop_symbol(s.op)]
while agenda:
p = agenda.pop()
if not inferred[p]:
inferred[p] = True
for c in KB.clauses_with_premise(p):
count[c] -= 1
if count[c] == 0:
agenda.append(c.args[1])
return False
Surya Teja Cheedella
a validé
""" [Figure 7.13]
Simple inference in a wumpus world example
"""
wumpus_world_inference = expr("(B11 <=> (P12 | P21)) & ~B11")
""" [Figure 7.16]
Propositional Logic Forward Chaining example
"""
horn_clauses_KB = PropDefiniteKB()
for s in "P==>Q; (L&M)==>P; (B&L)==>M; (A&P)==>L; (A&B)==>L; A;B".split(';'):
Surya Teja Cheedella
a validé
horn_clauses_KB.tell(expr(s))
"""
Definite clauses KB example
"""
definite_clauses_KB = PropDefiniteKB()
for clause in ['(B & F)==>E', '(A & E & F)==>G', '(B & C)==>F', '(A & B)==>D', '(E & F)==>H', '(H & I)==>J', 'A', 'B',
'C']:
definite_clauses_KB.tell(expr(clause))
# ______________________________________________________________________________
# DPLL-Satisfiable [Figure 7.17]
Donato Meoli
a validé
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def no_branching_heuristic(symbols, clauses):
return first(symbols), True
def min_clauses(clauses):
min_len = min(map(lambda c: len(c.args), clauses), default=2)
return filter(lambda c: len(c.args) == (min_len if min_len > 1 else 2), clauses)
def moms(symbols, clauses):
"""
MOMS (Maximum Occurrence in clauses of Minimum Size) heuristic
Returns the literal with the most occurrences in all clauses of minimum size
"""
scores = Counter(l for c in min_clauses(clauses) for l in prop_symbols(c))
return max(symbols, key=lambda symbol: scores[symbol]), True
def momsf(symbols, clauses, k=0):
"""
MOMS alternative heuristic
If f(x) the number of occurrences of the variable x in clauses with minimum size,
we choose the variable maximizing [f(x) + f(-x)] * 2^k + f(x) * f(-x)
Returns x if f(x) >= f(-x) otherwise -x
"""
scores = Counter(l for c in min_clauses(clauses) for l in disjuncts(c))
P = max(symbols,
key=lambda symbol: (scores[symbol] + scores[~symbol]) * pow(2, k) + scores[symbol] * scores[~symbol])
return P, True if scores[P] >= scores[~P] else False
def posit(symbols, clauses):
"""
Freeman's POSIT version of MOMs
Counts the positive x and negative x for each variable x in clauses with minimum size
Returns x if f(x) >= f(-x) otherwise -x
"""
scores = Counter(l for c in min_clauses(clauses) for l in disjuncts(c))
P = max(symbols, key=lambda symbol: scores[symbol] + scores[~symbol])
return P, True if scores[P] >= scores[~P] else False
def zm(symbols, clauses):
"""
Zabih and McAllester's version of MOMs
Counts the negative occurrences only of each variable x in clauses with minimum size
"""
scores = Counter(l for c in min_clauses(clauses) for l in disjuncts(c) if l.op == '~')
return max(symbols, key=lambda symbol: scores[~symbol]), True
def dlis(symbols, clauses):
"""
DLIS (Dynamic Largest Individual Sum) heuristic
Choose the variable and value that satisfies the maximum number of unsatisfied clauses
Like DLCS but we only consider the literal (thus Cp and Cn are individual)
"""
scores = Counter(l for c in clauses for l in disjuncts(c))
P = max(symbols, key=lambda symbol: scores[symbol])
return P, True if scores[P] >= scores[~P] else False
def dlcs(symbols, clauses):
"""
DLCS (Dynamic Largest Combined Sum) heuristic
Cp the number of clauses containing literal x
Cn the number of clauses containing literal -x
Here we select the variable maximizing Cp + Cn
Returns x if Cp >= Cn otherwise -x
"""
scores = Counter(l for c in clauses for l in disjuncts(c))
P = max(symbols, key=lambda symbol: scores[symbol] + scores[~symbol])
return P, True if scores[P] >= scores[~P] else False
def jw(symbols, clauses):
"""
Jeroslow-Wang heuristic
For each literal compute J(l) = \sum{l in clause c} 2^{-|c|}
Return the literal maximizing J
"""
scores = Counter()
for c in clauses:
for l in prop_symbols(c):
scores[l] += pow(2, -len(c.args))
return max(symbols, key=lambda symbol: scores[symbol]), True
def jw2(symbols, clauses):
"""
Two Sided Jeroslow-Wang heuristic
Compute J(l) also counts the negation of l = J(x) + J(-x)
Returns x if J(x) >= J(-x) otherwise -x
"""
scores = Counter()
for c in clauses:
for l in disjuncts(c):
scores[l] += pow(2, -len(c.args))
P = max(symbols, key=lambda symbol: scores[symbol] + scores[~symbol])
return P, True if scores[P] >= scores[~P] else False
def dpll_satisfiable(s, branching_heuristic=no_branching_heuristic):
"""Check satisfiability of a propositional sentence.
This differs from the book code in two ways: (1) it returns a model
rather than True when it succeeds; this is more useful. (2) The
function find_pure_symbol is passed a list of unknown clauses, rather
than a list of all clauses and the model; this is more efficient.
>>> dpll_satisfiable(A |'<=>'| B) == {A: True, B: True}
True
"""
Donato Meoli
a validé
return dpll(conjuncts(to_cnf(s)), prop_symbols(s), {}, branching_heuristic)
Donato Meoli
a validé
def dpll(clauses, symbols, model, branching_heuristic=no_branching_heuristic):
"""See if the clauses are true in a partial model."""
unknown_clauses = [] # clauses with an unknown truth value
for c in clauses:
return False
Donato Meoli
a validé
if val is None:
unknown_clauses.append(c)
if not unknown_clauses:
return model
P, value = find_pure_symbol(symbols, unknown_clauses)
if P:
Donato Meoli
a validé
return dpll(clauses, remove_all(P, symbols), extend(model, P, value), branching_heuristic)
P, value = find_unit_clause(clauses, model)
if P:
Donato Meoli
a validé
return dpll(clauses, remove_all(P, symbols), extend(model, P, value), branching_heuristic)
Donato Meoli
a validé
P, value = branching_heuristic(symbols, unknown_clauses)
Donato Meoli
a validé
return (dpll(clauses, remove_all(P, symbols), extend(model, P, value), branching_heuristic) or
dpll(clauses, remove_all(P, symbols), extend(model, P, not value), branching_heuristic))
def find_pure_symbol(symbols, clauses):
"""Find a symbol and its value if it appears only as a positive literal
(or only as a negative) in clauses.
>>> find_pure_symbol([A, B, C], [A|~B,~B|~C,C|A])
(A, True)
"""
for s in symbols:
found_pos, found_neg = False, False
if not found_pos and s in disjuncts(c):
found_pos = True
if not found_neg and ~s in disjuncts(c):
found_neg = True
if found_pos != found_neg:
return s, found_pos
return None, None
def find_unit_clause(clauses, model):
"""Find a forced assignment if possible from a clause with only 1
variable not bound in the model.
>>> find_unit_clause([A|B|C, B|~C, ~A|~B], {A:True})
(B, False)
"""
for clause in clauses:
return None, None
def unit_clause_assign(clause, model):
"""Return a single variable/value pair that makes clause true in
the model, if possible.
>>> unit_clause_assign(A|B|C, {A:True})
(None, None)
>>> unit_clause_assign(B|~C, {A:True})
(None, None)
>>> unit_clause_assign(~A|~B, {A:True})
(B, False)
"""
P, value = None, None
for literal in disjuncts(clause):
sym, positive = inspect_literal(literal)
if sym in model:
if model[sym] == positive:
return None, None # clause already True
elif P:
return None, None # more than 1 unbound variable
def inspect_literal(literal):
"""The symbol in this literal, and the value it should take to
make the literal true.
>>> inspect_literal(P)
(P, True)
>>> inspect_literal(~P)
(P, False)
"""
if literal.op == '~':
Donato Meoli
a validé
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
# ______________________________________________________________________________
# CDCL - Conflict-Driven Clause Learning with 1UIP Learning Scheme,
# 2WL Lazy Data Structure, VSIDS Branching Heuristic & Restarts
def no_restart(conflicts, restarts, queue_lbd, sum_lbd):
return False
def luby(conflicts, restarts, queue_lbd, sum_lbd, unit=512):
# in the state-of-art tested with unit value 1, 2, 4, 6, 8, 12, 16, 32, 64, 128, 256 and 512
def _luby(i):
k = 1
while True:
if i == (1 << k) - 1:
return 1 << (k - 1)
elif (1 << (k - 1)) <= i < (1 << k) - 1:
return _luby(i - (1 << (k - 1)) + 1)
k += 1
return unit * _luby(restarts) == len(queue_lbd)
def glucose(conflicts, restarts, queue_lbd, sum_lbd, x=100, k=0.7):
# in the state-of-art tested with (x, k) as (50, 0.8) and (100, 0.7)
# if there were at least x conflicts since the last restart, and then the average LBD of the last
# x learnt clauses was at least k times higher than the average LBD of all learnt clauses
return len(queue_lbd) >= x and sum(queue_lbd) / len(queue_lbd) * k > sum_lbd / conflicts
def cdcl_satisfiable(s, vsids_decay=0.95, restart_strategy=no_restart):
"""
>>> cdcl_satisfiable(A |'<=>'| B) == {A: True, B: True}
True
"""
clauses = TwoWLClauseDatabase(conjuncts(to_cnf(s)))
symbols = prop_symbols(s)
scores = Counter()
G = nx.DiGraph()
model = {}
dl = 0
conflicts = 0
restarts = 1
sum_lbd = 0
queue_lbd = []
while True:
conflict = unit_propagation(clauses, symbols, model, G, dl)
if conflict:
if dl == 0:
return False
conflicts += 1
dl, learn, lbd = conflict_analysis(G, dl)
queue_lbd.append(lbd)
sum_lbd += lbd
backjump(symbols, model, G, dl)
clauses.add(learn, model)
scores.update(l for l in disjuncts(learn))
for symbol in scores:
scores[symbol] *= vsids_decay
if restart_strategy(conflicts, restarts, queue_lbd, sum_lbd):
backjump(symbols, model, G)
queue_lbd.clear()
restarts += 1
else:
if not symbols:
return model
dl += 1
assign_decision_literal(symbols, model, scores, G, dl)
def assign_decision_literal(symbols, model, scores, G, dl):
P = max(symbols, key=lambda symbol: scores[symbol] + scores[~symbol])
value = True if scores[P] >= scores[~P] else False
symbols.remove(P)
model[P] = value
G.add_node(P, val=value, dl=dl)
def unit_propagation(clauses, symbols, model, G, dl):
def check(c):
if not model or clauses.get_first_watched(c) == clauses.get_second_watched(c):
return True
w1, _ = inspect_literal(clauses.get_first_watched(c))
if w1 in model:
return c in (clauses.get_neg_watched(w1) if model[w1] else clauses.get_pos_watched(w1))
w2, _ = inspect_literal(clauses.get_second_watched(c))
if w2 in model:
return c in (clauses.get_neg_watched(w2) if model[w2] else clauses.get_pos_watched(w2))
def unit_clause(watching):
w, p = inspect_literal(watching)
G.add_node(w, val=p, dl=dl)
G.add_edges_from(zip(prop_symbols(c) - {w}, itertools.cycle([w])), antecedent=c)
symbols.remove(w)
model[w] = p
def conflict_clause(c):
G.add_edges_from(zip(prop_symbols(c), itertools.cycle('K')), antecedent=c)
while True:
bcp = False
for c in filter(check, clauses.get_clauses()):
# we need only visit each clause when one of its two watched literals is assigned to 0 because, until
# this happens, we can guarantee that there cannot be more than n-2 literals in the clause assigned to 0
first_watched = pl_true(clauses.get_first_watched(c), model)
second_watched = pl_true(clauses.get_second_watched(c), model)
if first_watched is None and clauses.get_first_watched(c) == clauses.get_second_watched(c):
unit_clause(clauses.get_first_watched(c))
bcp = True
break
elif first_watched is False and second_watched is not True:
if clauses.update_second_watched(c, model):
bcp = True
else:
# if the only literal with a non-zero value is the other watched literal then
if second_watched is None: # if it is free, then the clause is a unit clause
unit_clause(clauses.get_second_watched(c))
bcp = True
break
else: # else (it is False) the clause is a conflict clause
conflict_clause(c)
return True
elif second_watched is False and first_watched is not True:
if clauses.update_first_watched(c, model):
bcp = True
else:
# if the only literal with a non-zero value is the other watched literal then
if first_watched is None: # if it is free, then the clause is a unit clause
unit_clause(clauses.get_first_watched(c))
bcp = True
break
else: # else (it is False) the clause is a conflict clause
conflict_clause(c)
return True
if not bcp:
return False
def conflict_analysis(G, dl):
conflict_clause = next(G[p]['K']['antecedent'] for p in G.pred['K'])
P = next(node for node in G.nodes() - 'K' if G.nodes[node]['dl'] == dl and G.in_degree(node) == 0)
first_uip = nx.immediate_dominators(G, P)['K']
G.remove_node('K')
conflict_side = nx.descendants(G, first_uip)
while True:
for l in prop_symbols(conflict_clause).intersection(conflict_side):
antecedent = next(G[p][l]['antecedent'] for p in G.pred[l])
conflict_clause = pl_binary_resolution(conflict_clause, antecedent)
# the literal block distance is calculated by taking the decision levels from variables of all
# literals in the clause, and counting how many different decision levels were in this set
lbd = [G.nodes[l]['dl'] for l in prop_symbols(conflict_clause)]
if lbd.count(dl) == 1 and first_uip in prop_symbols(conflict_clause):
return 0 if len(lbd) == 1 else heapq.nlargest(2, lbd)[-1], conflict_clause, len(set(lbd))
def pl_binary_resolution(ci, cj):
for di in disjuncts(ci):
for dj in disjuncts(cj):
if di == ~dj or ~di == dj:
Donato Meoli
a validé
return pl_binary_resolution(associate('|', remove_all(di, disjuncts(ci))),
associate('|', remove_all(dj, disjuncts(cj))))
Donato Meoli
a validé
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
return associate('|', unique(disjuncts(ci) + disjuncts(cj)))
def backjump(symbols, model, G, dl=0):
delete = {node for node in G.nodes() if G.nodes[node]['dl'] > dl}
G.remove_nodes_from(delete)
for node in delete:
del model[node]
symbols |= delete
class TwoWLClauseDatabase:
def __init__(self, clauses):
self.__twl = {}
self.__watch_list = defaultdict(lambda: [set(), set()])
for c in clauses:
self.add(c, None)
def get_clauses(self):
return self.__twl.keys()
def set_first_watched(self, clause, new_watching):
if len(clause.args) > 2:
self.__twl[clause][0] = new_watching
def set_second_watched(self, clause, new_watching):
if len(clause.args) > 2:
self.__twl[clause][1] = new_watching
def get_first_watched(self, clause):
if len(clause.args) == 2:
return clause.args[0]
if len(clause.args) > 2:
return self.__twl[clause][0]
return clause
def get_second_watched(self, clause):
if len(clause.args) == 2:
return clause.args[-1]
if len(clause.args) > 2:
return self.__twl[clause][1]
return clause
def get_pos_watched(self, l):
return self.__watch_list[l][0]
def get_neg_watched(self, l):