{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Sarah_Engheta_MidtermNotes.ipynb",
      "provenance": [],
      "collapsed_sections": [
        "GZZXyrV-xuAp",
        "elCCgY64spuq",
        "9xRbdqDox2zD",
        "46MQLR-Gx8dZ",
        "WHREsHSSyA-h",
        "F3FPMzG9yUls",
        "RYESi2kMybL8"
      ]
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 1\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4021dda2-be9e-4594-9bd0-bbeb0acf6bff"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ca8f61da-85e2-43ab-9f70-d99f5dd1ebe2"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": 2,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 1 - Intro to AI"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, Chapter 1 “Introduction”, Section 1.1 “What is AI”\n",
        "\n",
        "chapter1_1 = \"\"\" Chapter 1.1 summary. \"\"\" \n",
        "\n",
        "# Russell and Norvig, AIMA 4th Edition, Chapter 27 “Philosophical Foundations”, Sections 27.1 “The Limits of AI” and 27.2 “Can Machines Really Think?”\n",
        "chapter27_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter27_2 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA 4th Edition, Chapter 2 “Intelligent Agents” (whole chapter)\n",
        "chapter2_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter2_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter2_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter2_4 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module1_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 1.\n",
        "# You can define any bolded term in the textbook, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 20 words long.\n",
        "module1_definitions = {\n",
        "\"agent\" : \"anything that can perceive and act in an environment\",\n",
        "\"percept\" : \"your definitions here\",\n",
        "\"other concept\" : \"your definitions here\",\n",
        "\"etc.\": \"your definitions here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 4,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 1\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "cellView": "form",
        "outputId": "064fea5e-4623-4878-e5ab-89d49409c90d"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module1_sections = [\n",
        "  (\"AIMA Chapter 1.1 What is AI?\", chapter1_1),\n",
        "  (\"AIMA Chapter 27.1 The Limits of AI\", chapter27_1),\n",
        "  (\"AIMA Chapter 27.1 Can Machines Really Think?\", chapter27_2),\n",
        "  (\"AIMA 2.1 Agents and Environments\", chapter2_1),\n",
        "  (\"AIMA 2.2 Good Behavior: The Concept of Rationality\", chapter2_2),\n",
        "  (\"AIMA 2.3 The Nature of Environments\", chapter2_3),\n",
        "  (\"AIMA 2.4 The Structure of Agents\", chapter2_4),\n",
        "  (\"Module 1 Lecture Notes\", module1_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 20):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module1_markdown = format_module(1, \"Rational Agents and Task Environments\", module1_sections, module1_definitions)\n",
        "display(Markdown(module1_markdown))"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n Chapter 1.1 summary. \n\n## AIMA Chapter 27.1 The Limits of AI\n Your summary here \n\n## AIMA Chapter 27.1 Can Machines Really Think?\n Your summary here \n\n## AIMA 2.1 Agents and Environments\n Your summary here \n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n Your summary here \n\n## AIMA 2.3 The Nature of Environments\n Your summary here \n\n## AIMA 2.4 The Structure of Agents\n Your summary here \n\n## Module 1 Lecture Notes\n Your summary here \n\n## Module 1 Definitions\n* **Agent** - anything that can perceive and act in an environment\n* **Percept** - your definitions here\n* **Other concept** - your definitions here\n* **Etc.** - your definitions here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 2 - Python"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# No readings for this module.  Instead you can summarize the lecture instead.\n",
        "\n",
        "# Lecture notes \n",
        "module2_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Each definition should be at most 20 words long.\n",
        "module2_definitions = {\n",
        "\"mutability\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "34d548b4-4943-4b5f-b5f9-55dc021dd8f6"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module2_sections = [\n",
        "  (\"Module 2 Lecture Notes\", module2_lecture_notes),\n",
        "]\n",
        "\n",
        "module2_markdown = format_module(2, \"Python\", module2_sections, module2_definitions)\n",
        "display(Markdown(module2_markdown))"
      ],
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 2: Python\n## Module 2 Lecture Notes\n Your summary here \n\n## Module 2 Definitions\n* **Mutability** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 3 - Search Problems"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 3 “Problem Solving by Search” (3.1-3.4)\n",
        "chapter3_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter3_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter3_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter3_4 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module3_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions of concepts from Module 3.\n",
        "# You can define any bolded term in the textbook, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 20 words long.\n",
        "module3_definitions = {\n",
        "\"problem-solving agent\" : \"an agent that can formulate a plan via search\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 8,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "2cbcdbe3-49b3-43f1-cfc9-3b4bc3023bec"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module3_sections = [\n",
        "  (\"AIMA Chapter 3.1 Problem-Solving Agents\", chapter3_1),\n",
        "  (\"AIMA Chapter 3.2 Example Problems\", chapter3_2),\n",
        "  (\"AIMA Chapter 3.3 Search Algorithms\", chapter3_3),\n",
        "  (\"AIMA Chapter 3.4 Uninformed Search Strategies\", chapter3_4),\n",
        "  (\"Module 3 Lecture Notes\", module3_lecture_notes),\n",
        "]\n",
        "\n",
        "module3_markdown = format_module(3, \"Search Problems\", module3_sections, module3_definitions)\n",
        "display(Markdown(module3_markdown))"
      ],
      "execution_count": 9,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n Your summary here \n\n## AIMA Chapter 3.2 Example Problems\n Your summary here \n\n## AIMA Chapter 3.3 Search Algorithms\n Your summary here \n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n Your summary here \n\n## Module 3 Lecture Notes\n Your summary here \n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 4 - Informed Search"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 3 “Problem Solving by Search” (3.5-3.6)\n",
        "chapter3_5 = \"\"\" Your summary here \"\"\"\n",
        "chapter3_6 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module4_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module4_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 10,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "cellView": "form",
        "outputId": "6e962c19-20cc-40ec-8f69-bb19da513fe4"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module4_sections = [\n",
        "  (\"AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\", chapter3_5),\n",
        "  (\"AIMA Chapter 3.6 Heuristic Functions\", chapter3_6),\n",
        "  (\"Module 4 Lecture Notes\", module4_lecture_notes),\n",
        "]\n",
        "\n",
        "module4_markdown = format_module(4, \"Informed Search\", \n",
        "                         module4_sections, \n",
        "                         module4_definitions)\n",
        "display(Markdown(module4_markdown))"
      ],
      "execution_count": 11,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n Your summary here \n\n## AIMA Chapter 3.6 Heuristic Functions\n Your summary here \n\n## Module 4 Lecture Notes\n Your summary here \n\n## Module 4 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 5 - Adversarial Search and Games"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA chapter 5 \"Adversarial Search\"”\" (5.1-5.3, and 5.5).\n",
        "chapter5_1 = \"\"\" \n",
        "Two players: MAX and MIN\n",
        "- all play is computed from MAX's vantage point\n",
        "- when MAX moves, MAX attempts to MAXimize MAX's outcome\n",
        "  - when MIN move, MIN attempts to MINimize MAX's outcome \n",
        "\n",
        "- Initial State: board config of chess\n",
        "- Successor Function: list of (move, state) pairs specifying legal moves\n",
        "- Terminal Test: is the game finished?\n",
        "- utility function: gives numerical value of terminal states\n",
        "- MAX uses search tree to determine next move \"\"\"\n",
        "chapter5_2 = \"\"\" Two-player discrete deterministic turn-taking zero-sum games with perfect information:\n",
        "\n",
        "The minimax algorithm can select optimal moves by a DFS enumeration of the game tree\n",
        "\n",
        "Monte Carlo Tree Search: evaluates states not by applying a heuristic function, but by playing out the game all the way to the end and using the rules\n",
        "of the game to see who won. The moves chosen during the playout might not have been optimal moves, the process is repeated multiple times and the evaluation is an average of the results \"\"\"\n",
        "chapter5_3 = \"\"\" Don't play hope chess. Make the best move for MAX assuming that MIN always replies with the best move for MIN\n",
        "\n",
        "This will lead to a recursive process. \n",
        "\n",
        "- the backed-up value of each node in the tree is determined by the values of its children:\n",
        "\n",
        "\n",
        "The Minimax procedure:\n",
        "\n",
        "until the game is over:\n",
        "\n",
        "- start with the current position as a MAX node\n",
        "- Expand the game tree a fixed number of ply\n",
        "- apply the evaluation function to the leaf positions\n",
        "- calculate back-up values bottom-up\n",
        "- pick the move assigned to MAX at the root\n",
        "- wait for MIN to respond \"\"\"\n",
        "chapter5_5 = \"\"\"Alpha-BEta Pruning\n",
        "\n",
        "- $\\\\alpha$ : MAX's current lower bound on MAX's outcome. MAX will get \"at least\" $\\\\alpha$\n",
        "- $\\\\beta$ : MIN's current upper bound on MIN's outcome. \"at most\" $\\\\beta$\n",
        "- MAX will never allow a move that could lead to a worse score (for MAX) than $\\\\alpha$\n",
        "- MIN will never allow a move that could lead to a better score (for MAX) than $\\\\beta$\n",
        "- Therefore, stop evaluating a branch whenever:\n",
        "  - when evaluating a MAX node: a value *v* $\\\\geq$ $\\\\beta$ is backed-up\n",
        "    - MIN will never select that MAX node\n",
        "  - when evaluating a MIN node: a value *v* $\\\\leq$ $\\\\alpha$ is found\n",
        "    - MAX will never select that MIN node\n",
        "- $\\\\alpha$ is MAX's best option on path to root\n",
        "- $\\\\beta$ is MIN's best option on path to root\n",
        " \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 16 “Making Simple Decisions” (16.1-16.3)\n",
        "chapter16_1 = \"\"\" Expectimax Search\n",
        "\n",
        "- unpredictable opponents: the opponent isn't playing optimally\n",
        "- actions can fail: wheels of robot might slip up when moving\n",
        "\n",
        "Values should now reflect average case (expectimax) outcomes, not worst-case (minimax) outcomes\n",
        "\n",
        "Expectimax Search: compute the average score under optimal play\n",
        "- max nodes as in minimax search\n",
        "- chance nodes are like min nodes but the outcome is uncertain\n",
        "- calculate their expected utilities\n",
        "- i.e. take weighted average (expectation) of children\n",
        "\n",
        " \"\"\"\n",
        "chapter16_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module5_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module5_definitions = {\n",
        "\"new concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 12,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "b889c466-0793-4854-b1c7-126147ad4879"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module5_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter5_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter5_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter5_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter5_5),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"Module 5 Lecture Notes\", module5_lecture_notes),\n",
        "]\n",
        "\n",
        "module5_markdown = format_module(5, \"Adversarial Search and Games\", \n",
        "                         module5_sections, \n",
        "                         module5_definitions)\n",
        "display(Markdown(module5_markdown))"
      ],
      "execution_count": 13,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n \nTwo players: MAX and MIN\n- all play is computed from MAX's vantage point\n- when MAX moves, MAX attempts to MAXimize MAX's outcome\n  - when MIN move, MIN attempts to MINimize MAX's outcome \n\n- Initial State: board config of chess\n- Successor Function: list of (move, state) pairs specifying legal moves\n- Terminal Test: is the game finished?\n- utility function: gives numerical value of terminal states\n- MAX uses search tree to determine next move \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Two-player discrete deterministic turn-taking zero-sum games with perfect information:\n\nThe minimax algorithm can select optimal moves by a DFS enumeration of the game tree\n\nMonte Carlo Tree Search: evaluates states not by applying a heuristic function, but by playing out the game all the way to the end and using the rules\nof the game to see who won. The moves chosen during the playout might not have been optimal moves, the process is repeated multiple times and the evaluation is an average of the results \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Don't play hope chess. Make the best move for MAX assuming that MIN always replies with the best move for MIN\n\nThis will lead to a recursive process. \n\n- the backed-up value of each node in the tree is determined by the values of its children:\n\n\nThe Minimax procedure:\n\nuntil the game is over:\n\n- start with the current position as a MAX node\n- Expand the game tree a fixed number of ply\n- apply the evaluation function to the leaf positions\n- calculate back-up values bottom-up\n- pick the move assigned to MAX at the root\n- wait for MIN to respond \n\n## AIMA Chapter 5.5 Stochastic Games\nAlpha-BEta Pruning\n\n- $\\alpha$ : MAX's current lower bound on MAX's outcome. MAX will get \"at least\" $\\alpha$\n- $\\beta$ : MIN's current upper bound on MIN's outcome. \"at most\" $\\beta$\n- MAX will never allow a move that could lead to a worse score (for MAX) than $\\alpha$\n- MIN will never allow a move that could lead to a better score (for MAX) than $\\beta$\n- Therefore, stop evaluating a branch whenever:\n  - when evaluating a MAX node: a value *v* $\\geq$ $\\beta$ is backed-up\n    - MIN will never select that MAX node\n  - when evaluating a MIN node: a value *v* $\\leq$ $\\alpha$ is found\n    - MAX will never select that MIN node\n- $\\alpha$ is MAX's best option on path to root\n- $\\beta$ is MIN's best option on path to root\n \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Expectimax Search\n\n- unpredictable opponents: the opponent isn't playing optimally\n- actions can fail: wheels of robot might slip up when moving\n\nValues should now reflect average case (expectimax) outcomes, not worst-case (minimax) outcomes\n\nExpectimax Search: compute the average score under optimal play\n- max nodes as in minimax search\n- chance nodes are like min nodes but the outcome is uncertain\n- calculate their expected utilities\n- i.e. take weighted average (expectation) of children\n\n \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## Module 5 Lecture Notes\n Your summary here \n\n## Module 5 Definitions\n* **New concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "#Module 6 - \"Constraint Satisfaction Problems\""
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Russell and Norvig, AIMA, Chapter 6 “Constraint Satisfaction Problems” (6.1-6.5)\n",
        "chapter6_1 = \"\"\" CSP consists of 3 different things: \n",
        "* finite set of variables. \n",
        "* nonempty domain of possible values for each variable. \n",
        "* finite set of contstraints that limits the values that variable can take. \n",
        "\n",
        "A state is defined as an assignment of values to some or all variables.\n",
        "a consistent assignment does not violate constraints.\n",
        "\n",
        "An **assignment** is complete when every variable is assigned a value. A solution to a CSP is a **complete, consistent** assignment. Solutions to CSPs can\n",
        "be found by a completely general purpose algorithm, given only the formal specs of the CSP. Clean specifications of many problems\n",
        "general goal, successor function and heuristics. \n",
        "\n",
        "CSP knows which variables violate a constraint and CSPs automatically prune off all branches that violate constaints. \n",
        "\n",
        "Constraint graph:\n",
        "* nodes are variables\n",
        "* arcs are (binary) constraints\n",
        "* Discrete Variables: finite domains (e.g. Boolean CSPs, includes boolean satisfiability)\n",
        "vs infinite domains (job scheduling)\n",
        "* Continuous variables: start/end times \n",
        "\n",
        "Types of constraints:\n",
        "* unary constraints: involve a single variable</li>\n",
        "* binary constraints: involve pairs of vairables</li>\n",
        "* higher order constraints involve 3 or more variables</li>\n",
        "* soft constraints that indicate preferences </li>\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter6_2 = \"\"\" CSP as a search problem\n",
        "\n",
        "* initial state: the empty assignment {}\n",
        "* successor function: assign value to any unassigned variable provided there is not a constraint conflict\n",
        "* goal test: the current assignment is complete\n",
        "* path cost: a constant cost for every step\n",
        "\n",
        "Solution is always found at depth n for n variables, hence DFS is used \n",
        "\n",
        "*n variables of domain size d\n",
        "*branching factor at the root is n*d\n",
        "*branching factor at the next level is (n-1)*d\n",
        "*tree has n!*d^n leaves\n",
        "\n",
        "\n",
        "the variable assignments are commutative. i.e. order of steps is not important, so it is a tree search not a graph search\n",
        "- i.e. [step 1: WA = red; step 2: NT = green] is equivalent to [step 1: NT = green; step 2: WA = red]\n",
        "only need to consider assignments to a single variable at each node\n",
        "\n",
        "b = d and there are d^n leaves (n variables, domain size d)\n",
        "\n",
        "Search and backtracking: \n",
        "\n",
        "- dfs search for CSPs with single-variable assignments is called *backtracking*\n",
        "  - backtracking: a DFS search that chooses values for one variable at a time and backtracks when a variable has no legal values left to assign\n",
        "- backtracking search is the basic uninformed search for CSPs\n",
        "\"\"\"\n",
        "chapter6_3 = \"\"\" Heuristics to improve backtracking efficiency. \n",
        "\n",
        "General purpose methods and general purpose heuristics can give huge gains in speed, on average\n",
        "\n",
        "heuristics:\n",
        "\n",
        "- which variable should be assigned next? \n",
        "  - the most constrained variable\n",
        "  - if ties: most constraining variable\n",
        "- in what order should the variables values be tried:\n",
        "  - least constraining value\n",
        "- without actually going ahead with the search - can we detect inevitable failure early?\n",
        "  - forward checking\n",
        "  \n",
        "First heuristic: which variable should I pick?\n",
        " - choose a variable with the fewest legal values\n",
        " - aka minimum remaining values (MRV)\n",
        " - aka fast-fail method \n",
        "\n",
        "Second Heuristic:  most constraining variable\n",
        "  - tiebreaker among most constrained variables\n",
        "  - choose the variable with tthe most constraints on remaining variables\n",
        "\n",
        "Third Heuristic:\n",
        "- given a variable, choose the least constraining value\n",
        "- the one that rules out the fewest values in the remaining variables\n",
        "\n",
        "Fourth Heuristic: forward checking\n",
        "- keep track of remaining legal values for unassigned variables\n",
        "- terminate search when any unassigned variable has no remaining legal values\n",
        "- whenever a variable X is assigned, the forward checking process establishes arc consistency for it:\n",
        "  - for each unassigned variable Y that is connected to X by a constraint, delete from Y's domain any value that is inconsistent with the value chosen for X\n",
        "forward check and then if you terminate, backtrack and forward check for a different path\n",
        "- allows us to propogate information from assigned to unassigned variables but doesn't provide\n",
        "early detection for all failures\n",
        "- **Constraint Propogation** goes beyond forward checking and repeatedly enforces constraints locally\n",
        "  \"\"\"\n",
        "chapter6_4 = \"\"\" Big IDea: Inference in CSPs:\n",
        "- CSP solvers combine seaerch and inference\n",
        "  - search\n",
        "    - assigning a value to a variable\n",
        "  - constraint propogation (inference)\n",
        "      - eliminates possibel values for a variable if the value would violate local consistency\n",
        "  - can do inference first, or intertwine it with seaarch:\n",
        "- local consistency\n",
        "  - **node consistency**: satisfies unary constraints\n",
        "  - **arc consistency**: satisfies binary constraints. X is arc consistent with Y if for every value in X's domain, there is \n",
        "  some value in Y's domain that satisfies the binary constraint on the arc between X and Y\n",
        "\n",
        "k=1 is node consistency (given the empty set_ we can make any set of one variable consistent\n",
        "\n",
        "k=2 is arc consistency: a variable is arc-consistent if every value in its domain satisfies the variable's binary constraints for every . \n",
        "\n",
        "k=3 is path consistency\n",
        "\n",
        "A CSP is **strongly k-consistent if it is k-consistent and is also (k-1)-consistent, (k-2)-consistent, ...down to o1-consistent\n",
        "\n",
        "\n",
        "Global Constraint: involving an arbitrary number of variables but not necessarily all variables. \n",
        "\n",
        "Resource Constraint: at most constraint\n",
        "\n",
        "Bounds propogation: domains are represented by upper and lower bounds and are managed by this propogation\n",
        "\n",
        "Bounds-consistent: if for every variable X, and for both the lower bound and upper bound values of X, there exists some value of Y that satisfies the constraint between X and Y for every variable Y\"\"\"\n",
        "\n",
        "chapter6_5 = \"\"\" Commutativity: a problem is commutative if the order of application of any given set of actions does not matter\n",
        "\n",
        "MRV heuristic: most-constrained variable, or \"fail first\" heuristic - picks a variable that is most likely to cause a failure soon.\n",
        "\n",
        "Degree heuristic: attempts to reduce the branching factor on future choices by selecting the variable that is involved in the largest number of constraints on other unassigned variables\n",
        "\n",
        "Conflict-directed backjumping backtracks directly to the source of the problem.\n",
        "\n",
        "Constraint learning: finding min set of variables from the conflict set that causes the problem. this set of variables is called a no-good\n",
        "\n",
        "Cutset Conditioning: can redue a general CSP to a tree-structured one and is efficient - requires only linear memory\n",
        "\n",
        "Tree Decomposition: techniques that transform the CSP into a tree of subproblems and are efficient if the tree width of the constraint graph is small, however needs memory exponential in the tree width of the constraint graph\n",
        "\n",
        "Local search using the min-conflicts heuristic has also been applied to constraint satisfaction problems with great success.\n",
        "\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module6_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module6_definitions = {\n",
        "\"CSP\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 14,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "85e4dda9-90a9-4c92-d7db-5f2177dc4057"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module6_sections = [\n",
        "  (\"AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\", chapter6_1),\n",
        "  (\"AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\", chapter6_2),\n",
        "  (\"AIMA Chapter 6.3 Backtracking Search for CSPs\", chapter6_3),\n",
        "  (\"AIMA Chapter 6.4 Local Search for CSPs\", chapter6_4),\n",
        "  (\"AIMA Chapter 6.5 The Structure of Problems\", chapter6_5),\n",
        "  (\"Module 6 Lecture Notes\", module6_lecture_notes),\n",
        "]\n",
        "\n",
        "module6_markdown = format_module(6, \"Constraint Satisfaction Problems\", \n",
        "                         module6_sections, \n",
        "                         module6_definitions)\n",
        "display(Markdown(module6_markdown))"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n CSP consists of 3 different things: \n* finite set of variables. \n* nonempty domain of possible values for each variable. \n* finite set of contstraints that limits the values that variable can take. \n\nA state is defined as an assignment of values to some or all variables.\na consistent assignment does not violate constraints.\n\nAn **assignment** is complete when every variable is assigned a value. A solution to a CSP is a **complete, consistent** assignment. Solutions to CSPs can\nbe found by a completely general purpose algorithm, given only the formal specs of the CSP. Clean specifications of many problems\ngeneral goal, successor function and heuristics. \n\nCSP knows which variables violate a constraint and CSPs automatically prune off all branches that violate constaints. \n\nConstraint graph:\n* nodes are variables\n* arcs are (binary) constraints\n* Discrete Variables: finite domains (e.g. Boolean CSPs, includes boolean satisfiability)\nvs infinite domains (job scheduling)\n* Continuous variables: start/end times \n\nTypes of constraints:\n* unary constraints: involve a single variable</li>\n* binary constraints: involve pairs of vairables</li>\n* higher order constraints involve 3 or more variables</li>\n* soft constraints that indicate preferences </li>\n\n\n \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n CSP as a search problem\n\n* initial state: the empty assignment {}\n* successor function: assign value to any unassigned variable provided there is not a constraint conflict\n* goal test: the current assignment is complete\n* path cost: a constant cost for every step\n\nSolution is always found at depth n for n variables, hence DFS is used \n\n*n variables of domain size d\n*branching factor at the root is n*d\n*branching factor at the next level is (n-1)*d\n*tree has n!*d^n leaves\n\n\nthe variable assignments are commutative. i.e. order of steps is not important, so it is a tree search not a graph search\n- i.e. [step 1: WA = red; step 2: NT = green] is equivalent to [step 1: NT = green; step 2: WA = red]\nonly need to consider assignments to a single variable at each node\n\nb = d and there are d^n leaves (n variables, domain size d)\n\nSearch and backtracking: \n\n- dfs search for CSPs with single-variable assignments is called *backtracking*\n  - backtracking: a DFS search that chooses values for one variable at a time and backtracks when a variable has no legal values left to assign\n- backtracking search is the basic uninformed search for CSPs\n\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n Heuristics to improve backtracking efficiency. \n\nGeneral purpose methods and general purpose heuristics can give huge gains in speed, on average\n\nheuristics:\n\n- which variable should be assigned next? \n  - the most constrained variable\n  - if ties: most constraining variable\n- in what order should the variables values be tried:\n  - least constraining value\n- without actually going ahead with the search - can we detect inevitable failure early?\n  - forward checking\n  \nFirst heuristic: which variable should I pick?\n - choose a variable with the fewest legal values\n - aka minimum remaining values (MRV)\n - aka fast-fail method \n\nSecond Heuristic:  most constraining variable\n  - tiebreaker among most constrained variables\n  - choose the variable with tthe most constraints on remaining variables\n\nThird Heuristic:\n- given a variable, choose the least constraining value\n- the one that rules out the fewest values in the remaining variables\n\nFourth Heuristic: forward checking\n- keep track of remaining legal values for unassigned variables\n- terminate search when any unassigned variable has no remaining legal values\n- whenever a variable X is assigned, the forward checking process establishes arc consistency for it:\n  - for each unassigned variable Y that is connected to X by a constraint, delete from Y's domain any value that is inconsistent with the value chosen for X\nforward check and then if you terminate, backtrack and forward check for a different path\n- allows us to propogate information from assigned to unassigned variables but doesn't provide\nearly detection for all failures\n- **Constraint Propogation** goes beyond forward checking and repeatedly enforces constraints locally\n  \n\n## AIMA Chapter 6.4 Local Search for CSPs\n Big IDea: Inference in CSPs:\n- CSP solvers combine seaerch and inference\n  - search\n    - assigning a value to a variable\n  - constraint propogation (inference)\n      - eliminates possibel values for a variable if the value would violate local consistency\n  - can do inference first, or intertwine it with seaarch:\n- local consistency\n  - **node consistency**: satisfies unary constraints\n  - **arc consistency**: satisfies binary constraints. X is arc consistent with Y if for every value in X's domain, there is \n  some value in Y's domain that satisfies the binary constraint on the arc between X and Y\n\nk=1 is node consistency (given the empty set_ we can make any set of one variable consistent\n\nk=2 is arc consistency: a variable is arc-consistent if every value in its domain satisfies the variable's binary constraints for every . \n\nk=3 is path consistency\n\nA CSP is **strongly k-consistent if it is k-consistent and is also (k-1)-consistent, (k-2)-consistent, ...down to o1-consistent\n\n\nGlobal Constraint: involving an arbitrary number of variables but not necessarily all variables. \n\nResource Constraint: at most constraint\n\nBounds propogation: domains are represented by upper and lower bounds and are managed by this propogation\n\nBounds-consistent: if for every variable X, and for both the lower bound and upper bound values of X, there exists some value of Y that satisfies the constraint between X and Y for every variable Y\n\n## AIMA Chapter 6.5 The Structure of Problems\n Commutativity: a problem is commutative if the order of application of any given set of actions does not matter\n\nMRV heuristic: most-constrained variable, or \"fail first\" heuristic - picks a variable that is most likely to cause a failure soon.\n\nDegree heuristic: attempts to reduce the branching factor on future choices by selecting the variable that is involved in the largest number of constraints on other unassigned variables\n\nConflict-directed backjumping backtracks directly to the source of the problem.\n\nConstraint learning: finding min set of variables from the conflict set that causes the problem. this set of variables is called a no-good\n\nCutset Conditioning: can redue a general CSP to a tree-structured one and is efficient - requires only linear memory\n\nTree Decomposition: techniques that transform the CSP into a tree of subproblems and are efficient if the tree width of the constraint graph is small, however needs memory exponential in the tree width of the constraint graph\n\nLocal search using the min-conflicts heuristic has also been applied to constraint satisfaction problems with great success.\n\n\n\n\n\n## Module 6 Lecture Notes\n Your summary here \n\n## Module 6 Definitions\n* **Csp** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "#Module 7 - Logical Agents"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 7 “Logical Agents” (Sections 7.1-7.5)\n",
        "\n",
        "chapter7_1 = \"\"\" Knowledge Based Agents. KB-agents use a process of reasoning over an internal \n",
        "representation of knowledge to decide what actions to take. The main component \n",
        "is called a Knowledge Base (KB). KB contains a set of things that we refer to \n",
        "as sentences written in Knowledge representation language. \n",
        "Two kinds of sentences in KB: 1. Axiom - a sentence that is given. \n",
        "From this we can get 2. Derived Sentence this is called inference. \n",
        "Tell action and Ask action. In addition to asserting new knowledge\n",
        "into its KB, a KB agent can also query the KB and \n",
        "ask it to derive new knowledgein order to select what action it can take. Difference \n",
        "between \"knowledge level\" and \"implementation level\". Declarative approach\n",
        "to systems building uses Tell actions to the agent until it knows how to operate in\n",
        "its environment. Procedural approach on the other hand encodes the desired behaviors\n",
        "directly as program code\"\"\"\n",
        "chapter7_2 = \"\"\"Wampa world. We need a performance Measure, environment, actuators, \n",
        "sensors. Percept = [Stench, Breeze, Gasp, Bump, Scream] Vector of percepts. \"\"\"\n",
        "chapter7_3 = \"\"\" Logic can serve as a general class of representation for knowledge-\n",
        "based agent. we are going to examine propositional logic. KB consists of sentences in\n",
        "the representation language. Representation language has syntax that specifies sentences\n",
        "that are well-formed. \n",
        "\n",
        "A logic defines the semantics of the sentences, which is their meaning.\n",
        "the semantics defines the truth of each sentence with respect to a possible world, which we will often \n",
        "call a model. \n",
        "\n",
        "**Models** are mathematical abstractions that have a fixed set of truth values which are\n",
        "{true, false} for each sentence. \n",
        "\n",
        "* If sentence $\\\\alpha$ is true in model m then we say that m **satisfies**\n",
        "$\\\\alpha$ or m is a model of $\\\\alpha$. E.g. $\\\\alpha$ could be a sentence that means \"there is no pit in [2,2]\".\n",
        "  * in that case m($\\\\alpha$) would be all instances of Wampa world where [2,2] doesn't have a pit. \n",
        "  \n",
        "  \n",
        "Logical Entailment:\n",
        "once we have a notion of truth, we can start to define logical reasoning. This is the idea that\n",
        "a sentence follows logically from another sentencce. $\\\\alpha$ entails $\\\\beta$ if and only if M($\\\\alpha$) is a \n",
        "subset of M($\\\\beta$). $\\\\alpha$ is a more specific sentence than $\\\\beta$. \"My pet is a cat\" entails \n",
        "\"My pet is an animal\" \n",
        "\n",
        "Entailment can be applied to derive conclusions, which is the process of logical\n",
        "inference. We can think about the consequences of a KB as a large set of additional sentences that are \n",
        "entailed given the sentences that have been added to the KB. \n",
        "\n",
        "We want to design **inference algorithms**\n",
        "to enumerate these sentences. when an inference algo **i** allows us to conclude that $\\\\alpha$ is true, then we write \n",
        "that alpha is derived from KB by i. KB $\\\\vdash_{i}$ $\\\\alpha$\"\"\"\n",
        "chapter7_4 = \"\"\" Propositional Logic. \n",
        "\n",
        "Truth Tables - implication is only false if I lied to you/I broke my promise to you. i.e. if P implies Q and P is true but Q is false, \n",
        "then that statement is false. \n",
        "\n",
        "Premise/Antecedent $\\\\Rightarrow$ conclusion/consequent. \n",
        "\n",
        "Inference rules can be used to derive proofs. Monotonicity\n",
        "says that the set of entailed sentence can only increase as information is added to the KB. \n",
        "\n",
        "If we add additional information to the KB, it doesn't invalidate any other info that we've already inferred. **Monotonicity implies soundness**.  \"\"\"\n",
        "chapter7_5 = \"\"\" Conjunctive Normal Form (CNF).  Every sentence of propositional logic is logically\n",
        "equivalent to a conjunction of clauses. \n",
        "\n",
        "Clauses are disjunctions of literaals. \n",
        "\n",
        "the process is:\n",
        "1. Eliminate biconditionals $\\\\iff$ by replacing $\\\\alpha$ $\\\\iff$ $\\\\beta$ with $\\\\alpha$ $\\\\Rightarrow$ $\\\\beta$ $\\\\land$ $\\\\beta$ $\\\\Rightarrow$ $\\\\alpha$\n",
        "2. Eliminate $\\\\alpha$ $\\\\Rightarrow$ $\\\\beta$ with $\\\\lnot$ $\\\\alpha$ $\\\\lor$ $\\\\beta$\n",
        "3. Move $\\\\lnot$ inwards (eliminate double neagation, and apply deMorgans rules)\n",
        "4. Now the sentence will contain nested $\\\\land$ and $\\\\lor$ operators applied to literals. \n",
        "    \n",
        "Apply distributivity law to distribute $\\\\lor$ over $\\\\land$ wherever possible. \n",
        "    \n",
        "This gives us a resolution algorithm. Inference procedures based on resolution. \n",
        "\n",
        "Definite clause: disjunction of literals with exactly one positive one.  \n",
        "\n",
        "Horn Clause - disjunction of literals where\n",
        "at least one is positive. This includes definite clauses and clauses with no positive literals. \n",
        "    \n",
        "Validity: a sentence is valid if it is true in all models. for example, the sentence P $\\\\lor$ $\\\\not$ P is valid. Valid sentences\n",
        "are also known as **tautologies** they are necessarily true. Because the sentence True is in all models, every \n",
        "valid sentence is logically equivalent to True. \n",
        "\n",
        "**Deduction Theorem** comes from this. \n",
        "\n",
        "Satisfiability can be checked by enumerating the possible models until one is found that satisfies the sentence. \n",
        "\n",
        "Refutation or proof by contradiction: One assumes a sentence to be false and shows that this leads to a contradiction with known axioms. \"\"\"\n",
        "# Lecture notes \n",
        "module7_lecture_notes = \"\"\" Inference rules can be applied to derive a proof. \n",
        "\n",
        "Efficient model-checking inference algorithms for propositional logic include backtracking and local search methods and can often solve large problems quickly.\n",
        "\n",
        "\n",
        "Forward chaining and backward chaining are very natural reasoning algorithms for knowledge bases in Horn form.\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module7_definitions = {\n",
        "\"complete\" : \"an inference algo is complete if it can derive any sentence that is entailed\",\n",
        "\"sound/truth-preserving\" : \"an inference algo that derives only entailed sentences\",  \n",
        "\"grounding\" : \"the connection between logical reasoning processes and the real environment in which the agent exists \"  \n",
        "}\n",
        "\n"
      ],
      "execution_count": 16,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 0
        },
        "outputId": "1ab44e7c-e4fc-47b0-b80d-17b3a1fd4a41"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module7_sections = [\n",
        "  (\"AIMA Chapter 7.1 Knowledge-Based Agents\", chapter7_1),\n",
        "  (\"AIMA Chapter 7.2 The Wumpus World\", chapter7_2),\n",
        "  (\"AIMA Chapter 7.3 Logic\", chapter7_3),\n",
        "  (\"AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\", chapter7_4),\n",
        "  (\"AIMA 7.5 Propositional Theorem Proving\", chapter7_5),\n",
        "  (\"Module 7 Lecture Notes\", module7_lecture_notes),\n",
        "]\n",
        "\n",
        "module7_markdown = format_module(7, \"Logical Agents\", \n",
        "                         module7_sections, \n",
        "                         module7_definitions)\n",
        "display(Markdown(module7_markdown))"
      ],
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n Knowledge Based Agents. KB-agents use a process of reasoning over an internal \nrepresentation of knowledge to decide what actions to take. The main component \nis called a Knowledge Base (KB). KB contains a set of things that we refer to \nas sentences written in Knowledge representation language. \nTwo kinds of sentences in KB: 1. Axiom - a sentence that is given. \nFrom this we can get 2. Derived Sentence this is called inference. \nTell action and Ask action. In addition to asserting new knowledge\ninto its KB, a KB agent can also query the KB and \nask it to derive new knowledgein order to select what action it can take. Difference \nbetween \"knowledge level\" and \"implementation level\". Declarative approach\nto systems building uses Tell actions to the agent until it knows how to operate in\nits environment. Procedural approach on the other hand encodes the desired behaviors\ndirectly as program code\n\n## AIMA Chapter 7.2 The Wumpus World\nWampa world. We need a performance Measure, environment, actuators, \nsensors. Percept = [Stench, Breeze, Gasp, Bump, Scream] Vector of percepts. \n\n## AIMA Chapter 7.3 Logic\n Logic can serve as a general class of representation for knowledge-\nbased agent. we are going to examine propositional logic. KB consists of sentences in\nthe representation language. Representation language has syntax that specifies sentences\nthat are well-formed. \n\nA logic defines the semantics of the sentences, which is their meaning.\nthe semantics defines the truth of each sentence with respect to a possible world, which we will often \ncall a model. \n\n**Models** are mathematical abstractions that have a fixed set of truth values which are\n{true, false} for each sentence. \n\n* If sentence $\\alpha$ is true in model m then we say that m **satisfies**\n$\\alpha$ or m is a model of $\\alpha$. E.g. $\\alpha$ could be a sentence that means \"there is no pit in [2,2]\".\n  * in that case m($\\alpha$) would be all instances of Wampa world where [2,2] doesn't have a pit. \n  \n  \nLogical Entailment:\nonce we have a notion of truth, we can start to define logical reasoning. This is the idea that\na sentence follows logically from another sentencce. $\\alpha$ entails $\\beta$ if and only if M($\\alpha$) is a \nsubset of M($\\beta$). $\\alpha$ is a more specific sentence than $\\beta$. \"My pet is a cat\" entails \n\"My pet is an animal\" \n\nEntailment can be applied to derive conclusions, which is the process of logical\ninference. We can think about the consequences of a KB as a large set of additional sentences that are \nentailed given the sentences that have been added to the KB. \n\nWe want to design **inference algorithms**\nto enumerate these sentences. when an inference algo **i** allows us to conclude that $\\alpha$ is true, then we write \nthat alpha is derived from KB by i. KB $\\vdash_{i}$ $\\alpha$\n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n Propositional Logic. \n\nTruth Tables - implication is only false if I lied to you/I broke my promise to you. i.e. if P implies Q and P is true but Q is false, \nthen that statement is false. \n\nPremise/Antecedent $\\Rightarrow$ conclusion/consequent. \n\nInference rules can be used to derive proofs. Monotonicity\nsays that the set of entailed sentence can only increase as information is added to the KB. \n\nIf we add additional information to the KB, it doesn't invalidate any other info that we've already inferred. **Monotonicity implies soundness**.  \n\n## AIMA 7.5 Propositional Theorem Proving\n Conjunctive Normal Form (CNF).  Every sentence of propositional logic is logically\nequivalent to a conjunction of clauses. \n\nClauses are disjunctions of literaals. \n\nthe process is:\n1. Eliminate biconditionals $\\iff$ by replacing $\\alpha$ $\\iff$ $\\beta$ with $\\alpha$ $\\Rightarrow$ $\\beta$ $\\land$ $\\beta$ $\\Rightarrow$ $\\alpha$\n2. Eliminate $\\alpha$ $\\Rightarrow$ $\\beta$ with $\\lnot$ $\\alpha$ $\\lor$ $\\beta$\n3. Move $\\lnot$ inwards (eliminate double neagation, and apply deMorgans rules)\n4. Now the sentence will contain nested $\\land$ and $\\lor$ operators applied to literals. \n    \nApply distributivity law to distribute $\\lor$ over $\\land$ wherever possible. \n    \nThis gives us a resolution algorithm. Inference procedures based on resolution. \n\nDefinite clause: disjunction of literals with exactly one positive one.  \n\nHorn Clause - disjunction of literals where\nat least one is positive. This includes definite clauses and clauses with no positive literals. \n    \nValidity: a sentence is valid if it is true in all models. for example, the sentence P $\\lor$ $\\not$ P is valid. Valid sentences\nare also known as **tautologies** they are necessarily true. Because the sentence True is in all models, every \nvalid sentence is logically equivalent to True. \n\n**Deduction Theorem** comes from this. \n\nSatisfiability can be checked by enumerating the possible models until one is found that satisfies the sentence. \n\nRefutation or proof by contradiction: One assumes a sentence to be false and shows that this leads to a contradiction with known axioms. \n\n## Module 7 Lecture Notes\n Inference rules can be applied to derive a proof. \n\nEfficient model-checking inference algorithms for propositional logic include backtracking and local search methods and can often solve large problems quickly.\n\n\nForward chaining and backward chaining are very natural reasoning algorithms for knowledge bases in Horn form.\n\n\n\n\n## Module 7 Definitions\n* **Complete** - an inference algo is complete if it can derive any sentence that is entailed\n* **Sound/truth-preserving** - an inference algo that derives only entailed sentences\n* **Grounding** - the connection between logical reasoning processes and the real environment in which the agent exists \n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "dca47eaa-0e12-4747-faf0-6e2cf16c17c5"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module1_markdown, \n",
        "                             module2_markdown, \n",
        "                             module3_markdown, \n",
        "                             module4_markdown, \n",
        "                             module5_markdown,\n",
        "                             module6_markdown,\n",
        "                             module7_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n Chapter 1.1 summary. \n\n## AIMA Chapter 27.1 The Limits of AI\n Your summary here \n\n## AIMA Chapter 27.1 Can Machines Really Think?\n Your summary here \n\n## AIMA 2.1 Agents and Environments\n Your summary here \n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n Your summary here \n\n## AIMA 2.3 The Nature of Environments\n Your summary here \n\n## AIMA 2.4 The Structure of Agents\n Your summary here \n\n## Module 1 Lecture Notes\n Your summary here \n\n## Module 1 Definitions\n* **Agent** - anything that can perceive and act in an environment\n* **Percept** - your definitions here\n* **Other concept** - your definitions here\n* **Etc.** - your definitions here\n\n\n# Module 2: Python\n## Module 2 Lecture Notes\n Your summary here \n\n## Module 2 Definitions\n* **Mutability** - your definition here\n\n\n# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n Your summary here \n\n## AIMA Chapter 3.2 Example Problems\n Your summary here \n\n## AIMA Chapter 3.3 Search Algorithms\n Your summary here \n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n Your summary here \n\n## Module 3 Lecture Notes\n Your summary here \n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n\n\n# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n Your summary here \n\n## AIMA Chapter 3.6 Heuristic Functions\n Your summary here \n\n## Module 4 Lecture Notes\n Your summary here \n\n## Module 4 Definitions\n* **Concept** - definition\n\n\n# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n \nTwo players: MAX and MIN\n- all play is computed from MAX's vantage point\n- when MAX moves, MAX attempts to MAXimize MAX's outcome\n  - when MIN move, MIN attempts to MINimize MAX's outcome \n\n- Initial State: board config of chess\n- Successor Function: list of (move, state) pairs specifying legal moves\n- Terminal Test: is the game finished?\n- utility function: gives numerical value of terminal states\n- MAX uses search tree to determine next move \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n Two-player discrete deterministic turn-taking zero-sum games with perfect information:\n\nThe minimax algorithm can select optimal moves by a DFS enumeration of the game tree\n\nMonte Carlo Tree Search: evaluates states not by applying a heuristic function, but by playing out the game all the way to the end and using the rules\nof the game to see who won. The moves chosen during the playout might not have been optimal moves, the process is repeated multiple times and the evaluation is an average of the results \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n Don't play hope chess. Make the best move for MAX assuming that MIN always replies with the best move for MIN\n\nThis will lead to a recursive process. \n\n- the backed-up value of each node in the tree is determined by the values of its children:\n\n\nThe Minimax procedure:\n\nuntil the game is over:\n\n- start with the current position as a MAX node\n- Expand the game tree a fixed number of ply\n- apply the evaluation function to the leaf positions\n- calculate back-up values bottom-up\n- pick the move assigned to MAX at the root\n- wait for MIN to respond \n\n## AIMA Chapter 5.5 Stochastic Games\nAlpha-BEta Pruning\n\n- $\\alpha$ : MAX's current lower bound on MAX's outcome. MAX will get \"at least\" $\\alpha$\n- $\\beta$ : MIN's current upper bound on MIN's outcome. \"at most\" $\\beta$\n- MAX will never allow a move that could lead to a worse score (for MAX) than $\\alpha$\n- MIN will never allow a move that could lead to a better score (for MAX) than $\\beta$\n- Therefore, stop evaluating a branch whenever:\n  - when evaluating a MAX node: a value *v* $\\geq$ $\\beta$ is backed-up\n    - MIN will never select that MAX node\n  - when evaluating a MIN node: a value *v* $\\leq$ $\\alpha$ is found\n    - MAX will never select that MIN node\n- $\\alpha$ is MAX's best option on path to root\n- $\\beta$ is MIN's best option on path to root\n \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Expectimax Search\n\n- unpredictable opponents: the opponent isn't playing optimally\n- actions can fail: wheels of robot might slip up when moving\n\nValues should now reflect average case (expectimax) outcomes, not worst-case (minimax) outcomes\n\nExpectimax Search: compute the average score under optimal play\n- max nodes as in minimax search\n- chance nodes are like min nodes but the outcome is uncertain\n- calculate their expected utilities\n- i.e. take weighted average (expectation) of children\n\n \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## Module 5 Lecture Notes\n Your summary here \n\n## Module 5 Definitions\n* **New concept** - definition\n\n\n# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n CSP consists of 3 different things: \n* finite set of variables. \n* nonempty domain of possible values for each variable. \n* finite set of contstraints that limits the values that variable can take. \n\nA state is defined as an assignment of values to some or all variables.\na consistent assignment does not violate constraints.\n\nAn **assignment** is complete when every variable is assigned a value. A solution to a CSP is a **complete, consistent** assignment. Solutions to CSPs can\nbe found by a completely general purpose algorithm, given only the formal specs of the CSP. Clean specifications of many problems\ngeneral goal, successor function and heuristics. \n\nCSP knows which variables violate a constraint and CSPs automatically prune off all branches that violate constaints. \n\nConstraint graph:\n* nodes are variables\n* arcs are (binary) constraints\n* Discrete Variables: finite domains (e.g. Boolean CSPs, includes boolean satisfiability)\nvs infinite domains (job scheduling)\n* Continuous variables: start/end times \n\nTypes of constraints:\n* unary constraints: involve a single variable</li>\n* binary constraints: involve pairs of vairables</li>\n* higher order constraints involve 3 or more variables</li>\n* soft constraints that indicate preferences </li>\n\n\n \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n CSP as a search problem\n\n* initial state: the empty assignment {}\n* successor function: assign value to any unassigned variable provided there is not a constraint conflict\n* goal test: the current assignment is complete\n* path cost: a constant cost for every step\n\nSolution is always found at depth n for n variables, hence DFS is used \n\n*n variables of domain size d\n*branching factor at the root is n*d\n*branching factor at the next level is (n-1)*d\n*tree has n!*d^n leaves\n\n\nthe variable assignments are commutative. i.e. order of steps is not important, so it is a tree search not a graph search\n- i.e. [step 1: WA = red; step 2: NT = green] is equivalent to [step 1: NT = green; step 2: WA = red]\nonly need to consider assignments to a single variable at each node\n\nb = d and there are d^n leaves (n variables, domain size d)\n\nSearch and backtracking: \n\n- dfs search for CSPs with single-variable assignments is called *backtracking*\n  - backtracking: a DFS search that chooses values for one variable at a time and backtracks when a variable has no legal values left to assign\n- backtracking search is the basic uninformed search for CSPs\n\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n Heuristics to improve backtracking efficiency. \n\nGeneral purpose methods and general purpose heuristics can give huge gains in speed, on average\n\nheuristics:\n\n- which variable should be assigned next? \n  - the most constrained variable\n  - if ties: most constraining variable\n- in what order should the variables values be tried:\n  - least constraining value\n- without actually going ahead with the search - can we detect inevitable failure early?\n  - forward checking\n  \nFirst heuristic: which variable should I pick?\n - choose a variable with the fewest legal values\n - aka minimum remaining values (MRV)\n - aka fast-fail method \n\nSecond Heuristic:  most constraining variable\n  - tiebreaker among most constrained variables\n  - choose the variable with tthe most constraints on remaining variables\n\nThird Heuristic:\n- given a variable, choose the least constraining value\n- the one that rules out the fewest values in the remaining variables\n\nFourth Heuristic: forward checking\n- keep track of remaining legal values for unassigned variables\n- terminate search when any unassigned variable has no remaining legal values\n- whenever a variable X is assigned, the forward checking process establishes arc consistency for it:\n  - for each unassigned variable Y that is connected to X by a constraint, delete from Y's domain any value that is inconsistent with the value chosen for X\nforward check and then if you terminate, backtrack and forward check for a different path\n- allows us to propogate information from assigned to unassigned variables but doesn't provide\nearly detection for all failures\n- **Constraint Propogation** goes beyond forward checking and repeatedly enforces constraints locally\n  \n\n## AIMA Chapter 6.4 Local Search for CSPs\n Big IDea: Inference in CSPs:\n- CSP solvers combine seaerch and inference\n  - search\n    - assigning a value to a variable\n  - constraint propogation (inference)\n      - eliminates possibel values for a variable if the value would violate local consistency\n  - can do inference first, or intertwine it with seaarch:\n- local consistency\n  - **node consistency**: satisfies unary constraints\n  - **arc consistency**: satisfies binary constraints. X is arc consistent with Y if for every value in X's domain, there is \n  some value in Y's domain that satisfies the binary constraint on the arc between X and Y\n\nk=1 is node consistency (given the empty set_ we can make any set of one variable consistent\n\nk=2 is arc consistency: a variable is arc-consistent if every value in its domain satisfies the variable's binary constraints for every . \n\nk=3 is path consistency\n\nA CSP is **strongly k-consistent if it is k-consistent and is also (k-1)-consistent, (k-2)-consistent, ...down to o1-consistent\n\n\nGlobal Constraint: involving an arbitrary number of variables but not necessarily all variables. \n\nResource Constraint: at most constraint\n\nBounds propogation: domains are represented by upper and lower bounds and are managed by this propogation\n\nBounds-consistent: if for every variable X, and for both the lower bound and upper bound values of X, there exists some value of Y that satisfies the constraint between X and Y for every variable Y\n\n## AIMA Chapter 6.5 The Structure of Problems\n Commutativity: a problem is commutative if the order of application of any given set of actions does not matter\n\nMRV heuristic: most-constrained variable, or \"fail first\" heuristic - picks a variable that is most likely to cause a failure soon.\n\nDegree heuristic: attempts to reduce the branching factor on future choices by selecting the variable that is involved in the largest number of constraints on other unassigned variables\n\nConflict-directed backjumping backtracks directly to the source of the problem.\n\nConstraint learning: finding min set of variables from the conflict set that causes the problem. this set of variables is called a no-good\n\nCutset Conditioning: can redue a general CSP to a tree-structured one and is efficient - requires only linear memory\n\nTree Decomposition: techniques that transform the CSP into a tree of subproblems and are efficient if the tree width of the constraint graph is small, however needs memory exponential in the tree width of the constraint graph\n\nLocal search using the min-conflicts heuristic has also been applied to constraint satisfaction problems with great success.\n\n\n\n\n\n## Module 6 Lecture Notes\n Your summary here \n\n## Module 6 Definitions\n* **Csp** - definition\n\n\n# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n Knowledge Based Agents. KB-agents use a process of reasoning over an internal \nrepresentation of knowledge to decide what actions to take. The main component \nis called a Knowledge Base (KB). KB contains a set of things that we refer to \nas sentences written in Knowledge representation language. \nTwo kinds of sentences in KB: 1. Axiom - a sentence that is given. \nFrom this we can get 2. Derived Sentence this is called inference. \nTell action and Ask action. In addition to asserting new knowledge\ninto its KB, a KB agent can also query the KB and \nask it to derive new knowledgein order to select what action it can take. Difference \nbetween \"knowledge level\" and \"implementation level\". Declarative approach\nto systems building uses Tell actions to the agent until it knows how to operate in\nits environment. Procedural approach on the other hand encodes the desired behaviors\ndirectly as program code\n\n## AIMA Chapter 7.2 The Wumpus World\nWampa world. We need a performance Measure, environment, actuators, \nsensors. Percept = [Stench, Breeze, Gasp, Bump, Scream] Vector of percepts. \n\n## AIMA Chapter 7.3 Logic\n Logic can serve as a general class of representation for knowledge-\nbased agent. we are going to examine propositional logic. KB consists of sentences in\nthe representation language. Representation language has syntax that specifies sentences\nthat are well-formed. \n\nA logic defines the semantics of the sentences, which is their meaning.\nthe semantics defines the truth of each sentence with respect to a possible world, which we will often \ncall a model. \n\n**Models** are mathematical abstractions that have a fixed set of truth values which are\n{true, false} for each sentence. \n\n* If sentence $\\alpha$ is true in model m then we say that m **satisfies**\n$\\alpha$ or m is a model of $\\alpha$. E.g. $\\alpha$ could be a sentence that means \"there is no pit in [2,2]\".\n  * in that case m($\\alpha$) would be all instances of Wampa world where [2,2] doesn't have a pit. \n  \n  \nLogical Entailment:\nonce we have a notion of truth, we can start to define logical reasoning. This is the idea that\na sentence follows logically from another sentencce. $\\alpha$ entails $\\beta$ if and only if M($\\alpha$) is a \nsubset of M($\\beta$). $\\alpha$ is a more specific sentence than $\\beta$. \"My pet is a cat\" entails \n\"My pet is an animal\" \n\nEntailment can be applied to derive conclusions, which is the process of logical\ninference. We can think about the consequences of a KB as a large set of additional sentences that are \nentailed given the sentences that have been added to the KB. \n\nWe want to design **inference algorithms**\nto enumerate these sentences. when an inference algo **i** allows us to conclude that $\\alpha$ is true, then we write \nthat alpha is derived from KB by i. KB $\\vdash_{i}$ $\\alpha$\n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n Propositional Logic. \n\nTruth Tables - implication is only false if I lied to you/I broke my promise to you. i.e. if P implies Q and P is true but Q is false, \nthen that statement is false. \n\nPremise/Antecedent $\\Rightarrow$ conclusion/consequent. \n\nInference rules can be used to derive proofs. Monotonicity\nsays that the set of entailed sentence can only increase as information is added to the KB. \n\nIf we add additional information to the KB, it doesn't invalidate any other info that we've already inferred. **Monotonicity implies soundness**.  \n\n## AIMA 7.5 Propositional Theorem Proving\n Conjunctive Normal Form (CNF).  Every sentence of propositional logic is logically\nequivalent to a conjunction of clauses. \n\nClauses are disjunctions of literaals. \n\nthe process is:\n1. Eliminate biconditionals $\\iff$ by replacing $\\alpha$ $\\iff$ $\\beta$ with $\\alpha$ $\\Rightarrow$ $\\beta$ $\\land$ $\\beta$ $\\Rightarrow$ $\\alpha$\n2. Eliminate $\\alpha$ $\\Rightarrow$ $\\beta$ with $\\lnot$ $\\alpha$ $\\lor$ $\\beta$\n3. Move $\\lnot$ inwards (eliminate double neagation, and apply deMorgans rules)\n4. Now the sentence will contain nested $\\land$ and $\\lor$ operators applied to literals. \n    \nApply distributivity law to distribute $\\lor$ over $\\land$ wherever possible. \n    \nThis gives us a resolution algorithm. Inference procedures based on resolution. \n\nDefinite clause: disjunction of literals with exactly one positive one.  \n\nHorn Clause - disjunction of literals where\nat least one is positive. This includes definite clauses and clauses with no positive literals. \n    \nValidity: a sentence is valid if it is true in all models. for example, the sentence P $\\lor$ $\\not$ P is valid. Valid sentences\nare also known as **tautologies** they are necessarily true. Because the sentence True is in all models, every \nvalid sentence is logically equivalent to True. \n\n**Deduction Theorem** comes from this. \n\nSatisfiability can be checked by enumerating the possible models until one is found that satisfies the sentence. \n\nRefutation or proof by contradiction: One assumes a sentence to be false and shows that this leads to a contradiction with known axioms. \n\n## Module 7 Lecture Notes\n Inference rules can be applied to derive a proof. \n\nEfficient model-checking inference algorithms for propositional logic include backtracking and local search methods and can often solve large problems quickly.\n\n\nForward chaining and backward chaining are very natural reasoning algorithms for knowledge bases in Horn form.\n\n\n\n\n## Module 7 Definitions\n* **Complete** - an inference algo is complete if it can derive any sentence that is entailed\n* **Sound/truth-preserving** - an inference algo that derives only entailed sentences\n* **Grounding** - the connection between logical reasoning processes and the real environment in which the agent exists \n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}