{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "

CSCI - UA 9472 - Artificial Intelligence

\n", "\n", "

Assignment 3: Logical reasoning

\n", "\n", "
Given date: November 8 \n", "
\n", "
Due date: November 30 \n", "
\n", "
Total: 40 pts \n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
In this third assignment, we will implement a simple Logical agent by relying on the resolution algorithm of Propositional Logic.
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Introduction: logical propositions\n", "\n", "The final objective will be to code our logical agent to succeed in a simple world similar to the Wumpus world discussed in the lectures. The final world we will consider is shown below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before designing the full agent, we will focus on a series of simplified environments (see below). In order to help you in your implementation, you are provided with the class 'Expr' and the associated function 'expr' which can be used to store and process logical propositions. The logical expressions are stored as objects consisting of an operator 'op' which can be of the types '&' (and), '|' (or) '==>' (implication) or '<=>' (double implication) as well as '~' (not). A logical expression such as 'A & B' can be stored as a string by means of the function expr() as expr('A & B') or Expr('&', 'A', 'B').\n", "\n", "The function expr() takes operator precedence into account so that the two lines" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "e = expr('A & B ==> C & D')\n", "e.op" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "will return '==>'. The knowledge based can be created as a list of logical propositions. " ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "'''source : AIMA'''\n", "\n", "import collections\n", "\n", "Number = (int, float, complex)\n", "Expression = (Expr, Number)\n", "\n", "def Symbol(name):\n", " \"\"\"A Symbol is just an Expr with no args.\"\"\"\n", " return Expr(name)\n", "\n", "class Expr:\n", " \"\"\"source: Artificial Intelligence: A Modern Approach\n", " A mathematical expression with an operator and 0 or more arguments.\n", " op is a str like '+' or 'sin'; args are Expressions.\n", " Expr('x') or Symbol('x') creates a symbol (a nullary Expr).\n", " Expr('-', x) creates a unary; Expr('+', x, 1) creates a binary.\"\"\"\n", "\n", " def __init__(self, op, *args):\n", " self.op = str(op)\n", " self.args = args\n", "\n", " # Operator overloads\n", " def __neg__(self):\n", " return Expr('-', self)\n", "\n", " def __pos__(self):\n", " return Expr('+', self)\n", "\n", " def __invert__(self):\n", " return Expr('~', self)\n", "\n", " def __add__(self, rhs):\n", " return Expr('+', self, rhs)\n", "\n", " def __sub__(self, rhs):\n", " return Expr('-', self, rhs)\n", "\n", " def __mul__(self, rhs):\n", " return Expr('*', self, rhs)\n", "\n", " def __pow__(self, rhs):\n", " return Expr('**', self, rhs)\n", "\n", " def __mod__(self, rhs):\n", " return Expr('%', self, rhs)\n", "\n", " def __and__(self, rhs):\n", " return Expr('&', self, rhs)\n", "\n", " def __xor__(self, rhs):\n", " return Expr('^', self, rhs)\n", "\n", " def __rshift__(self, rhs):\n", " return Expr('>>', self, rhs)\n", "\n", " def __lshift__(self, rhs):\n", " return Expr('<<', self, rhs)\n", "\n", " def __truediv__(self, rhs):\n", " return Expr('/', self, rhs)\n", "\n", " def __floordiv__(self, rhs):\n", " return Expr('//', self, rhs)\n", "\n", " def __matmul__(self, rhs):\n", " return Expr('@', self, rhs)\n", "\n", " def __or__(self, rhs):\n", " \"\"\"Allow both P | Q, and P |'==>'| Q.\"\"\"\n", " if isinstance(rhs, Expression):\n", " return Expr('|', self, rhs)\n", " else:\n", " return PartialExpr(rhs, self)\n", "\n", " # Reverse operator overloads\n", " def __radd__(self, lhs):\n", " return Expr('+', lhs, self)\n", "\n", " def __rsub__(self, lhs):\n", " return Expr('-', lhs, self)\n", "\n", " def __rmul__(self, lhs):\n", " return Expr('*', lhs, self)\n", "\n", " def __rdiv__(self, lhs):\n", " return Expr('/', lhs, self)\n", "\n", " def __rpow__(self, lhs):\n", " return Expr('**', lhs, self)\n", "\n", " def __rmod__(self, lhs):\n", " return Expr('%', lhs, self)\n", "\n", " def __rand__(self, lhs):\n", " return Expr('&', lhs, self)\n", "\n", " def __rxor__(self, lhs):\n", " return Expr('^', lhs, self)\n", "\n", " def __ror__(self, lhs):\n", " return Expr('|', lhs, self)\n", "\n", " def __rrshift__(self, lhs):\n", " return Expr('>>', lhs, self)\n", "\n", " def __rlshift__(self, lhs):\n", " return Expr('<<', lhs, self)\n", "\n", " def __rtruediv__(self, lhs):\n", " return Expr('/', lhs, self)\n", "\n", " def __rfloordiv__(self, lhs):\n", " return Expr('//', lhs, self)\n", "\n", " def __rmatmul__(self, lhs):\n", " return Expr('@', lhs, self)\n", "\n", " def __call__(self, *args):\n", " \"\"\"Call: if 'f' is a Symbol, then f(0) == Expr('f', 0).\"\"\"\n", " if self.args:\n", " raise ValueError('Can only do a call for a Symbol, not an Expr')\n", " else:\n", " return Expr(self.op, *args)\n", "\n", " # Equality and repr\n", " def __eq__(self, other):\n", " \"\"\"x == y' evaluates to True or False; does not build an Expr.\"\"\"\n", " return isinstance(other, Expr) and self.op == other.op and self.args == other.args\n", "\n", " def __lt__(self, other):\n", " return isinstance(other, Expr) and str(self) < str(other)\n", "\n", " def __hash__(self):\n", " return hash(self.op) ^ hash(self.args)\n", "\n", " def __repr__(self):\n", " op = self.op\n", " args = [str(arg) for arg in self.args]\n", " if op.isidentifier(): # f(x) or f(x, y)\n", " return '{}({})'.format(op, ', '.join(args)) if args else op\n", " elif len(args) == 1: # -x or -(x + 1)\n", " return op + args[0]\n", " else: # (x - y)\n", " opp = (' ' + op + ' ')\n", " return '(' + opp.join(args) + ')'\n", "\n", " \n", "def expr(x):\n", " \"\"\"Shortcut to create an Expression. x is a str in which:\n", " - identifiers are automatically defined as Symbols.\n", " - ==> is treated as an infix |'==>'|, as are <== and <=>.\n", " If x is already an Expression, it is returned unchanged. Example:\n", " >>> expr('P & Q ==> Q')\n", " ((P & Q) ==> Q)\n", " \"\"\"\n", " return eval(expr_handle_infix_ops(x), defaultkeydict(Symbol)) if isinstance(x, str) else x\n", "\n", "def expr_handle_infix_ops(x):\n", " \"\"\"Given a str, return a new str with ==> replaced by |'==>'|, etc.\n", " >>> expr_handle_infix_ops('P ==> Q')\n", " \"P |'==>'| Q\"\n", " \"\"\"\n", " for op in infix_ops:\n", " x = x.replace(op, '|' + repr(op) + '|')\n", " return x\n", "\n", "infix_ops = '==> <== <=>'.split()\n", "\n", "class defaultkeydict(collections.defaultdict):\n", " \"\"\"Like defaultdict, but the default_factory is a function of the key.\n", " >>> d = defaultkeydict(len); d['four']\n", " 4\n", " \"\"\"\n", "\n", " def __missing__(self, key):\n", " self[key] = result = self.default_factory(key)\n", " return result\n", "\n", " \n", "class PartialExpr:\n", " \"\"\"Given 'P |'==>'| Q, first form PartialExpr('==>', P), then combine with Q.\"\"\"\n", "\n", " def __init__(self, op, lhs):\n", " self.op, self.lhs = op, lhs\n", "\n", " def __or__(self, rhs):\n", " return Expr(self.op, self.lhs, rhs)\n", "\n", " def __repr__(self):\n", " return \"PartialExpr('{}', {})\".format(self.op, self.lhs)\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Question 1: to CNF (7pts)\n", "\n", "Now that we can create a knowledge base, in order to implement the resolution algorithm that will ultimately enable our agent to leverage the information from the environment, we need our sentences to written in conjunctive normal form (CNF). That requires a number of steps which are recalled below:\n", "\n", "- Biconditional elimination: $(\\alpha \\Leftrightarrow \\beta) \\equiv ((\\alpha\\Rightarrow \\beta) \\wedge (\\beta \\Rightarrow \\alpha))$\n", "- Implication elimination $\\alpha \\Rightarrow \\beta \\equiv \\lnot \\alpha \\vee \\beta$\n", "- De Morgan's Law $\\lnot (A\\wedge B) = (\\lnot A \\vee \\lnot B)$, $\\lnot(\\alpha \\vee B) \\equiv (\\lnot A \\wedge \\lnot B)$\n", "- Distributivity of $\\vee$ over $\\wedge$: $(\\alpha \\vee (\\beta \\wedge \\gamma)) \\equiv ((\\alpha \\vee \\beta) \\wedge (\\alpha \\vee \\gamma))$\n", "\n", "Relying on the function propositional_exp given above (to avoid having all the questions depend on question 1, we will now rely on this implementation from AIMA), complete the function below which should return the CNF of the logical propostion $p$. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def to_CNF(p):\n", " \n", " '''function should return the CNF of proposition p'''\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " return CNF" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Question 2: The resolution rule (7pts)\n", "\n", "Now that you have a function that can turn any logical sentence to a CNF, we will code the resolution rule. For any two propositions $p_1$ and $p_2$ written in conjunctive normal form, write a function Resolution that returns empty if the resolution rule applied to the two sentences cannot produce any new sentence and that returns the set of all propositions $p_i$ following from the resolution of $p_1$ and $p_2$ otherwise. \n", "\n", "Study the disjuncts of both $p_1$ and $p_2$. For each of the disjunct in $p_1$ try to find in $p_2$ the negation of that disjunct. If this negation appears, returns the proposition resulting from combining $p_1$ and $p_2$ with a disjunction. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def resolution_rule(p_1, p_2):\n", " \n", " '''applies the resolution rule on two propositions p_1 and p_2'''\n", " \n", " \n", " \n", " \n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Question 3: The resolution algorithm (6pts)\n", "\n", "Now that we have a resolution function we can embed it into a resolution algorithm. Complete the function Resolution below which implements the resolution algorithm. The algorithm takes as input a knowledge base written in conjunctive normal form, and a proposition $\\alpha$ and should return true or false (as stored in the variable 'is_entailed') depending on whether $\\alpha$ is entailed by the knowledge base KB." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def resolution(KB, alpha):\n", " \n", " '''determines whether the sentence alpha \n", " is entailed by the knowledge base KB. The \n", " variable is_entailed should return true or false \n", " according to the outcome'''\n", " \n", " \n", " \n", " \n", " \n", " return is_entailed" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Question 4 (8pts): A first logical agent\n", "\n", "Given our resolution algorithm, we will finally be able to design our first logical agent. As a first step, we consider a simple agent located on the bottom left cell of a 5 by 5 grid world. The world contains a single threat represented by a ghost which occupies a single cell and emits a loud noise ('OOooo') audible in the immediately adjacent cells. \n", "\n", "To implement the agent, we will use the following approach:\n", "\n", "Each cell will be represented by its (x,y) coordinate ((0,0) being the bottom leftmost cell). On top of this we will consider the following symbols \n", "\n", "- $D_{(x, y)}$ (which you can store as the string 'Dxy' or 'D_xy' as you want) indicating whether there is an exit on the cell or not (when the agent reach the exit, the simulation ends), \n", "\n", "- $G_{(x, y)}$ which encodes whether the ghost is located on cell $(x, y)$ or not\n", "\n", "- $O_{(x, y)}$ which encodes whether a \"Ooooo\" is heard on the cell $(x, y)$\n", "\n", "Using those three symbols, the state of the world can be defined with a total of 3*25 symbols. \n", "\n", "In a while loop running until the door is found, code a simple logical agent that moves at random in the non-threatening cells until it finds the escape cell. Also consider the following:\n", "\n", "- The agent should keep track of a knowledge base KB (list of logically true propositions together with a dictionnary storing the symbols that are known to be true) including all the sentences that the agent can generate based on the information it collected at the previous steps. \n", "\n", "\n", "- You might want to have a simple function, which given a symbol returns the adjacent symbols (symbols corresponding to spatially adjacent cells). you can store those as strings\n", "\n", "\n", "- The agent should be equipped with the resolution algorithm that you coded above. Before each new move, the next cell should be determined at random (from the set of all non visited cells) and the agent should use the resolution algorithm to determine whether the ghost is on the cell or not. If there is no indication that the ghost is located on the cell, the agent should make the move. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "exitNotFound = True\n", "\n", "while exitNotFound:\n", " \n", " '''Agent should explore the world at random, probing the \n", " knowledge base for any potential threat. if the KB does not \n", " indicate any specific threat, the agent should move in one of \n", " the adacent (cleared) cell. The simulation ends when the agent \n", " reaches the exit door'''\n", " \n", " \n", " \n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Question 5: Getting used to danger.. (6pts)\n", "\n", "Now that our agent knows how to handle a ghost, we will increase the level of risk by including spike traps in the environment. \n", "\n", "- Our agent has an edge: evolution has endowed it with a sort of additional ($6^{th}$) sense so that it can feel something 'bad' is about to happen when it is in a cell adjacent to a trap. We represent this ability with the eye combined with the exclamation mark. \n", "\n", "\n", "- Since, as we all know, ghosts are purely imaginary entities, the $6th$ sense only works for the spike traps. \n", "\n", "\n", "- The ghost can still be located by means of the noise it generates which can be heard on all adjacent cells.\n", "\n", "\n", "\n", "Starting from the agent you designed in the previous questions, improve this agent so that it takes into account the spike traps. You should now have a knowledge base defined on a total of 25*5 symbols describing whether each cell contains a ghost, a 'OOoo' noise, a spike trap, activated the agent's'6th sense', or contains the exit door. The search ends when the agent reaches the door. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "exit_door = False \n", "\n", "while exit_door != True:\n", " \n", " '''Complete the loop with the simulation of the ghost \n", " + spike trap logical agent. The simulation should start \n", " from the bottom leftmost cell'''\n", " \n", " \n", " \n", " \n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Bonus: For where your treasure is.. (6pts)\n", "\n", "We finally consider the whole environment. This environment is composed of all the elements from the previous questions but it now also includes a treasure chest. The final objective this time is to find the chest first and then reach the exit. Although some of the previous symbols are omitted for clarity, the ghost can always be located by means of the sound it produces, the agent can still trust its $6^{\\text{th}}$ sense regarding the spike trap and the treasure chest can be perceived in adjacent cells, by means of the shine it produces.\n", "\n", "When the knowledge base does not indicate any threat, the agent should move at random in one of the adjacent cells. \n", "\n", "The world now contains a total of 25*7 symbols. \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "treasure_notFound = True\n", "exitFound = False\n", "\n", "\n", "while treasure_notFound and exitFound!=True:\n", " \n", " '''Simulation should complete when the treasure chest \n", " has been found and the exit has been reached. \n", " The agent should start from bottom leftmost cell'''\n", " \n", " \n", " " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" } }, "nbformat": 4, "nbformat_minor": 4 }