{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "FINAL Template_for CIS521_midterm notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "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": "924b9822-b98c-4be4-fdcb-577a9d4403a8"
      },
      "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": 2,
      "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": "5b2f69be-b0f7-44e7-a3e6-99886fa3eb1f"
      },
      "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": 3,
      "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 = True"
      ],
      "execution_count": 4,
      "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 = \"\"\"rational agent: acts to achieve the best outcome or best expected outcome \\\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "  \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 = \"\"\" - agent:perceiving its environment through sensors and acting upon that environment through actuators.  \n",
        "\n",
        "- percept:agent’s perceptual inputs at any given instant.  \n",
        "\n",
        "- percept sequence is the complete history.  \n",
        "\n",
        "- an agent’s choice decide by all history, no future  \n",
        "\n",
        "- agent function:abstract mathematical description;agent: program is a concrete implementation.  \n",
        "- The **state space** is the set of possible states of the environment  \n",
        "- A **solution** to a search problem is a path through the state space from the intial state to a goal  \n",
        "- State space; Initial state; Goal states; Actions; Transition model; Action; cost function\n",
        "- We call a search algorithm a graph search if it checks for **redundant paths**  \n",
        "- A search algorithm is complete if the algorithm is guaranteed to find a solution if there is one, and to correctly report failure when there is not  \n",
        "- A search algorithm is cost optimal when it is guaranteed to find the solution with the lowest path cost of all solutions\n",
        "\"\"\"\n",
        "chapter2_2 = \"\"\"  omniscient agent knows the actual outcome of its actions and can act accordingly  \n",
        " \"\"\"\n",
        "chapter2_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter2_4 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module1_lecture_notes = \"\"\" A solution is a sequence of actions from the initial state to a goal state.  \n",
        "\n",
        "Optimal Solution:if no solution has a lower\n",
        "path cost. \"\"\"\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": 5,
      "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": 986
        },
        "cellView": "form",
        "outputId": "38b28620-9cef-4c05-e271-5040c51f8af1"
      },
      "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": 6,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\nrational agent: acts to achieve the best outcome or best expected outcome \n\n\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 - agent:perceiving its environment through sensors and acting upon that environment through actuators.  \n\n- percept:agent’s perceptual inputs at any given instant.  \n\n- percept sequence is the complete history.  \n\n- an agent’s choice decide by all history, no future  \n\n- agent function:abstract mathematical description;agent: program is a concrete implementation.  \n- The **state space** is the set of possible states of the environment  \n- A **solution** to a search problem is a path through the state space from the intial state to a goal  \n- State space; Initial state; Goal states; Actions; Transition model; Action; cost function\n- We call a search algorithm a graph search if it checks for **redundant paths**  \n- A search algorithm is complete if the algorithm is guaranteed to find a solution if there is one, and to correctly report failure when there is not  \n- A search algorithm is cost optimal when it is guaranteed to find the solution with the lowest path cost of all solutions\n\n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n  omniscient agent knows the actual outcome of its actions and can act accordingly  \n \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 A solution is a sequence of actions from the initial state to a goal state.  \n\nOptimal Solution:if no solution has a lower\npath cost. \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": 7,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 210
        },
        "outputId": "093b925a-a0a1-4a9a-c660-2d029d5b9b6d"
      },
      "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": 8,
      "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 = \"\"\" - A search method is uninformed if it only has access to the problem definition \n",
        "- Breadth-first search expands the node which is shallowest  \n",
        "- iterative deepening search optimal only for unit actions costs\n",
        "- optimal:Breadth-First Search;Uniform-Cost Search;Iterative Deepening Search;Bidirectional Search\n",
        "\n",
        "\"\"\"\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": 9,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 535
        },
        "outputId": "c4d9b1e0-fa39-4486-96ca-ac1cfbbfcf5f"
      },
      "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": 10,
      "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 - A search method is uninformed if it only has access to the problem definition \n- Breadth-first search expands the node which is shallowest  \n- iterative deepening search optimal only for unit actions costs\n- optimal:Breadth-First Search;Uniform-Cost Search;Iterative Deepening Search;Bidirectional Search\n\n\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 = \"\"\" h(n) estimates the cost of a solution from a node n  \n",
        "biggest problem with A* is the space complexity\n",
        "An admissible heuristic is one that never overestimates the cost to reach a goal  \n",
        "IDA*: iterative deepening A* search\n",
        "RBFS: recursive best-first search\n",
        "SMA*: simplified memory-bounded A*  \n",
        "IDA*, SMA*, and RBFS are optimal search algorithms and is more space efficient than A*  \n",
        "Beam search limit size of frontier: not optimal, not complete; run faster than complete ones  \n",
        "Weighted A*:minimize f(n)=g(n)+W×h(n)f(n); not optimal, is complete; expands fewer nodes  \n",
        "Admissible heuristics are also called optimistic \"\"\"\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": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4QOwzd7xrwq4"
      },
      "source": [
        ""
      ],
      "execution_count": 11,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 447
        },
        "cellView": "form",
        "outputId": "17212056-5618-4a14-801c-fb617e0bb17a"
      },
      "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": 12,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n h(n) estimates the cost of a solution from a node n  \nbiggest problem with A* is the space complexity\nAn admissible heuristic is one that never overestimates the cost to reach a goal  \nIDA*: iterative deepening A* search\nRBFS: recursive best-first search\nSMA*: simplified memory-bounded A*  \nIDA*, SMA*, and RBFS are optimal search algorithms and is more space efficient than A*  \nBeam search limit size of frontier: not optimal, not complete; run faster than complete ones  \nWeighted A*:minimize f(n)=g(n)+W×h(n)f(n); not optimal, is complete; expands fewer nodes  \nAdmissible heuristics are also called optimistic \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 = \"\"\" perfect information:fully observable  \n",
        "#### minmax\n",
        "minmax evaluate each node as the value of the best terminal state reach by both player playing optimally.  \n",
        "time O(b^m)  \n",
        "beta:value of the best choice for MINMIN  \n",
        "the value of a node is the optimal value of its children  \n",
        "\n",
        "\n",
        "\"\"\"\n",
        "chapter5_2 = \"\"\" EVAL(s, p) returns an estimate of the expected utility of state s to player  p  \n",
        " For terminal states, the evaluation function is exactly equal to the utility.  \n",
        "\n",
        "The running time of alpha-beta pruning is impacted by the order in which we examine nodes. O(b^(0.5m)) as best \"\"\"\n",
        "chapter5_3 = \"\"\" \n",
        "#### type A strategy\n",
        "explores a wide but shallow portion of the tree  \n",
        "#### type B strategy  \n",
        "explores a deep but narrow portion of the tree \n",
        "use of type A and type B:For games with a large search space, it is not feasible to search the whole tree. As such, we have to make tradeoffs about what part of the tree to search   \n",
        "- Heuristic alpha-beta search replaces the utility function with an evaluation function( which estimates the value of non-terminal nodes) \n",
        "- the terminal test is replaced with a cutoff test(decide when to cut off the search)  \n",
        "- The evaluation function should be applied only to positions that are quiescent(there is no pending move that would wildly swing the valuation)  \n",
        "- horizon effect: when an agent try to erroneously delay the inevitable(no chance to win, but move to avoid loose)  \n",
        "- forward pruning: prunes moves that appear to be bad moves(but might be good one);Type B Strategy  \n",
        "- - beam search: example of forward pruning  \n",
        "- Monte Carlo tree search(MCTS): playing the game to the end while randomly selecting moves;evaluate an action: Repeatedly play the game from that state and take the average of the results\n",
        "\n",
        "\"\"\"\n",
        "chapter5_5 = \"\"\"  Expectiminimax uses expected value at chance nodes  \n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 16 “Making Simple Decisions” (16.1-16.3)\n",
        "chapter16_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter16_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter16_3 = \"\"\" utility function describe the desirebility of state  \n",
        "utility function U(s) gives the payoff for each player in terminal state s\n",
        "Utility functions map from lotteries to real numbers  \n",
        "expected utility EU(a)=$\\sum_{s'}P(result(a)=s')U(s')$ \n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module5_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module5_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 13,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "65055527-b555-4833-b2ad-8064bf686721"
      },
      "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": 14,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n perfect information:fully observable  \n#### minmax\nminmax evaluate each node as the value of the best terminal state reach by both player playing optimally.  \ntime O(b^m)  \nbeta:value of the best choice for MINMIN  \nthe value of a node is the optimal value of its children  \n\n\n\n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n EVAL(s, p) returns an estimate of the expected utility of state s to player  p  \n For terminal states, the evaluation function is exactly equal to the utility.  \n\nThe running time of alpha-beta pruning is impacted by the order in which we examine nodes. O(b^(0.5m)) as best \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \n#### type A strategy\nexplores a wide but shallow portion of the tree  \n#### type B strategy  \nexplores a deep but narrow portion of the tree \nuse of type A and type B:For games with a large search space, it is not feasible to search the whole tree. As such, we have to make tradeoffs about what part of the tree to search   \n- Heuristic alpha-beta search replaces the utility function with an evaluation function( which estimates the value of non-terminal nodes) \n- the terminal test is replaced with a cutoff test(decide when to cut off the search)  \n- The evaluation function should be applied only to positions that are quiescent(there is no pending move that would wildly swing the valuation)  \n- horizon effect: when an agent try to erroneously delay the inevitable(no chance to win, but move to avoid loose)  \n- forward pruning: prunes moves that appear to be bad moves(but might be good one);Type B Strategy  \n- - beam search: example of forward pruning  \n- Monte Carlo tree search(MCTS): playing the game to the end while randomly selecting moves;evaluate an action: Repeatedly play the game from that state and take the average of the results\n\n\n\n## AIMA Chapter 5.5 Stochastic Games\n  Expectiminimax uses expected value at chance nodes  \n\n \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n utility function describe the desirebility of state  \nutility function U(s) gives the payoff for each player in terminal state s\nUtility functions map from lotteries to real numbers  \nexpected utility EU(a)=$\\sum_{s'}P(result(a)=s')U(s')$ \n\n\n## Module 5 Lecture Notes\n Your summary here \n\n## Module 5 Definitions\n* **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 = \"\"\" CSPs represent a state with a set of variable/value pairs  \n",
        "CSPs represent the conditions for a solution with a set of constraints on the variables  \n",
        "In search problems, states are black boxes with a transition model to move between boxes. In CSPs, the agent can see inside the states and move between states accordingly.\n",
        "node-consistent: if all the values in the variable’s domain satisfy the variable’s unary constraints.  \n",
        "constraint propagation(inference): using the constraints to reduce the number of legal values for a variable, which in turn can reduce the legal values for another variable, and so on.  \n",
        "partial assignment:  one that leaves some variables unassigned, and a partial solution is a partial assignment that is consistent.  \n",
        "consistent or legal assignment: assignment that does not violate any constraints.   \n",
        "solution to a CSP:  a consistent, complete assignment  \n",
        "A complete assignment is one in which every variable is assigned a value  \n",
        "CSPs deal with assignments of values to variables, {Xi = vi,Xj = vj, …}\n",
        " \"\"\"\n",
        "chapter6_2 = \"\"\" CSPs can rule out variable assignments using search and inference  \n",
        "inferece: enforcing k-consistency  \n",
        "strongly kk-consistent: k-consistent, k-1k−1-consistent, ..., 11-consistent  \n",
        "AC3: enforcing arc consistency\"\"\"\n",
        "chapter6_3 = \"\"\" depth first; backtracking  \n",
        "The term backtracking search is used for a depth-first search that chooses\n",
        "values for one variable at a time and backtracks when a variable has no legal\n",
        "values left to assign.  \n",
        "uninformed  \n",
        "have 4 heuristic to make it faster \n",
        "tree has n!d^n leaves, leaves are complete assignment  \n",
        "if consider commutativity(A=1,B=2 is the same as A=2,B=1)  \n",
        "number of leaves:d^n  \n",
        "#### forward checking \n",
        "whenever a variable X is assigned,we establish arc consistency for X\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",
        "#### MAC maintain arc consistency(both search and inference while AC3 only inference)\n",
        "MAC recursively propogrates constraints, whereas forward checking does not\n",
        "forword checking only change domain of Y, MAC change other domain if domain of Y change  \n",
        "MAC first assign value on variable X, MAC only queues arcs incident on the assigned variable.then run as AC3\n",
        "##### CONSTRAIN learning \n",
        "records the conflicts（no-good:minimun set of variable from conflict set) as they are encountered in the search in order to avoid the same conflict later\n",
        "\"\"\"\n",
        "chapter6_4 = \"\"\" #### min conflict algorithm  \n",
        "first randomly choose value for each variable  \n",
        "then randomly choose conflict variable and assign a value which minimize conflict \n",
        "#### constraint weighting\n",
        "give each constraaint a weight  \n",
        "choose variable/value pair to change, which result in lowest total weight of all violated constrains  \n",
        "weight adjusted by increase the weight of constrains that is violated by current assinment \n",
        "Solving an arbitrary CSP takes exponential time with the number of variables, but linear time if convert to tree\"\"\"\n",
        "chapter6_5 = \"\"\" tree csp: a constrain gragh is tree when any two variable are connected by only one path.  \n",
        "any tree structure csp can be solved in time linear in the number of variable.  \n",
        "first randomlt choose a node as root, then convert it into topological sort. make all parent(x)->x are arc consistency  \n",
        "#### cutset(space efficient)\n",
        "The first way to reduce a constraint graph to a tree involves assigning values to some variables so that the remaining variables form a tree.  \n",
        "Cutset conditioning is efficient if a small cutset can be found  \n",
        "1. choose a subset of the CSP’s variables such that the constraint graph becomes a tree after removal of S. S is called a cycle cutset.\n",
        "2. For each possible assignment to the variables in  S that satisfies all constraints on S ,\n",
        "a. remove from the domains of the remaining variables any values that are\n",
        "inconsistent with the assignment for S , and\n",
        "b. if the remaining CSP has a solution, return it together with the assignment\n",
        "for S.  \n",
        "\n",
        "If the cycle cutset has size c , then the total run time is O(d^c ⋅ (n − c)d^2)\n",
        "#### tree decomposing(time efficient,but memory exponential in the tree width w)\n",
        "second way to reduce a gragh to tree \n",
        "convert to tree of subproblem  \n",
        "\n",
        "Tree decomposition subproblems are efficient if the tree width of the constraint graph is small \n",
        "O(nd^2) O(nd^(w+1)), w is tree width  \n",
        "CSPs with constraint graphs of bounded tree width are solvable in polynomial time.\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module6_lecture_notes = \"\"\"  Most constrained variable:Choose a variable with the fewest legal values(a variable with least color can choose)  \n",
        "a.k.a. minimum remaining values (MRV) heuristic  \n",
        "Most constraining variable(degree heuristic):Choose the variable with the most constraints on remaining variables(variable has large amount of neighbours)  \n",
        "Heuristic 3: Least constraining value:the one that rules out the fewest values in the remaining variables(choose same value if possible, to give more choice for rest of variables)  \n",
        "H4:forward checking:Keep track of remaining legal values for unassigned variables.Terminate search when any unassigned variable has no remaining legal values.\n",
        "(whenever assign a value for a area, delete unleagal value for other area. terminate if an area has no value to assign)  \n",
        "\n",
        "To make an arc (i,j) arc consistent,\n",
        "for each value v on Xi ,\n",
        "if there is no label on Yj consistent with v\n",
        "then remove v from Xi  \n",
        "Given d values, checking arc (i,j) takes O(d2 ) time worst case\n",
        "```\n",
        "function AC-3(csp) return the CSP, possibly with reduced domains\n",
        "inputs: csp, a binary csp with variables {X1, X2, …, Xn}\n",
        "local variables: queue, a queue of arcs initially the arcs in csp\n",
        "while queue is not empty do\n",
        "  (Xi,Xj)<-queue.pop()\n",
        "  if REMOVE-INCONSISTENT-VALUES(Xi, Xj) then\n",
        "    for each Xk in NEIGHBORS[Xi ] – {Xj} do\n",
        "      add (Xk, Xi) to queue \n",
        "```  \n",
        "\n",
        "```\n",
        "function REMOVE-INCONSISTENT-VALUES(Xi, Xj) return true iff we remove a value\n",
        "  removed <- false\n",
        "  for each x in DOMAIN[Xi] do\n",
        "    if no value y in DOMAIN[Xj] allows (x,y) to satisfy the constraints between Xi and Xj\n",
        "    then delete x from DOMAIN[Xi]; removed <- true\n",
        "  return removed\n",
        "```\n",
        "- All nodes can be connected to every other node,\n",
        "so each of n nodes must be compared against n-1 other nodes,\n",
        "so total # of arcs is 2*n*(n-1), i.e. O(n^2)\n",
        "- If there are d values, checking arc (i,j) takes O(d^2 ) time\n",
        "- Each arc (i,j) can only be inserted into the queue d times\n",
        "- Worst case complexity: O(n^2d^3 )\n",
        " \"\"\"\n",
        " \n",
        "\n",
        "# Definitions\n",
        "module6_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ],
      "execution_count": 15,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "fde63a12-6fb4-4e01-bffd-731346ee0ee6"
      },
      "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": 16,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n CSPs represent a state with a set of variable/value pairs  \nCSPs represent the conditions for a solution with a set of constraints on the variables  \nIn search problems, states are black boxes with a transition model to move between boxes. In CSPs, the agent can see inside the states and move between states accordingly.\nnode-consistent: if all the values in the variable’s domain satisfy the variable’s unary constraints.  \nconstraint propagation(inference): using the constraints to reduce the number of legal values for a variable, which in turn can reduce the legal values for another variable, and so on.  \npartial assignment:  one that leaves some variables unassigned, and a partial solution is a partial assignment that is consistent.  \nconsistent or legal assignment: assignment that does not violate any constraints.   \nsolution to a CSP:  a consistent, complete assignment  \nA complete assignment is one in which every variable is assigned a value  \nCSPs deal with assignments of values to variables, {Xi = vi,Xj = vj, …}\n \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n CSPs can rule out variable assignments using search and inference  \ninferece: enforcing k-consistency  \nstrongly kk-consistent: k-consistent, k-1k−1-consistent, ..., 11-consistent  \nAC3: enforcing arc consistency\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n depth first; backtracking  \nThe term backtracking search is used for a depth-first search that chooses\nvalues for one variable at a time and backtracks when a variable has no legal\nvalues left to assign.  \nuninformed  \nhave 4 heuristic to make it faster \ntree has n!d^n leaves, leaves are complete assignment  \nif consider commutativity(A=1,B=2 is the same as A=2,B=1)  \nnumber of leaves:d^n  \n#### forward checking \nwhenever a variable X is assigned,we establish arc consistency for X\nFor 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#### MAC maintain arc consistency(both search and inference while AC3 only inference)\nMAC recursively propogrates constraints, whereas forward checking does not\nforword checking only change domain of Y, MAC change other domain if domain of Y change  \nMAC first assign value on variable X, MAC only queues arcs incident on the assigned variable.then run as AC3\n##### CONSTRAIN learning \nrecords the conflicts（no-good:minimun set of variable from conflict set) as they are encountered in the search in order to avoid the same conflict later\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n #### min conflict algorithm  \nfirst randomly choose value for each variable  \nthen randomly choose conflict variable and assign a value which minimize conflict \n#### constraint weighting\ngive each constraaint a weight  \nchoose variable/value pair to change, which result in lowest total weight of all violated constrains  \nweight adjusted by increase the weight of constrains that is violated by current assinment \nSolving an arbitrary CSP takes exponential time with the number of variables, but linear time if convert to tree\n\n## AIMA Chapter 6.5 The Structure of Problems\n tree csp: a constrain gragh is tree when any two variable are connected by only one path.  \nany tree structure csp can be solved in time linear in the number of variable.  \nfirst randomlt choose a node as root, then convert it into topological sort. make all parent(x)->x are arc consistency  \n#### cutset(space efficient)\nThe first way to reduce a constraint graph to a tree involves assigning values to some variables so that the remaining variables form a tree.  \nCutset conditioning is efficient if a small cutset can be found  \n1. choose a subset of the CSP’s variables such that the constraint graph becomes a tree after removal of S. S is called a cycle cutset.\n2. For each possible assignment to the variables in  S that satisfies all constraints on S ,\na. remove from the domains of the remaining variables any values that are\ninconsistent with the assignment for S , and\nb. if the remaining CSP has a solution, return it together with the assignment\nfor S.  \n\nIf the cycle cutset has size c , then the total run time is O(d^c ⋅ (n − c)d^2)\n#### tree decomposing(time efficient,but memory exponential in the tree width w)\nsecond way to reduce a gragh to tree \nconvert to tree of subproblem  \n\nTree decomposition subproblems are efficient if the tree width of the constraint graph is small \nO(nd^2) O(nd^(w+1)), w is tree width  \nCSPs with constraint graphs of bounded tree width are solvable in polynomial time.\n \n\n## Module 6 Lecture Notes\n  Most constrained variable:Choose a variable with the fewest legal values(a variable with least color can choose)  \na.k.a. minimum remaining values (MRV) heuristic  \nMost constraining variable(degree heuristic):Choose the variable with the most constraints on remaining variables(variable has large amount of neighbours)  \nHeuristic 3: Least constraining value:the one that rules out the fewest values in the remaining variables(choose same value if possible, to give more choice for rest of variables)  \nH4:forward checking:Keep track of remaining legal values for unassigned variables.Terminate search when any unassigned variable has no remaining legal values.\n(whenever assign a value for a area, delete unleagal value for other area. terminate if an area has no value to assign)  \n\nTo make an arc (i,j) arc consistent,\nfor each value v on Xi ,\nif there is no label on Yj consistent with v\nthen remove v from Xi  \nGiven d values, checking arc (i,j) takes O(d2 ) time worst case\n```\nfunction AC-3(csp) return the CSP, possibly with reduced domains\ninputs: csp, a binary csp with variables {X1, X2, …, Xn}\nlocal variables: queue, a queue of arcs initially the arcs in csp\nwhile queue is not empty do\n  (Xi,Xj)<-queue.pop()\n  if REMOVE-INCONSISTENT-VALUES(Xi, Xj) then\n    for each Xk in NEIGHBORS[Xi ] – {Xj} do\n      add (Xk, Xi) to queue \n```  \n\n```\nfunction REMOVE-INCONSISTENT-VALUES(Xi, Xj) return true iff we remove a value\n  removed <- false\n  for each x in DOMAIN[Xi] do\n    if no value y in DOMAIN[Xj] allows (x,y) to satisfy the constraints between Xi and Xj\n    then delete x from DOMAIN[Xi]; removed <- true\n  return removed\n```\n- All nodes can be connected to every other node,\nso each of n nodes must be compared against n-1 other nodes,\nso total # of arcs is 2*n*(n-1), i.e. O(n^2)\n- If there are d values, checking arc (i,j) takes O(d^2 ) time\n- Each arc (i,j) can only be inserted into the queue d times\n- Worst case complexity: O(n^2d^3 )\n \n\n## Module 6 Definitions\n* **Concept** - 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 = \"\"\"  - problem-solving agents have performed a search over states in order to\n",
        "find a plan. The representation of states has been atomic.  \n",
        "- The process of deriving new sentences from old sentences is called inference.  \n",
        "- A KB can initially contain some background information about the world, and a\n",
        "knowledge-based agent can add to the information in the KB through its observations\n",
        "of the world.\n",
        " \"\"\"\n",
        "chapter7_2 = \"\"\" \n",
        "- environment: \n",
        "  - performance measure\n",
        "  - environment\n",
        "  - actions\n",
        "  - sensor \"\"\"\n",
        "chapter7_3 = \"\"\" Logic can serve as a general class of representations for knowledge-based agents.  \n",
        "- KB consists of sentences in the representation language\n",
        "- Representation language has a syntax that specifies sentences that are well-formed\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 call a model.\n",
        "- If sentence a is true in model m then we say\n",
        " - m satisfies a, or\n",
        " - m is a model of a\n",
        "- M(a) : set of all models of a.\n",
        "#### Logical Entailment\n",
        "a⊨β if and only if M(a) ⊆ M(β)(area of b bigger than a)\n",
        "- The KB is false in models that contradictwhat the agent knows.\n",
        "- Possible Worlds is the process of\n",
        "enumerating all Possible Worlds that are\n",
        "compatible with the KB. M(KB) ⊆ M(a1) \n",
        "#### Logical inference\n",
        "KB ⊢i a“a is derived from KB by i” i is a inference algorithm\n",
        "\n",
        " \"\"\"\n",
        "chapter7_4 = \"\"\" Atomic sentences are represented with a single propositional symbols. Propositional symbols stand for a statement that can be true or false.  \n",
        "e.g.$W_{1,3}$:There is a Wampa at location [1,3]\n",
        "- premise or antecede -> conclusion or consequence  \n",
        "- what KB looks like:R1: ¬ P1,1 ; R2: B1,1 ⇔ (P1,2 ⋁ P2,1 )\n",
        "- Sound – the inference algorithm should only derive entailed sentences.\n",
        "- Complete – an inference algorithm is complete if it can derive all sentences that are entailed\n",
        " \"\"\"\n",
        "chapter7_5 = \"\"\" - ((a ⋀ β) ⋁ ɣ) ≡ ((a ⋀ β) ⋁ (a ⋀ ɣ))) Distributivity of ⋀ over ⋁\n",
        "- (a ⋀ β) ≡ (β ⋀ a) Commutativity of ⋀  \n",
        "- ((a ⋀ β) ⋀ ɣ) ≡ (a ⋀ (β ⋀ ɣ)) Associativity of ⋀\n",
        "#### Inference Rules\n",
        "- Modus Ponens: (a->b),a/b   \n",
        "- And Elimination:a⋀β/a\n",
        "#### Monotonicity implies Soundness \n",
        "- the set of entailed sentence can only increase as information is assed to the KB.\n",
        "if KB⊨a then KB ⋀ β ⊨a\n",
        "#### resolution\n",
        "- yields a complete inference algorithm when coupled with any complete search algorithm.\n",
        "- unit resolution\n",
        " - If ℓi and m are complementary literals,which means that one is the negation of another, then we can eliminate them via unit resolution.\n",
        " - (ℓ1 ⋁… ⋁ ℓk), m /(ℓ1 ⋁ … ⋁ ℓi-1 ⋁ ℓi+1 ⋁… ⋁ ℓk)\n",
        "- full resolution\n",
        " - Full resolution rule for complementary literals ℓi and mj\n",
        " - ℓ1 ⋁… ⋁ ℓk, m1 ⋁… ⋁ mn / ℓ1 ⋁ ℓi-1 ⋁ … ⋁ ℓi+1 ⋁ ℓk ⋁ m1 ⋁… ⋁ mj-1 ⋁ … ⋁ mj+1 ⋁ mk\n",
        "#### Conjunctive Normal Form (CNF)\n",
        "conjunction of disconjunction\n",
        "#### Forward Chaining \n",
        "data-driven reasoning. An agent start with known data, adding premises as new percepts come in,\n",
        " and then incrementally apply the forward chaining algorithm to derive new conclusions. It doesn’t have to have a\n",
        "specific query in mind to do so.\n",
        "- start form what we know is true in KB, store all the conclution we get from what we know. \n",
        "- stop when we find the queue or no more inference can be made\n",
        "\n",
        "#### Backward chaining\n",
        "goal-directed reasoning.  \n",
        "works backwards from a query. If the query is known to be true,\n",
        "then no work is needed. Otherwise, the algorithm finds implications in the KB whose\n",
        "conclusions is the query. If all the premises of one of those can be proved to be true\n",
        "(via backward chaining), then the query is true.\n",
        "- start from goal(the queue), check what should be true to make the queue be true\n",
        "- stop when we find something we know is true or false\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module7_lecture_notes = \"\"\" \n",
        "#### Resolution Algorithm\n",
        " complete\n",
        "Inference procedures based on resolution work using the principle of proof by contradiction.  \n",
        "To show KB⊨a then we can show that KB ⋀ ¬a is unsatisfiable.\n",
        "- convert (KB ⋀ ¬a) into CNF\n",
        "- apply the resolution rule to the resulting clauses.\n",
        "- Resolve every pair that contains complementary literals to produce a new clause\n",
        "- If that new clause isn’t already present, then add it to the set.\n",
        "- Continue the process until one of two things happens:\n",
        "1. There are no new clauses that can be added. In this case, the KB does not entail a\n",
        "2. Two clauses resolve to yield the empty clause, in which case the KB does entail a\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module7_definitions = {\n",
        "\"Definite clause\" : \"– disjunction of literals where exactly one is positive\", \n",
        "\"Horn clause\" : \"disjunction of literals where at most one is positive\"   \n",
        "}\n",
        "\n"
      ],
      "execution_count": 17,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "71caa244-fc6d-40b8-ec1f-9a2c4546a664"
      },
      "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": 18,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n  - problem-solving agents have performed a search over states in order to\nfind a plan. The representation of states has been atomic.  \n- The process of deriving new sentences from old sentences is called inference.  \n- A KB can initially contain some background information about the world, and a\nknowledge-based agent can add to the information in the KB through its observations\nof the world.\n \n\n## AIMA Chapter 7.2 The Wumpus World\n \n- environment: \n  - performance measure\n  - environment\n  - actions\n  - sensor \n\n## AIMA Chapter 7.3 Logic\n Logic can serve as a general class of representations for knowledge-based agents.  \n- KB consists of sentences in the representation language\n- Representation language has a syntax that specifies sentences that are well-formed\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 call a model.\n- If sentence a is true in model m then we say\n - m satisfies a, or\n - m is a model of a\n- M(a) : set of all models of a.\n#### Logical Entailment\na⊨β if and only if M(a) ⊆ M(β)(area of b bigger than a)\n- The KB is false in models that contradictwhat the agent knows.\n- Possible Worlds is the process of\nenumerating all Possible Worlds that are\ncompatible with the KB. M(KB) ⊆ M(a1) \n#### Logical inference\nKB ⊢i a“a is derived from KB by i” i is a inference algorithm\n\n \n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n Atomic sentences are represented with a single propositional symbols. Propositional symbols stand for a statement that can be true or false.  \ne.g.$W_{1,3}$:There is a Wampa at location [1,3]\n- premise or antecede -> conclusion or consequence  \n- what KB looks like:R1: ¬ P1,1 ; R2: B1,1 ⇔ (P1,2 ⋁ P2,1 )\n- Sound – the inference algorithm should only derive entailed sentences.\n- Complete – an inference algorithm is complete if it can derive all sentences that are entailed\n \n\n## AIMA 7.5 Propositional Theorem Proving\n - ((a ⋀ β) ⋁ ɣ) ≡ ((a ⋀ β) ⋁ (a ⋀ ɣ))) Distributivity of ⋀ over ⋁\n- (a ⋀ β) ≡ (β ⋀ a) Commutativity of ⋀  \n- ((a ⋀ β) ⋀ ɣ) ≡ (a ⋀ (β ⋀ ɣ)) Associativity of ⋀\n#### Inference Rules\n- Modus Ponens: (a->b),a/b   \n- And Elimination:a⋀β/a\n#### Monotonicity implies Soundness \n- the set of entailed sentence can only increase as information is assed to the KB.\nif KB⊨a then KB ⋀ β ⊨a\n#### resolution\n- yields a complete inference algorithm when coupled with any complete search algorithm.\n- unit resolution\n - If ℓi and m are complementary literals,which means that one is the negation of another, then we can eliminate them via unit resolution.\n - (ℓ1 ⋁… ⋁ ℓk), m /(ℓ1 ⋁ … ⋁ ℓi-1 ⋁ ℓi+1 ⋁… ⋁ ℓk)\n- full resolution\n - Full resolution rule for complementary literals ℓi and mj\n - ℓ1 ⋁… ⋁ ℓk, m1 ⋁… ⋁ mn / ℓ1 ⋁ ℓi-1 ⋁ … ⋁ ℓi+1 ⋁ ℓk ⋁ m1 ⋁… ⋁ mj-1 ⋁ … ⋁ mj+1 ⋁ mk\n#### Conjunctive Normal Form (CNF)\nconjunction of disconjunction\n#### Forward Chaining \ndata-driven reasoning. An agent start with known data, adding premises as new percepts come in,\n and then incrementally apply the forward chaining algorithm to derive new conclusions. It doesn’t have to have a\nspecific query in mind to do so.\n- start form what we know is true in KB, store all the conclution we get from what we know. \n- stop when we find the queue or no more inference can be made\n\n#### Backward chaining\ngoal-directed reasoning.  \nworks backwards from a query. If the query is known to be true,\nthen no work is needed. Otherwise, the algorithm finds implications in the KB whose\nconclusions is the query. If all the premises of one of those can be proved to be true\n(via backward chaining), then the query is true.\n- start from goal(the queue), check what should be true to make the queue be true\n- stop when we find something we know is true or false\n\n\n\n\n## Module 7 Lecture Notes\n \n#### Resolution Algorithm\n complete\nInference procedures based on resolution work using the principle of proof by contradiction.  \nTo show KB⊨a then we can show that KB ⋀ ¬a is unsatisfiable.\n- convert (KB ⋀ ¬a) into CNF\n- apply the resolution rule to the resulting clauses.\n- Resolve every pair that contains complementary literals to produce a new clause\n- If that new clause isn’t already present, then add it to the set.\n- Continue the process until one of two things happens:\n1. There are no new clauses that can be added. In this case, the KB does not entail a\n2. Two clauses resolve to yield the empty clause, in which case the KB does entail a\n\n## Module 7 Definitions\n* **Definite clause** - – disjunction of literals where exactly one is positive\n* **Horn clause** - disjunction of literals where at most one is positive\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": "57aa3e47-b5b0-4c42-b953-da10d4811595"
      },
      "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": 19,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\nrational agent: acts to achieve the best outcome or best expected outcome \n\n\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 - agent:perceiving its environment through sensors and acting upon that environment through actuators.  \n\n- percept:agent’s perceptual inputs at any given instant.  \n\n- percept sequence is the complete history.  \n\n- an agent’s choice decide by all history, no future  \n\n- agent function:abstract mathematical description;agent: program is a concrete implementation.  \n- The **state space** is the set of possible states of the environment  \n- A **solution** to a search problem is a path through the state space from the intial state to a goal  \n- State space; Initial state; Goal states; Actions; Transition model; Action; cost function\n- We call a search algorithm a graph search if it checks for **redundant paths**  \n- A search algorithm is complete if the algorithm is guaranteed to find a solution if there is one, and to correctly report failure when there is not  \n- A search algorithm is cost optimal when it is guaranteed to find the solution with the lowest path cost of all solutions\n\n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n  omniscient agent knows the actual outcome of its actions and can act accordingly  \n \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 A solution is a sequence of actions from the initial state to a goal state.  \n\nOptimal Solution:if no solution has a lower\npath cost. \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 - A search method is uninformed if it only has access to the problem definition \n- Breadth-first search expands the node which is shallowest  \n- iterative deepening search optimal only for unit actions costs\n- optimal:Breadth-First Search;Uniform-Cost Search;Iterative Deepening Search;Bidirectional Search\n\n\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 h(n) estimates the cost of a solution from a node n  \nbiggest problem with A* is the space complexity\nAn admissible heuristic is one that never overestimates the cost to reach a goal  \nIDA*: iterative deepening A* search\nRBFS: recursive best-first search\nSMA*: simplified memory-bounded A*  \nIDA*, SMA*, and RBFS are optimal search algorithms and is more space efficient than A*  \nBeam search limit size of frontier: not optimal, not complete; run faster than complete ones  \nWeighted A*:minimize f(n)=g(n)+W×h(n)f(n); not optimal, is complete; expands fewer nodes  \nAdmissible heuristics are also called optimistic \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 perfect information:fully observable  \n#### minmax\nminmax evaluate each node as the value of the best terminal state reach by both player playing optimally.  \ntime O(b^m)  \nbeta:value of the best choice for MINMIN  \nthe value of a node is the optimal value of its children  \n\n\n\n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n EVAL(s, p) returns an estimate of the expected utility of state s to player  p  \n For terminal states, the evaluation function is exactly equal to the utility.  \n\nThe running time of alpha-beta pruning is impacted by the order in which we examine nodes. O(b^(0.5m)) as best \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \n#### type A strategy\nexplores a wide but shallow portion of the tree  \n#### type B strategy  \nexplores a deep but narrow portion of the tree \nuse of type A and type B:For games with a large search space, it is not feasible to search the whole tree. As such, we have to make tradeoffs about what part of the tree to search   \n- Heuristic alpha-beta search replaces the utility function with an evaluation function( which estimates the value of non-terminal nodes) \n- the terminal test is replaced with a cutoff test(decide when to cut off the search)  \n- The evaluation function should be applied only to positions that are quiescent(there is no pending move that would wildly swing the valuation)  \n- horizon effect: when an agent try to erroneously delay the inevitable(no chance to win, but move to avoid loose)  \n- forward pruning: prunes moves that appear to be bad moves(but might be good one);Type B Strategy  \n- - beam search: example of forward pruning  \n- Monte Carlo tree search(MCTS): playing the game to the end while randomly selecting moves;evaluate an action: Repeatedly play the game from that state and take the average of the results\n\n\n\n## AIMA Chapter 5.5 Stochastic Games\n  Expectiminimax uses expected value at chance nodes  \n\n \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n Your summary here \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n Your summary here \n\n## AIMA Chapter 16.3 Utility Functions\n utility function describe the desirebility of state  \nutility function U(s) gives the payoff for each player in terminal state s\nUtility functions map from lotteries to real numbers  \nexpected utility EU(a)=$\\sum_{s'}P(result(a)=s')U(s')$ \n\n\n## Module 5 Lecture Notes\n Your summary here \n\n## Module 5 Definitions\n* **Concept** - definition\n\n\n# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n CSPs represent a state with a set of variable/value pairs  \nCSPs represent the conditions for a solution with a set of constraints on the variables  \nIn search problems, states are black boxes with a transition model to move between boxes. In CSPs, the agent can see inside the states and move between states accordingly.\nnode-consistent: if all the values in the variable’s domain satisfy the variable’s unary constraints.  \nconstraint propagation(inference): using the constraints to reduce the number of legal values for a variable, which in turn can reduce the legal values for another variable, and so on.  \npartial assignment:  one that leaves some variables unassigned, and a partial solution is a partial assignment that is consistent.  \nconsistent or legal assignment: assignment that does not violate any constraints.   \nsolution to a CSP:  a consistent, complete assignment  \nA complete assignment is one in which every variable is assigned a value  \nCSPs deal with assignments of values to variables, {Xi = vi,Xj = vj, …}\n \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n CSPs can rule out variable assignments using search and inference  \ninferece: enforcing k-consistency  \nstrongly kk-consistent: k-consistent, k-1k−1-consistent, ..., 11-consistent  \nAC3: enforcing arc consistency\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n depth first; backtracking  \nThe term backtracking search is used for a depth-first search that chooses\nvalues for one variable at a time and backtracks when a variable has no legal\nvalues left to assign.  \nuninformed  \nhave 4 heuristic to make it faster \ntree has n!d^n leaves, leaves are complete assignment  \nif consider commutativity(A=1,B=2 is the same as A=2,B=1)  \nnumber of leaves:d^n  \n#### forward checking \nwhenever a variable X is assigned,we establish arc consistency for X\nFor 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#### MAC maintain arc consistency(both search and inference while AC3 only inference)\nMAC recursively propogrates constraints, whereas forward checking does not\nforword checking only change domain of Y, MAC change other domain if domain of Y change  \nMAC first assign value on variable X, MAC only queues arcs incident on the assigned variable.then run as AC3\n##### CONSTRAIN learning \nrecords the conflicts（no-good:minimun set of variable from conflict set) as they are encountered in the search in order to avoid the same conflict later\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n #### min conflict algorithm  \nfirst randomly choose value for each variable  \nthen randomly choose conflict variable and assign a value which minimize conflict \n#### constraint weighting\ngive each constraaint a weight  \nchoose variable/value pair to change, which result in lowest total weight of all violated constrains  \nweight adjusted by increase the weight of constrains that is violated by current assinment \nSolving an arbitrary CSP takes exponential time with the number of variables, but linear time if convert to tree\n\n## AIMA Chapter 6.5 The Structure of Problems\n tree csp: a constrain gragh is tree when any two variable are connected by only one path.  \nany tree structure csp can be solved in time linear in the number of variable.  \nfirst randomlt choose a node as root, then convert it into topological sort. make all parent(x)->x are arc consistency  \n#### cutset(space efficient)\nThe first way to reduce a constraint graph to a tree involves assigning values to some variables so that the remaining variables form a tree.  \nCutset conditioning is efficient if a small cutset can be found  \n1. choose a subset of the CSP’s variables such that the constraint graph becomes a tree after removal of S. S is called a cycle cutset.\n2. For each possible assignment to the variables in  S that satisfies all constraints on S ,\na. remove from the domains of the remaining variables any values that are\ninconsistent with the assignment for S , and\nb. if the remaining CSP has a solution, return it together with the assignment\nfor S.  \n\nIf the cycle cutset has size c , then the total run time is O(d^c ⋅ (n − c)d^2)\n#### tree decomposing(time efficient,but memory exponential in the tree width w)\nsecond way to reduce a gragh to tree \nconvert to tree of subproblem  \n\nTree decomposition subproblems are efficient if the tree width of the constraint graph is small \nO(nd^2) O(nd^(w+1)), w is tree width  \nCSPs with constraint graphs of bounded tree width are solvable in polynomial time.\n \n\n## Module 6 Lecture Notes\n  Most constrained variable:Choose a variable with the fewest legal values(a variable with least color can choose)  \na.k.a. minimum remaining values (MRV) heuristic  \nMost constraining variable(degree heuristic):Choose the variable with the most constraints on remaining variables(variable has large amount of neighbours)  \nHeuristic 3: Least constraining value:the one that rules out the fewest values in the remaining variables(choose same value if possible, to give more choice for rest of variables)  \nH4:forward checking:Keep track of remaining legal values for unassigned variables.Terminate search when any unassigned variable has no remaining legal values.\n(whenever assign a value for a area, delete unleagal value for other area. terminate if an area has no value to assign)  \n\nTo make an arc (i,j) arc consistent,\nfor each value v on Xi ,\nif there is no label on Yj consistent with v\nthen remove v from Xi  \nGiven d values, checking arc (i,j) takes O(d2 ) time worst case\n```\nfunction AC-3(csp) return the CSP, possibly with reduced domains\ninputs: csp, a binary csp with variables {X1, X2, …, Xn}\nlocal variables: queue, a queue of arcs initially the arcs in csp\nwhile queue is not empty do\n  (Xi,Xj)<-queue.pop()\n  if REMOVE-INCONSISTENT-VALUES(Xi, Xj) then\n    for each Xk in NEIGHBORS[Xi ] – {Xj} do\n      add (Xk, Xi) to queue \n```  \n\n```\nfunction REMOVE-INCONSISTENT-VALUES(Xi, Xj) return true iff we remove a value\n  removed <- false\n  for each x in DOMAIN[Xi] do\n    if no value y in DOMAIN[Xj] allows (x,y) to satisfy the constraints between Xi and Xj\n    then delete x from DOMAIN[Xi]; removed <- true\n  return removed\n```\n- All nodes can be connected to every other node,\nso each of n nodes must be compared against n-1 other nodes,\nso total # of arcs is 2*n*(n-1), i.e. O(n^2)\n- If there are d values, checking arc (i,j) takes O(d^2 ) time\n- Each arc (i,j) can only be inserted into the queue d times\n- Worst case complexity: O(n^2d^3 )\n \n\n## Module 6 Definitions\n* **Concept** - definition\n\n\n# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n  - problem-solving agents have performed a search over states in order to\nfind a plan. The representation of states has been atomic.  \n- The process of deriving new sentences from old sentences is called inference.  \n- A KB can initially contain some background information about the world, and a\nknowledge-based agent can add to the information in the KB through its observations\nof the world.\n \n\n## AIMA Chapter 7.2 The Wumpus World\n \n- environment: \n  - performance measure\n  - environment\n  - actions\n  - sensor \n\n## AIMA Chapter 7.3 Logic\n Logic can serve as a general class of representations for knowledge-based agents.  \n- KB consists of sentences in the representation language\n- Representation language has a syntax that specifies sentences that are well-formed\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 call a model.\n- If sentence a is true in model m then we say\n - m satisfies a, or\n - m is a model of a\n- M(a) : set of all models of a.\n#### Logical Entailment\na⊨β if and only if M(a) ⊆ M(β)(area of b bigger than a)\n- The KB is false in models that contradictwhat the agent knows.\n- Possible Worlds is the process of\nenumerating all Possible Worlds that are\ncompatible with the KB. M(KB) ⊆ M(a1) \n#### Logical inference\nKB ⊢i a“a is derived from KB by i” i is a inference algorithm\n\n \n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n Atomic sentences are represented with a single propositional symbols. Propositional symbols stand for a statement that can be true or false.  \ne.g.$W_{1,3}$:There is a Wampa at location [1,3]\n- premise or antecede -> conclusion or consequence  \n- what KB looks like:R1: ¬ P1,1 ; R2: B1,1 ⇔ (P1,2 ⋁ P2,1 )\n- Sound – the inference algorithm should only derive entailed sentences.\n- Complete – an inference algorithm is complete if it can derive all sentences that are entailed\n \n\n## AIMA 7.5 Propositional Theorem Proving\n - ((a ⋀ β) ⋁ ɣ) ≡ ((a ⋀ β) ⋁ (a ⋀ ɣ))) Distributivity of ⋀ over ⋁\n- (a ⋀ β) ≡ (β ⋀ a) Commutativity of ⋀  \n- ((a ⋀ β) ⋀ ɣ) ≡ (a ⋀ (β ⋀ ɣ)) Associativity of ⋀\n#### Inference Rules\n- Modus Ponens: (a->b),a/b   \n- And Elimination:a⋀β/a\n#### Monotonicity implies Soundness \n- the set of entailed sentence can only increase as information is assed to the KB.\nif KB⊨a then KB ⋀ β ⊨a\n#### resolution\n- yields a complete inference algorithm when coupled with any complete search algorithm.\n- unit resolution\n - If ℓi and m are complementary literals,which means that one is the negation of another, then we can eliminate them via unit resolution.\n - (ℓ1 ⋁… ⋁ ℓk), m /(ℓ1 ⋁ … ⋁ ℓi-1 ⋁ ℓi+1 ⋁… ⋁ ℓk)\n- full resolution\n - Full resolution rule for complementary literals ℓi and mj\n - ℓ1 ⋁… ⋁ ℓk, m1 ⋁… ⋁ mn / ℓ1 ⋁ ℓi-1 ⋁ … ⋁ ℓi+1 ⋁ ℓk ⋁ m1 ⋁… ⋁ mj-1 ⋁ … ⋁ mj+1 ⋁ mk\n#### Conjunctive Normal Form (CNF)\nconjunction of disconjunction\n#### Forward Chaining \ndata-driven reasoning. An agent start with known data, adding premises as new percepts come in,\n and then incrementally apply the forward chaining algorithm to derive new conclusions. It doesn’t have to have a\nspecific query in mind to do so.\n- start form what we know is true in KB, store all the conclution we get from what we know. \n- stop when we find the queue or no more inference can be made\n\n#### Backward chaining\ngoal-directed reasoning.  \nworks backwards from a query. If the query is known to be true,\nthen no work is needed. Otherwise, the algorithm finds implications in the KB whose\nconclusions is the query. If all the premises of one of those can be proved to be true\n(via backward chaining), then the query is true.\n- start from goal(the queue), check what should be true to make the queue be true\n- stop when we find something we know is true or false\n\n\n\n\n## Module 7 Lecture Notes\n \n#### Resolution Algorithm\n complete\nInference procedures based on resolution work using the principle of proof by contradiction.  \nTo show KB⊨a then we can show that KB ⋀ ¬a is unsatisfiable.\n- convert (KB ⋀ ¬a) into CNF\n- apply the resolution rule to the resulting clauses.\n- Resolve every pair that contains complementary literals to produce a new clause\n- If that new clause isn’t already present, then add it to the set.\n- Continue the process until one of two things happens:\n1. There are no new clauses that can be added. In this case, the KB does not entail a\n2. Two clauses resolve to yield the empty clause, in which case the KB does entail a\n\n## Module 7 Definitions\n* **Definite clause** - – disjunction of literals where exactly one is positive\n* **Horn clause** - disjunction of literals where at most one is positive\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}