{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# KNOWLEDGE\n",
    "\n",
    "The [knowledge](https://github.com/aimacode/aima-python/blob/master/knowledge.py) module covers **Chapter 19: Knowledge in Learning** from Stuart Russel's and Peter Norvig's book *Artificial Intelligence: A Modern Approach*.\n",
    "\n",
    "Execute the cell below to get started."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from knowledge import *\n",
    "\n",
    "from notebook import pseudocode, psource"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## CONTENTS\n",
    "\n",
    "* Overview\n",
    "* Inductive Logic Programming (FOIL)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## OVERVIEW\n",
    "\n",
    "Like the [learning module](https://github.com/aimacode/aima-python/blob/master/learning.ipynb), this chapter focuses on methods for generating a model/hypothesis for a domain. Unlike though the learning chapter, here we use prior knowledge to help us learn from new experiences and find a proper hypothesis.\n",
    "\n",
    "### First-Order Logic\n",
    "\n",
    "Usually knowledge in this field is represented as **first-order logic**, a type of logic that uses variables and quantifiers in logical sentences. Hypotheses are represented by logical sentences with variables, while examples are logical sentences with set values instead of variables. The goal is to assign a value to a special first-order logic predicate, called **goal predicate**, for new examples given a hypothesis. We learn this hypothesis by infering knowledge from some given examples.\n",
    "\n",
    "### Representation\n",
    "\n",
    "In this module, we use dictionaries to represent examples, with keys the attribute names and values the corresponding example values. Examples also have an extra boolean field, 'GOAL', for the goal predicate. A hypothesis is represented as a list of dictionaries. Each dictionary in that list represents a disjunction. Inside these dictionaries/disjunctions we have conjunctions.\n",
    "\n",
    "For example, say we want to predict if an animal (cat or dog) will take an umbrella given whether or not it rains or the animal wears a coat. The goal value is 'take an umbrella' and is denoted by the key 'GOAL'. An example:\n",
    "\n",
    "`{'Species': 'Cat', 'Coat': 'Yes', 'Rain': 'Yes', 'GOAL': True}`\n",
    "\n",
    "A hypothesis can be the following:\n",
    "\n",
    "`[{'Species': 'Cat'}]`\n",
    "\n",
    "which means an animal will take an umbrella if and only if it is a cat.\n",
    "\n",
    "### Consistency\n",
    "\n",
    "We say that an example `e` is **consistent** with an hypothesis `h` if the assignment from the hypothesis for `e` is the same as `e['GOAL']`. If the above example and hypothesis are `e` and `h` respectively, then `e` is consistent with `h` since `e['Species'] == 'Cat'`. For `e = {'Species': 'Dog', 'Coat': 'Yes', 'Rain': 'Yes', 'GOAL': True}`, the example is no longer consistent with `h`, since the value assigned to `e` is *False* while `e['GOAL']` is *True*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inductive Logic Programming (FOIL)\n",
    "\n",
    "Inductive logic programming (ILP) combines inductive methods with the power of first-order representations, concentrating in particular on the representation of hypotheses as logic programs. The general knowledge-based induction problem is to solve the entailment constrant: <br> <br>\n",
    "$ Background ∧ Hypothesis ∧ Descriptions \\vDash Classifications $\n",
    "\n",
    "for the __unknown__ $Hypothesis$, given the $Background$ knowledge described by $Descriptions$ and $Classifications$.\n",
    "\n",
    "\n",
    "\n",
    "The first approach to ILP works by starting with a very general rule and gradually specializing\n",
    "it so that it fits the data. <br> \n",
    "This is essentially what happens in decision-tree learning, where a\n",
    "decision tree is gradually grown until it is consistent with the observations. <br> To do ILP we\n",
    "use first-order literals instead of attributes, and the $Hypothesis$ is a set of clauses (set of first order rules, where each rule is similar to a Horn clause) instead of a decision tree. <br>\n",
    "\n",
    "\n",
    "The FOIL algorithm learns new rules, one at a time, in order to cover all given possitive and negative examples. <br>\n",
    "More precicely, FOIL contains an inner and an outer while loop. <br>\n",
    "-  __outer loop__: <font color='blue'>(function __foil()__) </font>  add rules untill all positive examples are covered. <br>\n",
    "   (each rule is a conjuction of literals, which are chosen inside the inner loop)\n",
    "   \n",
    "   \n",
    "-  __inner loop__: <font color ='blue'>(function __new_clause()__) </font>  add new literals untill all negative examples are covered, and some positive examples are covered. <br>\n",
    "   -  In each iteration, we select/add the most promising literal, according to an estimate of its utility. <font color ='blue'>(function __new_literal()__) </font> <br>\n",
    "   \n",
    "   -  The evaluation function to estimate utility of adding literal $L$ to a set of rules $R$ is <font color ='blue'>(function __gain()__) </font> : \n",
    "   \n",
    "   $$ FoilGain(L,R) = t \\big( \\log_2{\\frac{p_1}{p_1+n_1}} - \\log_2{\\frac{p_0}{p_0+n_0}} \\big) $$\n",
    "      where: \n",
    "      \n",
    "      $p_0: \\text{is the number of possitive bindings of rule R } \\\\ n_0: \\text{is the number of negative bindings of R} \\\\ p_1: \\text{is the is the number of possitive bindings of rule R'}\\\\ n_0: \\text{is the number of negative bindings of R'}\\\\ t: \\text{is the number of possitive bindings of rule R that are still covered after adding literal L to R}$\n",
    "   \n",
    "   - Calculate the extended examples for the chosen literal <font color ='blue'>(function __extend_example()__) </font> <br>\n",
    "        (the set of examples created by extending example with each possible constant value for each new variable in literal)\n",
    "   \n",
    "-  Finally the algorithm returns a disjunction of first order rules (= conjuction of literals)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "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\">class</span> <span class=\"nc\">FOIL_container</span><span class=\"p\">(</span><span class=\"n\">FolKB</span><span class=\"p\">):</span>\n",
       "    <span class=\"sd\">&quot;&quot;&quot;Hold the kb and other necessary elements required by FOIL.&quot;&quot;&quot;</span>\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">clauses</span><span class=\"o\">=</span><span class=\"bp\">None</span><span class=\"p\">):</span>\n",
       "        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">const_syms</span> <span class=\"o\">=</span> <span class=\"nb\">set</span><span class=\"p\">()</span>\n",
       "        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">pred_syms</span> <span class=\"o\">=</span> <span class=\"nb\">set</span><span class=\"p\">()</span>\n",
       "        <span class=\"n\">FolKB</span><span class=\"o\">.</span><span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">clauses</span><span class=\"p\">)</span>\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">tell</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">sentence</span><span class=\"p\">):</span>\n",
       "        <span class=\"k\">if</span> <span class=\"n\">is_definite_clause</span><span class=\"p\">(</span><span class=\"n\">sentence</span><span class=\"p\">):</span>\n",
       "            <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">clauses</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">sentence</span><span class=\"p\">)</span>\n",
       "            <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">const_syms</span><span class=\"o\">.</span><span class=\"n\">update</span><span class=\"p\">(</span><span class=\"n\">constant_symbols</span><span class=\"p\">(</span><span class=\"n\">sentence</span><span class=\"p\">))</span>\n",
       "            <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">pred_syms</span><span class=\"o\">.</span><span class=\"n\">update</span><span class=\"p\">(</span><span class=\"n\">predicate_symbols</span><span class=\"p\">(</span><span class=\"n\">sentence</span><span class=\"p\">))</span>\n",
       "        <span class=\"k\">else</span><span class=\"p\">:</span>\n",
       "            <span class=\"k\">raise</span> <span class=\"ne\">Exception</span><span class=\"p\">(</span><span class=\"s2\">&quot;Not a definite clause: {}&quot;</span><span class=\"o\">.</span><span class=\"n\">format</span><span class=\"p\">(</span><span class=\"n\">sentence</span><span class=\"p\">))</span>\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">foil</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">examples</span><span class=\"p\">,</span> <span class=\"n\">target</span><span class=\"p\">):</span>\n",
       "        <span class=\"sd\">&quot;&quot;&quot;Learn a list of first-order horn clauses</span>\n",
       "<span class=\"sd\">        &#39;examples&#39; is a tuple: (positive_examples, negative_examples).</span>\n",
       "<span class=\"sd\">        positive_examples and negative_examples are both lists which contain substitutions.&quot;&quot;&quot;</span>\n",
       "        <span class=\"n\">clauses</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n",
       "\n",
       "        <span class=\"n\">pos_examples</span> <span class=\"o\">=</span> <span class=\"n\">examples</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]</span>\n",
       "        <span class=\"n\">neg_examples</span> <span class=\"o\">=</span> <span class=\"n\">examples</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">]</span>\n",
       "\n",
       "        <span class=\"k\">while</span> <span class=\"n\">pos_examples</span><span class=\"p\">:</span>\n",
       "            <span class=\"n\">clause</span><span class=\"p\">,</span> <span class=\"n\">extended_pos_examples</span> <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">new_clause</span><span class=\"p\">((</span><span class=\"n\">pos_examples</span><span class=\"p\">,</span> <span class=\"n\">neg_examples</span><span class=\"p\">),</span> <span class=\"n\">target</span><span class=\"p\">)</span>\n",
       "            <span class=\"c1\"># remove positive examples covered by clause</span>\n",
       "            <span class=\"n\">pos_examples</span> <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">update_examples</span><span class=\"p\">(</span><span class=\"n\">target</span><span class=\"p\">,</span> <span class=\"n\">pos_examples</span><span class=\"p\">,</span> <span class=\"n\">extended_pos_examples</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\">clause</span><span class=\"p\">)</span>\n",
       "\n",
       "        <span class=\"k\">return</span> <span class=\"n\">clauses</span>\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">new_clause</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">examples</span><span class=\"p\">,</span> <span class=\"n\">target</span><span class=\"p\">):</span>\n",
       "        <span class=\"sd\">&quot;&quot;&quot;Find a horn clause which satisfies part of the positive</span>\n",
       "<span class=\"sd\">        examples but none of the negative examples.</span>\n",
       "<span class=\"sd\">        The horn clause is specified as [consequent, list of antecedents]</span>\n",
       "<span class=\"sd\">        Return value is the tuple (horn_clause, extended_positive_examples).&quot;&quot;&quot;</span>\n",
       "        <span class=\"n\">clause</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"n\">target</span><span class=\"p\">,</span> <span class=\"p\">[]]</span>\n",
       "        <span class=\"c1\"># [positive_examples, negative_examples]</span>\n",
       "        <span class=\"n\">extended_examples</span> <span class=\"o\">=</span> <span class=\"n\">examples</span>\n",
       "        <span class=\"k\">while</span> <span class=\"n\">extended_examples</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">]:</span>\n",
       "            <span class=\"n\">l</span> <span class=\"o\">=</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">choose_literal</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">new_literals</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">),</span> <span class=\"n\">extended_examples</span><span class=\"p\">)</span>\n",
       "            <span class=\"n\">clause</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">]</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">l</span><span class=\"p\">)</span>\n",
       "            <span class=\"n\">extended_examples</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"nb\">sum</span><span class=\"p\">([</span><span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">extend_example</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">,</span> <span class=\"n\">l</span><span class=\"p\">))</span> <span class=\"k\">for</span> <span class=\"n\">example</span> <span class=\"ow\">in</span>\n",
       "                                      <span class=\"n\">extended_examples</span><span class=\"p\">[</span><span class=\"n\">i</span><span class=\"p\">]],</span> <span class=\"p\">[])</span> <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=\"mi\">2</span><span class=\"p\">)]</span>\n",
       "\n",
       "        <span class=\"k\">return</span> <span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">,</span> <span class=\"n\">extended_examples</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])</span>\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">extend_example</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">example</span><span class=\"p\">,</span> <span class=\"n\">literal</span><span class=\"p\">):</span>\n",
       "        <span class=\"sd\">&quot;&quot;&quot;Generate extended examples which satisfy the literal.&quot;&quot;&quot;</span>\n",
       "        <span class=\"c1\"># find all substitutions that satisfy literal</span>\n",
       "        <span class=\"k\">for</span> <span class=\"n\">s</span> <span class=\"ow\">in</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">ask_generator</span><span class=\"p\">(</span><span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">,</span> <span class=\"n\">literal</span><span class=\"p\">)):</span>\n",
       "            <span class=\"n\">s</span><span class=\"o\">.</span><span class=\"n\">update</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">)</span>\n",
       "            <span class=\"k\">yield</span> <span class=\"n\">s</span>\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">new_literals</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">clause</span><span class=\"p\">):</span>\n",
       "        <span class=\"sd\">&quot;&quot;&quot;Generate new literals based on known predicate symbols.</span>\n",
       "<span class=\"sd\">        Generated literal must share atleast one variable with clause&quot;&quot;&quot;</span>\n",
       "        <span class=\"n\">share_vars</span> <span class=\"o\">=</span> <span class=\"n\">variables</span><span class=\"p\">(</span><span class=\"n\">clause</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])</span>\n",
       "        <span class=\"k\">for</span> <span class=\"n\">l</span> <span class=\"ow\">in</span> <span class=\"n\">clause</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">]:</span>\n",
       "            <span class=\"n\">share_vars</span><span class=\"o\">.</span><span class=\"n\">update</span><span class=\"p\">(</span><span class=\"n\">variables</span><span class=\"p\">(</span><span class=\"n\">l</span><span class=\"p\">))</span>\n",
       "        <span class=\"c1\"># creates literals with different order every time  </span>\n",
       "        <span class=\"k\">for</span> <span class=\"n\">pred</span><span class=\"p\">,</span> <span class=\"n\">arity</span> <span class=\"ow\">in</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">pred_syms</span><span class=\"p\">:</span>\n",
       "            <span class=\"n\">new_vars</span> <span class=\"o\">=</span> <span class=\"p\">{</span><span class=\"n\">standardize_variables</span><span class=\"p\">(</span><span class=\"n\">expr</span><span class=\"p\">(</span><span class=\"s1\">&#39;x&#39;</span><span class=\"p\">))</span> <span class=\"k\">for</span> <span class=\"n\">_</span> <span class=\"ow\">in</span> <span class=\"nb\">range</span><span class=\"p\">(</span><span class=\"n\">arity</span> <span class=\"o\">-</span> <span class=\"mi\">1</span><span class=\"p\">)}</span>\n",
       "            <span class=\"k\">for</span> <span class=\"n\">args</span> <span class=\"ow\">in</span> <span class=\"n\">product</span><span class=\"p\">(</span><span class=\"n\">share_vars</span><span class=\"o\">.</span><span class=\"n\">union</span><span class=\"p\">(</span><span class=\"n\">new_vars</span><span class=\"p\">),</span> <span class=\"n\">repeat</span><span class=\"o\">=</span><span class=\"n\">arity</span><span class=\"p\">):</span>\n",
       "                <span class=\"k\">if</span> <span class=\"nb\">any</span><span class=\"p\">(</span><span class=\"n\">var</span> <span class=\"ow\">in</span> <span class=\"n\">share_vars</span> <span class=\"k\">for</span> <span class=\"n\">var</span> <span class=\"ow\">in</span> <span class=\"n\">args</span><span class=\"p\">):</span>\n",
       "                    <span class=\"c1\"># make sure we don&#39;t return an existing rule</span>\n",
       "                    <span class=\"k\">if</span> <span class=\"ow\">not</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"n\">pred</span><span class=\"p\">,</span> <span class=\"n\">args</span><span class=\"p\">)</span> <span class=\"ow\">in</span> <span class=\"n\">clause</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">]:</span>\n",
       "                        <span class=\"k\">yield</span> <span class=\"n\">Expr</span><span class=\"p\">(</span><span class=\"n\">pred</span><span class=\"p\">,</span> <span class=\"o\">*</span><span class=\"p\">[</span><span class=\"n\">var</span> <span class=\"k\">for</span> <span class=\"n\">var</span> <span class=\"ow\">in</span> <span class=\"n\">args</span><span class=\"p\">])</span>\n",
       "\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">choose_literal</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">literals</span><span class=\"p\">,</span> <span class=\"n\">examples</span><span class=\"p\">):</span> \n",
       "        <span class=\"sd\">&quot;&quot;&quot;Choose the best literal based on the information gain.&quot;&quot;&quot;</span>\n",
       "\n",
       "        <span class=\"k\">return</span> <span class=\"nb\">max</span><span class=\"p\">(</span><span class=\"n\">literals</span><span class=\"p\">,</span> <span class=\"n\">key</span> <span class=\"o\">=</span> <span class=\"n\">partial</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">gain</span> <span class=\"p\">,</span> <span class=\"n\">examples</span> <span class=\"o\">=</span> <span class=\"n\">examples</span><span class=\"p\">))</span>\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">gain</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">l</span> <span class=\"p\">,</span><span class=\"n\">examples</span><span class=\"p\">):</span>\n",
       "        <span class=\"n\">pre_pos</span><span class=\"o\">=</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">examples</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])</span>\n",
       "        <span class=\"n\">pre_neg</span><span class=\"o\">=</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">examples</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">])</span>\n",
       "        <span class=\"n\">extended_examples</span> <span class=\"o\">=</span> <span class=\"p\">[</span><span class=\"nb\">sum</span><span class=\"p\">([</span><span class=\"nb\">list</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">extend_example</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">,</span> <span class=\"n\">l</span><span class=\"p\">))</span> <span class=\"k\">for</span> <span class=\"n\">example</span> <span class=\"ow\">in</span> <span class=\"n\">examples</span><span class=\"p\">[</span><span class=\"n\">i</span><span class=\"p\">]],</span> <span class=\"p\">[])</span> <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=\"mi\">2</span><span class=\"p\">)]</span>\n",
       "        <span class=\"n\">post_pos</span> <span class=\"o\">=</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">extended_examples</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">])</span>          \n",
       "        <span class=\"n\">post_neg</span> <span class=\"o\">=</span> <span class=\"nb\">len</span><span class=\"p\">(</span><span class=\"n\">extended_examples</span><span class=\"p\">[</span><span class=\"mi\">1</span><span class=\"p\">])</span> \n",
       "        <span class=\"k\">if</span> <span class=\"n\">pre_pos</span> <span class=\"o\">+</span> <span class=\"n\">pre_neg</span> <span class=\"o\">==</span><span class=\"mi\">0</span> <span class=\"ow\">or</span> <span class=\"n\">post_pos</span> <span class=\"o\">+</span> <span class=\"n\">post_neg</span><span class=\"o\">==</span><span class=\"mi\">0</span><span class=\"p\">:</span>\n",
       "            <span class=\"k\">return</span> <span class=\"o\">-</span><span class=\"mi\">1</span>\n",
       "        <span class=\"c1\"># number of positive example that are represented in extended_examples</span>\n",
       "        <span class=\"n\">T</span> <span class=\"o\">=</span> <span class=\"mi\">0</span>\n",
       "        <span class=\"k\">for</span> <span class=\"n\">example</span> <span class=\"ow\">in</span> <span class=\"n\">examples</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]:</span>\n",
       "            <span class=\"k\">def</span> <span class=\"nf\">represents</span><span class=\"p\">(</span><span class=\"n\">d</span><span class=\"p\">):</span>\n",
       "                <span class=\"k\">return</span> <span class=\"nb\">all</span><span class=\"p\">(</span><span class=\"n\">d</span><span class=\"p\">[</span><span class=\"n\">x</span><span class=\"p\">]</span> <span class=\"o\">==</span> <span class=\"n\">example</span><span class=\"p\">[</span><span class=\"n\">x</span><span class=\"p\">]</span> <span class=\"k\">for</span> <span class=\"n\">x</span> <span class=\"ow\">in</span> <span class=\"n\">example</span><span class=\"p\">)</span>\n",
       "            <span class=\"k\">if</span> <span class=\"nb\">any</span><span class=\"p\">(</span><span class=\"n\">represents</span><span class=\"p\">(</span><span class=\"n\">l_</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">l_</span> <span class=\"ow\">in</span> <span class=\"n\">extended_examples</span><span class=\"p\">[</span><span class=\"mi\">0</span><span class=\"p\">]):</span>\n",
       "                <span class=\"n\">T</span> <span class=\"o\">+=</span> <span class=\"mi\">1</span>\n",
       "        <span class=\"n\">value</span> <span class=\"o\">=</span> <span class=\"n\">T</span> <span class=\"o\">*</span> <span class=\"p\">(</span><span class=\"n\">log</span><span class=\"p\">(</span><span class=\"n\">post_pos</span> <span class=\"o\">/</span> <span class=\"p\">(</span><span class=\"n\">post_pos</span> <span class=\"o\">+</span> <span class=\"n\">post_neg</span><span class=\"p\">)</span> <span class=\"o\">+</span> <span class=\"mf\">1e-12</span><span class=\"p\">,</span><span class=\"mi\">2</span><span class=\"p\">)</span> <span class=\"o\">-</span> <span class=\"n\">log</span><span class=\"p\">(</span><span class=\"n\">pre_pos</span> <span class=\"o\">/</span> <span class=\"p\">(</span><span class=\"n\">pre_pos</span> <span class=\"o\">+</span> <span class=\"n\">pre_neg</span><span class=\"p\">),</span><span class=\"mi\">2</span><span class=\"p\">))</span>\n",
       "        <span class=\"c1\">#print (l, value)</span>\n",
       "        <span class=\"k\">return</span> <span class=\"n\">value</span>\n",
       "\n",
       "\n",
       "    <span class=\"k\">def</span> <span class=\"nf\">update_examples</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">target</span><span class=\"p\">,</span> <span class=\"n\">examples</span><span class=\"p\">,</span> <span class=\"n\">extended_examples</span><span class=\"p\">):</span>\n",
       "        <span class=\"sd\">&quot;&quot;&quot;Add to the kb those examples what are represented in extended_examples</span>\n",
       "<span class=\"sd\">        List of omitted examples is returned.&quot;&quot;&quot;</span>\n",
       "        <span class=\"n\">uncovered</span> <span class=\"o\">=</span> <span class=\"p\">[]</span>\n",
       "        <span class=\"k\">for</span> <span class=\"n\">example</span> <span class=\"ow\">in</span> <span class=\"n\">examples</span><span class=\"p\">:</span>\n",
       "            <span class=\"k\">def</span> <span class=\"nf\">represents</span><span class=\"p\">(</span><span class=\"n\">d</span><span class=\"p\">):</span>\n",
       "                <span class=\"k\">return</span> <span class=\"nb\">all</span><span class=\"p\">(</span><span class=\"n\">d</span><span class=\"p\">[</span><span class=\"n\">x</span><span class=\"p\">]</span> <span class=\"o\">==</span> <span class=\"n\">example</span><span class=\"p\">[</span><span class=\"n\">x</span><span class=\"p\">]</span> <span class=\"k\">for</span> <span class=\"n\">x</span> <span class=\"ow\">in</span> <span class=\"n\">example</span><span class=\"p\">)</span>\n",
       "            <span class=\"k\">if</span> <span class=\"nb\">any</span><span class=\"p\">(</span><span class=\"n\">represents</span><span class=\"p\">(</span><span class=\"n\">l</span><span class=\"p\">)</span> <span class=\"k\">for</span> <span class=\"n\">l</span> <span class=\"ow\">in</span> <span class=\"n\">extended_examples</span><span class=\"p\">):</span>\n",
       "                <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">tell</span><span class=\"p\">(</span><span class=\"n\">subst</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">,</span> <span class=\"n\">target</span><span class=\"p\">))</span>\n",
       "            <span class=\"k\">else</span><span class=\"p\">:</span>\n",
       "                <span class=\"n\">uncovered</span><span class=\"o\">.</span><span class=\"n\">append</span><span class=\"p\">(</span><span class=\"n\">example</span><span class=\"p\">)</span>\n",
       "\n",
       "        <span class=\"k\">return</span> <span class=\"n\">uncovered</span>\n",
       "</pre></div>\n",
       "</body>\n",
       "</html>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "psource(FOIL_container)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example Family \n",
    "Suppose we have the following family relations:\n",
    "<br>\n",
    "![title](images/knowledge_foil_family.png)\n",
    "<br>\n",
    "Given some positive and negative examples of the relation 'Parent(x,y)', we want to find a set of rules that satisfies all the examples. <br>\n",
    "\n",
    "A definition of Parent is $Parent(x,y) \\Leftrightarrow Mother(x,y) \\lor Father(x,y)$, which is the result that we expect from the algorithm. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "A, B, C, D, E, F, G, H, I, x, y, z = map(expr, 'ABCDEFGHIxyz')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "small_family = FOIL_container([expr(\"Mother(Anne, Peter)\"),\n",
    "                               expr(\"Mother(Anne, Zara)\"),\n",
    "                               expr(\"Mother(Sarah, Beatrice)\"),\n",
    "                               expr(\"Mother(Sarah, Eugenie)\"),\n",
    "                               expr(\"Father(Mark, Peter)\"),\n",
    "                               expr(\"Father(Mark, Zara)\"),\n",
    "                               expr(\"Father(Andrew, Beatrice)\"),\n",
    "                               expr(\"Father(Andrew, Eugenie)\"),\n",
    "                               expr(\"Father(Philip, Anne)\"),\n",
    "                               expr(\"Father(Philip, Andrew)\"),\n",
    "                               expr(\"Mother(Elizabeth, Anne)\"),\n",
    "                               expr(\"Mother(Elizabeth, Andrew)\"),\n",
    "                               expr(\"Male(Philip)\"),\n",
    "                               expr(\"Male(Mark)\"),\n",
    "                               expr(\"Male(Andrew)\"),\n",
    "                               expr(\"Male(Peter)\"),\n",
    "                               expr(\"Female(Elizabeth)\"),\n",
    "                               expr(\"Female(Anne)\"),\n",
    "                               expr(\"Female(Sarah)\"),\n",
    "                               expr(\"Female(Zara)\"),\n",
    "                               expr(\"Female(Beatrice)\"),\n",
    "                               expr(\"Female(Eugenie)\"),\n",
    "])\n",
    "\n",
    "target = expr('Parent(x, y)')\n",
    "\n",
    "examples_pos = [{x: expr('Elizabeth'), y: expr('Anne')},\n",
    "                {x: expr('Elizabeth'), y: expr('Andrew')},\n",
    "                {x: expr('Philip'), y: expr('Anne')},\n",
    "                {x: expr('Philip'), y: expr('Andrew')},\n",
    "                {x: expr('Anne'), y: expr('Peter')},\n",
    "                {x: expr('Anne'), y: expr('Zara')},\n",
    "                {x: expr('Mark'), y: expr('Peter')},\n",
    "                {x: expr('Mark'), y: expr('Zara')},\n",
    "                {x: expr('Andrew'), y: expr('Beatrice')},\n",
    "                {x: expr('Andrew'), y: expr('Eugenie')},\n",
    "                {x: expr('Sarah'), y: expr('Beatrice')},\n",
    "                {x: expr('Sarah'), y: expr('Eugenie')}]\n",
    "examples_neg = [{x: expr('Anne'), y: expr('Eugenie')},\n",
    "                {x: expr('Beatrice'), y: expr('Eugenie')},\n",
    "                {x: expr('Mark'), y: expr('Elizabeth')},\n",
    "                {x: expr('Beatrice'), y: expr('Philip')}]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[Parent(x, y), [Mother(x, y)]], [Parent(x, y), [Father(x, y)]]]\n"
     ]
    }
   ],
   "source": [
    "# run the FOIL algorithm \n",
    "clauses = small_family.foil([examples_pos, examples_neg], target)\n",
    "print (clauses)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indeed the algorithm returned the rule: \n",
    "<br>$Parent(x,y) \\Leftrightarrow Mother(x,y) \\lor Father(x,y)$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Suppose that we have some possitive and negative results for the relation 'GrandParent(x,y)' and we want to find a set of rules that satisfies the examples. <br>\n",
    "One possible set of rules for the relation $Grandparent(x,y)$ could be: <br>\n",
    "![title](images/knowledge_FOIL_grandparent.png)\n",
    "<br>\n",
    "Or, if $Background$ included the sentence $Parent(x,y) \\Leftrightarrow [Mother(x,y) \\lor Father(x,y)]$ then:  \n",
    "\n",
    "$$Grandparent(x,y) \\Leftrightarrow \\exists \\: z \\quad  Parent(x,z) \\land Parent(z,y)$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[Grandparent(x, y), [Parent(x, v_5), Parent(v_5, y)]]]\n"
     ]
    }
   ],
   "source": [
    "target = expr('Grandparent(x, y)')\n",
    "\n",
    "examples_pos = [{x: expr('Elizabeth'), y: expr('Peter')},\n",
    "                {x: expr('Elizabeth'), y: expr('Zara')},\n",
    "                {x: expr('Elizabeth'), y: expr('Beatrice')},\n",
    "                {x: expr('Elizabeth'), y: expr('Eugenie')},\n",
    "                {x: expr('Philip'), y: expr('Peter')},\n",
    "                {x: expr('Philip'), y: expr('Zara')},\n",
    "                {x: expr('Philip'), y: expr('Beatrice')},\n",
    "                {x: expr('Philip'), y: expr('Eugenie')}]\n",
    "examples_neg = [{x: expr('Anne'), y: expr('Eugenie')},\n",
    "                {x: expr('Beatrice'), y: expr('Eugenie')},\n",
    "                {x: expr('Elizabeth'), y: expr('Andrew')},\n",
    "                {x: expr('Elizabeth'), y: expr('Anne')},\n",
    "                {x: expr('Elizabeth'), y: expr('Mark')},\n",
    "                {x: expr('Elizabeth'), y: expr('Sarah')},\n",
    "                {x: expr('Philip'), y: expr('Anne')},\n",
    "                {x: expr('Philip'), y: expr('Andrew')},\n",
    "                {x: expr('Anne'), y: expr('Peter')},\n",
    "                {x: expr('Anne'), y: expr('Zara')},\n",
    "                {x: expr('Mark'), y: expr('Peter')},\n",
    "                {x: expr('Mark'), y: expr('Zara')},\n",
    "                {x: expr('Andrew'), y: expr('Beatrice')},\n",
    "                {x: expr('Andrew'), y: expr('Eugenie')},\n",
    "                {x: expr('Sarah'), y: expr('Beatrice')},\n",
    "                {x: expr('Mark'), y: expr('Elizabeth')},\n",
    "                {x: expr('Beatrice'), y: expr('Philip')}, \n",
    "                {x: expr('Peter'), y: expr('Andrew')}, \n",
    "                {x: expr('Zara'), y: expr('Mark')},\n",
    "                {x: expr('Peter'), y: expr('Anne')},\n",
    "                {x: expr('Zara'), y: expr('Eugenie')},     ]\n",
    "\n",
    "clauses = small_family.foil([examples_pos, examples_neg], target)\n",
    "\n",
    "print(clauses)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indeed the algorithm returned the rule: \n",
    "<br>$Grandparent(x,y) \\Leftrightarrow \\exists \\: v \\: \\: Parent(x,v) \\land Parent(v,y)$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example Network\n",
    "\n",
    "Suppose that we have the following directed graph and we want to find a rule that describes the reachability between two nodes (Reach(x,y)). <br>\n",
    "Such a rule could be recursive, since y can be reached from x if and only if there is a sequence of adjacent nodes from x to y: \n",
    "\n",
    "$$ Reach(x,y) \\Leftrightarrow \\begin{cases} \n",
    "                Conn(x,y), \\: \\text{(if there is a directed edge from x to y)} \\\\\n",
    "                \\lor \\quad \\exists \\: z \\quad Reach(x,z) \\land Reach(z,y) \\end{cases}$$\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "A              H\n",
    "|\\            /|\n",
    "| \\          / |\n",
    "v  v        v  v\n",
    "B  D-->E-->G-->I\n",
    "|  /   |\n",
    "| /    |\n",
    "vv     v\n",
    "C      F\n",
    "\"\"\"\n",
    "small_network = FOIL_container([expr(\"Conn(A, B)\"),\n",
    "                               expr(\"Conn(A ,D)\"),\n",
    "                               expr(\"Conn(B, C)\"),\n",
    "                               expr(\"Conn(D, C)\"),\n",
    "                               expr(\"Conn(D, E)\"),\n",
    "                               expr(\"Conn(E ,F)\"),\n",
    "                               expr(\"Conn(E, G)\"),\n",
    "                               expr(\"Conn(G, I)\"),\n",
    "                               expr(\"Conn(H, G)\"),\n",
    "                               expr(\"Conn(H, I)\")])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[Reach(x, y), [Conn(x, y)]], [Reach(x, y), [Reach(x, v_12), Reach(v_14, y), Reach(v_12, v_16), Reach(v_12, y)]], [Reach(x, y), [Reach(x, v_20), Reach(v_20, y)]]]\n"
     ]
    }
   ],
   "source": [
    "target = expr('Reach(x, y)')\n",
    "examples_pos = [{x: A, y: B},\n",
    "                {x: A, y: C},\n",
    "                {x: A, y: D},\n",
    "                {x: A, y: E},\n",
    "                {x: A, y: F},\n",
    "                {x: A, y: G},\n",
    "                {x: A, y: I},\n",
    "                {x: B, y: C},\n",
    "                {x: D, y: C},\n",
    "                {x: D, y: E},\n",
    "                {x: D, y: F},\n",
    "                {x: D, y: G},\n",
    "                {x: D, y: I},\n",
    "                {x: E, y: F},\n",
    "                {x: E, y: G},\n",
    "                {x: E, y: I},\n",
    "                {x: G, y: I},\n",
    "                {x: H, y: G},\n",
    "                {x: H, y: I}]\n",
    "nodes = {A, B, C, D, E, F, G, H, I}\n",
    "examples_neg = [example for example in [{x: a, y: b} for a in nodes for b in nodes]\n",
    "                    if example not in examples_pos]\n",
    "clauses = small_network.foil([examples_pos, examples_neg], target)\n",
    "\n",
    "print(clauses)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The algorithm produced something close to the recursive rule: \n",
    " $$ Reach(x,y) \\Leftrightarrow [Conn(x,y)] \\: \\lor \\: [\\exists \\: z \\: \\: Reach(x,z) \\, \\land  \\, Reach(z,y)]$$\n",
    " \n",
    "This happened because the size of the example is small. "
   ]
  }
 ],
 "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.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
