Newer
Older
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This Jupyter notebook acts as supporting material for topics covered in __Chapter 6 Logical Agents__, __Chapter 7 First-Order Logic__ and __Chapter 8 Inference in First-Order Logic__ of the book *[Artificial Intelligence: A Modern Approach](http://aima.cs.berkeley.edu)*. We make use the implementations in the [logic.py](https://github.com/aimacode/aima-python/blob/master/logic.py) module. See the [intro notebook](https://github.com/aimacode/aima-python/blob/master/intro.ipynb) for instructions.\n",
"Let's first import everything from the `logic` module."
"from logic import *\n",
"from notebook import psource"
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## CONTENTS\n",
"- Logical sentences\n",
" - Expr\n",
" - PropKB\n",
" - Knowledge-based agents\n",
" - Inference in propositional knowledge base\n",
" - Truth table enumeration\n",
" - Proof by resolution\n",
" - Forward and backward chaining\n",
" - DPLL\n",
" - WalkSAT\n",
" - SATPlan\n",
" - FolKB\n",
" - Inference in first order knowledge base\n",
" - Unification\n",
" - Forward chaining algorithm\n",
" - Backward chaining algorithm"
]
},
"metadata": {
"collapsed": true
},
{
"cell_type": "markdown",
"metadata": {},
"The `Expr` class is designed to represent any kind of mathematical expression. The simplest type of `Expr` is a symbol, which can be defined with the function `Symbol`:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"outputs": [
{
"data": {
"text/plain": [
"x"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Symbol('x')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Or we can define multiple symbols at the same time with the function `symbols`:"
]
},
{
"cell_type": "code",
"execution_count": 3,
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can combine `Expr`s with the regular Python infix and prefix operators. Here's how we would form the logical sentence \"P and not Q\":"
]
},
{
"cell_type": "code",
"execution_count": 4,
"outputs": [
{
"data": {
"text/plain": [
"(P & ~Q)"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This works because the `Expr` class overloads the `&` operator with this definition:\n",
"\n",
"```python\n",
"def __and__(self, other): return Expr('&', self, other)```\n",
" \n",
"and does similar overloads for the other operators. An `Expr` has two fields: `op` for the operator, which is always a string, and `args` for the arguments, which is a tuple of 0 or more expressions. By \"expression,\" I mean either an instance of `Expr`, or a number. Let's take a look at the fields for some `Expr` examples:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"outputs": [
{
"data": {
"text/plain": [
"'&'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "code",
"execution_count": 6,
"outputs": [
{
"data": {
"text/plain": [
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "code",
"execution_count": 7,
"outputs": [
{
"data": {
"text/plain": [
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"P.op"
]
},
{
"cell_type": "code",
"execution_count": 8,
"outputs": [
{
"data": {
"text/plain": [
"()"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"P.args"
]
},
{
"cell_type": "code",
"execution_count": 9,
"outputs": [
{
"data": {
"text/plain": [
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "code",
"execution_count": 10,
"data": {
"text/plain": [
"(x, y)"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is important to note that the `Expr` class does not define the *logic* of Propositional Logic sentences; it just gives you a way to *represent* expressions. Think of an `Expr` as an [abstract syntax tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree). Each of the `args` in an `Expr` can be either a symbol, a number, or a nested `Expr`. We can nest these trees to any depth. Here is a deply nested `Expr`:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"data": {
"text/plain": [
"(((3 * f(x, y)) + (P(y) / 2)) + 1)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
"3 * f(x, y) + P(y) / 2 + 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Operators for Constructing Logical Sentences\n",
"Here is a table of the operators that can be used to form sentences. Note that we have a problem: we want to use Python operators to make sentences, so that our programs (and our interactive sessions like the one here) will show simple code. But Python does not allow implication arrows as operators, so for now we have to use a more verbose notation that Python does allow: `|'==>'|` instead of just `==>`. Alternately, you can always use the more verbose `Expr` constructor forms:\n",
"| Operation | Book | Python Infix Input | Python Output | Python `Expr` Input\n",
"|--------------------------|----------------------|-------------------------|---|---|\n",
"| Negation | ¬ P | `~P` | `~P` | `Expr('~', P)`\n",
"| And | P ∧ Q | `P & Q` | `P & Q` | `Expr('&', P, Q)`\n",
"| Or | P ∨ Q | `P`<tt> | </tt>`Q`| `P`<tt> | </tt>`Q` | `Expr('`|`', P, Q)`\n",
"| Inequality (Xor) | P ≠ Q | `P ^ Q` | `P ^ Q` | `Expr('^', P, Q)`\n",
"| Implication | P → Q | `P` <tt>|</tt>`'==>'`<tt>|</tt> `Q` | `P ==> Q` | `Expr('==>', P, Q)`\n",
"| Reverse Implication | Q ← P | `Q` <tt>|</tt>`'<=='`<tt>|</tt> `P` |`Q <== P` | `Expr('<==', Q, P)`\n",
"| Equivalence | P ↔ Q | `P` <tt>|</tt>`'<=>'`<tt>|</tt> `Q` |`P <=> Q` | `Expr('<=>', P, Q)`\n",
"Here's an example of defining a sentence with an implication arrow:"
]
},
{
"cell_type": "code",
"execution_count": 12,
"outputs": [
{
"data": {
"text/plain": [
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## `expr`: a Shortcut for Constructing Sentences\n",
"If the `|'==>'|` notation looks ugly to you, you can use the function `expr` instead:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"outputs": [
{
"data": {
"text/plain": [
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`expr` takes a string as input, and parses it into an `Expr`. The string can contain arrow operators: `==>`, `<==`, or `<=>`, which are handled as if they were regular Python infix operators. And `expr` automatically defines any symbols, so you don't need to pre-define them:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"outputs": [
{
"data": {
"text/plain": [
"sqrt(((b ** 2) - ((4 * a) * c)))"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"expr('sqrt(b ** 2 - 4 * a * c)')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For now that's all you need to know about `expr`. If you are interested, we explain the messy details of how `expr` is implemented and how `|'==>'|` is handled in the appendix."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Propositional Knowledge Bases: `PropKB`\n",
"The class `PropKB` can be used to represent a knowledge base of propositional logic sentences.\n",
"We see that the class `KB` has four methods, apart from `__init__`. A point to note here: the `ask` method simply calls the `ask_generator` method. Thus, this one has already been implemented, and what you'll have to actually implement when you create your own knowledge base class (though you'll probably never need to, considering the ones we've created for you) will be the `ask_generator` function and not the `ask` function itself.\n",
"\n",
"The class `PropKB` now.\n",
"* `__init__(self, sentence=None)` : The constructor `__init__` creates a single field `clauses` which will be a list of all the sentences of the knowledge base. Note that each one of these sentences will be a 'clause' i.e. a sentence which is made up of only literals and `or`s.\n",
"* `tell(self, sentence)` : When you want to add a sentence to the KB, you use the `tell` method. This method takes a sentence, converts it to its CNF, extracts all the clauses, and adds all these clauses to the `clauses` field. So, you need not worry about `tell`ing only clauses to the knowledge base. You can `tell` the knowledge base a sentence in any form that you wish; converting it to CNF and adding the resulting clauses will be handled by the `tell` method.\n",
"* `ask_generator(self, query)` : The `ask_generator` function is used by the `ask` function. It calls the `tt_entails` function, which in turn returns `True` if the knowledge base entails query and `False` otherwise. The `ask_generator` itself returns an empty dict `{}` if the knowledge base entails query and `None` otherwise. This might seem a little bit weird to you. After all, it makes more sense just to return a `True` or a `False` instead of the `{}` or `None` But this is done to maintain consistency with the way things are in First-Order Logic, where an `ask_generator` function is supposed to return all the substitutions that make the query true. Hence the dict, to return all these substitutions. I will be mostly be using the `ask` function which returns a `{}` or a `False`, but if you don't like this, you can always use the `ask_if_true` function which returns a `True` or a `False`.\n",
"* `retract(self, sentence)` : This function removes all the clauses of the sentence given, from the knowledge base. Like the `tell` function, you don't have to pass clauses to remove them from the knowledge base; any sentence will do fine. The function will take care of converting that sentence to clauses and then remove those."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Wumpus World KB\n",
"Let us create a `PropKB` for the wumpus world with the sentences mentioned in `section 7.4.3`."
]
},
{
"cell_type": "code",
"execution_count": 15,
"outputs": [],
"source": [
"wumpus_kb = PropKB()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We define the symbols we use in our clauses.<br/>\n",
"$P_{x, y}$ is true if there is a pit in `[x, y]`.<br/>\n",
"$B_{x, y}$ is true if the agent senses breeze in `[x, y]`.<br/>"
]
},
{
"cell_type": "code",
"execution_count": 16,
"outputs": [],
"source": [
"P11, P12, P21, P22, P31, B11, B21 = expr('P11, P12, P21, P22, P31, B11, B21')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we tell sentences based on `section 7.4.3`.<br/>\n",
"There is no pit in `[1,1]`."
]
},
{
"cell_type": "code",
"execution_count": 17,
"outputs": [],
"source": [
"wumpus_kb.tell(~P11)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A square is breezy if and only if there is a pit in a neighboring square. This has to be stated for each square but for now, we include just the relevant squares."
]
},
{
"cell_type": "code",
"execution_count": 18,
"outputs": [],
"source": [
"wumpus_kb.tell(B11 | '<=>' | ((P12 | P21)))\n",
"wumpus_kb.tell(B21 | '<=>' | ((P11 | P22 | P31)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we include the breeze percepts for the first two squares leading up to the situation in `Figure 7.3(b)`"
]
},
{
"cell_type": "code",
"execution_count": 19,
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
"outputs": [],
"source": [
"wumpus_kb.tell(~B11)\n",
"wumpus_kb.tell(B21)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can check the clauses stored in a `KB` by accessing its `clauses` variable"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[~P11,\n",
" (~P12 | B11),\n",
" (~P21 | B11),\n",
" (P12 | P21 | ~B11),\n",
" (~P11 | B21),\n",
" (~P22 | B21),\n",
" (~P31 | B21),\n",
" (P11 | P22 | P31 | ~B21),\n",
" ~B11,\n",
" B21]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"wumpus_kb.clauses"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We see that the equivalence $B_{1, 1} \\iff (P_{1, 2} \\lor P_{2, 1})$ was automatically converted to two implications which were inturn converted to CNF which is stored in the `KB`.<br/>\n",
"$B_{1, 1} \\iff (P_{1, 2} \\lor P_{2, 1})$ was split into $B_{1, 1} \\implies (P_{1, 2} \\lor P_{2, 1})$ and $B_{1, 1} \\Longleftarrow (P_{1, 2} \\lor P_{2, 1})$.<br/>\n",
"$B_{1, 1} \\implies (P_{1, 2} \\lor P_{2, 1})$ was converted to $P_{1, 2} \\lor P_{2, 1} \\lor \\neg B_{1, 1}$.<br/>\n",
"$B_{1, 1} \\Longleftarrow (P_{1, 2} \\lor P_{2, 1})$ was converted to $\\neg (P_{1, 2} \\lor P_{2, 1}) \\lor B_{1, 1}$ which becomes $(\\neg P_{1, 2} \\lor B_{1, 1}) \\land (\\neg P_{2, 1} \\lor B_{1, 1})$ after applying De Morgan's laws and distributing the disjunction.<br/>\n",
"$B_{2, 1} \\iff (P_{1, 1} \\lor P_{2, 2} \\lor P_{3, 2})$ is converted in similar manner."
]
},
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Knowledge based agents"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A knowledge-based agent is a simple generic agent that maintains and handles a knowledge base.\n",
"The knowledge base may initially contain some background knowledge.\n",
"<br>\n",
"The purpose of a KB agent is to provide a level of abstraction over knowledge-base manipulation and is to be used as a base class for agents that work on a knowledge base.\n",
"<br>\n",
"Given a percept, the KB agent adds the percept to its knowledge base, asks the knowledge base for the best action, and tells the knowledge base that it has infact taken that action.\n",
"<br>\n",
"Our implementation of `KB-Agent` is encapsulated in a class `KB_AgentProgram` which inherits from the `KB` class.\n",
"<br>\n",
"Let's have a look."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">KB_AgentProgram</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""A generic logical knowledge-based agent program. [Figure 7.1]"""</span>\n",
" <span class=\"n\">steps</span> <span class=\"o\">=</span> <span class=\"n\">itertools</span><span class=\"o\">.</span><span class=\"n\">count</span><span class=\"p\">()</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">program</span><span class=\"p\">(</span><span class=\"n\">percept</span><span class=\"p\">):</span>\n",
" <span class=\"n\">t</span> <span class=\"o\">=</span> <span class=\"nb\">next</span><span class=\"p\">(</span><span class=\"n\">steps</span><span class=\"p\">)</span>\n",
" <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">tell</span><span class=\"p\">(</span><span class=\"n\">make_percept_sentence</span><span class=\"p\">(</span><span class=\"n\">percept</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">))</span>\n",
" <span class=\"n\">action</span> <span class=\"o\">=</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">ask</span><span class=\"p\">(</span><span class=\"n\">make_action_query</span><span class=\"p\">(</span><span class=\"n\">t</span><span class=\"p\">))</span>\n",
" <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">tell</span><span class=\"p\">(</span><span class=\"n\">make_action_sentence</span><span class=\"p\">(</span><span class=\"n\">action</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">))</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">action</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">make_percept_sentence</span><span class=\"p\">(</span><span class=\"n\">percept</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"s2\">"Percept"</span><span class=\"p\">)(</span><span class=\"n\">percept</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">)</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">make_action_query</span><span class=\"p\">(</span><span class=\"n\">t</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"s2\">"ShouldDo(action, {})"</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"n\">t</span><span class=\"p\">))</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">make_action_sentence</span><span class=\"p\">(</span><span class=\"n\">action</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"s2\">"Did"</span><span class=\"p\">)(</span><span class=\"n\">action</span><span class=\"p\">[</span><span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"s1\">'action'</span><span class=\"p\">)],</span> <span class=\"n\">t</span><span class=\"p\">)</span>\n",
"\n",
" <span class=\"k\">return</span> <span class=\"n\">program</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(KB_AgentProgram)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The helper functions `make_percept_sentence`, `make_action_query` and `make_action_sentence` are all aptly named and as expected,\n",
"`make_percept_sentence` makes first-order logic sentences about percepts we want our agent to receive,\n",
"`make_action_query` asks the underlying `KB` about the action that should be taken and\n",
"`make_action_sentence` tells the underlying `KB` about the action it has just taken."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference in Propositional Knowledge Base\n",
"In this section we will look at two algorithms to check if a sentence is entailed by the `KB`. Our goal is to decide whether $\\text{KB} \\vDash \\alpha$ for some sentence $\\alpha$.\n",
"### Truth Table Enumeration\n",
"It is a model-checking approach which, as the name suggests, enumerates all possible models in which the `KB` is true and checks if $\\alpha$ is also true in these models. We list the $n$ symbols in the `KB` and enumerate the $2^{n}$ models in a depth-first manner and check the truth of `KB` and $\\alpha$."
]
},
{
"cell_type": "code",
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
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
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">tt_check_all</span><span class=\"p\">(</span><span class=\"n\">kb</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Auxiliary routine to implement tt_entails."""</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">symbols</span><span class=\"p\">:</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">pl_true</span><span class=\"p\">(</span><span class=\"n\">kb</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">):</span>\n",
" <span class=\"n\">result</span> <span class=\"o\">=</span> <span class=\"n\">pl_true</span><span class=\"p\">(</span><span class=\"n\">alpha</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">)</span>\n",
" <span class=\"k\">assert</span> <span class=\"n\">result</span> <span class=\"ow\">in</span> <span class=\"p\">(</span><span class=\"bp\">True</span><span class=\"p\">,</span> <span class=\"bp\">False</span><span class=\"p\">)</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">result</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">True</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">rest</span> <span class=\"o\">=</span> <span class=\"n\">symbols</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">],</span> <span class=\"n\">symbols</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">:]</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">(</span><span class=\"n\">tt_check_all</span><span class=\"p\">(</span><span class=\"n\">kb</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">,</span> <span class=\"n\">rest</span><span class=\"p\">,</span> <span class=\"n\">extend</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">,</span> <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"bp\">True</span><span class=\"p\">))</span> <span class=\"ow\">and</span>\n",
" <span class=\"n\">tt_check_all</span><span class=\"p\">(</span><span class=\"n\">kb</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">,</span> <span class=\"n\">rest</span><span class=\"p\">,</span> <span class=\"n\">extend</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">,</span> <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"bp\">False</span><span class=\"p\">)))</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(tt_check_all)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The algorithm basically computes every line of the truth table $KB\\implies \\alpha$ and checks if it is true everywhere.\n",
"<br>\n",
"If symbols are defined, the routine recursively constructs every combination of truth values for the symbols and then, \n",
"it checks whether `model` is consistent with `kb`.\n",
"The given models correspond to the lines in the truth table,\n",
"which have a `true` in the KB column, \n",
"and for these lines it checks whether the query evaluates to true\n",
"<br>\n",
"`result = pl_true(alpha, model)`.\n",
"<br>\n",
"<br>\n",
"In short, `tt_check_all` evaluates this logical expression for each `model`\n",
"<br>\n",
"`pl_true(kb, model) => pl_true(alpha, model)`\n",
"<br>\n",
"which is logically equivalent to\n",
"<br>\n",
"`pl_true(kb, model) & ~pl_true(alpha, model)` \n",
"<br>\n",
"that is, the knowledge base and the negation of the query are logically inconsistent.\n",
"<br>\n",
"<br>\n",
"`tt_entails()` just extracts the symbols from the query and calls `tt_check_all()` with the proper parameters.\n"
]
},
{
"cell_type": "code",
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
951
952
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
1001
1002
1003
1004
1005
1006
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">tt_entails</span><span class=\"p\">(</span><span class=\"n\">kb</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Does kb entail the sentence alpha? Use truth tables. For propositional</span>\n",
"<span class=\"sd\"> kb's and sentences. [Figure 7.10]. Note that the 'kb' should be an</span>\n",
"<span class=\"sd\"> Expr which is a conjunction of clauses.</span>\n",
"<span class=\"sd\"> >>> tt_entails(expr('P & Q'), expr('Q'))</span>\n",
"<span class=\"sd\"> True</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"k\">assert</span> <span class=\"ow\">not</span> <span class=\"n\">variables</span><span class=\"p\">(</span><span class=\"n\">alpha</span><span class=\"p\">)</span>\n",
" <span class=\"n\">symbols</span> <span class=\"o\">=</span> <span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"n\">prop_symbols</span><span class=\"p\">(</span><span class=\"n\">kb</span> <span class=\"o\">&</span> <span class=\"n\">alpha</span><span class=\"p\">))</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">tt_check_all</span><span class=\"p\">(</span><span class=\"n\">kb</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">,</span> <span class=\"p\">{})</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(tt_entails)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Keep in mind that for two symbols P and Q, P => Q is false only when P is `True` and Q is `False`.\n",
"Example usage of `tt_entails()`:"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tt_entails(P & Q, Q)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"P & Q is True only when both P and Q are True. Hence, (P & Q) => Q is True"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tt_entails(P | Q, Q)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tt_entails(P | Q, P)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we know that P | Q is true, we cannot infer the truth values of P and Q. \n",
"Hence (P | Q) => Q is False and so is (P | Q) => P."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(A, B, C, D, E, F, G) = symbols('A, B, C, D, E, F, G')\n",
"tt_entails(A & (B | C) & D & E & ~(F | G), A & D & E & ~F & ~G)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"We can see that for the KB to be true, A, D, E have to be True and F and G have to be False.\n",
"Nothing can be said about B or C."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Coming back to our problem, note that `tt_entails()` takes an `Expr` which is a conjunction of clauses as the input instead of the `KB` itself. \n",
"You can use the `ask_if_true()` method of `PropKB` which does all the required conversions. \n",
"Let's check what `wumpus_kb` tells us about $P_{1, 1}$."
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(True, False)"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"wumpus_kb.ask_if_true(~P11), wumpus_kb.ask_if_true(P11)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Looking at Figure 7.9 we see that in all models in which the knowledge base is `True`, $P_{1, 1}$ is `False`. It makes sense that `ask_if_true()` returns `True` for $\\alpha = \\neg P_{1, 1}$ and `False` for $\\alpha = P_{1, 1}$. This begs the question, what if $\\alpha$ is `True` in only a portion of all models. Do we return `True` or `False`? This doesn't rule out the possibility of $\\alpha$ being `True` but it is not entailed by the `KB` so we return `False` in such cases. We can see this is the case for $P_{2, 2}$ and $P_{3, 1}$."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(False, False)"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"wumpus_kb.ask_if_true(~P22), wumpus_kb.ask_if_true(P22)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Proof by Resolution\n",
"Recall that our goal is to check whether $\\text{KB} \\vDash \\alpha$ i.e. is $\\text{KB} \\implies \\alpha$ true in every model. Suppose we wanted to check if $P \\implies Q$ is valid. We check the satisfiability of $\\neg (P \\implies Q)$, which can be rewritten as $P \\land \\neg Q$. If $P \\land \\neg Q$ is unsatisfiable, then $P \\implies Q$ must be true in all models. This gives us the result \"$\\text{KB} \\vDash \\alpha$ <em>if and only if</em> $\\text{KB} \\land \\neg \\alpha$ is unsatisfiable\".<br/>\n",
"This technique corresponds to <em>proof by <strong>contradiction</strong></em>, a standard mathematical proof technique. We assume $\\alpha$ to be false and show that this leads to a contradiction with known axioms in $\\text{KB}$. We obtain a contradiction by making valid inferences using inference rules. In this proof we use a single inference rule, <strong>resolution</strong> which states $(l_1 \\lor \\dots \\lor l_k) \\land (m_1 \\lor \\dots \\lor m_n) \\land (l_i \\iff \\neg m_j) \\implies l_1 \\lor \\dots \\lor l_{i - 1} \\lor l_{i + 1} \\lor \\dots \\lor l_k \\lor m_1 \\lor \\dots \\lor m_{j - 1} \\lor m_{j + 1} \\lor \\dots \\lor m_n$. Applying the resolution yeilds us a clause which we add to the KB. We keep doing this until:\n",
"\n",
"* There are no new clauses that can be added, in which case $\\text{KB} \\nvDash \\alpha$.\n",
"* Two clauses resolve to yield the <em>empty clause</em>, in which case $\\text{KB} \\vDash \\alpha$.\n",
"\n",
"The <em>empty clause</em> is equivalent to <em>False</em> because it arises only from resolving two complementary\n",
"unit clauses such as $P$ and $\\neg P$ which is a contradiction as both $P$ and $\\neg P$ can't be <em>True</em> at the same time."
]
},
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There is one catch however, the algorithm that implements proof by resolution cannot handle complex sentences. \n",
"Implications and bi-implications have to be simplified into simpler clauses. \n",
"We already know that *every sentence of a propositional logic is logically equivalent to a conjunction of clauses*.\n",
"We will use this fact to our advantage and simplify the input sentence into the **conjunctive normal form** (CNF) which is a conjunction of disjunctions of literals.\n",
"For eg:\n",
"<br>\n",
"$$(A\\lor B)\\land (\\neg B\\lor C\\lor\\neg D)\\land (D\\lor\\neg E)$$\n",
"This is equivalent to the POS (Product of sums) form in digital electronics.\n",
"<br>\n",
"Here's an outline of how the conversion is done:\n",
"1. Convert bi-implications to implications\n",
"<br>\n",
"$\\alpha\\iff\\beta$ can be written as $(\\alpha\\implies\\beta)\\land(\\beta\\implies\\alpha)$\n",
"<br>\n",
"This also applies to compound sentences\n",
"<br>\n",
"$\\alpha\\iff(\\beta\\lor\\gamma)$ can be written as $(\\alpha\\implies(\\beta\\lor\\gamma))\\land((\\beta\\lor\\gamma)\\implies\\alpha)$\n",
"<br>\n",
"2. Convert implications to their logical equivalents\n",
"<br>\n",
"$\\alpha\\implies\\beta$ can be written as $\\neg\\alpha\\lor\\beta$\n",
"<br>\n",
"3. Move negation inwards\n",
"<br>\n",
"CNF requires atomic literals. Hence, negation cannot appear on a compound statement.\n",
"De Morgan's laws will be helpful here.\n",
"<br>\n",
"$\\neg(\\alpha\\land\\beta)\\equiv(\\neg\\alpha\\lor\\neg\\beta)$\n",
"<br>\n",
"$\\neg(\\alpha\\lor\\beta)\\equiv(\\neg\\alpha\\land\\neg\\beta)$\n",
"<br>\n",
"4. Distribute disjunction over conjunction\n",
"<br>\n",
"Disjunction and conjunction are distributive over each other.\n",
"Now that we only have conjunctions, disjunctions and negations in our expression, \n",
"we will distribute disjunctions over conjunctions wherever possible as this will give us a sentence which is a conjunction of simpler clauses, \n",
"which is what we wanted in the first place.\n",
"<br>\n",
"We need a term of the form\n",
"<br>\n",
"$(\\alpha_{1}\\lor\\alpha_{2}\\lor\\alpha_{3}...)\\land(\\beta_{1}\\lor\\beta_{2}\\lor\\beta_{3}...)\\land(\\gamma_{1}\\lor\\gamma_{2}\\lor\\gamma_{3}...)\\land...$\n",
"<br>\n",
"<br>\n",
"The `to_cnf` function executes this conversion using helper subroutines."
]
},
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">to_cnf</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Convert a propositional logical sentence to conjunctive normal form.</span>\n",
"<span class=\"sd\"> That is, to the form ((A | ~B | ...) & (B | C | ...) & ...) [p. 253]</span>\n",
"<span class=\"sd\"> >>> to_cnf('~(B | C)')</span>\n",
"<span class=\"sd\"> (~B & ~C)</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"nb\">str</span><span class=\"p\">):</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">eliminate_implications</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span> <span class=\"c1\"># Steps 1, 2 from p. 253</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">move_not_inwards</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span> <span class=\"c1\"># Step 3</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">distribute_and_over_or</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span> <span class=\"c1\"># Step 4</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(to_cnf)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`to_cnf` calls three subroutines.\n",
"<br>\n",
"`eliminate_implications` converts bi-implications and implications to their logical equivalents.\n",
"<br>\n",
"`move_not_inwards` removes negations from compound statements and moves them inwards using De Morgan's laws.\n",
"<br>\n",
"`distribute_and_over_or` distributes disjunctions over conjunctions.\n",
"<br>\n",
"Run the cell below for implementation details."
]
},
{
"cell_type": "code",
"execution_count": 31,
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">eliminate_implications</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Change implications into equivalent form with only &, |, and ~ as logical operators."""</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span> <span class=\"ow\">or</span> <span class=\"n\">is_symbol</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">s</span> <span class=\"c1\"># Atoms are unchanged.</span>\n",
" <span class=\"n\">args</span> <span class=\"o\">=</span> <span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"nb\">map</span><span class=\"p\">(</span><span class=\"n\">eliminate_implications</span><span class=\"p\">,</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">))</span>\n",
" <span class=\"n\">a</span><span class=\"p\">,</span> <span class=\"n\">b</span> <span class=\"o\">=</span> <span class=\"n\">args</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">],</span> <span class=\"n\">args</span><span class=\"p\">[</span><span class=\"o\">-</span><span class=\"mi\">1</span><span class=\"p\">]</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'==>'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">b</span> <span class=\"o\">|</span> <span class=\"o\">~</span><span class=\"n\">a</span>\n",
" <span class=\"k\">elif</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'<=='</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">a</span> <span class=\"o\">|</span> <span class=\"o\">~</span><span class=\"n\">b</span>\n",
" <span class=\"k\">elif</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'<=>'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">(</span><span class=\"n\">a</span> <span class=\"o\">|</span> <span class=\"o\">~</span><span class=\"n\">b</span><span class=\"p\">)</span> <span class=\"o\">&</span> <span class=\"p\">(</span><span class=\"n\">b</span> <span class=\"o\">|</span> <span class=\"o\">~</span><span class=\"n\">a</span><span class=\"p\">)</span>\n",
" <span class=\"k\">elif</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'^'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">assert</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">args</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"mi\">2</span> <span class=\"c1\"># TODO: relax this restriction</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">(</span><span class=\"n\">a</span> <span class=\"o\">&</span> <span class=\"o\">~</span><span class=\"n\">b</span><span class=\"p\">)</span> <span class=\"o\">|</span> <span class=\"p\">(</span><span class=\"o\">~</span><span class=\"n\">a</span> <span class=\"o\">&</span> <span class=\"n\">b</span><span class=\"p\">)</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"k\">assert</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"ow\">in</span> <span class=\"p\">(</span><span class=\"s1\">'&'</span><span class=\"p\">,</span> <span class=\"s1\">'|'</span><span class=\"p\">,</span> <span class=\"s1\">'~'</span><span class=\"p\">)</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span><span class=\"p\">,</span> <span class=\"o\">*</span><span class=\"n\">args</span><span class=\"p\">)</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">move_not_inwards</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Rewrite sentence s by moving negation sign inward.</span>\n",
"<span class=\"sd\"> >>> move_not_inwards(~(A | B))</span>\n",
"<span class=\"sd\"> (~A & ~B)"""</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'~'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">def</span> <span class=\"nf\">NOT</span><span class=\"p\">(</span><span class=\"n\">b</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">move_not_inwards</span><span class=\"p\">(</span><span class=\"o\">~</span><span class=\"n\">b</span><span class=\"p\">)</span>\n",
" <span class=\"n\">a</span> <span class=\"o\">=</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">a</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'~'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">move_not_inwards</span><span class=\"p\">(</span><span class=\"n\">a</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])</span> <span class=\"c1\"># ~~A ==> A</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">a</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'&'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'|'</span><span class=\"p\">,</span> <span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"nb\">map</span><span class=\"p\">(</span><span class=\"n\">NOT</span><span class=\"p\">,</span> <span class=\"n\">a</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)))</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">a</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'|'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'&'</span><span class=\"p\">,</span> <span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"nb\">map</span><span class=\"p\">(</span><span class=\"n\">NOT</span><span class=\"p\">,</span> <span class=\"n\">a</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)))</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">s</span>\n",
" <span class=\"k\">elif</span> <span class=\"n\">is_symbol</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span><span class=\"p\">)</span> <span class=\"ow\">or</span> <span class=\"ow\">not</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">s</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span><span class=\"p\">,</span> <span class=\"o\">*</span><span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"nb\">map</span><span class=\"p\">(</span><span class=\"n\">move_not_inwards</span><span class=\"p\">,</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)))</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">distribute_and_over_or</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Given a sentence s consisting of conjunctions and disjunctions</span>\n",
"<span class=\"sd\"> of literals, return an equivalent sentence in CNF.</span>\n",
"<span class=\"sd\"> >>> distribute_and_over_or((A & B) | C)</span>\n",
"<span class=\"sd\"> ((A | C) & (B | C))</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'|'</span><span class=\"p\">:</span>\n",
" <span class=\"n\">s</span> <span class=\"o\">=</span> <span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'|'</span><span class=\"p\">,</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">!=</span> <span class=\"s1\">'|'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">distribute_and_over_or</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"mi\">0</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">False</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)</span> <span class=\"o\">==</span> <span class=\"mi\">1</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">distribute_and_over_or</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])</span>\n",
" <span class=\"n\">conj</span> <span class=\"o\">=</span> <span class=\"n\">first</span><span class=\"p\">(</span><span class=\"n\">arg</span> <span class=\"k\">for</span> <span class=\"n\">arg</span> <span class=\"ow\">in</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span> <span class=\"k\">if</span> <span class=\"n\">arg</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'&'</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">conj</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">s</span>\n",
" <span class=\"n\">others</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"n\">a</span> <span class=\"k\">for</span> <span class=\"n\">a</span> <span class=\"ow\">in</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span> <span class=\"k\">if</span> <span class=\"n\">a</span> <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"n\">conj</span><span class=\"p\">]</span>\n",
" <span class=\"n\">rest</span> <span class=\"o\">=</span> <span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'|'</span><span class=\"p\">,</span> <span class=\"n\">others</span><span class=\"p\">)</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'&'</span><span class=\"p\">,</span> <span class=\"p\">[</span><span class=\"n\">distribute_and_over_or</span><span class=\"p\">(</span><span class=\"n\">c</span> <span class=\"o\">|</span> <span class=\"n\">rest</span><span class=\"p\">)</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"n\">conj</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">])</span>\n",
" <span class=\"k\">elif</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'&'</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'&'</span><span class=\"p\">,</span> <span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"nb\">map</span><span class=\"p\">(</span><span class=\"n\">distribute_and_over_or</span><span class=\"p\">,</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)))</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">s</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(eliminate_implications)\n",
"psource(move_not_inwards)\n",
"psource(distribute_and_over_or)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's convert some sentences to see how it works\n"
]
},
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((A | ~B) & (B | ~A))"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A, B, C, D = expr('A, B, C, D')\n",
"to_cnf(A |'<=>'| B)"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((A | ~B | ~C) & (B | ~A) & (C | ~A))"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"to_cnf(A |'<=>'| (B & C))"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(A & (C | B) & (D | B))"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"to_cnf(A & (B | (C & D)))"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((B | ~A | C | ~D) & (A | ~A | C | ~D) & (B | ~B | C | ~D) & (A | ~B | C | ~D))"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"to_cnf((A |'<=>'| ~B) |'==>'| (C | ~D))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Coming back to our resolution problem, we can see how the `to_cnf` function is utilized here"
]
},
{
"cell_type": "code",
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">pl_resolution</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Propositional-logic resolution: say if alpha follows from KB. [Figure 7.12]"""</span>\n",
" <span class=\"n\">clauses</span> <span class=\"o\">=</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span> <span class=\"o\">+</span> <span class=\"n\">conjuncts</span><span class=\"p\">(</span><span class=\"n\">to_cnf</span><span class=\"p\">(</span><span class=\"o\">~</span><span class=\"n\">alpha</span><span class=\"p\">))</span>\n",
" <span class=\"n\">new</span> <span class=\"o\">=</span> <span class=\"nb\">set</span><span class=\"p\">()</span>\n",
" <span class=\"k\">while</span> <span class=\"bp\">True</span><span class=\"p\">:</span>\n",
" <span class=\"n\">n</span> <span class=\"o\">=</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">)</span>\n",
" <span class=\"n\">pairs</span> <span class=\"o\">=</span> <span class=\"p\">[(</span><span class=\"n\">clauses</span><span class=\"p\">[</span><span class=\"n\">i</span><span class=\"p\">],</span> <span class=\"n\">clauses</span><span class=\"p\">[</span><span class=\"n\">j</span><span class=\"p\">])</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">i</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">n</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">j</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">i</span><span class=\"o\">+</span><span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"n\">n</span><span class=\"p\">)]</span>\n",
" <span class=\"k\">for</span> <span class=\"p\">(</span><span class=\"n\">ci</span><span class=\"p\">,</span> <span class=\"n\">cj</span><span class=\"p\">)</span> <span class=\"ow\">in</span> <span class=\"n\">pairs</span><span class=\"p\">:</span>\n",
" <span class=\"n\">resolvents</span> <span class=\"o\">=</span> <span class=\"n\">pl_resolve</span><span class=\"p\">(</span><span class=\"n\">ci</span><span class=\"p\">,</span> <span class=\"n\">cj</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"bp\">False</span> <span class=\"ow\">in</span> <span class=\"n\">resolvents</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">True</span>\n",
" <span class=\"n\">new</span> <span class=\"o\">=</span> <span class=\"n\">new</span><span class=\"o\">.</span><span class=\"n\">union</span><span class=\"p\">(</span><span class=\"nb\">set</span><span class=\"p\">(</span><span class=\"n\">resolvents</span><span class=\"p\">))</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">new</span><span class=\"o\">.</span><span class=\"n\">issubset</span><span class=\"p\">(</span><span class=\"nb\">set</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">)):</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">False</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"n\">new</span><span class=\"p\">:</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">c</span> <span class=\"ow\">not</span> <span class=\"ow\">in</span> <span class=\"n\">clauses</span><span class=\"p\">:</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">c</span><span class=\"p\">)</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(pl_resolution)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(True, False)"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pl_resolution(wumpus_kb, ~P11), pl_resolution(wumpus_kb, P11)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(False, False)"
]
},
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pl_resolution(wumpus_kb, ~P22), pl_resolution(wumpus_kb, P22)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Forward and backward chaining\n",
"Previously, we said we will look at two algorithms to check if a sentence is entailed by the `KB`, \n",
"but here's a third one. \n",
"The difference here is that our goal now is to determine if a knowledge base of definite clauses entails a single proposition symbol *q* - the query.\n",
"There is a catch however, the knowledge base can only contain **Horn clauses**.\n",
"<br>\n",
"#### Horn Clauses\n",
"Horn clauses can be defined as a *disjunction* of *literals* with **at most** one positive literal. \n",
"<br>\n",
"A Horn clause with exactly one positive literal is called a *definite clause*.\n",
"<br>\n",
"A Horn clause might look like \n",
"<br>\n",
"$\\neg a\\lor\\neg b\\lor\\neg c\\lor\\neg d... \\lor z$\n",
"<br>\n",
"This, coincidentally, is also a definite clause.\n",
"<br>\n",
"Using De Morgan's laws, the example above can be simplified to \n",
"<br>\n",
"$a\\land b\\land c\\land d ... \\implies z$\n",
"<br>\n",
"This seems like a logical representation of how humans process known data and facts. \n",
"Assuming percepts `a`, `b`, `c`, `d` ... to be true simultaneously, we can infer `z` to also be true at that point in time. \n",
"There are some interesting aspects of Horn clauses that make algorithmic inference or *resolution* easier.\n",
"- Definite clauses can be written as implications:\n",
"<br>\n",
"The most important simplification a definite clause provides is that it can be written as an implication.\n",
"The premise (or the knowledge that leads to the implication) is a conjunction of positive literals.\n",
"The conclusion (the implied statement) is also a positive literal.\n",
"The sentence thus becomes easier to understand.\n",
"The premise and the conclusion are conventionally called the *body* and the *head* respectively.\n",
"A single positive literal is called a *fact*.\n",
"- Forward chaining and backward chaining can be used for inference from Horn clauses:\n",
"<br>\n",
"Forward chaining is semantically identical to `AND-OR-Graph-Search` from the chapter on search algorithms.\n",
"Implementational details will be explained shortly.\n",
"- Deciding entailment with Horn clauses is linear in size of the knowledge base:\n",
"<br>\n",
"Surprisingly, the forward and backward chaining algorithms traverse each element of the knowledge base at most once, greatly simplifying the problem.\n",
"<br>\n",
"<br>\n",
"The function `pl_fc_entails` implements forward chaining to see if a knowledge base `KB` entails a symbol `q`.\n",
"<br>\n",
"Before we proceed further, note that `pl_fc_entails` doesn't use an ordinary `KB` instance. \n",
"The knowledge base here is an instance of the `PropDefiniteKB` class, derived from the `PropKB` class, \n",
"but modified to store definite clauses.\n",
"<br>\n",
"The main point of difference arises in the inclusion of a helper method to `PropDefiniteKB` that returns a list of clauses in KB that have a given symbol `p` in their premise."
]
},
{
"cell_type": "code",
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span> <span class=\"k\">def</span> <span class=\"nf\">clauses_with_premise</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">p</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Return a list of the clauses in KB that have p in their premise.</span>\n",
"<span class=\"sd\"> This could be cached away for O(1) speed, but we'll recompute it."""</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">[</span><span class=\"n\">c</span> <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">clauses</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">c</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'==>'</span> <span class=\"ow\">and</span> <span class=\"n\">p</span> <span class=\"ow\">in</span> <span class=\"n\">conjuncts</span><span class=\"p\">(</span><span class=\"n\">c</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])]</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(PropDefiniteKB.clauses_with_premise)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's now have a look at the `pl_fc_entails` algorithm."
]
},
{
"cell_type": "code",
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">pl_fc_entails</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">q</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Use forward chaining to see if a PropDefiniteKB entails symbol q.</span>\n",
"<span class=\"sd\"> [Figure 7.15]</span>\n",
"<span class=\"sd\"> >>> pl_fc_entails(horn_clauses_KB, expr('Q'))</span>\n",
"<span class=\"sd\"> True</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"n\">count</span> <span class=\"o\">=</span> <span class=\"p\">{</span><span class=\"n\">c</span><span class=\"p\">:</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">conjuncts</span><span class=\"p\">(</span><span class=\"n\">c</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]))</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">c</span><span class=\"o\">.</span><span class=\"n\">op</span> <span class=\"o\">==</span> <span class=\"s1\">'==>'</span><span class=\"p\">}</span>\n",
" <span class=\"n\">inferred</span> <span class=\"o\">=</span> <span class=\"n\">defaultdict</span><span class=\"p\">(</span><span class=\"nb\">bool</span><span class=\"p\">)</span>\n",
" <span class=\"n\">agenda</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"n\">s</span> <span class=\"k\">for</span> <span class=\"n\">s</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span> <span class=\"k\">if</span> <span class=\"n\">is_prop_symbol</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">op</span><span class=\"p\">)]</span>\n",
" <span class=\"k\">while</span> <span class=\"n\">agenda</span><span class=\"p\">:</span>\n",
" <span class=\"n\">p</span> <span class=\"o\">=</span> <span class=\"n\">agenda</span><span class=\"o\">.</span><span class=\"n\">pop</span><span class=\"p\">()</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">p</span> <span class=\"o\">==</span> <span class=\"n\">q</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">True</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">inferred</span><span class=\"p\">[</span><span class=\"n\">p</span><span class=\"p\">]:</span>\n",
" <span class=\"n\">inferred</span><span class=\"p\">[</span><span class=\"n\">p</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"bp\">True</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses_with_premise</span><span class=\"p\">(</span><span class=\"n\">p</span><span class=\"p\">):</span>\n",
" <span class=\"n\">count</span><span class=\"p\">[</span><span class=\"n\">c</span><span class=\"p\">]</span> <span class=\"o\">-=</span> <span class=\"mi\">1</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">count</span><span class=\"p\">[</span><span class=\"n\">c</span><span class=\"p\">]</span> <span class=\"o\">==</span> <span class=\"mi\">0</span><span class=\"p\">:</span>\n",
" <span class=\"n\">agenda</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">c</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">])</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">False</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(pl_fc_entails)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function accepts a knowledge base `KB` (an instance of `PropDefiniteKB`) and a query `q` as inputs.\n",
"<br>\n",
"<br>\n",
"`count` initially stores the number of symbols in the premise of each sentence in the knowledge base.\n",
"<br>\n",
"The `conjuncts` helper function separates a given sentence at conjunctions.\n",
"<br>\n",
"`inferred` is initialized as a *boolean* defaultdict. \n",
"This will be used later to check if we have inferred all premises of each clause of the agenda.\n",
"<br>\n",
"`agenda` initially stores a list of clauses that the knowledge base knows to be true.\n",
"The `is_prop_symbol` helper function checks if the given symbol is a valid propositional logic symbol.\n",
"<br>\n",
"<br>\n",
"We now iterate through `agenda`, popping a symbol `p` on each iteration.\n",
"If the query `q` is the same as `p`, we know that entailment holds.\n",
"<br>\n",
"The agenda is processed, reducing `count` by one for each implication with a premise `p`.\n",
"A conclusion is added to the agenda when `count` reaches zero. This means we know all the premises of that particular implication to be true.\n",
"<br>\n",
"`clauses_with_premise` is a helpful method of the `PropKB` class.\n",
"It returns a list of clauses in the knowledge base that have `p` in their premise.\n",
"<br>\n",
"<br>\n",
"Now that we have an idea of how this function works, let's see a few examples of its usage, but we first need to define our knowledge base. We assume we know the following clauses to be true."
]
},
{
"cell_type": "code",
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
"outputs": [],
"source": [
"clauses = ['(B & F)==>E', \n",
" '(A & E & F)==>G', \n",
" '(B & C)==>F', \n",
" '(A & B)==>D', \n",
" '(E & F)==>H', \n",
" '(H & I)==>J',\n",
" 'A', \n",
" 'B', \n",
" 'C']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We will now `tell` this information to our knowledge base."
]
},
{
"cell_type": "code",
"outputs": [],
"source": [
"definite_clauses_KB = PropDefiniteKB()\n",
"for clause in clauses:\n",
" definite_clauses_KB.tell(expr(clause))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now check if our knowledge base entails the following queries."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
"pl_fc_entails(definite_clauses_KB, expr('G'))"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pl_fc_entails(definite_clauses_KB, expr('H'))"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pl_fc_entails(definite_clauses_KB, expr('I'))"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"pl_fc_entails(definite_clauses_KB, expr('J'))"
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Effective Propositional Model Checking\n",
"\n",
"The previous segments elucidate the algorithmic procedure for model checking. \n",
"In this segment, we look at ways of making them computationally efficient.\n",
"<br>\n",
"The problem we are trying to solve is conventionally called the _propositional satisfiability problem_, abbreviated as the _SAT_ problem.\n",
"In layman terms, if there exists a model that satisfies a given Boolean formula, the formula is called satisfiable.\n",
"<br>\n",
"The SAT problem was the first problem to be proven _NP-complete_.\n",
"The main characteristics of an NP-complete problem are:\n",
"- Given a solution to such a problem, it is easy to verify if the solution solves the problem.\n",
"- The time required to actually solve the problem using any known algorithm increases exponentially with respect to the size of the problem.\n",
"<br>\n",
"<br>\n",
"Due to these properties, heuristic and approximational methods are often applied to find solutions to these problems.\n",
"<br>\n",
"It is extremely important to be able to solve large scale SAT problems efficiently because \n",
"many combinatorial problems in computer science can be conveniently reduced to checking the satisfiability of a propositional sentence under some constraints.\n",
"<br>\n",
"We will introduce two new algorithms that perform propositional model checking in a computationally effective way.\n",
"<br>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1. DPLL (Davis-Putnam-Logeman-Loveland) algorithm\n",
"This algorithm is very similar to Backtracking-Search.\n",
"It recursively enumerates possible models in a depth-first fashion with the following improvements over algorithms like `tt_entails`:\n",
"1. Early termination:\n",
"<br>\n",
"In certain cases, the algorithm can detect the truth value of a statement using just a partially completed model.\n",
"For example, $(P\\lor Q)\\land(P\\lor R)$ is true if P is true, regardless of other variables.\n",
"This reduces the search space significantly.\n",
"2. Pure symbol heuristic:\n",
"<br>\n",
"A symbol that has the same sign (positive or negative) in all clauses is called a _pure symbol_.\n",
"It isn't difficult to see that any satisfiable model will have the pure symbols assigned such that its parent clause becomes _true_.\n",
"For example, $(P\\lor\\neg Q)\\land(\\neg Q\\lor\\neg R)\\land(R\\lor P)$ has P and Q as pure symbols\n",
"and for the sentence to be true, P _has_ to be true and Q _has_ to be false.\n",
"The pure symbol heuristic thus simplifies the problem a bit.\n",
"3. Unit clause heuristic:\n",
"<br>\n",
"In the context of DPLL, clauses with just one literal and clauses with all but one _false_ literals are called unit clauses.\n",
"If a clause is a unit clause, it can only be satisfied by assigning the necessary value to make the last literal true.\n",
"We have no other choice.\n",
"<br>\n",
"Assigning one unit clause can create another unit clause.\n",
"For example, when P is false, $(P\\lor Q)$ becomes a unit clause, causing _true_ to be assigned to Q.\n",
"A series of forced assignments derived from previous unit clauses is called _unit propagation_.\n",
"In this way, this heuristic simplifies the problem further.\n",
"<br>\n",
"The algorithm often employs other tricks to scale up to large problems.\n",
"However, these tricks are currently out of the scope of this notebook. Refer to section 7.6 of the book for more details.\n",
"<br>\n",
"<br>\n",
"Let's have a look at the algorithm."
]
},
{
"cell_type": "code",
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">dpll</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""See if the clauses are true in a partial model."""</span>\n",
" <span class=\"n\">unknown_clauses</span> <span class=\"o\">=</span> <span class=\"p\">[]</span> <span class=\"c1\"># clauses with an unknown truth value</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"n\">clauses</span><span class=\"p\">:</span>\n",
" <span class=\"n\">val</span> <span class=\"o\">=</span> <span class=\"n\">pl_true</span><span class=\"p\">(</span><span class=\"n\">c</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">val</span> <span class=\"ow\">is</span> <span class=\"bp\">False</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">False</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">val</span> <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"bp\">True</span><span class=\"p\">:</span>\n",
" <span class=\"n\">unknown_clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">c</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">unknown_clauses</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">model</span>\n",
" <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">value</span> <span class=\"o\">=</span> <span class=\"n\">find_pure_symbol</span><span class=\"p\">(</span><span class=\"n\">symbols</span><span class=\"p\">,</span> <span class=\"n\">unknown_clauses</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">P</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">dpll</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">removeall</span><span class=\"p\">(</span><span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">),</span> <span class=\"n\">extend</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">,</span> <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">value</span><span class=\"p\">))</span>\n",
" <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">value</span> <span class=\"o\">=</span> <span class=\"n\">find_unit_clause</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">P</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">dpll</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">removeall</span><span class=\"p\">(</span><span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">),</span> <span class=\"n\">extend</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">,</span> <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">value</span><span class=\"p\">))</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">symbols</span><span class=\"p\">:</span>\n",
" <span class=\"k\">raise</span> <span class=\"ne\">TypeError</span><span class=\"p\">(</span><span class=\"s2\">"Argument should be of the type Expr."</span><span class=\"p\">)</span>\n",
" <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"n\">symbols</span> <span class=\"o\">=</span> <span class=\"n\">symbols</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">],</span> <span class=\"n\">symbols</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">:]</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">(</span><span class=\"n\">dpll</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">,</span> <span class=\"n\">extend</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">,</span> <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"bp\">True</span><span class=\"p\">))</span> <span class=\"ow\">or</span>\n",
" <span class=\"n\">dpll</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">,</span> <span class=\"n\">extend</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">,</span> <span class=\"n\">P</span><span class=\"p\">,</span> <span class=\"bp\">False</span><span class=\"p\">)))</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(dpll)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The algorithm uses the ideas described above to check satisfiability of a sentence in propositional logic.\n",
"It recursively calls itself, simplifying the problem at each step. It also uses helper functions `find_pure_symbol` and `find_unit_clause` to carry out steps 2 and 3 above.\n",
"<br>\n",
"The `dpll_satisfiable` helper function converts the input clauses to _conjunctive normal form_ and calls the `dpll` function with the correct parameters."
]
},
{
"cell_type": "code",
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">dpll_satisfiable</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Check satisfiability of a propositional sentence.</span>\n",
"<span class=\"sd\"> This differs from the book code in two ways: (1) it returns a model</span>\n",
"<span class=\"sd\"> rather than True when it succeeds; this is more useful. (2) The</span>\n",
"<span class=\"sd\"> function find_pure_symbol is passed a list of unknown clauses, rather</span>\n",
"<span class=\"sd\"> than a list of all clauses and the model; this is more efficient."""</span>\n",
" <span class=\"n\">clauses</span> <span class=\"o\">=</span> <span class=\"n\">conjuncts</span><span class=\"p\">(</span><span class=\"n\">to_cnf</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">))</span>\n",
" <span class=\"n\">symbols</span> <span class=\"o\">=</span> <span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"n\">prop_symbols</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">))</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">dpll</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">symbols</span><span class=\"p\">,</span> <span class=\"p\">{})</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(dpll_satisfiable)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see a few examples of usage."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [],
"source": [
"A, B, C, D = expr('A, B, C, D')"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{A: True, B: True, C: False, D: True}"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dpll_satisfiable(A & B & ~C & D)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a simple case to highlight that the algorithm actually works."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dpll_satisfiable((A & B) | (C & ~A) | (B & ~D))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If a particular symbol isn't present in the solution, \n",
"it means that the solution is independent of the value of that symbol.\n",
"In this case, the solution is independent of A."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{A: True, B: True}"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dpll_satisfiable(A |'<=>'| B)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dpll_satisfiable((A |'<=>'| B) |'==>'| (C & ~A))"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dpll_satisfiable((A | (B & C)) |'<=>'| ((A | B) & (A | C)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2. WalkSAT algorithm\n",
"This algorithm is very similar to Hill climbing.\n",
"On every iteration, the algorithm picks an unsatisfied clause and flips a symbol in the clause.\n",
"This is similar to finding a neighboring state in the `hill_climbing` algorithm.\n",
"<br>\n",
"The symbol to be flipped is decided by an evaluation function that counts the number of unsatisfied clauses.\n",
"Sometimes, symbols are also flipped randomly, to avoid local optima. A subtle balance between greediness and randomness is required. Alternatively, some versions of the algorithm restart with a completely new random assignment if no solution has been found for too long, as a way of getting out of local minima of numbers of unsatisfied clauses.\n",
"<br>\n",
"<br>\n",
"Let's have a look at the algorithm."
]
},
{
"cell_type": "code",
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">WalkSAT</span><span class=\"p\">(</span><span class=\"n\">clauses</span><span class=\"p\">,</span> <span class=\"n\">p</span><span class=\"o\">=</span><span class=\"mf\">0.5</span><span class=\"p\">,</span> <span class=\"n\">max_flips</span><span class=\"o\">=</span><span class=\"mi\">10000</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Checks for satisfiability of all clauses by randomly flipping values of variables</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"c1\"># Set of all symbols in all clauses</span>\n",
" <span class=\"n\">symbols</span> <span class=\"o\">=</span> <span class=\"p\">{</span><span class=\"n\">sym</span> <span class=\"k\">for</span> <span class=\"n\">clause</span> <span class=\"ow\">in</span> <span class=\"n\">clauses</span> <span class=\"k\">for</span> <span class=\"n\">sym</span> <span class=\"ow\">in</span> <span class=\"n\">prop_symbols</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">)}</span>\n",
" <span class=\"c1\"># model is a random assignment of true/false to the symbols in clauses</span>\n",
" <span class=\"n\">model</span> <span class=\"o\">=</span> <span class=\"p\">{</span><span class=\"n\">s</span><span class=\"p\">:</span> <span class=\"n\">random</span><span class=\"o\">.</span><span class=\"n\">choice</span><span class=\"p\">([</span><span class=\"bp\">True</span><span class=\"p\">,</span> <span class=\"bp\">False</span><span class=\"p\">])</span> <span class=\"k\">for</span> <span class=\"n\">s</span> <span class=\"ow\">in</span> <span class=\"n\">symbols</span><span class=\"p\">}</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">i</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">max_flips</span><span class=\"p\">):</span>\n",
" <span class=\"n\">satisfied</span><span class=\"p\">,</span> <span class=\"n\">unsatisfied</span> <span class=\"o\">=</span> <span class=\"p\">[],</span> <span class=\"p\">[]</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">clause</span> <span class=\"ow\">in</span> <span class=\"n\">clauses</span><span class=\"p\">:</span>\n",
" <span class=\"p\">(</span><span class=\"n\">satisfied</span> <span class=\"k\">if</span> <span class=\"n\">pl_true</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">)</span> <span class=\"k\">else</span> <span class=\"n\">unsatisfied</span><span class=\"p\">)</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">unsatisfied</span><span class=\"p\">:</span> <span class=\"c1\"># if model satisfies all the clauses</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">model</span>\n",
" <span class=\"n\">clause</span> <span class=\"o\">=</span> <span class=\"n\">random</span><span class=\"o\">.</span><span class=\"n\">choice</span><span class=\"p\">(</span><span class=\"n\">unsatisfied</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">probability</span><span class=\"p\">(</span><span class=\"n\">p</span><span class=\"p\">):</span>\n",
" <span class=\"n\">sym</span> <span class=\"o\">=</span> <span class=\"n\">random</span><span class=\"o\">.</span><span class=\"n\">choice</span><span class=\"p\">(</span><span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"n\">prop_symbols</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">)))</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"c1\"># Flip the symbol in clause that maximizes number of sat. clauses</span>\n",
" <span class=\"k\">def</span> <span class=\"nf\">sat_count</span><span class=\"p\">(</span><span class=\"n\">sym</span><span class=\"p\">):</span>\n",
" <span class=\"c1\"># Return the the number of clauses satisfied after flipping the symbol.</span>\n",
" <span class=\"n\">model</span><span class=\"p\">[</span><span class=\"n\">sym</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"ow\">not</span> <span class=\"n\">model</span><span class=\"p\">[</span><span class=\"n\">sym</span><span class=\"p\">]</span>\n",
" <span class=\"n\">count</span> <span class=\"o\">=</span> <span class=\"nb\">len</span><span class=\"p\">([</span><span class=\"n\">clause</span> <span class=\"k\">for</span> <span class=\"n\">clause</span> <span class=\"ow\">in</span> <span class=\"n\">clauses</span> <span class=\"k\">if</span> <span class=\"n\">pl_true</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">,</span> <span class=\"n\">model</span><span class=\"p\">)])</span>\n",
" <span class=\"n\">model</span><span class=\"p\">[</span><span class=\"n\">sym</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"ow\">not</span> <span class=\"n\">model</span><span class=\"p\">[</span><span class=\"n\">sym</span><span class=\"p\">]</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">count</span>\n",
" <span class=\"n\">sym</span> <span class=\"o\">=</span> <span class=\"n\">argmax</span><span class=\"p\">(</span><span class=\"n\">prop_symbols</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">),</span> <span class=\"n\">key</span><span class=\"o\">=</span><span class=\"n\">sat_count</span><span class=\"p\">)</span>\n",
" <span class=\"n\">model</span><span class=\"p\">[</span><span class=\"n\">sym</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"ow\">not</span> <span class=\"n\">model</span><span class=\"p\">[</span><span class=\"n\">sym</span><span class=\"p\">]</span>\n",
" <span class=\"c1\"># If no solution is found within the flip limit, we return failure</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">None</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(WalkSAT)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The function takes three arguments:\n",
"<br>\n",
"1. The `clauses` we want to satisfy.\n",
"<br>\n",
"2. The probability `p` of randomly changing a symbol.\n",
"<br>\n",
"3. The maximum number of flips (`max_flips`) the algorithm will run for. If the clauses are still unsatisfied, the algorithm returns `None` to denote failure.\n",
"<br>\n",
"The algorithm is identical in concept to Hill climbing and the code isn't difficult to understand.\n",
"<br>\n",
"<br>\n",
"Let's see a few examples of usage."
]
},
{
"cell_type": "code",
"outputs": [],
"source": [
"A, B, C, D = expr('A, B, C, D')"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{A: True, B: True, C: False, D: True}"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"WalkSAT([A, B, ~C, D], 0.5, 100)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is a simple case to show that the algorithm converges."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"WalkSAT([A & B, A & C], 0.5, 100)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{A: True, B: True, C: True, D: True}"
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"WalkSAT([A & B, C & D, C & B], 0.5, 100)"
]
},
{
"cell_type": "code",
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
"metadata": {},
"outputs": [],
"source": [
"WalkSAT([A & B, C | D, ~(D | B)], 0.5, 1000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This one doesn't give any output because WalkSAT did not find any model where these clauses hold. We can solve these clauses to see that they together form a contradiction and hence, it isn't supposed to have a solution."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One point of difference between this algorithm and the `dpll_satisfiable` algorithms is that both these algorithms take inputs differently. \n",
"For WalkSAT to take complete sentences as input, \n",
"we can write a helper function that converts the input sentence into conjunctive normal form and then calls WalkSAT with the list of conjuncts of the CNF form of the sentence."
]
},
{
"cell_type": "code",
"outputs": [],
"source": [
"def WalkSAT_CNF(sentence, p=0.5, max_flips=10000):\n",
" return WalkSAT(conjuncts(to_cnf(sentence)), 0, max_flips)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can call `WalkSAT_CNF` and `DPLL_Satisfiable` with the same arguments."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"WalkSAT_CNF((A & B) | (C & ~A) | (B & ~D), 0.5, 1000)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It works!\n",
"<br>\n",
"Notice that the solution generated by WalkSAT doesn't omit variables that the sentence doesn't depend upon. \n",
"If the sentence is independent of a particular variable, the solution contains a random value for that variable because of the stochastic nature of the algorithm.\n",
"<br>\n",
"<br>\n",
"Let's compare the runtime of WalkSAT and DPLL for a few cases. We will use the `%%timeit` magic to do this."
]
},
{
"cell_type": "code",
"outputs": [],
"source": [
"sentence_1 = A |'<=>'| B\n",
"sentence_2 = (A & B) | (C & ~A) | (B & ~D)\n",
"sentence_3 = (A | (B & C)) |'<=>'| ((A | B) & (A | C))"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.55 ms ± 64.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%%timeit\n",
"dpll_satisfiable(sentence_1)\n",
"dpll_satisfiable(sentence_2)\n",
"dpll_satisfiable(sentence_3)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1.02 ms ± 6.92 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n"
]
}
],
"source": [
"%%timeit\n",
"WalkSAT_CNF(sentence_1)\n",
"WalkSAT_CNF(sentence_2)\n",
"WalkSAT_CNF(sentence_3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On an average, for solvable cases, `WalkSAT` is quite faster than `dpll` because, for a small number of variables, \n",
"`WalkSAT` can reduce the search space significantly. \n",
"Results can be different for sentences with more symbols though.\n",
"Feel free to play around with this to understand the trade-offs of these algorithms better."
]
},
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### SATPlan"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this section we show how to make plans by logical inference. The basic idea is very simple. It includes the following three steps:\n",
"1. Constuct a sentence that includes:\n",
" 1. A colection of assertions about the initial state.\n",
" 2. The successor-state axioms for all the possible actions at each time up to some maximum time t.\n",
" 3. The assertion that the goal is achieved at time t.\n",
"2. Present the whole sentence to a SAT solver.\n",
"3. Assuming a model is found, extract from the model those variables that represent actions and are assigned true. Together they represent a plan to achieve the goals.\n",
"\n",
"\n",
"Lets have a look at the algorithm"
]
},
{
"cell_type": "code",
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">SAT_plan</span><span class=\"p\">(</span><span class=\"n\">init</span><span class=\"p\">,</span> <span class=\"n\">transition</span><span class=\"p\">,</span> <span class=\"n\">goal</span><span class=\"p\">,</span> <span class=\"n\">t_max</span><span class=\"p\">,</span> <span class=\"n\">SAT_solver</span><span class=\"o\">=</span><span class=\"n\">dpll_satisfiable</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Converts a planning problem to Satisfaction problem by translating it to a cnf sentence.</span>\n",
"<span class=\"sd\"> [Figure 7.22]"""</span>\n",
"\n",
" <span class=\"c1\"># Functions used by SAT_plan</span>\n",
" <span class=\"k\">def</span> <span class=\"nf\">translate_to_SAT</span><span class=\"p\">(</span><span class=\"n\">init</span><span class=\"p\">,</span> <span class=\"n\">transition</span><span class=\"p\">,</span> <span class=\"n\">goal</span><span class=\"p\">,</span> <span class=\"n\">time</span><span class=\"p\">):</span>\n",
" <span class=\"n\">clauses</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n",
" <span class=\"n\">states</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"n\">state</span> <span class=\"k\">for</span> <span class=\"n\">state</span> <span class=\"ow\">in</span> <span class=\"n\">transition</span><span class=\"p\">]</span>\n",
"\n",
" <span class=\"c1\"># Symbol claiming state s at time t</span>\n",
" <span class=\"n\">state_counter</span> <span class=\"o\">=</span> <span class=\"n\">itertools</span><span class=\"o\">.</span><span class=\"n\">count</span><span class=\"p\">()</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">s</span> <span class=\"ow\">in</span> <span class=\"n\">states</span><span class=\"p\">:</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">t</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">time</span><span class=\"o\">+</span><span class=\"mi\">1</span><span class=\"p\">):</span>\n",
" <span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"s2\">"State_{}"</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"nb\">next</span><span class=\"p\">(</span><span class=\"n\">state_counter</span><span class=\"p\">)))</span>\n",
"\n",
" <span class=\"c1\"># Add initial state axiom</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">init</span><span class=\"p\">,</span> <span class=\"mi\">0</span><span class=\"p\">])</span>\n",
"\n",
" <span class=\"c1\"># Add goal state axiom</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">goal</span><span class=\"p\">,</span> <span class=\"n\">time</span><span class=\"p\">])</span>\n",
"\n",
" <span class=\"c1\"># All possible transitions</span>\n",
" <span class=\"n\">transition_counter</span> <span class=\"o\">=</span> <span class=\"n\">itertools</span><span class=\"o\">.</span><span class=\"n\">count</span><span class=\"p\">()</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">s</span> <span class=\"ow\">in</span> <span class=\"n\">states</span><span class=\"p\">:</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">action</span> <span class=\"ow\">in</span> <span class=\"n\">transition</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">]:</span>\n",
" <span class=\"n\">s_</span> <span class=\"o\">=</span> <span class=\"n\">transition</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">][</span><span class=\"n\">action</span><span class=\"p\">]</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">t</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">time</span><span class=\"p\">):</span>\n",
" <span class=\"c1\"># Action 'action' taken from state 's' at time 't' to reach 's_'</span>\n",
" <span class=\"n\">action_sym</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">action</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"n\">Expr</span><span class=\"p\">(</span>\n",
" <span class=\"s2\">"Transition_{}"</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"nb\">next</span><span class=\"p\">(</span><span class=\"n\">transition_counter</span><span class=\"p\">)))</span>\n",
"\n",
" <span class=\"c1\"># Change the state from s to s_</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">action_sym</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">action</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">]</span> <span class=\"o\">|</span><span class=\"s1\">'==>'</span><span class=\"o\">|</span> <span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">])</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">action_sym</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">action</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">]</span> <span class=\"o\">|</span><span class=\"s1\">'==>'</span><span class=\"o\">|</span> <span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">s_</span><span class=\"p\">,</span> <span class=\"n\">t</span> <span class=\"o\">+</span> <span class=\"mi\">1</span><span class=\"p\">])</span>\n",
"\n",
" <span class=\"c1\"># Allow only one state at any time</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">t</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">time</span><span class=\"o\">+</span><span class=\"mi\">1</span><span class=\"p\">):</span>\n",
" <span class=\"c1\"># must be a state at any time</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'|'</span><span class=\"p\">,</span> <span class=\"p\">[</span><span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">]</span> <span class=\"k\">for</span> <span class=\"n\">s</span> <span class=\"ow\">in</span> <span class=\"n\">states</span><span class=\"p\">]))</span>\n",
"\n",
" <span class=\"k\">for</span> <span class=\"n\">s</span> <span class=\"ow\">in</span> <span class=\"n\">states</span><span class=\"p\">:</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">s_</span> <span class=\"ow\">in</span> <span class=\"n\">states</span><span class=\"p\">[</span><span class=\"n\">states</span><span class=\"o\">.</span><span class=\"n\">index</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">)</span> <span class=\"o\">+</span> <span class=\"mi\">1</span><span class=\"p\">:]:</span>\n",
" <span class=\"c1\"># for each pair of states s, s_ only one is possible at time t</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">((</span><span class=\"o\">~</span><span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">])</span> <span class=\"o\">|</span> <span class=\"p\">(</span><span class=\"o\">~</span><span class=\"n\">state_sym</span><span class=\"p\">[</span><span class=\"n\">s_</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">]))</span>\n",
"\n",
" <span class=\"c1\"># Restrict to one transition per timestep</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">t</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">time</span><span class=\"p\">):</span>\n",
" <span class=\"c1\"># list of possible transitions at time t</span>\n",
" <span class=\"n\">transitions_t</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"n\">tr</span> <span class=\"k\">for</span> <span class=\"n\">tr</span> <span class=\"ow\">in</span> <span class=\"n\">action_sym</span> <span class=\"k\">if</span> <span class=\"n\">tr</span><span class=\"p\">[</span><span class=\"mi\">2</span><span class=\"p\">]</span> <span class=\"o\">==</span> <span class=\"n\">t</span><span class=\"p\">]</span>\n",
"\n",
" <span class=\"c1\"># make sure at least one of the transitions happens</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'|'</span><span class=\"p\">,</span> <span class=\"p\">[</span><span class=\"n\">action_sym</span><span class=\"p\">[</span><span class=\"n\">tr</span><span class=\"p\">]</span> <span class=\"k\">for</span> <span class=\"n\">tr</span> <span class=\"ow\">in</span> <span class=\"n\">transitions_t</span><span class=\"p\">]))</span>\n",
"\n",
" <span class=\"k\">for</span> <span class=\"n\">tr</span> <span class=\"ow\">in</span> <span class=\"n\">transitions_t</span><span class=\"p\">:</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">tr_</span> <span class=\"ow\">in</span> <span class=\"n\">transitions_t</span><span class=\"p\">[</span><span class=\"n\">transitions_t</span><span class=\"o\">.</span><span class=\"n\">index</span><span class=\"p\">(</span><span class=\"n\">tr</span><span class=\"p\">)</span> <span class=\"o\">+</span> <span class=\"mi\">1</span><span class=\"p\">:]:</span>\n",
" <span class=\"c1\"># there cannot be two transitions tr and tr_ at time t</span>\n",
" <span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"o\">~</span><span class=\"n\">action_sym</span><span class=\"p\">[</span><span class=\"n\">tr</span><span class=\"p\">]</span> <span class=\"o\">|</span> <span class=\"o\">~</span><span class=\"n\">action_sym</span><span class=\"p\">[</span><span class=\"n\">tr_</span><span class=\"p\">])</span>\n",
"\n",
" <span class=\"c1\"># Combine the clauses to form the cnf</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">associate</span><span class=\"p\">(</span><span class=\"s1\">'&'</span><span class=\"p\">,</span> <span class=\"n\">clauses</span><span class=\"p\">)</span>\n",
"\n",
" <span class=\"k\">def</span> <span class=\"nf\">extract_solution</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">):</span>\n",
" <span class=\"n\">true_transitions</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"n\">t</span> <span class=\"k\">for</span> <span class=\"n\">t</span> <span class=\"ow\">in</span> <span class=\"n\">action_sym</span> <span class=\"k\">if</span> <span class=\"n\">model</span><span class=\"p\">[</span><span class=\"n\">action_sym</span><span class=\"p\">[</span><span class=\"n\">t</span><span class=\"p\">]]]</span>\n",
" <span class=\"c1\"># Sort transitions based on time, which is the 3rd element of the tuple</span>\n",
" <span class=\"n\">true_transitions</span><span class=\"o\">.</span><span class=\"n\">sort</span><span class=\"p\">(</span><span class=\"n\">key</span><span class=\"o\">=</span><span class=\"k\">lambda</span> <span class=\"n\">x</span><span class=\"p\">:</span> <span class=\"n\">x</span><span class=\"p\">[</span><span class=\"mi\">2</span><span class=\"p\">])</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">[</span><span class=\"n\">action</span> <span class=\"k\">for</span> <span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">action</span><span class=\"p\">,</span> <span class=\"n\">time</span> <span class=\"ow\">in</span> <span class=\"n\">true_transitions</span><span class=\"p\">]</span>\n",
"\n",
" <span class=\"c1\"># Body of SAT_plan algorithm</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">t</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">t_max</span><span class=\"p\">):</span>\n",
" <span class=\"c1\"># dictionaries to help extract the solution from model</span>\n",
" <span class=\"n\">state_sym</span> <span class=\"o\">=</span> <span class=\"p\">{}</span>\n",
" <span class=\"n\">action_sym</span> <span class=\"o\">=</span> <span class=\"p\">{}</span>\n",
"\n",
" <span class=\"n\">cnf</span> <span class=\"o\">=</span> <span class=\"n\">translate_to_SAT</span><span class=\"p\">(</span><span class=\"n\">init</span><span class=\"p\">,</span> <span class=\"n\">transition</span><span class=\"p\">,</span> <span class=\"n\">goal</span><span class=\"p\">,</span> <span class=\"n\">t</span><span class=\"p\">)</span>\n",
" <span class=\"n\">model</span> <span class=\"o\">=</span> <span class=\"n\">SAT_solver</span><span class=\"p\">(</span><span class=\"n\">cnf</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">model</span> <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"bp\">False</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">extract_solution</span><span class=\"p\">(</span><span class=\"n\">model</span><span class=\"p\">)</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">None</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(SAT_plan)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's see few examples of its usage. First we define a transition and then call `SAT_plan`."
]
},
{
"cell_type": "code",
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n",
"['Right']\n",
"['Left', 'Left']\n"
]
}
],
"source": [
"transition = {'A': {'Left': 'A', 'Right': 'B'},\n",
" 'B': {'Left': 'A', 'Right': 'C'},\n",
" 'C': {'Left': 'B', 'Right': 'C'}}\n",
"\n",
"\n",
"print(SAT_plan('A', transition, 'C', 2)) \n",
"print(SAT_plan('A', transition, 'B', 3))\n",
"print(SAT_plan('C', transition, 'A', 3))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let us do the same for another transition."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Right', 'Down']\n"
]
}
],
"source": [
"transition = {(0, 0): {'Right': (0, 1), 'Down': (1, 0)},\n",
" (0, 1): {'Left': (1, 0), 'Down': (1, 1)},\n",
" (1, 0): {'Right': (1, 0), 'Up': (1, 0), 'Left': (1, 0), 'Down': (1, 0)},\n",
" (1, 1): {'Left': (1, 0), 'Up': (0, 1)}}\n",
"\n",
"\n",
"print(SAT_plan((0, 0), transition, (1, 1), 4))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## First-Order Logic Knowledge Bases: `FolKB`\n",
"\n",
"The class `FolKB` can be used to represent a knowledge base of First-order logic sentences. You would initialize and use it the same way as you would for `PropKB` except that the clauses are first-order definite clauses. We will see how to write such clauses to create a database and query them in the following sections."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Criminal KB\n",
"In this section we create a `FolKB` based on the following paragraph.<br/>\n",
"<em>The law says that it is a crime for an American to sell weapons to hostile nations. The country Nono, an enemy of America, has some missiles, and all of its missiles were sold to it by Colonel West, who is American.</em><br/>\n",
"The first step is to extract the facts and convert them into first-order definite clauses. Extracting the facts from data alone is a challenging task. Fortunately, we have a small paragraph and can do extraction and conversion manually. We'll store the clauses in list aptly named `clauses`."
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [],
"source": [
"clauses = []"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<em>“... it is a crime for an American to sell weapons to hostile nations”</em><br/>\n",
"The keywords to look for here are 'crime', 'American', 'sell', 'weapon' and 'hostile'. We use predicate symbols to make meaning of them.\n",
"\n",
"* `Criminal(x)`: `x` is a criminal\n",
"* `American(x)`: `x` is an American\n",
"* `Sells(x ,y, z)`: `x` sells `y` to `z`\n",
"* `Weapon(x)`: `x` is a weapon\n",
"* `Hostile(x)`: `x` is a hostile nation\n",
"\n",
"Let us now combine them with appropriate variable naming to depict the meaning of the sentence. The criminal `x` is also the American `x` who sells weapon `y` to `z`, which is a hostile nation.\n",
"\n",
"$\\text{American}(x) \\land \\text{Weapon}(y) \\land \\text{Sells}(x, y, z) \\land \\text{Hostile}(z) \\implies \\text{Criminal} (x)$"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [],
"source": [
"clauses.append(expr(\"(American(x) & Weapon(y) & Sells(x, y, z) & Hostile(z)) ==> Criminal(x)\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<em>\"The country Nono, an enemy of America\"</em><br/>\n",
"We now know that Nono is an enemy of America. We represent these nations using the constant symbols `Nono` and `America`. the enemy relation is show using the predicate symbol `Enemy`.\n",
"\n",
"$\\text{Enemy}(\\text{Nono}, \\text{America})$"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [],
"source": [
"clauses.append(expr(\"Enemy(Nono, America)\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<em>\"Nono ... has some missiles\"</em><br/>\n",
"This states the existence of some missile which is owned by Nono. $\\exists x \\text{Owns}(\\text{Nono}, x) \\land \\text{Missile}(x)$. We invoke existential instantiation to introduce a new constant `M1` which is the missile owned by Nono.\n",
"\n",
"$\\text{Owns}(\\text{Nono}, \\text{M1}), \\text{Missile}(\\text{M1})$"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [],
"source": [
"clauses.append(expr(\"Owns(Nono, M1)\"))\n",
"clauses.append(expr(\"Missile(M1)\"))"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"<em>\"All of its missiles were sold to it by Colonel West\"</em><br/>\n",
"If Nono owns something and it classifies as a missile, then it was sold to Nono by West.\n",
"\n",
"$\\text{Missile}(x) \\land \\text{Owns}(\\text{Nono}, x) \\implies \\text{Sells}(\\text{West}, x, \\text{Nono})$"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [],
"source": [
"clauses.append(expr(\"(Missile(x) & Owns(Nono, x)) ==> Sells(West, x, Nono)\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<em>\"West, who is American\"</em><br/>\n",
"West is an American.\n",
"\n",
"$\\text{American}(\\text{West})$"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [],
"source": [
"clauses.append(expr(\"American(West)\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We also know, from our understanding of language, that missiles are weapons and that an enemy of America counts as “hostile”.\n",
"\n",
"$\\text{Missile}(x) \\implies \\text{Weapon}(x), \\text{Enemy}(x, \\text{America}) \\implies \\text{Hostile}(x)$"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [],
"source": [
"clauses.append(expr(\"Missile(x) ==> Weapon(x)\"))\n",
"clauses.append(expr(\"Enemy(x, America) ==> Hostile(x)\"))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have converted the information into first-order definite clauses we can create our first-order logic knowledge base."
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
"crime_kb = FolKB(clauses)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `subst` helper function substitutes variables with given values in first-order logic statements.\n",
"This will be useful in later algorithms.\n",
"It's implementation is quite simple and self-explanatory."
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">subst</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">x</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""Substitute the substitution s into the expression x.</span>\n",
"<span class=\"sd\"> >>> subst({x: 42, y:0}, F(x) + y)</span>\n",
"<span class=\"sd\"> (F(42) + 0)</span>\n",
"<span class=\"sd\"> """</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">x</span><span class=\"p\">,</span> <span class=\"nb\">list</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"p\">[</span><span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">xi</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">xi</span> <span class=\"ow\">in</span> <span class=\"n\">x</span><span class=\"p\">]</span>\n",
" <span class=\"k\">elif</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">x</span><span class=\"p\">,</span> <span class=\"nb\">tuple</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"nb\">tuple</span><span class=\"p\">([</span><span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">xi</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">xi</span> <span class=\"ow\">in</span> <span class=\"n\">x</span><span class=\"p\">])</span>\n",
" <span class=\"k\">elif</span> <span class=\"ow\">not</span> <span class=\"nb\">isinstance</span><span class=\"p\">(</span><span class=\"n\">x</span><span class=\"p\">,</span> <span class=\"n\">Expr</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">x</span>\n",
" <span class=\"k\">elif</span> <span class=\"n\">is_var_symbol</span><span class=\"p\">(</span><span class=\"n\">x</span><span class=\"o\">.</span><span class=\"n\">op</span><span class=\"p\">):</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">get</span><span class=\"p\">(</span><span class=\"n\">x</span><span class=\"p\">,</span> <span class=\"n\">x</span><span class=\"p\">)</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"k\">return</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"n\">x</span><span class=\"o\">.</span><span class=\"n\">op</span><span class=\"p\">,</span> <span class=\"o\">*</span><span class=\"p\">[</span><span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">s</span><span class=\"p\">,</span> <span class=\"n\">arg</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">arg</span> <span class=\"ow\">in</span> <span class=\"n\">x</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">])</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"psource(subst)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here's an example of how `subst` can be used."
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Owns(Nono, M1)"
]
},
"execution_count": 78,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"subst({x: expr('Nono'), y: expr('M1')}, expr('Owns(x, y)'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Inference in First-Order Logic\n",
"In this section we look at a forward chaining and a backward chaining algorithm for `FolKB`. Both aforementioned algorithms rely on a process called <strong>unification</strong>, a key component of all first-order inference algorithms."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Unification\n",
"We sometimes require finding substitutions that make different logical expressions look identical. This process, called unification, is done by the `unify` algorithm. It takes as input two sentences and returns a <em>unifier</em> for them if one exists. A unifier is a dictionary which stores the substitutions required to make the two sentences identical. It does so by recursively unifying the components of a sentence, where the unification of a variable symbol `var` with a constant symbol `Const` is the mapping `{var: Const}`. Let's look at a few examples."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{x: 3}"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"unify(expr('x'), 3)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{x: B}"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"unify(expr('A(x)'), expr('A(B)'))"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{x: Bella, y: Dobby}"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"unify(expr('Cat(x) & Dog(Dobby)'), expr('Cat(Bella) & Dog(y)'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In cases where there is no possible substitution that unifies the two sentences the function return `None`."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"print(unify(expr('Cat(x)'), expr('Dog(Dobby)')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We also need to take care we do not unintentionally use the same variable name. Unify treats them as a single variable which prevents it from taking multiple value."
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"None\n"
]
}
],
"source": [
"print(unify(expr('Cat(x) & Dog(Dobby)'), expr('Cat(Bella) & Dog(x)')))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Forward Chaining Algorithm\n",
"We consider the simple forward-chaining algorithm presented in <em>Figure 9.3</em>. We look at each rule in the knoweldge base and see if the premises can be satisfied. This is done by finding a substitution which unifies each of the premise with a clause in the `KB`. If we are able to unify the premises, the conclusion (with the corresponding substitution) is added to the `KB`. This inferencing process is repeated until either the query can be answered or till no new sentences can be added. We test if the newly added clause unifies with the query in which case the substitution yielded by `unify` is an answer to the query. If we run out of sentences to infer, this means the query was a failure.\n",
"The function `fol_fc_ask` is a generator which yields all substitutions which validate the query."
]
},
{
"cell_type": "code",
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">fol_fc_ask</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">):</span>\n",
" <span class=\"sd\">"""A simple forward-chaining algorithm. [Figure 9.3]"""</span>\n",
" <span class=\"c1\"># TODO: Improve efficiency</span>\n",
" <span class=\"n\">kb_consts</span> <span class=\"o\">=</span> <span class=\"nb\">list</span><span class=\"p\">({</span><span class=\"n\">c</span> <span class=\"k\">for</span> <span class=\"n\">clause</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span> <span class=\"k\">for</span> <span class=\"n\">c</span> <span class=\"ow\">in</span> <span class=\"n\">constant_symbols</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">)})</span>\n",
" <span class=\"k\">def</span> <span class=\"nf\">enum_subst</span><span class=\"p\">(</span><span class=\"n\">p</span><span class=\"p\">):</span>\n",
" <span class=\"n\">query_vars</span> <span class=\"o\">=</span> <span class=\"nb\">list</span><span class=\"p\">({</span><span class=\"n\">v</span> <span class=\"k\">for</span> <span class=\"n\">clause</span> <span class=\"ow\">in</span> <span class=\"n\">p</span> <span class=\"k\">for</span> <span class=\"n\">v</span> <span class=\"ow\">in</span> <span class=\"n\">variables</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">)})</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">assignment_list</span> <span class=\"ow\">in</span> <span class=\"n\">itertools</span><span class=\"o\">.</span><span class=\"n\">product</span><span class=\"p\">(</span><span class=\"n\">kb_consts</span><span class=\"p\">,</span> <span class=\"n\">repeat</span><span class=\"o\">=</span><span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">query_vars</span><span class=\"p\">)):</span>\n",
" <span class=\"n\">theta</span> <span class=\"o\">=</span> <span class=\"p\">{</span><span class=\"n\">x</span><span class=\"p\">:</span> <span class=\"n\">y</span> <span class=\"k\">for</span> <span class=\"n\">x</span><span class=\"p\">,</span> <span class=\"n\">y</span> <span class=\"ow\">in</span> <span class=\"nb\">zip</span><span class=\"p\">(</span><span class=\"n\">query_vars</span><span class=\"p\">,</span> <span class=\"n\">assignment_list</span><span class=\"p\">)}</span>\n",
" <span class=\"k\">yield</span> <span class=\"n\">theta</span>\n",
"\n",
" <span class=\"c1\"># check if we can answer without new inferences</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">q</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span><span class=\"p\">:</span>\n",
" <span class=\"n\">phi</span> <span class=\"o\">=</span> <span class=\"n\">unify</span><span class=\"p\">(</span><span class=\"n\">q</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">,</span> <span class=\"p\">{})</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">phi</span> <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"bp\">None</span><span class=\"p\">:</span>\n",
" <span class=\"k\">yield</span> <span class=\"n\">phi</span>\n",
"\n",
" <span class=\"k\">while</span> <span class=\"bp\">True</span><span class=\"p\">:</span>\n",
" <span class=\"n\">new</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">rule</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span><span class=\"p\">:</span>\n",
" <span class=\"n\">p</span><span class=\"p\">,</span> <span class=\"n\">q</span> <span class=\"o\">=</span> <span class=\"n\">parse_definite_clause</span><span class=\"p\">(</span><span class=\"n\">rule</span><span class=\"p\">)</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">theta</span> <span class=\"ow\">in</span> <span class=\"n\">enum_subst</span><span class=\"p\">(</span><span class=\"n\">p</span><span class=\"p\">):</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">set</span><span class=\"p\">(</span><span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">theta</span><span class=\"p\">,</span> <span class=\"n\">p</span><span class=\"p\">))</span><span class=\"o\">.</span><span class=\"n\">issubset</span><span class=\"p\">(</span><span class=\"nb\">set</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span><span class=\"p\">)):</span>\n",
" <span class=\"n\">q_</span> <span class=\"o\">=</span> <span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">theta</span><span class=\"p\">,</span> <span class=\"n\">q</span><span class=\"p\">)</span>\n",
" <span class=\"k\">if</span> <span class=\"nb\">all</span><span class=\"p\">([</span><span class=\"n\">unify</span><span class=\"p\">(</span><span class=\"n\">x</span><span class=\"p\">,</span> <span class=\"n\">q_</span><span class=\"p\">,</span> <span class=\"p\">{})</span> <span class=\"ow\">is</span> <span class=\"bp\">None</span> <span class=\"k\">for</span> <span class=\"n\">x</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">clauses</span> <span class=\"o\">+</span> <span class=\"n\">new</span><span class=\"p\">]):</span>\n",
" <span class=\"n\">new</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">q_</span><span class=\"p\">)</span>\n",
" <span class=\"n\">phi</span> <span class=\"o\">=</span> <span class=\"n\">unify</span><span class=\"p\">(</span><span class=\"n\">q_</span><span class=\"p\">,</span> <span class=\"n\">alpha</span><span class=\"p\">,</span> <span class=\"p\">{})</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">phi</span> <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"bp\">None</span><span class=\"p\">:</span>\n",
" <span class=\"k\">yield</span> <span class=\"n\">phi</span>\n",
" <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">new</span><span class=\"p\">:</span>\n",
" <span class=\"k\">break</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">clause</span> <span class=\"ow\">in</span> <span class=\"n\">new</span><span class=\"p\">:</span>\n",
" <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">tell</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">)</span>\n",
" <span class=\"k\">return</span> <span class=\"bp\">None</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's find out all the hostile nations. Note that we only told the `KB` that Nono was an enemy of America, not that it was hostile."
]
},
{
"cell_type": "code",
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[{x: Nono}]\n"
]
}
],
"source": [
"answer = fol_fc_ask(crime_kb, expr('Hostile(x)'))\n",
"print(list(answer))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The generator returned a single substitution which says that Nono is a hostile nation. See how after adding another enemy nation the generator returns two substitutions."
]
},
{
"cell_type": "code",
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[{x: Nono}, {x: JaJa}]\n"
]
}
],
"source": [
"crime_kb.tell(expr('Enemy(JaJa, America)'))\n",
"answer = fol_fc_ask(crime_kb, expr('Hostile(x)'))\n",
"print(list(answer))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<strong><em>Note</em>:</strong> `fol_fc_ask` makes changes to the `KB` by adding sentences to it."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Backward Chaining Algorithm\n",
"This algorithm works backward from the goal, chaining through rules to find known facts that support the proof. Suppose `goal` is the query we want to find the substitution for. We find rules of the form $\\text{lhs} \\implies \\text{goal}$ in the `KB` and try to prove `lhs`. There may be multiple clauses in the `KB` which give multiple `lhs`. It is sufficient to prove only one of these. But to prove a `lhs` all the conjuncts in the `lhs` of the clause must be proved. This makes it similar to <em>And/Or</em> search."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### OR\n",
"The <em>OR</em> part of the algorithm comes from our choice to select any clause of the form $\\text{lhs} \\implies \\text{goal}$. Looking at all rules's `lhs` whose `rhs` unify with the `goal`, we yield a substitution which proves all the conjuncts in the `lhs`. We use `parse_definite_clause` to attain `lhs` and `rhs` from a clause of the form $\\text{lhs} \\implies \\text{rhs}$. For atomic facts the `lhs` is an empty list."
]
},
{
"cell_type": "code",
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
"execution_count": 87,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">fol_bc_or</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">goal</span><span class=\"p\">,</span> <span class=\"n\">theta</span><span class=\"p\">):</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">rule</span> <span class=\"ow\">in</span> <span class=\"n\">KB</span><span class=\"o\">.</span><span class=\"n\">fetch_rules_for_goal</span><span class=\"p\">(</span><span class=\"n\">goal</span><span class=\"p\">):</span>\n",
" <span class=\"n\">lhs</span><span class=\"p\">,</span> <span class=\"n\">rhs</span> <span class=\"o\">=</span> <span class=\"n\">parse_definite_clause</span><span class=\"p\">(</span><span class=\"n\">standardize_variables</span><span class=\"p\">(</span><span class=\"n\">rule</span><span class=\"p\">))</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">theta1</span> <span class=\"ow\">in</span> <span class=\"n\">fol_bc_and</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">lhs</span><span class=\"p\">,</span> <span class=\"n\">unify</span><span class=\"p\">(</span><span class=\"n\">rhs</span><span class=\"p\">,</span> <span class=\"n\">goal</span><span class=\"p\">,</span> <span class=\"n\">theta</span><span class=\"p\">)):</span>\n",
" <span class=\"k\">yield</span> <span class=\"n\">theta1</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### AND\n",
"The <em>AND</em> corresponds to proving all the conjuncts in the `lhs`. We need to find a substitution which proves each <em>and</em> every clause in the list of conjuncts."
]
},
{
"cell_type": "code",
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
"execution_count": 88,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n",
" \"http://www.w3.org/TR/html4/strict.dtd\">\n",
"\n",
"<html>\n",
"<head>\n",
" <title></title>\n",
" <meta http-equiv=\"content-type\" content=\"text/html; charset=None\">\n",
" <style type=\"text/css\">\n",
"td.linenos { background-color: #f0f0f0; padding-right: 10px; }\n",
"span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\n",
"pre { line-height: 125%; }\n",
"body .hll { background-color: #ffffcc }\n",
"body { background: #f8f8f8; }\n",
"body .c { color: #408080; font-style: italic } /* Comment */\n",
"body .err { border: 1px solid #FF0000 } /* Error */\n",
"body .k { color: #008000; font-weight: bold } /* Keyword */\n",
"body .o { color: #666666 } /* Operator */\n",
"body .ch { color: #408080; font-style: italic } /* Comment.Hashbang */\n",
"body .cm { color: #408080; font-style: italic } /* Comment.Multiline */\n",
"body .cp { color: #BC7A00 } /* Comment.Preproc */\n",
"body .cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */\n",
"body .c1 { color: #408080; font-style: italic } /* Comment.Single */\n",
"body .cs { color: #408080; font-style: italic } /* Comment.Special */\n",
"body .gd { color: #A00000 } /* Generic.Deleted */\n",
"body .ge { font-style: italic } /* Generic.Emph */\n",
"body .gr { color: #FF0000 } /* Generic.Error */\n",
"body .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n",
"body .gi { color: #00A000 } /* Generic.Inserted */\n",
"body .go { color: #888888 } /* Generic.Output */\n",
"body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n",
"body .gs { font-weight: bold } /* Generic.Strong */\n",
"body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n",
"body .gt { color: #0044DD } /* Generic.Traceback */\n",
"body .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n",
"body .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n",
"body .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n",
"body .kp { color: #008000 } /* Keyword.Pseudo */\n",
"body .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n",
"body .kt { color: #B00040 } /* Keyword.Type */\n",
"body .m { color: #666666 } /* Literal.Number */\n",
"body .s { color: #BA2121 } /* Literal.String */\n",
"body .na { color: #7D9029 } /* Name.Attribute */\n",
"body .nb { color: #008000 } /* Name.Builtin */\n",
"body .nc { color: #0000FF; font-weight: bold } /* Name.Class */\n",
"body .no { color: #880000 } /* Name.Constant */\n",
"body .nd { color: #AA22FF } /* Name.Decorator */\n",
"body .ni { color: #999999; font-weight: bold } /* Name.Entity */\n",
"body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */\n",
"body .nf { color: #0000FF } /* Name.Function */\n",
"body .nl { color: #A0A000 } /* Name.Label */\n",
"body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */\n",
"body .nt { color: #008000; font-weight: bold } /* Name.Tag */\n",
"body .nv { color: #19177C } /* Name.Variable */\n",
"body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */\n",
"body .w { color: #bbbbbb } /* Text.Whitespace */\n",
"body .mb { color: #666666 } /* Literal.Number.Bin */\n",
"body .mf { color: #666666 } /* Literal.Number.Float */\n",
"body .mh { color: #666666 } /* Literal.Number.Hex */\n",
"body .mi { color: #666666 } /* Literal.Number.Integer */\n",
"body .mo { color: #666666 } /* Literal.Number.Oct */\n",
"body .sa { color: #BA2121 } /* Literal.String.Affix */\n",
"body .sb { color: #BA2121 } /* Literal.String.Backtick */\n",
"body .sc { color: #BA2121 } /* Literal.String.Char */\n",
"body .dl { color: #BA2121 } /* Literal.String.Delimiter */\n",
"body .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n",
"body .s2 { color: #BA2121 } /* Literal.String.Double */\n",
"body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */\n",
"body .sh { color: #BA2121 } /* Literal.String.Heredoc */\n",
"body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */\n",
"body .sx { color: #008000 } /* Literal.String.Other */\n",
"body .sr { color: #BB6688 } /* Literal.String.Regex */\n",
"body .s1 { color: #BA2121 } /* Literal.String.Single */\n",
"body .ss { color: #19177C } /* Literal.String.Symbol */\n",
"body .bp { color: #008000 } /* Name.Builtin.Pseudo */\n",
"body .fm { color: #0000FF } /* Name.Function.Magic */\n",
"body .vc { color: #19177C } /* Name.Variable.Class */\n",
"body .vg { color: #19177C } /* Name.Variable.Global */\n",
"body .vi { color: #19177C } /* Name.Variable.Instance */\n",
"body .vm { color: #19177C } /* Name.Variable.Magic */\n",
"body .il { color: #666666 } /* Literal.Number.Integer.Long */\n",
"\n",
" </style>\n",
"</head>\n",
"<body>\n",
"<h2></h2>\n",
"\n",
"<div class=\"highlight\"><pre><span></span><span class=\"k\">def</span> <span class=\"nf\">fol_bc_and</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">goals</span><span class=\"p\">,</span> <span class=\"n\">theta</span><span class=\"p\">):</span>\n",
" <span class=\"k\">if</span> <span class=\"n\">theta</span> <span class=\"ow\">is</span> <span class=\"bp\">None</span><span class=\"p\">:</span>\n",
" <span class=\"k\">pass</span>\n",
" <span class=\"k\">elif</span> <span class=\"ow\">not</span> <span class=\"n\">goals</span><span class=\"p\">:</span>\n",
" <span class=\"k\">yield</span> <span class=\"n\">theta</span>\n",
" <span class=\"k\">else</span><span class=\"p\">:</span>\n",
" <span class=\"n\">first</span><span class=\"p\">,</span> <span class=\"n\">rest</span> <span class=\"o\">=</span> <span class=\"n\">goals</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">],</span> <span class=\"n\">goals</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">:]</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">theta1</span> <span class=\"ow\">in</span> <span class=\"n\">fol_bc_or</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">theta</span><span class=\"p\">,</span> <span class=\"n\">first</span><span class=\"p\">),</span> <span class=\"n\">theta</span><span class=\"p\">):</span>\n",
" <span class=\"k\">for</span> <span class=\"n\">theta2</span> <span class=\"ow\">in</span> <span class=\"n\">fol_bc_and</span><span class=\"p\">(</span><span class=\"n\">KB</span><span class=\"p\">,</span> <span class=\"n\">rest</span><span class=\"p\">,</span> <span class=\"n\">theta1</span><span class=\"p\">):</span>\n",
" <span class=\"k\">yield</span> <span class=\"n\">theta2</span>\n",
"</pre></div>\n",
"</body>\n",
"</html>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now the main function `fl_bc_ask` calls `fol_bc_or` with substitution initialized as empty. The `ask` method of `FolKB` uses `fol_bc_ask` and fetches the first substitution returned by the generator to answer query. Let's query the knowledge base we created from `clauses` to find hostile nations."
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [],
"source": [
"# Rebuild KB because running fol_fc_ask would add new facts to the KB\n",
"crime_kb = FolKB(clauses)"
]
},
{
"cell_type": "code",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{v_5: x, x: Nono}"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"crime_kb.ask(expr('Hostile(x)'))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You may notice some new variables in the substitution. They are introduced to standardize the variable names to prevent naming problems as discussed in the [Unification section](#Unification)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Appendix: The Implementation of `|'==>'|`\n",
"Consider the `Expr` formed by this syntax:"
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What is the funny `|'==>'|` syntax? The trick is that \"`|`\" is just the regular Python or-operator, and so is exactly equivalent to this: "
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In other words, there are two applications of or-operators. Here's the first one:"
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"What is going on here is that the `__or__` method of `Expr` serves a dual purpose. If the right-hand-side is another `Expr` (or a number), then the result is an `Expr`, as in `(P | Q)`. But if the right-hand-side is a string, then the string is taken to be an operator, and we create a node in the abstract syntax tree corresponding to a partially-filled `Expr`, one where we know the left-hand-side is `P` and the operator is `==>`, but we don't yet know the right-hand-side.\n",
"The `PartialExpr` class has an `__or__` method that says to create an `Expr` node with the right-hand-side filled in. Here we can see the combination of the `PartialExpr` with `Q` to create a complete `Expr`:"
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"partial = PartialExpr('==>', P) \n",
"partial | ~Q"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This [trick](http://code.activestate.com/recipes/384122-infix-operators/) is due to [Ferdinand Jamitzky](http://code.activestate.com/recipes/users/98863/), with a modification by [C. G. Vedant](https://github.com/Chipe1),\n",
"who suggested using a string inside the or-bars.\n",
"\n",
"## Appendix: The Implementation of `expr`\n",
"\n",
"How does `expr` parse a string into an `Expr`? It turns out there are two tricks (besides the Jamitzky/Vedant trick):\n",
"\n",
"1. We do a string substitution, replacing \"`==>`\" with \"`|'==>'|`\" (and likewise for other operators).\n",
"2. We `eval` the resulting string in an environment in which every identifier\n",
"is bound to a symbol with that identifier as the `op`.\n",
"\n",
"In other words,"
{
"cell_type": "code",
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"outputs": [
{
"data": {
"text/plain": [
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"P, Q = symbols('P, Q')\n",
"~(P & Q) |'==>'| (~P | ~Q)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"One thing to beware of: this puts `==>` at the same precedence level as `\"|\"`, which is not quite right. For example, we get this:"
]
},
{
"cell_type": "code",
"outputs": [
{
"data": {
"text/plain": [
"(((P & Q) ==> P) | Q)"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"P & Q |'==>'| P | Q"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which is probably not what we meant; when in doubt, put in extra parens:"
]
},
{
"cell_type": "code",
"outputs": [
{
"data": {
"text/plain": [
"((P & Q) ==> (P | Q))"
]
},
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(P & Q) |'==>'| (P | Q)"
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Examples"
]
},
{
"cell_type": "code",
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"\n",
"<script type=\"text/javascript\" src=\"./js/canvas.js\"></script>\n",
"<div>\n",
"<canvas id=\"canvas_bc_ask\" width=\"800\" height=\"600\" style=\"background:rgba(158, 167, 184, 0.2);\" onclick='click_callback(this, event, \"canvas_bc_ask\")'></canvas>\n",
"</div>\n",
"\n",
"<script> var canvas_bc_ask_canvas_object = new Canvas(\"canvas_bc_ask\");</script>\n"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<script>\n",
"canvas_bc_ask_canvas_object.clear();\n",
"canvas_bc_ask_canvas_object.strokeWidth(3);\n",
"canvas_bc_ask_canvas_object.stroke(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.font(\"12px Arial\");\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(340, 85, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(340, 85, 460, 85);\n",
"canvas_bc_ask_canvas_object.line(340, 85, 340, 115);\n",
"canvas_bc_ask_canvas_object.line(460, 85, 460, 115);\n",
"canvas_bc_ask_canvas_object.line(340, 115, 460, 115);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Criminal(West)\", 348, 109);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(55, 255, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(55, 255, 175, 255);\n",
"canvas_bc_ask_canvas_object.line(55, 255, 55, 285);\n",
"canvas_bc_ask_canvas_object.line(175, 255, 175, 285);\n",
"canvas_bc_ask_canvas_object.line(55, 285, 175, 285);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"American(West)\", 63, 279);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(245, 255, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(245, 255, 365, 255);\n",
"canvas_bc_ask_canvas_object.line(245, 255, 245, 285);\n",
"canvas_bc_ask_canvas_object.line(365, 255, 365, 285);\n",
"canvas_bc_ask_canvas_object.line(245, 285, 365, 285);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Weapon(M1)\", 253, 279);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(435, 255, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(435, 255, 555, 255);\n",
"canvas_bc_ask_canvas_object.line(435, 255, 435, 285);\n",
"canvas_bc_ask_canvas_object.line(555, 255, 555, 285);\n",
"canvas_bc_ask_canvas_object.line(435, 285, 555, 285);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Sells(West, M1, Nono)\", 443, 279);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(625, 255, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(625, 255, 745, 255);\n",
"canvas_bc_ask_canvas_object.line(625, 255, 625, 285);\n",
"canvas_bc_ask_canvas_object.line(745, 255, 745, 285);\n",
"canvas_bc_ask_canvas_object.line(625, 285, 745, 285);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Hostile(Nono)\", 633, 279);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(55, 425, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(55, 425, 175, 425);\n",
"canvas_bc_ask_canvas_object.line(55, 425, 55, 455);\n",
"canvas_bc_ask_canvas_object.line(175, 425, 175, 455);\n",
"canvas_bc_ask_canvas_object.line(55, 455, 175, 455);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Missile(M1)\", 63, 449);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(245, 425, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(245, 425, 365, 425);\n",
"canvas_bc_ask_canvas_object.line(245, 425, 245, 455);\n",
"canvas_bc_ask_canvas_object.line(365, 425, 365, 455);\n",
"canvas_bc_ask_canvas_object.line(245, 455, 365, 455);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Missile(M1)\", 253, 449);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(435, 425, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(435, 425, 555, 425);\n",
"canvas_bc_ask_canvas_object.line(435, 425, 435, 455);\n",
"canvas_bc_ask_canvas_object.line(555, 425, 555, 455);\n",
"canvas_bc_ask_canvas_object.line(435, 455, 555, 455);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Owns(Nono, M1)\", 443, 449);\n",
"canvas_bc_ask_canvas_object.fill(200, 200, 200);\n",
"canvas_bc_ask_canvas_object.rect(625, 425, 120, 30);\n",
"canvas_bc_ask_canvas_object.line(625, 425, 745, 425);\n",
"canvas_bc_ask_canvas_object.line(625, 425, 625, 455);\n",
"canvas_bc_ask_canvas_object.line(745, 425, 745, 455);\n",
"canvas_bc_ask_canvas_object.line(625, 455, 745, 455);\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Enemy(Nono, America)\", 633, 449);\n",
"canvas_bc_ask_canvas_object.line(400, 115, 495, 255);\n",
"canvas_bc_ask_canvas_object.line(305, 285, 115, 425);\n",
"canvas_bc_ask_canvas_object.line(495, 285, 305, 425);\n",
"canvas_bc_ask_canvas_object.line(685, 285, 685, 425);\n",
"canvas_bc_ask_canvas_object.line(400, 115, 685, 255);\n",
"canvas_bc_ask_canvas_object.line(400, 115, 305, 255);\n",
"canvas_bc_ask_canvas_object.line(400, 115, 115, 255);\n",
"canvas_bc_ask_canvas_object.line(495, 285, 495, 425);\n",
"canvas_bc_ask_canvas_object.fill(255, 255, 255);\n",
"canvas_bc_ask_canvas_object.rect(0, 540, 800, 60);\n",
"canvas_bc_ask_canvas_object.strokeWidth(5);\n",
"canvas_bc_ask_canvas_object.stroke(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.line(0, 540, 800, 540);\n",
"canvas_bc_ask_canvas_object.font(\"22px Arial\");\n",
"canvas_bc_ask_canvas_object.fill(0, 0, 0);\n",
"canvas_bc_ask_canvas_object.fill_text(\"Click for text\", 20, 585);\n",
"</script>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"from notebook import Canvas_fol_bc_ask\n",
"canvas_bc_ask = Canvas_fol_bc_ask('canvas_bc_ask', crime_kb, expr('Criminal(x)'))"
]
},
"metadata": {
"collapsed": true
},
"This notebook by [Chirag Vartak](https://github.com/chiragvartak) and [Peter Norvig](https://github.com/norvig).\n",
}
],
"metadata": {
"kernelspec": {
"language": "python",
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
}
},
"nbformat": 4,