{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "import actions, kb, sample"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## AQE: A Query Engine\n",
    "\n",
    "This is an implementation of a knowledge base, hacked together in Python\n",
    "3 (it won't work in Python 2 for reasons of modules) for now to quickly\n",
    "iterate on ideas.\n",
    "\n",
    "The `KnowledgeBase` is a repository of facts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "skb = sample.load()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A fact is a tuple: (relationship, subject, object). `object` is admittedly a terrible name (and is subject to change) but it's what I came up with and what I'm working with for now."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('is', 'cbr600', 'Driver'),\n",
       " ('at', 'cbr600', 'oakland'),\n",
       " ('at', 'airliner', 'denver'),\n",
       " ('is', 'oakland', 'Airport'),\n",
       " ('is', 'airliner', 'Flyer'),\n",
       " ('is', 'oakland', 'City'),\n",
       " ('is', 'trooper', 'Driver'),\n",
       " ('is', 'denver', 'City'),\n",
       " ('is', 'denver', 'Airport')]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "skb.facts()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A KB can be told a fact with the `tell` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "skb.tell(('is', 'san francisco', 'cool'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, the KB can be told a fact is *not* true with the `retract` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "skb.retract(('is', 'san francisco', 'cool'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The KB can be queried about the facts it has. There are two types of queries. The first is done with a full fact, and represents the question \"Is this fact true?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('is', 'oakland', 'City')]\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "print(skb.ask(('is', 'oakland', 'City')))\n",
    "print(skb.ask(('is', 'cbr600', 'City')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A query returns a list of facts; the empty list means no facts were found. This might seem an odd way to represent this first question; an invalid fact is represented by an empty list, or it returns a list of a single fact. The reason for doing it this way is to support the second type of question: \"What are the facts for which this query is valid?\" This is done by providing a `None` value to *either* the subject or object. (Eventually, I'll get around to adding support for empty relationships too...)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('is', 'oakland', 'City'), ('is', 'denver', 'City')]\n"
     ]
    }
   ],
   "source": [
    "print(skb.ask(('is', None, 'City')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another thing the KB can do is provide some basic substution using the `subst` method. It takes a fact template, a subject, and an object, and returns a fact (without making any statement as to the validity of the fact). The subject and object can be one of several values:\n",
    "\n",
    "+ `None`: the subject or object (depending on which position is `None`) from the arguments is substituted into the fact.\n",
    "+ `?subject`: substitutes the subject.\n",
    "+ `?object`: substitutes the object.\n",
    "+ `?current`: the current value is kept --- this must be used only with singleton facts.\n",
    "+ `?any`: the value is kept as `None`.\n",
    "\n",
    "Some examples should clarify this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('is', 'oakland', 'City')\n",
      "('at', 'cbr600', 'oakland')\n",
      "('is', 'City', 'oakland')\n"
     ]
    }
   ],
   "source": [
    "print(skb.subst(('is', None, 'City'), 'oakland', None))\n",
    "print(skb.subst(('at', '?subject', '?current'), 'cbr600', None))\n",
    "print(skb.subst(('is', '?object', '?subject'), 'oakland', 'City'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To understand `subst`, it's useful to note that it was written to support actions.\n",
    "\n",
    "Actions are initialised with a positive precondition (facts that must be valid for the action to be performed), a negative precondition (facts that must not be valid for the action to be performed), a set of retractions, and a set of updates.\n",
    "\n",
    "To illustrate this, here's a small example of airplanes and airports."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "airport_kb = kb.from_facts([\n",
    "    ('is', 'N29EO', 'Plane'),\n",
    "    ('at', 'N29EO', 'dia'),\n",
    "    ('is', 'N10IV', 'Plane'),\n",
    "    ('at', 'N10IV', 'oak'),\n",
    "    ('is', 'N33FR', 'Plane'),\n",
    "    ('at', 'N33FR', 'lga'),\n",
    "    ('is', 'dia', 'Airport'),\n",
    "    ('is', 'lga', 'Airport'),\n",
    "    ('is', 'oak', 'Airport'),\n",
    "])\n",
    "\n",
    "fly = actions.Action(\n",
    "    [('is', '?subject', 'Plane'), ('is', '?object', 'Airport')],  # Positive preconditions.\n",
    "    [('at', '?subject', '?object'),],                             # Negative preconditions.\n",
    "    [('at', '?subject', '?current'),],                            # Retractions.\n",
    "    [('at', '?subject', '?object')])                              # Updates."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a `fly` action to be performed, there's a few facts we should make sure are true:\n",
    "\n",
    "1. The subject of the action is a `Plane`, and\n",
    "2. The object of the action is an `Airport`.\n",
    "\n",
    "We should make sure that the subject isn't currently at our target airport.\n",
    "\n",
    "If these hold, we can perform the action. The retraction says that the subject is no longer at the airport it was at before the action, and the KB is updated to say that the plane is at a new airport."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Before flying, is N10IV at LGA?  []\n",
      "Before flying, is N10IV at OAK?  [('at', 'N10IV', 'oak')]\n",
      "After flying, is N10IV at LGA?  [('at', 'N10IV', 'lga')]\n",
      "After flying, is N10IV at OAK?  []\n"
     ]
    }
   ],
   "source": [
    "print('Before flying, is N10IV at LGA? ', airport_kb.ask(('at', 'N10IV', 'lga')))\n",
    "print('Before flying, is N10IV at OAK? ', airport_kb.ask(('at', 'N10IV', 'oak')))\n",
    "\n",
    "new_airport_kb = fly.perform(airport_kb, 'N10IV', 'lga')\n",
    "\n",
    "print('After flying, is N10IV at LGA? ', new_airport_kb.ask(('at', 'N10IV', 'lga')))\n",
    "print('After flying, is N10IV at OAK? ', new_airport_kb.ask(('at', 'N10IV', 'oak')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There's more work to be done, but this represents a solid night of putting the plan into action based on what I'd learned from the AI nanodegree. I've got a bigger vision for what I want to do out of this, but it's nice to have a baseline to reason about."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
