{
  "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",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lzaavW96tcxM",
        "outputId": "7c5cdea4-fab7-49d0-daab-45049c3068af"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ],
      "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)))"
      ]
    },
    {
      "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",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8DvZ57A-djo1",
        "outputId": "0fba2813-5f70-45b4-a740-0e496effad3c"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ],
      "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))"
      ]
    },
    {
      "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",
      "execution_count": null,
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "outputs": [],
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 1 - Intro to AI"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "outputs": [],
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, Chapter 1 “Introduction”, Section 1.1 “What is AI”\n",
        "\n",
        "chapter1_1 = \"\"\" \n",
        "* Human thought:\n",
        "  * introspection—catch own thoughts; \n",
        "  * psychological experiments—observe person in action; \n",
        "  * brain imaging—observe brain in action. \n",
        "\n",
        "Rational agent achieves best expected outcome when where is uncertainty, \n",
        "and best outcome if not.\"\"\" \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 = \"\"\"\n",
        "An agent is anything that can be viewed as perceiving its \n",
        "environment through sensors and acting upon that environment through actuators. \"\"\"\n",
        "chapter2_2 = \"\"\" \n",
        "* Consequentialism: evaluate behavior by action\n",
        "* Performance measures: better to design with the actual goal than what the robot \n",
        "should do\n",
        "* What is rational at any time depends on:\n",
        "  * performance measure\n",
        "  * the action that the agent can perform\n",
        "  * the agnent history of percept\n",
        "  * prior knowledge\n",
        "* Omniscience 先知: know the actual outcome of the actions and act accordingly;\n",
        "impossible to be perfect\n",
        "* Lack autonomy: rely completely on prior knowledge\n",
        "\"\"\"\n",
        "chapter2_3 = \"\"\"\n",
        "* Task env: the problem to solve - performance, environment, actuators, sensors (PEAS)\n",
        "* Fully observable: access to the complete state of env; sensors can detect all info\n",
        "* Deterministic: the next state of the env completely depends on current state \n",
        "and the next action by agents\n",
        "* Dynamic env: the env change when the agent is thinking\n",
        "* Fully observable can still be unknown; partially observable can be known\n",
        "\"\"\"\n",
        "chapter2_4 = \"\"\"\n",
        "* Agent function: current percept as input\n",
        "* Agent program: depend on all percepts in past history\n",
        "* Different types of intelligent systems:\n",
        "  * Simple reflex agents: select action based on current percept but does not consider past ones;\n",
        "  * Model-based reflex agents: transition model and sensor model;\n",
        "  * Goal-based agents: can be combined with model-based agents; less efficient but more flexible;\n",
        "  * Utility-based agents: utility of ways to achieve the goal\n",
        "* model free agent can learn without ever learning how that action changes the enviroment.\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module1_lecture_notes = \"\"\"\n",
        "\n",
        " \"\"\"\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"
      ]
    },
    {
      "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",
      "execution_count": 6,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "gYYeNcdM_maE",
        "outputId": "c1251f3e-fac6-48fe-f785-1b2e3288449b"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "# Module 1: Rational Agents and Task Environments\n",
              "## AIMA Chapter 1.1 What is AI?\n",
              " \n",
              "* Human thought:\n",
              "  * introspection—catch own thoughts; \n",
              "  * psychological experiments—observe person in action; \n",
              "  * brain imaging—observe brain in action. \n",
              "\n",
              "Rational agent achieves best expected outcome when where is uncertainty, \n",
              "and best outcome if not.\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",
              "\n",
              "An agent is anything that can be viewed as perceiving its \n",
              "environment through sensors and acting upon that environment through actuators. \n",
              "\n",
              "## AIMA 2.2 Good Behavior: The Concept of Rationality\n",
              " \n",
              "* Consequentialism: evaluate behavior by action\n",
              "* Performance measures: better to design with the actual goal than what the robot \n",
              "should do\n",
              "* What is rational at any time depends on:\n",
              "  * performance measure\n",
              "  * the action that the agent can perform\n",
              "  * the agnent history of percept\n",
              "  * prior knowledge\n",
              "* Omniscience 先知: know the actual outcome of the actions and act accordingly;\n",
              "impossible to be perfect\n",
              "* Lack autonomy: rely completely on prior knowledge\n",
              "\n",
              "\n",
              "## AIMA 2.3 The Nature of Environments\n",
              "\n",
              "* Task env: the problem to solve - performance, environment, actuators, sensors (PEAS)\n",
              "* Fully observable: access to the complete state of env; sensors can detect all info\n",
              "* Deterministic: the next state of the env completely depends on current state \n",
              "and the next action by agents\n",
              "* Dynamic env: the env change when the agent is thinking\n",
              "* Fully observable can still be unknown; partially observable can be known\n",
              "\n",
              "\n",
              "## AIMA 2.4 The Structure of Agents\n",
              "\n",
              "* Agent function: current percept as input\n",
              "* Agent program: depend on all percepts in past history\n",
              "* Different types of intelligent systems:\n",
              "  * Simple reflex agents: select action based on current percept but does not consider past ones;\n",
              "  * Model-based reflex agents: transition model and sensor model;\n",
              "  * Goal-based agents: can be combined with model-based agents; less efficient but more flexible;\n",
              "  * Utility-based agents: utility of ways to achieve the goal\n",
              "* model free agent can learn without ever learning how that action changes the enviroment.\n",
              "\n",
              "\n",
              "## Module 1 Lecture Notes\n",
              "\n",
              "\n",
              " \n",
              "\n",
              "## Module 1 Definitions\n",
              "* **Agent** - anything that can perceive and act in an environment\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "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))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 2 - Python"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "outputs": [],
      "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\" : \"list is mutable, sets are not; once created you cannot change it\",\n",
        "}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 209
        },
        "id": "ydOK__lwWgdp",
        "outputId": "b1b889c2-b098-4d19-d770-d10f3660dac6"
      },
      "outputs": [
        {
          "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": {},
          "output_type": "display_data"
        }
      ],
      "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))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 3 - Search Problems"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "outputs": [],
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 3 “Problem Solving by Search” (3.1-3.4)\n",
        "chapter3_1 = \"\"\"\n",
        "* Problem solving agent:\n",
        "  * Goal formulation\n",
        "  * Problem formulation\n",
        "  * Search\n",
        "  * Execution\n",
        "* In a fully observable, deterministic, known environment: the solution to any\n",
        "problem is a fixed sequence of actions (a path)\n",
        "* Use open loop: the model is right; use closed loop: \n",
        "if the model is incorrect or env is non-deterministic\n",
        "* Search:\n",
        "  * Key elements:\n",
        "    * states/state space (like the complete board)\n",
        "    * initial state (like the status of the board)\n",
        "    * goal states (when the problem is solved)\n",
        "    * actions available \n",
        "    * transition model: what each action does; result of each action\n",
        "    * action cost function: numerical cost of action moving from s to s'\n",
        "  * Optimal solution: lowest path cost\n",
        "* Abstraction: useful (less detailed world) vs. valid (more detailed world)\n",
        "  * a good choice need to balance the two\n",
        "\"\"\"\n",
        "\n",
        "chapter3_2 = \"\"\"\n",
        "* Standard vs real world problems\n",
        " \"\"\"\n",
        "chapter3_3 = \"\"\"\n",
        "* Search algorithms: return solution or indicate failure\n",
        "* Node: correspond to a state in the state space\n",
        "* Frontier separates an interior region (expanded) and exterior region (reached)\n",
        "* Best first search: \n",
        "  * Expands with min(f(n))\n",
        "  * Uses late goal tests (waiting until a node is poped off the queue)\n",
        "* Search data structures:\n",
        "  * node.State, node.Parent, node.Action, node.PathCost\n",
        "* Cycle is a special case of a redundant path\n",
        "* Graph search algorithm: search for redundent paths\n",
        "* Tree like search algorithm: do not check for redundent paths\n",
        "* If we check for redundent path: memory is costly; if we don't, then it runs slow\n",
        "  * We compromise to check for cycles but not redundant paths\n",
        "  * We can follow the parent node to see if state has appeared early in the path\n",
        "    * If followed all the way, then all redundant paths are checked\n",
        "    * If followed to a few links, only eliminates the short cycles\n",
        "* There are problems formulations where it is impossible to for two paths to reach\n",
        "to the same state; in this case we can use a tree like search algorithm. \n",
        "* Measuring performance of the search algo:\n",
        "  * Completeness: guaranteed to find a solution (if there is one), and report failure if not\n",
        "    * Must be systematic: reach any state that is connected to the initial state\n",
        "  * Cost optimality: find solutions with lowest path cost\n",
        "  * Time complexity\n",
        "  * Space complexity\n",
        "* Problem difficulty can also be measured using time and space complexity:\n",
        "  * In graph: number of nodes + number of edges\n",
        "  * If not possible to phrase in a graphical way: \n",
        "    * d: depth\n",
        "    * m: maximum # of actions in any path\n",
        "    * b: the branching factor/the number of successors in a node needed to be considered\n",
        "\"\"\"\n",
        "chapter3_4 = \"\"\"\n",
        "# Uninformed search\n",
        "* Breath first search: expands the earliert nodes; complete even on infinite state spaces\n",
        "  * A couple tricks to be more efficient: \n",
        "    * First in first out is faster than priority queue\n",
        "    * Reached can a set of states\n",
        "    * Early goal test\n",
        "    * O(b^d); and memory issue could be a bigger problem than run time issue\n",
        "* Uniform cost search/Dijkstra’s algorithm (without a goal state):\n",
        "  * Uniform cost search = best first search where the path cost function is \n",
        "  the cost of path from the root to the current node (kinda of distance from the root node)\n",
        "  * Can explore large trees of actions with low costs before expanding the one that is actually\n",
        "  optimal\n",
        "  * Complete and cost optimal\n",
        "* Depth first search: expands the deepest/latest nodes\n",
        "  * Incomplete\n",
        "  * Implemented not as a tree graph, so does not check for redundancy\n",
        "  * Return the first answer it finds, even if it is not cost optimal\n",
        "  * For infinite space it may stuck in a infinite loop\n",
        "  * However, for a problem where tree-like search is possible, dfs has much smaller\n",
        "  need for memory\n",
        "* Backtracking search: a variation of dfs:\n",
        "  * Uses even less memory\n",
        "  * Only one successor is generated at a time\n",
        "  * Each partially generated node remembers which succssor to generate next\n",
        "* Depth-limited search: prevent dfs from going down a infinite path\n",
        "  * need to have a good selection of l; based on knowledge\n",
        "* Iterative deepening search\n",
        "  * Like depth-limited search except trying all values up to l\n",
        "  * Like bfs except each level is not stored in memory but generated by repeating \n",
        "  the previous level\n",
        "  * O(bm) on finite state with no solution and O(bd) when there is a solution\n",
        "  * Optimal for problems where all actions have the same costs; complete on finite \n",
        "  acyclic state spaces\n",
        "  * States near the top are generated multiple times\n",
        "* Bidirectional search: forward and backward\n",
        "  * O(2*b^(d/2))\n",
        "  * Need to keep track of two frontiers\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"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "lvtN3p7ET3Tx",
        "outputId": "61ea1dea-e18b-4419-a005-839797f9b5e1"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "# Module 3: Search Problems\n",
              "## AIMA Chapter 3.1 Problem-Solving Agents\n",
              "\n",
              "* Problem solving agent:\n",
              "  * Goal formulation\n",
              "  * Problem formulation\n",
              "  * Search\n",
              "  * Execution\n",
              "* In a fully observable, deterministic, known environment: the solution to any\n",
              "problem is a fixed sequence of actions (a path)\n",
              "* Use open loop: the model is right; use closed loop: \n",
              "if the model is incorrect or env is non-deterministic\n",
              "* Search:\n",
              "  * Key elements:\n",
              "    * states/state space (like the complete board)\n",
              "    * initial state (like the status of the board)\n",
              "    * goal states (when the problem is solved)\n",
              "    * actions available \n",
              "    * transition model: what each action does; result of each action\n",
              "    * action cost function: numerical cost of action moving from s to s'\n",
              "  * Optimal solution: lowest path cost\n",
              "* Abstraction: useful (less detailed world) vs. valid (more detailed world)\n",
              "  * a good choice need to balance the two\n",
              "\n",
              "\n",
              "## AIMA Chapter 3.2 Example Problems\n",
              "\n",
              "* Standard vs real world problems\n",
              " \n",
              "\n",
              "## AIMA Chapter 3.3 Search Algorithms\n",
              "\n",
              "* Search algorithms: return solution or indicate failure\n",
              "* Node: correspond to a state in the state space\n",
              "* Frontier separates an interior region (expanded) and exterior region (reached)\n",
              "* Best first search: greedy\n",
              "  * Expands with min(f(n))\n",
              "  * Uses late goal tests (waiting until a node is poped off the queue)\n",
              "* Search data structures:\n",
              "  * node.State, node.Parent, node.Action, node.PathCost\n",
              "* Cycle is a special case of a redundant path\n",
              "* Graph search algorithm: search for redundent paths\n",
              "* Tree like search algorithm: do not check for redundent paths\n",
              "* If we check for redundent path: memory is costly; if we don't, then it runs slow\n",
              "  * We compromise to check for cycles but not redundant paths\n",
              "  * We can follow the parent node to see if state has appeared early in the path\n",
              "    * If followed all the way, then all redundant paths are checked\n",
              "    * If followed to a few links, only eliminates the short cycles\n",
              "* There are problems formulations where it is impossible to for two paths to reach\n",
              "to the same state; in this case we can use a tree like search algorithm. \n",
              "* Measuring performance of the search algo:\n",
              "  * Completeness: guaranteed to find a solution (if there is one), and report failure if not\n",
              "    * Must be systematic: reach any state that is connected to the initial state\n",
              "  * Cost optimality: find solutions with lowest path cost\n",
              "  * Time complexity\n",
              "  * Space complexity\n",
              "* Problem difficulty can also be measured using time and space complexity:\n",
              "  * In graph: number of nodes + number of edges\n",
              "  * If not possible to phrase in a graphical way: \n",
              "    * d: depth\n",
              "    * m: maximum # of actions in any path\n",
              "    * b: the branching factor/the number of successors in a node needed to be considered\n",
              "\n",
              "\n",
              "## AIMA Chapter 3.4 Uninformed Search Strategies\n",
              "\n",
              "# Uninformed search\n",
              "* Breath first search: expands the earliert nodes; complete even on infinite state spaces\n",
              "  * A couple tricks to be more efficient: \n",
              "    * First in first out is faster than priority queue\n",
              "    * Reached can a set of states\n",
              "    * Early goal test\n",
              "    * O(b^d); and memory issue could be a bigger problem than run time issue\n",
              "* Uniform cost search/Dijkstra’s algorithm (without a goal state):\n",
              "  * Uniform cost search = best first search where the path cost function is \n",
              "  the cost of path from the root to the current node (kinda of distance from the root node)\n",
              "  * Can explore large trees of actions with low costs before expanding the one that is actually\n",
              "  optimal\n",
              "  * Complete and cost optimal\n",
              "* Depth first search: expands the deepest/latest nodes\n",
              "  * Incomplete\n",
              "  * Implemented not as a tree graph, so does not check for redundancy\n",
              "  * Return the first answer it finds, even if it is not cost optimal\n",
              "  * For infinite space it may stuck in a infinite loop\n",
              "  * However, for a problem where tree-like search is possible, dfs has much smaller\n",
              "  need for memory\n",
              "* Backtracking search: a variation of dfs:\n",
              "  * Uses even less memory\n",
              "  * Only one successor is generated at a time\n",
              "  * Each partially generated node remembers which succssor to generate next\n",
              "* Depth-limited search: prevent dfs from going down a infinite path\n",
              "  * need to have a good selection of l; based on knowledge\n",
              "* Iterative deepening search\n",
              "  * Like depth-limited search except trying all values up to l\n",
              "  * Like bfs except each level is not stored in memory but generated by repeating \n",
              "  the previous level\n",
              "  * O(bm) on finite state with no solution and O(bd) when there is a solution\n",
              "  * Optimal for problems where all actions have the same costs; complete on finite \n",
              "  acyclic state spaces\n",
              "  * States near the top are generated multiple times\n",
              "* Bidirectional search: forward and backward\n",
              "  * O(2*b^(d/2))\n",
              "  * Need to keep track of two frontiers\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": {},
          "output_type": "display_data"
        }
      ],
      "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))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 4 - Informed Search"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "outputs": [],
      "source": [
        "# Russell and Norvig, AIMA Chapter 3 “Problem Solving by Search” (3.5-3.6)\n",
        "chapter3_5 = \"\"\"\n",
        "* Informed strategy: domain-specific hints \n",
        "  * h(n): heuristic function; \n",
        "    * shortest distance/path from the state at node n to the goal state\n",
        "    * admissible heuristics never overestimate the cost to reach to a goal\n",
        "     \n",
        "    * consistent heuristics forms triangular inequality; \n",
        "      * every consistent heurics is admissble but not vice versa\n",
        "      * will not have multiple paths reaching the same state; but if inconsistent, \n",
        "      there could be multiple paths and the need to update successors of the state\n",
        "      (need to have a child pointer and parent pointer)\n",
        "  * g(n): path cost from initial state to node n\n",
        "  * h(n) + g(n): this will monotonically increase if consistent heurics\n",
        "* Greedy best first search: a best first search that uses h(n) as evaluation function\n",
        "* A* search: a best first search that uses g(n)+h(n) as evaluation function\n",
        "  * complete, cost optimal, optimally efficient\n",
        "  * A* with consistent heuristics is optimally efficient; efficient bc it prunes away\n",
        "  nodes that are not on the optimal path\n",
        "  * If inadmissible heuristics, A* may not be optimal (but could be under some situations)\n",
        "  * If we allow for suboptimal solutions but are still satisfacing, we can allow \n",
        "  inadmissible heuristics but it will be faster.\n",
        "* Weighted A* search: bounded suboptimal search - cost is within a constant factor w\n",
        "* Bounded cost search -  cost is within a constant C\n",
        "* Unbounded cost search  - accept a solution of any cost\n",
        "* Memory efficient tricks:\n",
        "  * keep only one of frontiers and reached\n",
        "  * remove states from reached when we can prove that they are no longer needed\n",
        "  * keep reference counts of how many states could be reached and remove it if no other \n",
        "  way can reach the state\n",
        "  * Beam search limits the size of the frontier: keep top k nodes with the best f-score\n",
        "  * Iterative deepening search: gives us the benefits of A* without the requirement to keep reached\n",
        "  states in memory\n",
        "    * Cutoff is cutoff is the f(n)= g(n) + h(n)\n",
        "    * Memory: only maintains a single number\n",
        "    * May revisit the same states\n",
        "  * Recursive best-first search: mimic standard best-first search but linear space\n",
        "    * Uses a f-limit variable; if exceeds, revert back to alternative nodes\n",
        "    * Replaces each node along the path with a backed-up value (best value of children)\n",
        "    * Liner memory\n",
        "    * May revisit the same states\n",
        "  * Memory-bounded A* and Simplified memory-bounded A* (to do)\n",
        "* Bidirectional A* (to do)\n",
        "  * Front to end search: initial to node + node to goal\n",
        "  * Front to front: estimate distance to the other frontiers\n",
        "  * Only more efficient sometimes\n",
        "\n",
        "\"\"\"\n",
        "chapter3_6 = \"\"\"\n",
        "* Quality of heuristics:\n",
        "  * Effective branching factor b*\n",
        "  * Effective depth\n",
        "  * Higher heuritics (if still consistent) is preferred\n",
        "    * Higher dominates lower\n",
        "* Generate heuristics \n",
        "  * From relaxed problems (less restrictions)\n",
        "    * Absolver - a program that can generate that\n",
        "  * From subproblem: pattern databases - store solution cost for subproblems\n",
        "  * From landmarks (to do)\n",
        "  * From experience (to do)\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module4_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module4_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "vqtEs0gHs9sO",
        "outputId": "17b18b22-2ef7-4a16-973a-97c246d7ee26"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "## WARNING: Your summary of 'AIMA Chapter 3.5 Informed (Heuristic) Search Strategies' is too long!\n",
              "# Module 4: Informed Search\n",
              "## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n",
              "\n",
              "* Informed strategy: domain-specific hints \n",
              "  * h(n): heuristic function; \n",
              "    * shortest distance/path from the state at node n to the goal state\n",
              "    * admissible heuristics never overestimate the cost to reach to a goal\n",
              "     \n",
              "    * consistent heuristics forms triangular inequality; \n",
              "      * every consistent heurics is admissble but not vice versa\n",
              "      * will not have multiple paths reaching the same state; but if inconsistent, \n",
              "      there could be multiple paths and the need to update successors of the state\n",
              "      (need to have a child pointer and parent pointer)\n",
              "  * g(n): path cost from initial state to node n\n",
              "  * h(n) + g(n): this will monotonically increase if consistent heurics\n",
              "* Greedy best first search: a best first search that uses h(n) as evaluation function\n",
              "* A* search: a best first search that uses g(n)+h(n) as evaluation function\n",
              "  * complete, cost optimal, optimally efficient\n",
              "  * A* with consistent heuristics is optimally efficient; efficient bc it prunes away\n",
              "  nodes that are not on the optimal path\n",
              "  * If inadmissible heuristics, A* may not be optimal (but could be under some situations)\n",
              "  * If we allow for suboptimal solutions but are still satisfacing, we can allow \n",
              "  inadmissible heuristics but it will be faster.\n",
              "* Weighted A* search: bounded suboptimal search - cost is within a constant factor w\n",
              "* Bounded cost search -  cost is within a constant C\n",
              "* Unbounded cost search  - accept a solution of any cost\n",
              "* Memory efficient tricks:\n",
              "  * keep only one of frontiers and reached\n",
              "  * remove states from reached when we can prove that they are no longer needed\n",
              "  * keep reference counts of how many states could be reached and remove it if no other \n",
              "  way can reach the state\n",
              "  * Beam search limits the size of the frontier: keep top k nodes with the best f-score\n",
              "  * Iterative deepening search: gives us the benefits of A* without the requirement to keep reached\n",
              "  states in memory\n",
              "    * Cutoff is cutoff is the f(n)= g(n) + h(n)\n",
              "    * Memory: only maintains a single number\n",
              "    * May revisit the same states\n",
              "  * Recursive best-first search: mimic standard best-first search but linear space\n",
              "    * Uses a f-limit variable; if exceeds, revert back to alternative nodes\n",
              "    * Replaces each node along the path with a backed-up value (best value of children)\n",
              "    * Liner memory\n",
              "    * May revisit the same states\n",
              "  * Memory-bounded A* and Simplified memory-bounded A* (to do)\n",
              "* Bidirectional A* (to do)\n",
              "  * Front to end search: initial to node + node to goal\n",
              "  * Front to front: estimate distance to the other frontiers\n",
              "  * Only more efficient sometimes\n",
              "\n",
              "\n",
              "\n",
              "## AIMA Chapter 3.6 Heuristic Functions\n",
              "\n",
              "* Quality of heuristics:\n",
              "  * Effective branching factor b*\n",
              "  * Effective depth\n",
              "  * Higher heuritics (if still consistent) is preferred\n",
              "    * Higher dominates lower\n",
              "* Generate heuristics \n",
              "  * From relaxed problems (less restrictions)\n",
              "    * Absolver - a program that can generate that\n",
              "  * From subproblem: pattern databases - store solution cost for subproblems\n",
              "  * From landmarks (to do)\n",
              "  * From experience (to do)\n",
              "\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": {},
          "output_type": "display_data"
        }
      ],
      "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\", module3_lecture_notes),\n",
        "]\n",
        "\n",
        "module4_markdown = format_module(4, \"Informed Search\", \n",
        "                         module4_sections, \n",
        "                         module4_definitions)\n",
        "display(Markdown(module4_markdown))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 5 - Adversarial Search and Games"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "outputs": [],
      "source": [
        "# Russell and Norvig, AIMA chapter 5 \"Adversarial Search\"”\" (5.1-5.3, and 5.5).\n",
        "chapter5_1 = \"\"\"\n",
        "* Two player perfect information zero sums (no win-win) game:\n",
        "  * Key elements\n",
        "    * Initial state\n",
        "    * Whose turn it is\n",
        "    * Legal actions/moves\n",
        "    * Result: transition model that defines the results from the actions\n",
        "    * If the game terminated\n",
        "    * Utility function\n",
        "  * State space graph:\n",
        "    * Vertices are states, edges are moves --> can superimpose a search tree\n",
        "  * Game Tree:\n",
        "    * Complete tree from beginning to end\n",
        "\"\"\"\n",
        "chapter5_2 = \"\"\"\n",
        "* Minmax search: for games with multiple outcome scores\n",
        "* Ply: one move by one player\n",
        "* Minmax value: utility (for max) for that state\n",
        "  * Time complexity: O(b^m)\n",
        "  * Space complexity: O(bm)\n",
        "* Multiplayer:\n",
        "  1. Replace the single value for each node with a vector of values\n",
        "  2. Consider non-terminal states\n",
        "* Alpha-beta Pruning:\n",
        "  * Prune unnecessary nodes\n",
        "  * Highly dependent on the order\n",
        "* Dynamic move-ordering, ex\n",
        "  * Trying first the moves that were found to be best in the past\n",
        "  * Iterative deepening: search one ply first, record the ranking of moves, \n",
        "  then search one ply deeper and use previous ranking to inform the ordering\n",
        "  * Killer moves: best moves; try them first: killer move heuristic\n",
        "  * Transpositions: different paths that end up in the same position\n",
        "    * Transposition table: caches the heuristic value of states\n",
        "    * Type A strategy: considers all possible moves to estimate the utility\n",
        "    * Type B strategy: ignore move that look bad; follow promising lines as much \n",
        "    as possible\n",
        "\"\"\"\n",
        "chapter5_3 = \"\"\"\n",
        "* Can cut off the search early and apply a heuristic evaluation function to states\n",
        "* Terminal test -> cutoff test\n",
        "* Heuristic Evaluation functions:\n",
        "  * Terminal: eval = utility; nonterminal: utility loss < eval < utility win （todo)\n",
        "* Forward pruning: prunes moves that appear to be poor but actually may not be\n",
        "\"\"\"\n",
        "chapter5_5 = \"\"\"\n",
        "* Stochastic game:\n",
        "  * Chance node\n",
        "\"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 16 “Making Simple Decisions” (16.1-16.3)\n",
        "chapter16_1 = \"\"\"\n",
        "* Utility function (over all the states * conditional probability) --> expected utility function\n",
        "\"\"\"\n",
        "chapter16_2 = \"\"\"\n",
        "* Maximize expected utility\n",
        "* Reasonable preferences:\n",
        "  * Orderability: much choose or indifferent\n",
        "  * Transitivity\n",
        "  * Continuity (continuous distribution)\n",
        "  * Substitutability\n",
        "  * Monotonicity\n",
        "  * Decomposability\n",
        "\"\"\"\n",
        "chapter16_3 = \"\"\"\n",
        "* Preference elicitation: work out the utility function\n",
        "* Normalized utilities\n",
        "* Expected monetary value\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module5_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module5_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "KUc_LgzDvWf-",
        "outputId": "face5089-6b7c-4cc4-ccbc-d678aac496b1"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "# Module 5: Adversarial Search and Games\n",
              "## AIMA Chapter 5.1 Game Theory\n",
              "\n",
              "* Two player perfect information zero sums (no win-win) game:\n",
              "  * Key elements\n",
              "    * Initial state\n",
              "    * Whose turn it is\n",
              "    * Legal actions/moves\n",
              "    * Result: transition model that defines the results from the actions\n",
              "    * If the game terminated\n",
              "    * Utility function\n",
              "  * State space graph:\n",
              "    * Vertices are states, edges are moves --> can superimpose a search tree\n",
              "  * Game Tree:\n",
              "    * Complete tree from beginning to end\n",
              "\n",
              "\n",
              "## AIMA Chapter 5.2 Optimal Decisions in Games\n",
              "\n",
              "* Minmax search: for games with multiple outcome scores\n",
              "* Ply: one move by one player\n",
              "* Minmax value: utility (for max) for that state\n",
              "  * Time complexity: O(b^m)\n",
              "  * Space complexity: O(bm)\n",
              "* Multiplayer:\n",
              "  1. Replace the single value for each node with a vector of values\n",
              "  2. Consider non-terminal states\n",
              "* Alpha-beta Pruning:\n",
              "  * Prune unnecessary nodes\n",
              "  * Highly dependent on the order\n",
              "* Dynamic move-ordering, ex\n",
              "  * Trying first the moves that were found to be best in the past\n",
              "  * Iterative deepening: search one ply first, record the ranking of moves, \n",
              "  then search one ply deeper and use previous ranking to inform the ordering\n",
              "  * Killer moves: best moves; try them first: killer move heuristic\n",
              "  * Transpositions: different paths that end up in the same position\n",
              "    * Transposition table: caches the heuristic value of states\n",
              "    * Type A strategy: considers all possible moves to estimate the utility\n",
              "    * Type B strategy: ignore move that look bad; follow promising lines as much \n",
              "    as possible\n",
              "\n",
              "\n",
              "## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n",
              "\n",
              "* Can cut off the search early and apply a heuristic evaluation function to states\n",
              "* Terminal test -> cutoff test\n",
              "* Heuristic Evaluation functions:\n",
              "  * Terminal: eval = utility; nonterminal: utility loss < eval < utility win （todo)\n",
              "* Forward pruning: prunes moves that appear to be poor but actually may not be\n",
              "\n",
              "\n",
              "## AIMA Chapter 5.5 Stochastic Games\n",
              "\n",
              "* Stochastic game:\n",
              "  * Chance node\n",
              "\n",
              "\n",
              "## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n",
              "\n",
              "* Utility function (over all the states * conditional probability) --> expected utility function\n",
              "\n",
              "\n",
              "## AIMA Chapter 16.2 The Basis of Utility Theory\n",
              "\n",
              "* Maximize expected utility\n",
              "* Reasonable preferences:\n",
              "  * Orderability: much choose or indifferent\n",
              "  * Transitivity\n",
              "  * Continuity (continuous distribution)\n",
              "  * Substitutability\n",
              "  * Monotonicity\n",
              "  * Decomposability\n",
              "\n",
              "\n",
              "## AIMA Chapter 16.3 Utility Functions\n",
              "\n",
              "* Preference elicitation: work out the utility function\n",
              "* Normalized utilities\n",
              "* Expected monetary value\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": {},
          "output_type": "display_data"
        }
      ],
      "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))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "#Module 6 - \"Constraint Satisfaction Problems\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "outputs": [],
      "source": [
        "# Russell and Norvig, AIMA, Chapter 6 “Constraint Satisfaction Problems” (6.1-6.5)\n",
        "chapter6_1 = \"\"\"\n",
        "* CSP: NP complete problem in general\n",
        "* Disjunctive constraint: no overlaps\n",
        "* Linear constraints vs nonlinear constraints\n",
        "  * Linear: each variable appears in linear form\n",
        "* Global constraint: arbitrary number of variablesl example: all diff\n",
        "\"\"\"\n",
        "chapter6_2 = \"\"\"\n",
        "* Constraint probagation: uses constraints to reduce legal values\n",
        "* Local consistency: \n",
        "  * Node: satisfy unary constraint (1)\n",
        "  * Arc: satisfy binary constraint (2)\n",
        "  * Path: tightens arc by infering constraints from triples of variables (3)\n",
        "  * k-consistency: consistent on all ks\n",
        "\"\"\"\n",
        "chapter6_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter6_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter6_5 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module6_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module6_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 541
        },
        "id": "kKWbCsbfxL3R",
        "outputId": "f51aeef3-74ac-4ec6-b389-54aae53b8cbc"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "# Module 6: Constraint Satisfaction Problems\n",
              "## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.3 Backtracking Search for CSPs\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.4 Local Search for CSPs\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.5 The Structure of Problems\n",
              " Your summary here \n",
              "\n",
              "## Module 6 Lecture Notes\n",
              " Your summary here \n",
              "\n",
              "## Module 6 Definitions\n",
              "* **Concept** - definition\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "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))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "#Module 7 - Logical Agents"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "outputs": [],
      "source": [
        "# Russell and Norvig, AIMA Chapter 7 “Logical Agents” (Sections 7.1-7.5)\n",
        "\n",
        "chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module7_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module7_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 541
        },
        "id": "lXNcHuKjyNXa",
        "outputId": "fd406b8c-6eaa-4be5-be5f-3639d4b7fa43"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "# Module 7: Logical Agents\n",
              "## AIMA Chapter 7.1 Knowledge-Based Agents\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 7.2 The Wumpus World\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 7.3 Logic\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n",
              " Your summary here \n",
              "\n",
              "## AIMA 7.5 Propositional Theorem Proving\n",
              " Your summary here \n",
              "\n",
              "## Module 7 Lecture Notes\n",
              " Your summary here \n",
              "\n",
              "## Module 7 Definitions\n",
              "* **Concept** - definition\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "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))"
      ]
    },
    {
      "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",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 3366
        },
        "id": "T3cm1WV542_a",
        "outputId": "a929c6c6-b72b-4fd8-bd35-a014674c9230"
      },
      "outputs": [
        {
          "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",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 5.2 Optimal Decisions in Games\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 5.5 Stochastic Games\n",
              " Your summary here \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",
              " Your summary here \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",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.3 Backtracking Search for CSPs\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.4 Local Search for CSPs\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 6.5 The Structure of Problems\n",
              " Your summary here \n",
              "\n",
              "## Module 6 Lecture Notes\n",
              " Your summary here \n",
              "\n",
              "## Module 6 Definitions\n",
              "* **Concept** - definition\n",
              "\n",
              "\n",
              "# Module 7: Logical Agents\n",
              "## AIMA Chapter 7.1 Knowledge-Based Agents\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 7.2 The Wumpus World\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 7.3 Logic\n",
              " Your summary here \n",
              "\n",
              "## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n",
              " Your summary here \n",
              "\n",
              "## AIMA 7.5 Propositional Theorem Proving\n",
              " Your summary here \n",
              "\n",
              "## Module 7 Lecture Notes\n",
              " Your summary here \n",
              "\n",
              "## Module 7 Definitions\n",
              "* **Concept** - definition\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "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))"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "YZ_FINAL Template_for CIS521_midterm notes.ipynb",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
