diff --git a/aima/logic.py b/aima/logic.py index 268171bfa..0d98fe33a 100644 --- a/aima/logic.py +++ b/aima/logic.py @@ -327,9 +327,9 @@ def pl_true(exp, model={}): return result p, q = args if op == '==>': - return pl_true(~p | q, model) + return pl_true(Expr('|', Expr('~', p), q), model) elif op == '<==': - return pl_true(p | ~q, model) + return pl_true(Expr('|', p, Expr('~', q)), model) pt = pl_true(p, model) if pt is None: return None @@ -368,22 +368,49 @@ def to_cnf(s): def eliminate_implications(s): r"""Change implications into equivalent form with only &, \|, and ~ as logical operators.""" s = expr(s) - if not s.args or is_symbol(s.op): - return s # Atoms are unchanged. + if isinstance(s, bool) or not s.args or is_symbol(s.op): + return s # Atoms and the constants True and False are unchanged. args = list(map(eliminate_implications, s.args)) a, b = args[0], args[-1] if s.op == '==>': - return b | ~a + return _or(b, _not(a)) elif s.op == '<==': - return a | ~b + return _or(a, _not(b)) elif s.op == '<=>': - return (a | ~b) & (b | ~a) + return _and(_or(a, _not(b)), _or(b, _not(a))) elif s.op == '^': assert len(args) == 2 # TODO: relax this restriction - return (a & ~b) | (~a & b) + return _or(_and(a, _not(b)), _and(_not(a), b)) + elif s.op == '~': + return _not(a) + elif s.op == '&': + return _and(*args) else: - assert s.op in ('&', '|', '~') - return Expr(s.op, *args) + assert s.op == '|' + return _or(*args) + + +def _not(a): + """~a, with ~True = False and ~False = True.""" + return (not a) if isinstance(a, bool) else ~a + + +def _and(*args): + """The conjunction of args, simplified: False if one of them is False, and + without the conjuncts True.""" + if any(a is False for a in args): + return False + args = [a for a in args if a is not True] + return Expr('&', *args) if len(args) > 1 else (args[0] if args else True) + + +def _or(*args): + """The disjunction of args, simplified: True if one of them is True, and + without the disjuncts False.""" + if any(a is True for a in args): + return True + args = [a for a in args if a is not False] + return Expr('|', *args) if len(args) > 1 else (args[0] if args else False) def move_not_inwards(s): @@ -392,11 +419,15 @@ def move_not_inwards(s): (~A & ~B) """ s = expr(s) + if isinstance(s, bool): + return s if s.op == '~': def NOT(b): - return move_not_inwards(~b) + return move_not_inwards(_not(b)) a = s.args[0] + if isinstance(a, bool): + return not a if a.op == '~': return move_not_inwards(a.args[0]) # ~~A ==> A if a.op == '&': @@ -417,6 +448,8 @@ def distribute_and_over_or(s): ((A | C) & (B | C)) """ s = expr(s) + if isinstance(s, bool): + return s if s.op == '|': s = associate('|', s.args) if s.op != '|': @@ -471,7 +504,11 @@ def dissociate(op, args): def collect(subargs): for arg in subargs: - if arg.op == op: + if isinstance(arg, bool) and arg is _op_identity.get(op): + continue # True in a conjunction, False in a disjunction + if isinstance(arg, bool): + result.append(arg) + elif arg.op == op: collect(arg.args) else: result.append(arg) @@ -510,7 +547,9 @@ def pl_resolution(kb, alpha): >>> pl_resolution(horn_clauses_KB, A) True """ - clauses = kb.clauses + conjuncts(to_cnf(~alpha)) + clauses = kb.clauses + conjuncts(to_cnf(_not(expr(alpha)))) + if False in clauses: + return True # the empty clause is already there new = set() while True: n = len(clauses) @@ -747,11 +786,12 @@ def dpll_satisfiable(s, branching_heuristic=no_branching_heuristic): associate('&', []) returns) is satisfied by the empty model, while False has no model. """ + s = to_cnf(s) if s is True or s is False: return {} if s else False # the symbols in the order of their names, so that the model found is the same # in every run (the order of a set changes with PYTHONHASHSEED) - return dpll(conjuncts(to_cnf(s)), sorted(prop_symbols(s), key=str), {}, branching_heuristic) + return dpll(conjuncts(s), sorted(prop_symbols(s), key=str), {}, branching_heuristic) def dpll(clauses, symbols, model, branching_heuristic=no_branching_heuristic): @@ -934,9 +974,10 @@ def cdcl_satisfiable(s, vsids_decay=0.95, restart_strategy=no_restart): As for dpll_satisfiable, the sentence True (no clauses) has the empty model and False has none. """ + s = to_cnf(s) if s is True or s is False: return {} if s else False - clauses = TwoWLClauseDatabase(simplify_clauses(conjuncts(to_cnf(s)))) + clauses = TwoWLClauseDatabase(simplify_clauses(conjuncts(s))) symbols = prop_symbols(s) scores = Counter() G = nx.DiGraph() @@ -1215,6 +1256,8 @@ def WalkSAT(clauses, p=0.5, max_flips=10000): >>> WalkSAT([A & ~A], 0.5, 100) is None True """ + if any(clause is False for clause in clauses): + return None # the empty clause has no model # Set of all symbols in all clauses symbols = {sym for clause in clauses for sym in prop_symbols(clause)} # model is a random assignment of true/false to the symbols in clauses diff --git a/aima/perception.py b/aima/perception.py index a7dad6d72..78364144b 100644 --- a/aima/perception.py +++ b/aima/perception.py @@ -132,20 +132,21 @@ def show_edges(edges): # 24.3.3 Optical flow -def sum_squared_difference(pic1, pic2): - """SSD of two frames: the displacement (Dx, Dy) of pic2, in -30..30 on each axis, - that minimizes the sum of squared differences with pic1, and that sum. As - np.roll wraps around, several displacements can tie (e.g., identical frames - smaller than 30 pixels), and the one of smallest abs(Dx) + abs(Dy) is returned.""" +def sum_squared_difference(pic1, pic2, max_shift=30): + """SSD of two frames: the displacement (Dx, Dy) of pic2, in -max_shift..max_shift + on each axis, that minimizes the sum of squared differences with pic1, and that + sum. As np.roll wraps around, several displacements can tie (e.g., identical + frames smaller than max_shift pixels), and the one of smallest abs(Dx) + abs(Dy) + is returned.""" pic1 = np.asarray(pic1) pic2 = np.asarray(pic2) assert pic1.shape == pic2.shape min_ssd = np.inf min_dxy = (np.inf, np.inf) - # consider picture shift from -30 to 30 - for Dx in range(-30, 31): - for Dy in range(-30, 31): + # consider picture shift from -max_shift to max_shift + for Dx in range(-max_shift, max_shift + 1): + for Dy in range(-max_shift, max_shift + 1): # shift the image shifted_pic = np.roll(pic2, Dx, axis=0) shifted_pic = np.roll(shifted_pic, Dy, axis=1) diff --git a/aima/planning.py b/aima/planning.py index 4b4c92d91..d53f4046c 100644 --- a/aima/planning.py +++ b/aima/planning.py @@ -774,16 +774,19 @@ def double_tennis_problem(): A multiagent planning problem involving two partner tennis players trying to return an approaching ball and repositioning around in the court. - Example: + The goal of the book is Returned(Ball) & (At(x, RightNet) | At(x, LeftNet)), i.e., + some player at either net; the goals of a PlanningProblem are a conjunction of + literals, so the disjunct At(B, RightNet) stands for the disjunction. + + Example, with the joint plan of Figure 18.2 (B does nothing): >>> from planning import * >>> dtp = double_tennis_problem() >>> goal_test(dtp.goals, dtp.initial) False >>> dtp.act(expr('Go(A, RightBaseLine, LeftBaseLine)')) - >>> dtp.act(expr('Hit(A, Ball, RightBaseLine)')) >>> goal_test(dtp.goals, dtp.initial) False - >>> dtp.act(expr('Go(A, LeftNet, RightBaseLine)')) + >>> dtp.act(expr('Hit(A, Ball, RightBaseLine)')) >>> goal_test(dtp.goals, dtp.initial) True >>> @@ -791,7 +794,7 @@ def double_tennis_problem(): return PlanningProblem( initial='At(A, LeftBaseLine) & At(B, RightNet) & Approaching(Ball, RightBaseLine) & Partner(A, B) & Partner(B, A)', - goals='Returned(Ball) & At(a, LeftNet) & At(a, RightNet)', + goals='Returned(Ball) & At(B, RightNet)', actions=[Action('Hit(actor, Ball, loc)', precond='Approaching(Ball, loc) & At(actor, loc)', effect='Returned(Ball)'), diff --git a/aima/utils.py b/aima/utils.py index 30cc72431..41d715b9d 100644 --- a/aima/utils.py +++ b/aima/utils.py @@ -10,6 +10,7 @@ import operator import os.path import random +import re from itertools import chain, combinations from statistics import mean @@ -684,7 +685,7 @@ class PartialExpr: r"""Given 'P \|'==>'\| Q, first form PartialExpr('==>', P), then combine with Q.""" def __init__(self, op, lhs): - self.op, self.lhs = op, lhs + self.op, self.lhs = str(op) if isinstance(op, str) else op, lhs def __or__(self, rhs): return Expr(self.op, self.lhs, rhs) @@ -702,7 +703,38 @@ def expr(x): >>> expr('P & Q ==> Q') ((P & Q) ==> Q) """ - return eval(expr_handle_infix_ops(x), defaultkeydict(Symbol)) if isinstance(x, str) else x + if not isinstance(x, str): + return x + x = expr_handle_infix_ops(expr_negate_constants(x)) + # the operators as InfixOp, so that a left operand True or False works too + names = defaultkeydict(Symbol) + for i, op in enumerate(infix_ops): + x = x.replace('|' + repr(op) + '|', '|_infix_op_{}_|'.format(i)) + names['_infix_op_{}_'.format(i)] = InfixOp(op) + return eval(x, names) + + +class InfixOp(str): + r"""An infix operator such as '==>' in P \|'==>'\| Q: with a left operand that is + not an Expr, such as False, Python calls __ror__.""" + + def __ror__(self, lhs): + return PartialExpr(self, lhs) + + +def expr_negate_constants(x): + """Replace ~True and ~False with False and True, since Python evaluates ~ on a + bool as an integer (~False is -1). + + >>> expr_negate_constants('A | ~~False') + 'A | (False)' + """ + pattern = re.compile(r'~\s*(?:(True|False)\b|\(\s*(True|False)\s*\))') + while True: + y = pattern.sub(lambda m: '(False)' if 'True' in (m.group(1), m.group(2)) else '(True)', x) + if y == x: + return x + x = y infix_ops = '==> <== <=>'.split() diff --git a/notebooks/planning.ipynb b/notebooks/planning.ipynb index f83b48bda..90ac3477f 100644 --- a/notebooks/planning.ipynb +++ b/notebooks/planning.ipynb @@ -3803,11 +3803,9 @@ "\n", "**Go(actor, to, loc)**: moves an `actor` from location `loc` to location `to`.\n", "\n", - "We notice something different in this problem though, \n", - "which is quite unlike any other problem we have seen so far. \n", - "The goal state of the problem contains a variable `a`.\n", - "This happens sometimes in multiagent planning problems \n", - "and it means that it doesn't matter _which_ actor is at the `LeftNet` or the `RightNet`, as long as there is atleast one actor at either `LeftNet` or `RightNet`." + "The goal of the book is `Returned(Ball) & (At(x, RightNet) | At(x, LeftNet))`, i.e., some actor at either net.\n", + "The goals of a `PlanningProblem` are a conjunction of literals, so the module takes the disjunct `At(B, RightNet)`, which already holds.\n", + "The joint plan of the book has A go to the right baseline and hit the ball, while B does nothing." ] }, { @@ -3817,8 +3815,7 @@ "outputs": [], "source": [ "solution = [expr('Go(A, RightBaseLine, LeftBaseLine)'),\n", - " expr('Hit(A, Ball, RightBaseLine)'),\n", - " expr('Go(A, LeftNet, RightBaseLine)')]\n", + " expr('Hit(A, Ball, RightBaseLine)')]\n", "\n", "for action in solution:\n", " doubleTennisProblem.act(action)" diff --git a/notebooks/planning.py b/notebooks/planning.py index 23900d375..a88c5fe59 100644 --- a/notebooks/planning.py +++ b/notebooks/planning.py @@ -850,16 +850,13 @@ def goal_test(kb): # # **Go(actor, to, loc)**: moves an `actor` from location `loc` to location `to`. # -# We notice something different in this problem though, -# which is quite unlike any other problem we have seen so far. -# The goal state of the problem contains a variable `a`. -# This happens sometimes in multiagent planning problems -# and it means that it doesn't matter _which_ actor is at the `LeftNet` or the `RightNet`, as long as there is atleast one actor at either `LeftNet` or `RightNet`. +# The goal of the book is `Returned(Ball) & (At(x, RightNet) | At(x, LeftNet))`, i.e., some actor at either net. +# The goals of a `PlanningProblem` are a conjunction of literals, so the module takes the disjunct `At(B, RightNet)`, which already holds. +# The joint plan of the book has A go to the right baseline and hit the ball, while B does nothing. # %% solution = [expr('Go(A, RightBaseLine, LeftBaseLine)'), - expr('Hit(A, Ball, RightBaseLine)'), - expr('Go(A, LeftNet, RightBaseLine)')] + expr('Hit(A, Ball, RightBaseLine)')] for action in solution: doubleTennisProblem.act(action) diff --git a/tests/test_logic.py b/tests/test_logic.py index cd1062701..c5424a88b 100644 --- a/tests/test_logic.py +++ b/tests/test_logic.py @@ -939,3 +939,32 @@ def test_dpll_and_cdcl_do_not_depend_on_the_hash_seed(): env={**os.environ, 'PYTHONHASHSEED': seed}).stdout for seed in ('0', '1', '2', '3')} assert len(outputs) == 1 and outputs != {''} assert dpll_satisfiable(expr('A | B | C')) == {A: True} + + +def test_propositional_constants_inside_a_sentence(): + # True and False are constants: A & False is unsatisfiable, A | False is A and + # A | True is valid; ~False is True (Python made it the integer -1) + sentences = ['False', 'True', 'A & False', 'A | False', 'A | True', '~False'] + assert expr('~False') is True and expr('~~False') is False and expr('~(True)') is False + assert [to_cnf(s) for s in sentences] == [False, True, False, A, True, True] + models = [False, {}, False, {A: True}, {}, {}] + for sat in (dpll_satisfiable, cdcl_satisfiable): + assert [sat(expr(s)) for s in sentences] == models + random.seed(0) + walksat = [WalkSAT(conjuncts(to_cnf(s)), 0.5, 100) for s in sentences] + assert walksat == [None, {}, None, {A: True}, {}, {}] + # from an empty KB only the valid sentences follow + entailed = [pl_resolution(PropKB(), expr(s)) for s in sentences] + assert entailed == [False, True, False, False, True, True] + assert pl_resolution(PropKB(expr('A & False')), B) + assert pl_resolution(PropKB(expr('A | False')), A) + assert not pl_resolution(PropKB(expr('A | True')), A) + # the constants are operands of ==>, <== and <=> too + assert expr('False ==> A') == Expr('==>', False, A) + assert expr('A <== True') == Expr('<==', A, True) + assert to_cnf('False ==> A') is True and to_cnf('A ==> False') == ~A + assert to_cnf('True <=> A') == A + assert to_cnf('False <=> A') == ~A and to_cnf('True ==> A') == A + assert pl_resolution(PropKB(), expr('False ==> A')) + assert dpll_satisfiable(expr('A ==> False')) == {A: False} + assert cdcl_satisfiable(expr('True <=> A')) == {A: True} and tt_true('False ==> A') diff --git a/tests/test_perception.py b/tests/test_perception.py index b127564be..2b1ac9cab 100644 --- a/tests/test_perception.py +++ b/tests/test_perception.py @@ -194,6 +194,15 @@ def test_optical_flow_of_blank_frames(): assert sum_squared_difference(np.zeros((4, 4)), np.zeros((4, 4))) == ((0, 0), 0) +def test_optical_flow_without_shifts(): + # with max_shift = 0 the only candidate is (0, 0), even when the frame has moved + frame = np.arange(36).reshape(6, 6) + assert sum_squared_difference(frame, frame, max_shift=0) == ((0, 0), 0) + moved = np.roll(frame, 1, axis=0) + assert sum_squared_difference(frame, moved, max_shift=0) == ((0, 0), np.sum((frame - moved) ** 2)) + assert sum_squared_difference(frame, moved, max_shift=1) == ((-1, 0), 0) + + def test_segmentation_of_a_single_pixel_and_of_a_constant_image(): assert image_to_graph(np.zeros((1, 1))) == {(0, 0): [None, None]} assert group_contour_detection(np.array([[7]], dtype=np.uint8), cluster_num=1).tolist() == [[7]] diff --git a/tests/test_planning.py b/tests/test_planning.py index 0710d53f0..6ac50da98 100644 --- a/tests/test_planning.py +++ b/tests/test_planning.py @@ -519,14 +519,12 @@ def test_double_tennis(): p = double_tennis_problem() assert not goal_test(p.goals, p.initial) - solution = [expr('Go(A, RightBaseLine, LeftBaseLine)'), - expr('Hit(A, Ball, RightBaseLine)'), - expr('Go(A, LeftNet, RightBaseLine)')] - - for action in solution: - p.act(action) - - assert goal_test(p.goals, p.initial) + # [Figure 18.2] the joint plan of the book: A goes to the right baseline and hits the + # ball, while B stays at the right net + p.act(expr('Go(A, RightBaseLine, LeftBaseLine)')) + assert not goal_test(p.goals, p.initial) + p.act(expr('Hit(A, Ball, RightBaseLine)')) + assert goal_test(p.goals, p.initial) and p.goal_test() def test_job_shop_problem():