{
  "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": "344222ad-a216-45e3-9726-b566dead59fe"
      },
      "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": null,
      "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": "ef81cd11-e574-43c8-fb57-4c2e2e3d803c"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": null,
      "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 = \"\"\" Two dimension : human and rationality, thought and behavior. \n",
        "Acting humanly: Turing test(NLP,Knoledge representation, automated reasoning, ML, CV, robotics) \\ \n",
        "internal thought(thingking humanly): cognitive thinking\\\n",
        "thinking rationally: logic & probability. from raw information to let machine understand the world and predict future.(not intelligent behavior)\\  \n",
        "acting rationally, agent: something that acts. Do the right thing(we define machine's objectives using cost function)(standard model).\\\n",
        "in reallity, we may not achieve perfect rationality because of limited computation.(limited rationality).\\\n",
        "Also, in reallity, standard model might not the final model because machine might not recognize the goal/objective completely(tradeoff the value alignment problem).\\\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 = \"\"\" \n",
        "weak AI: machine imitate/simulate to act to reach desired result. just appearance, surface. \\\n",
        "strong AI: cand do real thinking like human. \n",
        "\n",
        "(Qualification problem)Turing think some argument are informal used by human, which can never be applied in a formal set on machine\\\n",
        "Good Old-Fashioned AI (GOFAL): intelligent behavior can be captured by rules and logical reasoning.\n",
        "\n",
        "embodied cognition: study from real enviroment rather than logic inference. can not separate cognition with body.\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "chapter27_2 = \"\"\"\n",
        "it's hard to define consciousness.(aware of subjective experience, itself, the world.)\n",
        "Polite convention: we can not know whether others have mental states, but we have polite convention\\\n",
        "human has own subjective apparatus to think while machine only runs ode\"\"\\ \n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA 4th Edition, Chapter 2 “Intelligent Agents” (whole chapter)\n",
        "chapter2_1 = \"\"\"\n",
        "The agent program implements the agent function\n",
        "agent problem is more practical and need more details to take into account.\n",
        "agent function is just abstract description\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter2_2 = \"\"\"\n",
        "rationality: doing the right thing.\n",
        "We use performance measure to evaluate consequences that agent brings.\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "chapter2_3 = \"\"\" \n",
        "taks environment: PEAS (Performance, Environment, Actuators, Sensors)\n",
        "\n",
        "Property of task environment:\n",
        "Fully observable vs. partially observable\n",
        "Single-agent vs. multiagent\n",
        "Deterministic vs. nondeterministic  stochastic(has possibility)\n",
        "Episodic vs. sequential\n",
        "Static vs. dynamic\n",
        "Discrete vs. continuous\n",
        "Known vs. unknown \n",
        "  \"\"\"\n",
        "chapter2_4 = \"\"\" \n",
        "agent = architecture+program\n",
        "types of agents:\\\n",
        "simple reflex agent\n",
        "model-based reflex agent\n",
        "goal-based agent\n",
        "utility-based agent\n",
        "learning agent(All agents can improve their performance through learning.)\n",
        "\n",
        "component fo agent : atomic representation, factored representation, structured representation\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module1_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 1.\n",
        "# You can define any bolded term in the textbook, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 20 words long.\n",
        "module1_definitions = {\n",
        "\"agent\" : \"anything that can perceive and act in an environment\",\n",
        "\"percept\" : \"your definitions here\",\n",
        "\"percept sequence\" : \"everything from past to present the agent has perceived\",\n",
        "\"other concept\" : \"your definitions here\",\n",
        "\"etc.\": \"your definitions here\",\n",
        "\"rational agent\" : \"for each step, rational agent should act that maximizes its performance measure. \"\n",
        "\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "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": 1000
        },
        "outputId": "e81d6253-aff5-41c5-d504-84cdbdd11ea6"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n Two dimension : human and rationality, thought and behavior. \nActing humanly: Turing test(NLP,Knoledge representation, automated reasoning, ML, CV, robotics) \\ \ninternal thought(thingking humanly): cognitive thinkingthinking rationally: logic & probability. from raw information to let machine understand the world and predict future.(not intelligent behavior)\\  \nacting rationally, agent: something that acts. Do the right thing(we define machine's objectives using cost function)(standard model).in reallity, we may not achieve perfect rationality because of limited computation.(limited rationality).Also, in reallity, standard model might not the final model because machine might not recognize the goal/objective completely(tradeoff the value alignment problem).\n\n\n\n\n\n\n## AIMA Chapter 27.1 The Limits of AI\n \nweak AI: machine imitate/simulate to act to reach desired result. just appearance, surface. strong AI: cand do real thinking like human. \n\n(Qualification problem)Turing think some argument are informal used by human, which can never be applied in a formal set on machineGood Old-Fashioned AI (GOFAL): intelligent behavior can be captured by rules and logical reasoning.\n\nembodied cognition: study from real enviroment rather than logic inference. can not separate cognition with body.\n\n\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n\nit's hard to define consciousness.(aware of subjective experience, itself, the world.)\nPolite convention: we can not know whether others have mental states, but we have polite conventionhuman has own subjective apparatus to think while machine only runs ode\"\"\\ \n\n \n\n## AIMA 2.1 Agents and Environments\n\nThe agent program implements the agent function\nagent problem is more practical and need more details to take into account.\nagent function is just abstract description\n\n\n \n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n\nrationality: doing the right thing.\nWe use performance measure to evaluate consequences that agent brings.\n\n\n\n\n## AIMA 2.3 The Nature of Environments\n \ntaks environment: PEAS (Performance, Environment, Actuators, Sensors)\n\nProperty of task environment:\nFully observable vs. partially observable\nSingle-agent vs. multiagent\nDeterministic vs. nondeterministic  stochastic(has possibility)\nEpisodic vs. sequential\nStatic vs. dynamic\nDiscrete vs. continuous\nKnown vs. unknown \n  \n\n## AIMA 2.4 The Structure of Agents\n \nagent = architecture+program\ntypes of agents:simple reflex agent\nmodel-based reflex agent\ngoal-based agent\nutility-based agent\nlearning agent(All agents can improve their performance through learning.)\n\ncomponent fo agent : atomic representation, factored representation, structured representation\n\n\n \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* **Percept sequence** - everything from past to present the agent has perceived\n* **Other concept** - your definitions here\n* **Etc.** - your definitions here\n* **Rational agent** - for each step, rational agent should act that maximizes its performance measure. \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": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 209
        },
        "outputId": "e4e99835-ac8f-4d30-9713-ad97983dcd5b"
      },
      "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": null,
      "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 = \"\"\"\n",
        "evironment: fully observable, deterministic\n",
        "four phase problem solving process: goal formulation, problem formulation(abstract model about states and action), search(find a sequence to reach the goal), execution;\\\n",
        "open-loop system: since solution is guranteed and not change, machine does not need to percept environment.\\\n",
        "close-loop system: machine need to percept the environment and change its action since the environment may change.(not fully observable or non deterministic0)\\\n",
        "\n",
        "search problems and solutions:\\\n",
        "state space, initial state, goal state, action, transition model, action cost function.\n",
        "\n",
        "to show the problem, we can use a graph to describe it: arc is action, vertice is point.\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter3_2 = \"\"\"\n",
        "standardized problems: grid world, route finding\n",
        "real world problems: travel-planning Web, TSP(traveling salesperson problem), VLSI, Robot navigation\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter3_3 = \"\"\"\n",
        "\n",
        "difference between state space and search tree: state space displays all possible state, while search tree shows the path between nodes.\n",
        "\n",
        "Best-first search, every step we choose node with lowest cost function f(n) to check goal and expand.\n",
        "frontier: queue of nodes that need to expand. usually we use a queue to store based on f(n). priority queue, FIFO(BFS),LIFO(DFS)\n",
        "expand: generate its child node to frontier if its child node was never reached, or update if it has a lower path cost than its previous.\n",
        "\n",
        "\n",
        "search node : node.STATE, node.Parent, node.Action, node.Path-Cost\n",
        "\n",
        "Search tree : has repeated state by cycle(loopy path), might be infinite. has redundant path\n",
        "\n",
        "how to reduce redundant path: 1. remember reached states. 2. some problem formulation does not generate or expand repeated state.\\\n",
        "3. use node.Parent to check whether its Parent == itself. \n",
        "\n",
        "how to measure algo performance : completeness, optimality. Time complexity, Space complexity.\n",
        "\n",
        "different f(n)\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter3_4 = \"\"\" Breadth first search: suppose all action has the same cost \\\n",
        "f(n): the number of actions it takes to reach the node. using FIFO queue is better than priority queue, which can do early goal test\\\n",
        "rather than late goal test.  always find a solution with a minimal number of action.\n",
        "O(b^d), S(b^d)\n",
        "\n",
        "Uniform cost search(Dijkstra's algorithm)  : action have different costs. weighted graph.\\\n",
        "f(n): path cost\n",
        "using late goal test. test for goals when it expand node not generate node\n",
        "not always find a solution with a minimal number of action but with minimal cost path.\n",
        "O(b^(1+⌊C∗/ǫ⌋))(much greater than b^d) When all action costs are equal, b1+⌊C∗/ǫ⌋ is just b^(d+1)\\\n",
        "C^∗\n",
        "\n",
        "Depth first search : f(n) negative of the depth\n",
        "always expand deepest node in the frontier first. usually implemented as a tree-like search that not keep reached node\\\n",
        "not complete, not optimal but save space.\n",
        "O(b^m)\n",
        "S(bm) m is the maximum depth of the tree\\\n",
        "\n",
        "Depth-limited and iterative deepening search\n",
        "not complete, not optimal\\\n",
        "set a limit depth for DFS, if depth is large than l then cutoff \\ \n",
        "can eliminate cycles by trace the parent chain\n",
        "O(b^l) S(b^l) \\\n",
        "\n",
        "Iterative deepening search:\n",
        "iterativly select l for Depth limited search\n",
        "O(b^d) S(bd) or O(b^m), S(bm) when there is no solution\n",
        "advantage: complete, optimal, save space\n",
        "disadvantage: does not have reached set, so might viste same state severla times. also has risk to be caught in a loop.\\\n",
        "N(IDS) = (d)b^1 +(d−1)b^2+(d−2)b^3 · · ·+b^d, therefore won't regenerate too much node to waste.\\\n",
        "\n",
        "\n",
        "Bidirectional search\n",
        "simulaneously search forward and backward from initial state and goal state.\n",
        "b^(d/2) + b^(d/2) is less than b^d\n",
        "try to find two direction's intersection. when A's frontier has a state that is also in B's frontier, the path is connected.\n",
        "but the first solution is not necessarily the optimal. \n",
        "it depends on what f(n) it will use. \n",
        "if f(n) is path cost, then is bidirectional uniform-cost search, if the cost is the optimal path C^*, node with cost > C*/2 will not be expanded.\\\n",
        "this method will be optimal.\n",
        "\n",
        "for other f(n), we need store solutions, and compare them to find best solution.\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\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",
        "\"path\" : \"order/sequence of actions\",\n",
        "\"solution\" : \"a path from initial to goal state.\",\n",
        "\"optimal solution\" : \"a solution that has the lowest total cost\",\n",
        "\"uninformed search\" : \"don't know distance from its current state to goal state. \"\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "34f48f9b-3d20-4974-9995-2e84d31be532"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n\nevironment: fully observable, deterministic\nfour phase problem solving process: goal formulation, problem formulation(abstract model about states and action), search(find a sequence to reach the goal), execution;open-loop system: since solution is guranteed and not change, machine does not need to percept environment.close-loop system: machine need to percept the environment and change its action since the environment may change.(not fully observable or non deterministic0)\nsearch problems and solutions:state space, initial state, goal state, action, transition model, action cost function.\n\nto show the problem, we can use a graph to describe it: arc is action, vertice is point.\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 3.2 Example Problems\n\nstandardized problems: grid world, route finding\nreal world problems: travel-planning Web, TSP(traveling salesperson problem), VLSI, Robot navigation\n\n\n \n\n## AIMA Chapter 3.3 Search Algorithms\n\n\ndifference between state space and search tree: state space displays all possible state, while search tree shows the path between nodes.\n\nBest-first search, every step we choose node with lowest cost function f(n) to check goal and expand.\nfrontier: queue of nodes that need to expand. usually we use a queue to store based on f(n). priority queue, FIFO(BFS),LIFO(DFS)\nexpand: generate its child node to frontier if its child node was never reached, or update if it has a lower path cost than its previous.\n\n\nsearch node : node.STATE, node.Parent, node.Action, node.Path-Cost\n\nSearch tree : has repeated state by cycle(loopy path), might be infinite. has redundant path\n\nhow to reduce redundant path: 1. remember reached states. 2. some problem formulation does not generate or expand repeated state.3. use node.Parent to check whether its Parent == itself. \n\nhow to measure algo performance : completeness, optimality. Time complexity, Space complexity.\n\ndifferent f(n)\n\n\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n Breadth first search: suppose all action has the same cost f(n): the number of actions it takes to reach the node. using FIFO queue is better than priority queue, which can do early goal testrather than late goal test.  always find a solution with a minimal number of action.\nO(b^d), S(b^d)\n\nUniform cost search(Dijkstra's algorithm)  : action have different costs. weighted graph.f(n): path cost\nusing late goal test. test for goals when it expand node not generate node\nnot always find a solution with a minimal number of action but with minimal cost path.\nO(b^(1+⌊C∗/ǫ⌋))(much greater than b^d) When all action costs are equal, b1+⌊C∗/ǫ⌋ is just b^(d+1)C^∗\n\nDepth first search : f(n) negative of the depth\nalways expand deepest node in the frontier first. usually implemented as a tree-like search that not keep reached nodenot complete, not optimal but save space.\nO(b^m)\nS(bm) m is the maximum depth of the tree\nDepth-limited and iterative deepening search\nnot complete, not optimalset a limit depth for DFS, if depth is large than l then cutoff \\ \ncan eliminate cycles by trace the parent chain\nO(b^l) S(b^l) \nIterative deepening search:\niterativly select l for Depth limited search\nO(b^d) S(bd) or O(b^m), S(bm) when there is no solution\nadvantage: complete, optimal, save space\ndisadvantage: does not have reached set, so might viste same state severla times. also has risk to be caught in a loop.N(IDS) = (d)b^1 +(d−1)b^2+(d−2)b^3 · · ·+b^d, therefore won't regenerate too much node to waste.\n\nBidirectional search\nsimulaneously search forward and backward from initial state and goal state.\nb^(d/2) + b^(d/2) is less than b^d\ntry to find two direction's intersection. when A's frontier has a state that is also in B's frontier, the path is connected.\nbut the first solution is not necessarily the optimal. \nit depends on what f(n) it will use. \nif f(n) is path cost, then is bidirectional uniform-cost search, if the cost is the optimal path C^*, node with cost > C*/2 will not be expanded.this method will be optimal.\n\nfor other f(n), we need store solutions, and compare them to find best solution.\n\n\n\n\n\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* **Path** - order/sequence of actions\n* **Solution** - a path from initial to goal state.\n* **Optimal solution** - a solution that has the lowest total cost\n* **Uninformed search** - don't know distance from its current state to goal state. \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 = \"\"\" \n",
        "\n",
        "heuristic function : h(n) = estimated cost of the cheapest path from the state at node n to a goal state.\n",
        "\n",
        "Greedy best-first search: \n",
        "f(n) = h(n)\n",
        "h(n) is not from problem itself but from the world knowledge.\n",
        "not optimal, complete in finite state space, but incomplete in infinite state space.\n",
        "always focus next step, not the whole states. kind of short sighted but is goal guided.\\\n",
        "it will not expand a node that is not on the solution path, which might fast(always find shorpath) but miss some best path that at first it seems twisting but finally have a good result.\\\n",
        "worst case : O(|V|), but if good h(n), it might reach O(bm).\n",
        "\n",
        "\n",
        "A* search: \n",
        "\n",
        "f(n) = g(n) + h(n), estimated cost of the best path that continues from n to a goal.\\\n",
        "\n",
        "complete, optimal if h(n) is admissible/optimistic (which means never overestimates the cost to reach the goal)\\\n",
        "\n",
        "Admissiblity: if h*(n) represent real minimal cost from n to goal, then h(n) <= h*(n)\\\n",
        "\n",
        "\n",
        "if for every node and action, h(n) ≤ c(n,a,n′)+h(n′). h(n) is consistent. (triangle inequality)\\\n",
        "\n",
        "consistent h(x) is admissible but admissible h(x) is not necessarily consistent.\\\n",
        "\n",
        "for consistent h(x), we don't need to update reached, but just add new node, since every new node is on the optimal path.\n",
        "even for inconsistent h(x), we may still have same path if each new path has a lower path cost than the previous.(if we find better path\\\n",
        "we can update in the fronier tracing parent and children)\\\n",
        "\n",
        "non admissible h(n) not necessarily can not reach a optimal solution, if the optimal solution has cost C∗, and the second-best has cost C2,\\ \n",
        "and if h(n) overestimates some costs, but never by more than C2 −C∗, then A∗ is guaranteed to return cost-optimal solutions.\n",
        "\n",
        "search contours: stretch toward the goal and become more narrowly focused around optimal path. (contour lines won't cross each other) line is between two node\\\n",
        "if h(n) is consistent then path cost f(n) will monotonically increase.\\\n",
        "\n",
        "A* might expand some node on the goal contour.\n",
        "A* expand no node with f(n) > C*.\n",
        "\n",
        "A* can prune search node that not lead to optimal solution(for n that f(n)> C*).\\\n",
        "\n",
        "satisficing search: inadmissible heuristics and weighted A* (because A* expand too much nodes)\n",
        "f (n) = g(n)+W ×h(n), W > 1.\n",
        "might overestimate but save time expanding nodes. it focuses more towards the goal than admissible A*\\\n",
        "\n",
        "\n",
        "bounded suboptimal search: solution is guaranteed within a constant factor W.\n",
        "bounded cost search : search solution that its cost less than specified cost C.\n",
        "unbounded cost search(speedy search) : no matter cost is, just find solution. quite like greedy best first search.\n",
        "\n",
        "IDA,RBFS(backed up value, optimal)\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter3_6 = \"\"\" \n",
        "effective branching factor b∗\n",
        "N +1 = 1+b∗+(b∗)2+· · ·+(b∗)d\n",
        "\n",
        "A well-designed heuristic would have a value of b∗ close to 1, allowing fairly large problems to be solved at reasonable computational cost\\\n",
        "\n",
        "\n",
        "effective depth\n",
        "O(b^(d−kh) )\n",
        "\n",
        "h2(n) ≥ h1(n) h2 dominates h1, h2 expand less nodes\n",
        "\n",
        "relaxed problem: remove restriction on actions to generate more admissable h(n) which is a supergraph of the original state.\n",
        "\n",
        "pattern database : store subproblem costs to generate h(n)\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module4_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module4_definitions = {\n",
        "\"surely expanded nodes\" : \"if node's f(n) < actual cost(C*), then the node is called surely expanded node which means will be expanded by A*\",\n",
        "\"optimally efficient\" : \"expand all nodes that are f(n) < actual cost(SEN)\"\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 922
        },
        "cellView": "form",
        "outputId": "4244f511-afcf-40ec-fb62-98c1db9c74f6"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "## WARNING: Your definition of 'surely expanded nodes' is too long!\n# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n \n\nheuristic function : h(n) = estimated cost of the cheapest path from the state at node n to a goal state.\n\nGreedy best-first search: \nf(n) = h(n)\nh(n) is not from problem itself but from the world knowledge.\nnot optimal, complete in finite state space, but incomplete in infinite state space.\nalways focus next step, not the whole states. kind of short sighted but is goal guided.it will not expand a node that is not on the solution path, which might fast(always find shorpath) but miss some best path that at first it seems twisting but finally have a good result.worst case : O(|V|), but if good h(n), it might reach O(bm).\n\n\nA* search: \n\nf(n) = g(n) + h(n), estimated cost of the best path that continues from n to a goal.\ncomplete, optimal if h(n) is admissible/optimistic (which means never overestimates the cost to reach the goal)\nAdmissiblity: if h*(n) represent real minimal cost from n to goal, then h(n) <= h*(n)\n\nif for every node and action, h(n) ≤ c(n,a,n′)+h(n′). h(n) is consistent. (triangle inequality)\nconsistent h(x) is admissible but admissible h(x) is not necessarily consistent.\nfor consistent h(x), we don't need to update reached, but just add new node, since every new node is on the optimal path.\neven for inconsistent h(x), we may still have same path if each new path has a lower path cost than the previous.(if we find better pathwe can update in the fronier tracing parent and children)\nnon admissible h(n) not necessarily can not reach a optimal solution, if the optimal solution has cost C∗, and the second-best has cost C2,\\ \nand if h(n) overestimates some costs, but never by more than C2 −C∗, then A∗ is guaranteed to return cost-optimal solutions.\n\nsearch contours: stretch toward the goal and become more narrowly focused around optimal path. (contour lines won't cross each other) line is between two nodeif h(n) is consistent then path cost f(n) will monotonically increase.\nA* might expand some node on the goal contour.\nA* expand no node with f(n) > C*.\n\nA* can prune search node that not lead to optimal solution(for n that f(n)> C*).\nsatisficing search: inadmissible heuristics and weighted A* (because A* expand too much nodes)\nf (n) = g(n)+W ×h(n), W > 1.\nmight overestimate but save time expanding nodes. it focuses more towards the goal than admissible A*\n\nbounded suboptimal search: solution is guaranteed within a constant factor W.\nbounded cost search : search solution that its cost less than specified cost C.\nunbounded cost search(speedy search) : no matter cost is, just find solution. quite like greedy best first search.\n\nIDA,RBFS(backed up value, optimal)\n\n\n\n \n\n## AIMA Chapter 3.6 Heuristic Functions\n \neffective branching factor b∗\nN +1 = 1+b∗+(b∗)2+· · ·+(b∗)d\n\nA well-designed heuristic would have a value of b∗ close to 1, allowing fairly large problems to be solved at reasonable computational cost\n\neffective depth\nO(b^(d−kh) )\n\nh2(n) ≥ h1(n) h2 dominates h1, h2 expand less nodes\n\nrelaxed problem: remove restriction on actions to generate more admissable h(n) which is a supergraph of the original state.\n\npattern database : store subproblem costs to generate h(n)\n\n\n\n\n\n\n\n\n \n\n## Module 4 Lecture Notes\n Your summary here \n\n## Module 4 Definitions\n* **Surely expanded nodes** - if node's f(n) < actual cost(C*), then the node is called surely expanded node which means will be expanded by A*\n* **Optimally efficient** - expand all nodes that are f(n) < actual cost(SEN)\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 5 - Adversarial Search and Games"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA chapter 5 \"Adversarial Search\"”\" (5.1-5.3, and 5.5).\n",
        "chapter5_1 = \"\"\" \n",
        "three stances for multi-agent : general economy, adversatial agent as a part of environment. model adversarial game tree search.\\\n",
        "perfect information : fully observable\n",
        "zero-sum: one gain, one lose\\\n",
        "\n",
        "game problem define : initial state, ToMove(the turn for player), action, transition(result), is_terminal, utility.\\\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter5_2 = \"\"\" move: both players finish one round play\\\n",
        "\n",
        "ply: one move by one player.\n",
        "\n",
        "minimax value is the utility for max player.\n",
        "\n",
        "strategy : for Max : Math.max(Min(state)), for Min : Math.min(Max(state))\n",
        "\n",
        "\n",
        "MiniMax : go through whole tree until to the terminal states(leaves), compare leaves value then determine backup value and move\\\n",
        "to its parent node. this is a complete, O(b^m),S(bm) if is backtraking then is S(m)  \n",
        "Disadvantage : exponential time, which make algo impractical\n",
        "\n",
        "if is a multiplayer game(>2 players) , we need to store utility value using vector <va,vb,vc>\n",
        "\n",
        "\n",
        "\n",
        "alpha-beta Pruning: describe bounds on the backed up values(the worst case think pessimisticlly),can prune entire subtrees\\\n",
        "alpha : the lowest bound (at least value )along the path for max\\ \n",
        "beta : the highest bound (at most value) along the path for min\\\n",
        "generally, alpha-beta search will prune the remainig branch if the value of the current node is known to be worse than alpha or beta.\n",
        "for max, if alpha(root tree) > beta(subtree) in the path then we can prune the beta subtree.\n",
        "for min, if beta(root tree) < alpha(subtree) in the path, then we can prune the alpha subtree.\n",
        "\n",
        "\n",
        "if done perfectly O(b^(m/2)), braching factor = b^(1/2), randomly (b^(3m/4)) \n",
        "\n",
        "iterative deepening \n",
        "transpositon table that store h(n) to reduce redundant path\n",
        "\n",
        "A strategy(h(n) estimate ulitilty, wide and shallow tree)\n",
        "B strategy(ignore some move looks bad, explore deep and narrow tree)\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter5_3 = \"\"\" \n",
        "\n",
        "replace the ulility function with evaluation function (g(n)-->h(n)) estimate a state's utility.\n",
        "replace the terminal test by cutoff test(depth limited)\n",
        "for terminal states: EVAL(s,p) = UTILITY(s,p)\n",
        "for nonterminal states: UTILITY(loss, p) ≤ EVAL(s, p) ≤ UTILITY(win, p)\\\n",
        "\n",
        "evaluation calculates many features of the state, using some function to calculate (expected value)possiblity value to win or loss.\n",
        "weighted linear function allocate value for every feature and calculate sum: EVAL(s) = w1 f1(s)+w2 f2(s)+···+wnf(s)(assumpthion\\\n",
        "every feature is independent) from our experience.\\\n",
        "\n",
        "how to find a depth to cutoff? sometimes just set a depth then iterative deepen but it might choose wrong move.\\\n",
        "therefore evaluation function back position should be quiescent that is no pending move (quiescence search)\n",
        "\n",
        "use singular extension to mitigate horizon effect\n",
        "\n",
        "\n",
        "\n",
        "Forward pruning B type, think ahead to eliminate some moves \n",
        "\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter5_5 = \"\"\" \n",
        "expectiminimax: we use expected value rather than minimax value to solve stochastic games\\\n",
        "\n",
        "evaluation function should return value that positive linear transformation of probability of wining.\\\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 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module5_lecture_notes = \"\"\" \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module5_definitions = {\n",
        "\"stochastic games\" : \" uncertain outcome in the playing \" \n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "1f9a9840-370f-4c08-80a1-f7b2e6089683"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n \nthree stances for multi-agent : general economy, adversatial agent as a part of environment. model adversarial game tree search.perfect information : fully observable\nzero-sum: one gain, one lose\ngame problem define : initial state, ToMove(the turn for player), action, transition(result), is_terminal, utility.\n\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n move: both players finish one round play\nply: one move by one player.\n\nminimax value is the utility for max player.\n\nstrategy : for Max : Math.max(Min(state)), for Min : Math.min(Max(state))\n\n\nMiniMax : go through whole tree until to the terminal states(leaves), compare leaves value then determine backup value and moveto its parent node. this is a complete, O(b^m),S(bm) if is backtraking then is S(m)  \nDisadvantage : exponential time, which make algo impractical\n\nif is a multiplayer game(>2 players) , we need to store utility value using vector <va,vb,vc>\n\n\n\nalpha-beta Pruning: describe bounds on the backed up values(the worst case think pessimisticlly),can prune entire subtreesalpha : the lowest bound (at least value )along the path for max\\ \nbeta : the highest bound (at most value) along the path for mingenerally, alpha-beta search will prune the remainig branch if the value of the current node is known to be worse than alpha or beta.\nfor max, if alpha(root tree) > beta(subtree) in the path then we can prune the beta subtree.\nfor min, if beta(root tree) < alpha(subtree) in the path, then we can prune the alpha subtree.\n\n\nif done perfectly O(b^(m/2)), braching factor = b^(1/2), randomly (b^(3m/4)) \n\niterative deepening \ntranspositon table that store h(n) to reduce redundant path\n\nA strategy(h(n) estimate ulitilty, wide and shallow tree)\nB strategy(ignore some move looks bad, explore deep and narrow tree)\n\n\n\n \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \n\nreplace the ulility function with evaluation function (g(n)-->h(n)) estimate a state's utility.\nreplace the terminal test by cutoff test(depth limited)\nfor terminal states: EVAL(s,p) = UTILITY(s,p)\nfor nonterminal states: UTILITY(loss, p) ≤ EVAL(s, p) ≤ UTILITY(win, p)\nevaluation calculates many features of the state, using some function to calculate (expected value)possiblity value to win or loss.\nweighted linear function allocate value for every feature and calculate sum: EVAL(s) = w1 f1(s)+w2 f2(s)+···+wnf(s)(assumpthionevery feature is independent) from our experience.\nhow to find a depth to cutoff? sometimes just set a depth then iterative deepen but it might choose wrong move.therefore evaluation function back position should be quiescent that is no pending move (quiescence search)\n\nuse singular extension to mitigate horizon effect\n\n\n\nForward pruning B type, think ahead to eliminate some moves \n\n\n\n\n \n\n## AIMA Chapter 5.5 Stochastic Games\n \nexpectiminimax: we use expected value rather than minimax value to solve stochastic games\nevaluation function should return value that positive linear transformation of probability of wining.\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 Your summary here \n\n## Module 5 Lecture Notes\n \n\n## Module 5 Definitions\n* **Stochastic games** -  uncertain outcome in the playing \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 = \"\"\" \n",
        "\n",
        "for nomal search problem, we usually treat every state as a black box, but for CSPs problem, we use factored representation\\\n",
        "in the state: we got variables and try to make every value comply with each others.\n",
        "do not need actions and transition function in the problem description.\n",
        "\n",
        "enumerate:h(X1,X2),{(3,1), (3,2), (2,1)} or  abbreviation(h(X1,X2),X1 > X2i)\n",
        "\n",
        "CSP solution: a consistent and complete assignment. it's an NP problem\\\n",
        "\n",
        "\n",
        "advantage of CSP, it can prune large nodes in the search space that atomic state search can not\\\n",
        "that is if we find partial assignment violates constraint we can discard any node include that status.\\\n",
        "also, we can know which variable violate constraints so that we can focus on that variable.\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "type of constraints : unary constraint, binary constraint ,higher-order constraint(related variables>2),\\\n",
        "global constraint(arbitrary constraint,ex All diff)\n",
        "\n",
        "finite-domain constraint can be transfered to a set of binary constraints using auxiliary variables\n",
        "sometimes we can shift constraints to variables and shift original constraints'values to domain values\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter6_2 = \"\"\"\n",
        "\n",
        "\n",
        "compared with atomic search, CSP can discard some value assignment to do some constraint propagation, \\\n",
        "and also choose some variable assignment. (local consistency)\\\n",
        "\n",
        "\n",
        "AC-3 algorithm: queue contains all arcs(in 2 directions), then check every arc whether they are arc consistent. \\\n",
        "if revise Di, add(Xk,Xi) in the queue, Xk is neighborof Xi not include Xj\n",
        "\n",
        "function AC-3(csp) returns false if an inconsistency is found and true otherwise\\\n",
        "queue←a queue of arcs, initially all the arcs in csp\\\n",
        "while queue is not empty do\\\n",
        "  (Xi, Xj)←POP(queue)\\\n",
        "  if REVISE(csp, Xi, Xj) then\\\n",
        "    if size of Di = 0 then return false\\\n",
        "    for each Xk in Xi.NEIGHBORS - {Xj} do\\\n",
        "    add (Xk, Xi) to queue\\\n",
        "  return true\\\n",
        "function REVISE(csp, Xi, Xj) returns true iff we revise the domain of Xi\\\n",
        "  revised←false\\\n",
        "  for each x in Di do\\\n",
        "    if no value y in Dj allows (x,y) to satisfy the constraint between Xi and Xj then\\\n",
        "    delete x from Di\\\n",
        "    revised←true\\\n",
        "return revised\\\n",
        "\n",
        "O(cd^3)\n",
        "\n",
        "for strongly k-consistency O(d*n^2)\n",
        "\n",
        " \"\"\"\n",
        "chapter6_3 = \"\"\" \n",
        "Backtracking Search: after pruning, DFS, only focus on single variables \n",
        "\n",
        "n variables , domain size d\n",
        "\n",
        "function BACKTRACKING-SEARCH(csp) returns a solution or failure\n",
        "  return BACKTRACK(csp, {})\n",
        "\n",
        "function BACKTRACK(csp, assignment) returns a solution or failure\n",
        "  if assignment is complete then return assignment\n",
        "  var←SELECT-UNASSIGNED-VARIABLE(csp, assignment)\n",
        "  for each value in ORDER-DOMAIN-VALUES(csp, var, assignment) do\n",
        "    if value is consistent with assignment then\n",
        "      add {var = value} to assignment\n",
        "      inferences←INFERENCE(csp, var, assignment)\n",
        "      if inferences 6= failure then\n",
        "        add inferences to csp\n",
        "        result←BACKTRACK(csp, assignment)\n",
        "        if result 6= failure then return result\n",
        "        remove inferences from csp\n",
        "      remove {var = value} from assignment\n",
        "return failure\n",
        "\n",
        "\n",
        "\n",
        "In forward checking, whenever a variable XX is assigned, we establish arc consistency for XX\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "chapter6_4 = \"\"\" MAC do search and inference. AC-3 is juest pure inference.\n",
        "\n",
        "MAC only queue arc incident on the assigned variable.\n",
        "\n",
        " \"\"\"\n",
        "chapter6_5 = \"\"\" Tree decomposition techniques transform the CSP into a tree of subproblems.\n",
        "Tree decomposition subproblems are efficient if the tree width of the constraint graph is small \n",
        "Cutset conditioning save space( linear memory), tree decomosition(exponential memory) save time\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module6_lecture_notes = \"\"\" CSPs represent with a set of variable/value pairs(the conditions for a solution with set of constraints)\n",
        "CSP has 2 ruling out variable assignments (choose value assignment, constraint propagation),using search or inference to rule out possible value.\n",
        "inference use constraints to rule out(idea is enforcing k-consistency).\n",
        "\n",
        "Backtracking occurs when no legal assignment can be found for a variable.\n",
        "MRV heuristic stands for Minimum Remaining Value, which chooses the variable with the fewest legal values\n",
        "The degree heuristic chooses the variable with the largest number of constraints.\n",
        "The least constraining value heuristic chooses the value that rules out the fewest values for neighboring variables.\n",
        "Constraint learning records the conflicts as they are encountered in the search in order to avoid the same conflict later\n",
        "Solving an arbitrary CSP takes expoential time in the number of variables, while solving a tree-structued CSP takes time in the number of variables\n",
        "\n",
        "Cutset conditioning is used to reduce a general CSP to a tree structured one \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module6_definitions = {\n",
        "\"consistent\" : \"does not make conflict with other variables\",  \n",
        "\"complete\" : \"every variable has some value rather than empty set\"  ,\n",
        "\"precedence constraints\" : \"some variables have order constraint\",\n",
        "\"preference constraints\" : \"some variables's values are preferred but not must be \",\n",
        "\"node-consistent\": \"for a specific variable, its all possible values are meet the unary constraints, even it may violate binary constraints\",\n",
        "\"arc-consistent\" : \"variable's all values obey binary constraints,(Di,Dj),Di must find a value in Dj which can be related\",\n",
        "\"CSP arc-consistent\" : \" for every variable in CSP, it is arc-consistent(it and its related variables are mutually arc consistent)\",\n",
        "\n",
        "\"Path-consitency\" : \"find a middle variable m, for every value in variables{Xi,Xj} complys {Xi,Xm} and {Xm,XJ}}\",\n",
        "\"k-consistency\" : \" for constraint {v1, v2, v3 ,....vk-1}, any consistent value assignment in this set can be consist with kth variable value\",\n",
        "\n",
        "\"strongly k-consistent\" : \"k consistent, (k-1)consitent, k-2 consistent, 1 consistent\",\n",
        "\"bounds - consistent\" : \"every variable X, there exists some value of Y that satisfies the constraint between X and Y for every variable Y\",\n",
        "\"MAC\" : \"Maintaing Arc Consistency,recursively propogrates constraints\"\n",
        "}\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "0c8ce361-2abc-4fb4-9411-b72a27a7203b"
      },
      "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": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "## WARNING: Your definition of 'k-consistency' is too long!\nWARNING: Your definition of 'bounds - consistent' is too long!\n# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n \n\nfor nomal search problem, we usually treat every state as a black box, but for CSPs problem, we use factored representationin the state: we got variables and try to make every value comply with each others.\ndo not need actions and transition function in the problem description.\n\nenumerate:h(X1,X2),{(3,1), (3,2), (2,1)} or  abbreviation(h(X1,X2),X1 > X2i)\n\nCSP solution: a consistent and complete assignment. it's an NP problem\n\nadvantage of CSP, it can prune large nodes in the search space that atomic state search can notthat is if we find partial assignment violates constraint we can discard any node include that status.also, we can know which variable violate constraints so that we can focus on that variable.\n\n\n\n\ntype of constraints : unary constraint, binary constraint ,higher-order constraint(related variables>2),global constraint(arbitrary constraint,ex All diff)\n\nfinite-domain constraint can be transfered to a set of binary constraints using auxiliary variables\nsometimes we can shift constraints to variables and shift original constraints'values to domain values\n\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n\n\n\ncompared with atomic search, CSP can discard some value assignment to do some constraint propagation, and also choose some variable assignment. (local consistency)\n\nAC-3 algorithm: queue contains all arcs(in 2 directions), then check every arc whether they are arc consistent. if revise Di, add(Xk,Xi) in the queue, Xk is neighborof Xi not include Xj\n\nfunction AC-3(csp) returns false if an inconsistency is found and true otherwisequeue←a queue of arcs, initially all the arcs in cspwhile queue is not empty do  (Xi, Xj)←POP(queue)  if REVISE(csp, Xi, Xj) then    if size of Di = 0 then return false    for each Xk in Xi.NEIGHBORS - {Xj} do    add (Xk, Xi) to queue  return truefunction REVISE(csp, Xi, Xj) returns true iff we revise the domain of Xi  revised←false  for each x in Di do    if no value y in Dj allows (x,y) to satisfy the constraint between Xi and Xj then    delete x from Di    revised←truereturn revised\nO(cd^3)\n\nfor strongly k-consistency O(d*n^2)\n\n \n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n \nBacktracking Search: after pruning, DFS, only focus on single variables \n\nn variables , domain size d\n\nfunction BACKTRACKING-SEARCH(csp) returns a solution or failure\n  return BACKTRACK(csp, {})\n\nfunction BACKTRACK(csp, assignment) returns a solution or failure\n  if assignment is complete then return assignment\n  var←SELECT-UNASSIGNED-VARIABLE(csp, assignment)\n  for each value in ORDER-DOMAIN-VALUES(csp, var, assignment) do\n    if value is consistent with assignment then\n      add {var = value} to assignment\n      inferences←INFERENCE(csp, var, assignment)\n      if inferences 6= failure then\n        add inferences to csp\n        result←BACKTRACK(csp, assignment)\n        if result 6= failure then return result\n        remove inferences from csp\n      remove {var = value} from assignment\nreturn failure\n\n\n\nIn forward checking, whenever a variable XX is assigned, we establish arc consistency for XX\n\n\n\n\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n MAC do search and inference. AC-3 is juest pure inference.\n\nMAC only queue arc incident on the assigned variable.\n\n \n\n## AIMA Chapter 6.5 The Structure of Problems\n Tree decomposition techniques transform the CSP into a tree of subproblems.\nTree decomposition subproblems are efficient if the tree width of the constraint graph is small \nCutset conditioning save space( linear memory), tree decomosition(exponential memory) save time\n\n\n## Module 6 Lecture Notes\n CSPs represent with a set of variable/value pairs(the conditions for a solution with set of constraints)\nCSP has 2 ruling out variable assignments (choose value assignment, constraint propagation),using search or inference to rule out possible value.\ninference use constraints to rule out(idea is enforcing k-consistency).\n\nBacktracking occurs when no legal assignment can be found for a variable.\nMRV heuristic stands for Minimum Remaining Value, which chooses the variable with the fewest legal values\nThe degree heuristic chooses the variable with the largest number of constraints.\nThe least constraining value heuristic chooses the value that rules out the fewest values for neighboring variables.\nConstraint learning records the conflicts as they are encountered in the search in order to avoid the same conflict later\nSolving an arbitrary CSP takes expoential time in the number of variables, while solving a tree-structued CSP takes time in the number of variables\n\nCutset conditioning is used to reduce a general CSP to a tree structured one \n\n## Module 6 Definitions\n* **Consistent** - does not make conflict with other variables\n* **Complete** - every variable has some value rather than empty set\n* **Precedence constraints** - some variables have order constraint\n* **Preference constraints** - some variables's values are preferred but not must be \n* **Node-consistent** - for a specific variable, its all possible values are meet the unary constraints, even it may violate binary constraints\n* **Arc-consistent** - variable's all values obey binary constraints,(Di,Dj),Di must find a value in Dj which can be related\n* **Csp arc-consistent** -  for every variable in CSP, it is arc-consistent(it and its related variables are mutually arc consistent)\n* **Path-consitency** - find a middle variable m, for every value in variables{Xi,Xj} complys {Xi,Xm} and {Xm,XJ}}\n* **K-consistency** -  for constraint {v1, v2, v3 ,....vk-1}, any consistent value assignment in this set can be consist with kth variable value\n* **Strongly k-consistent** - k consistent, (k-1)consitent, k-2 consistent, 1 consistent\n* **Bounds - consistent** - every variable X, and for both the lower-bound Bounds-consistent and upper-bound values of X, there exists some value of Y that satisfies the constraint between X and Y for every variable Y\n* **Mac** - Maintaing Arc Consistency,recursively propogrates constraints\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 = \"\"\" \n",
        "\n",
        "function KB-AGENT(percept) returns an action\n",
        "  persistent: KB, a knowledge base\n",
        "    t, a counter, initially 0, indicating time\n",
        "  TELL(KB,MAKE-PERCEPT-SENTENCE(percept, t))\n",
        "  action ← ASK(KB,MAKE-ACTION-QUERY(t))\n",
        "  TELL(KB,MAKE-ACTION-SENTENCE(action, t))\n",
        "  t ← t + 1\n",
        "  return action\n",
        "\n",
        "using tell to update KB\n",
        "using ask to reasoning best action, both can include inference.\n",
        "\n",
        "the KB agent do three things: 1. Make percept sentence 2. MAKE ACTION QUERY \\\n",
        "extensive reasoning to make action decision 3. MAKE-ACTION-SENTENCE update KB action  \n",
        "\n",
        "need to combine declarative approach and procedural approach.\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "chapter7_2 = \"\"\"\n",
        "wumpus world : Performance measure, Environment, Actuators, Sensors.\n",
        "reasoning neighboring square based on its percept and reasoning\n",
        "Percept:[Stench,Breeze,Glitter,None,None]\n",
        "update reasoning information on the map/state\n",
        "\n",
        "what the agent can conclude should be guaranteed to be correct.\n",
        "\n",
        "\"\"\"\n",
        "chapter7_3 = \"\"\" \n",
        "\n",
        "how to make logic representation and logic reasoning?\n",
        "syntax & semantics\n",
        "semantics shoud be either true or false in a specific possible world(which is like context)\n",
        "\n",
        "If a sentence α is true in model（possible world）m, we say that m satisfies α or sometimes m is a model of α.\n",
        "We use the notation M(α) to mean the set of all models of α.\n",
        "\n",
        "α|=β if and only if M(α) ⊆ M(β)  a entails b, a is more stronger assertion.\n",
        "M(KB) ⊆ M(α)\n",
        "\n",
        "\n",
        "KB ⊢i α\n",
        "α is derived from KB by i” or “i derives α from KB\n",
        "\n",
        "an inference algorithm is complete if it can derive any sentence that is entailed.\n",
        "\n",
        "\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter7_4 = \"\"\" \n",
        "\n",
        "function TT-ENTAILS?(KB,α) returns true or false\n",
        "  inputs: KB, the knowledge base, a sentence in propositional logic\n",
        "    α, the query, a sentence in propositional logic\n",
        "  symbols←a list of the proposition symbols in KB and α\n",
        "  return TT-CHECK-ALL(KB,α, symbols, {})\n",
        "\n",
        "function TT-CHECK-ALL(KB,α, symbols,model) returns true or false\n",
        "  if EMPTY?(symbols) then\n",
        "    if PL-TRUE?(KB,model) then return PL-TRUE?(α,model)\n",
        "    else return true // when KB is false, always return true\n",
        "  else\n",
        "    P←FIRST(symbols)\n",
        "    rest←REST(symbols)\n",
        "    return (TT-CHECK-ALL(KB,α, rest,model ∪ {P = true}) and TT-CHECK-ALL(KB,α, rest,model ∪ {P = false }))\n",
        "\n",
        "the algorithm is sound and complete\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter7_5 = \"\"\" \n",
        "we can use search to find conclusion.\n",
        "INITIAL STATE: the initial knowledge base.\n",
        "ACTIONS: the set of actions consists of all the inference rules applied to all the sentences\n",
        "that match the top half of the inference rule.\n",
        "RESULT: the result of an action is to add the sentence in the bottom half of the inference\n",
        "rule.\n",
        "GOAL: the goal is a state that contains the sentence we are trying to prove.\n",
        "\n",
        "function PL-FC-ENTAILS?(KB, q) returns true or false\n",
        "  inputs: KB, the knowledge base, a set of propositional definite clauses\n",
        "    q, the query, a proposition symbol\n",
        "  count←a table, where count[c] is initially the number of symbols in clause c’s premise\n",
        "  inferred←a table, where inferred[s] is initially false for all symbols\n",
        "  queue←a queue of symbols, initially symbols known to be true in KB\n",
        "  while queue is not empty do\n",
        "    p←POP(queue)\n",
        "    if p = q then return true\n",
        "    if inferred[p] = false then\n",
        "      inferred[p]←true\n",
        "      for each clause c in KB where p is in c.PREMISE do\n",
        "        decrement count[c]\n",
        "        if count[c] = 0 then add c.CONCLUSION to queue\n",
        "  return false\n",
        "\n",
        "Forward chaining is data driven reasoning, derive from KB.\n",
        "\n",
        "Backward chaining is a form of goal-directed reasoning\n",
        "\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module7_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module7_definitions = {\n",
        "\"knowledge-based agents\" : \"agents use its internal knowledge to reason to make decisions\",   \n",
        "\"knowledge base(KB)\" : \"a set of sentences that are expressed by knoledge representation language.\",\n",
        "\"axiom\" : \"not concluded by other sentences\",\n",
        "\"inference\" : \"generate new knowldege from prior internal knowledge\",\n",
        "\"atomic sentence\" : \"just contain one argument without logic combination.\",\n",
        "\"validity/taytologies\" : \"if the sentence is true in all possible world\",\n",
        "\"Modus Ponens\" : \"if a to b and a are given then we can conclude b.(sufficient)\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1180
        },
        "outputId": "d4f407c2-d9b0-475b-f924-a25bcf84ec15"
      },
      "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": 31,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n \n\nfunction KB-AGENT(percept) returns an action\n  persistent: KB, a knowledge base\n    t, a counter, initially 0, indicating time\n  TELL(KB,MAKE-PERCEPT-SENTENCE(percept, t))\n  action ← ASK(KB,MAKE-ACTION-QUERY(t))\n  TELL(KB,MAKE-ACTION-SENTENCE(action, t))\n  t ← t + 1\n  return action\n\nusing tell to update KB\nusing ask to reasoning best action, both can include inference.\n\nthe KB agent do three things: 1. Make percept sentence 2. MAKE ACTION QUERY extensive reasoning to make action decision 3. MAKE-ACTION-SENTENCE update KB action  \n\nneed to combine declarative approach and procedural approach.\n\n\n\n\n## AIMA Chapter 7.2 The Wumpus World\n\nwumpus world : Performance measure, Environment, Actuators, Sensors.\nreasoning neighboring square based on its percept and reasoning\nPercept:[Stench,Breeze,Glitter,None,None]\nupdate reasoning information on the map/state\n\nwhat the agent can conclude should be guaranteed to be correct.\n\n\n\n## AIMA Chapter 7.3 Logic\n \n\nhow to make logic representation and logic reasoning?\nsyntax & semantics\nsemantics shoud be either true or false in a specific possible world(which is like context)\n\nIf a sentence α is true in model（possible world）m, we say that m satisfies α or sometimes m is a model of α.\nWe use the notation M(α) to mean the set of all models of α.\n\nα|=β if and only if M(α) ⊆ M(β)  a entails b, a is more stronger assertion.\nM(KB) ⊆ M(α)\n\n\nKB ⊢i α\nα is derived from KB by i” or “i derives α from KB\n\nan inference algorithm is complete if it can derive any sentence that is entailed.\n\n\n\n\n \n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n \n\nfunction TT-ENTAILS?(KB,α) returns true or false\n  inputs: KB, the knowledge base, a sentence in propositional logic\n    α, the query, a sentence in propositional logic\n  symbols←a list of the proposition symbols in KB and α\n  return TT-CHECK-ALL(KB,α, symbols, {})\n\nfunction TT-CHECK-ALL(KB,α, symbols,model) returns true or false\n  if EMPTY?(symbols) then\n    if PL-TRUE?(KB,model) then return PL-TRUE?(α,model)\n    else return true // when KB is false, always return true\n  else\n    P←FIRST(symbols)\n    rest←REST(symbols)\n    return (TT-CHECK-ALL(KB,α, rest,model ∪ {P = true}) and TT-CHECK-ALL(KB,α, rest,model ∪ {P = false }))\n\nthe algorithm is sound and complete\n\n\n \n\n## AIMA 7.5 Propositional Theorem Proving\n \nwe can use search to find conclusion.\nINITIAL STATE: the initial knowledge base.\nACTIONS: the set of actions consists of all the inference rules applied to all the sentences\nthat match the top half of the inference rule.\nRESULT: the result of an action is to add the sentence in the bottom half of the inference\nrule.\nGOAL: the goal is a state that contains the sentence we are trying to prove.\n\nfunction PL-FC-ENTAILS?(KB, q) returns true or false\n  inputs: KB, the knowledge base, a set of propositional definite clauses\n    q, the query, a proposition symbol\n  count←a table, where count[c] is initially the number of symbols in clause c’s premise\n  inferred←a table, where inferred[s] is initially false for all symbols\n  queue←a queue of symbols, initially symbols known to be true in KB\n  while queue is not empty do\n    p←POP(queue)\n    if p = q then return true\n    if inferred[p] = false then\n      inferred[p]←true\n      for each clause c in KB where p is in c.PREMISE do\n        decrement count[c]\n        if count[c] = 0 then add c.CONCLUSION to queue\n  return false\n\nForward chaining is data driven reasoning, derive from KB.\n\nBackward chaining is a form of goal-directed reasoning\n\n\n \n\n## Module 7 Lecture Notes\n Your summary here \n\n## Module 7 Definitions\n* **Knowledge-based agents** - agents use its internal knowledge to reason to make decisions\n* **Knowledge base(kb)** - a set of sentences that are expressed by knoledge representation language.\n* **Axiom** - not concluded by other sentences\n* **Inference** - generate new knowldege from prior internal knowledge\n* **Atomic sentence** - just contain one argument without logic combination.\n* **Validity/taytologies** - if the sentence is true in all possible world\n* **Modus ponens** - if a to b and a are given then we can conclude b.(sufficient)\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": 6858
        },
        "id": "T3cm1WV542_a",
        "cellView": "code",
        "outputId": "cd96adce-1a93-4230-83ad-e45fde432d84"
      },
      "source": [
        "#@title 默认标题文本\n",
        "# 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": 30,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n Two dimension : human and rationality, thought and behavior. \nActing humanly: Turing test(NLP,Knoledge representation, automated reasoning, ML, CV, robotics) \\ \ninternal thought(thingking humanly): cognitive thinkingthinking rationally: logic & probability. from raw information to let machine understand the world and predict future.(not intelligent behavior)\\  \nacting rationally, agent: something that acts. Do the right thing(we define machine's objectives using cost function)(standard model).in reallity, we may not achieve perfect rationality because of limited computation.(limited rationality).Also, in reallity, standard model might not the final model because machine might not recognize the goal/objective completely(tradeoff the value alignment problem).\n\n\n\n\n\n\n## AIMA Chapter 27.1 The Limits of AI\n \nweak AI: machine imitate/simulate to act to reach desired result. just appearance, surface. strong AI: cand do real thinking like human. \n\n(Qualification problem)Turing think some argument are informal used by human, which can never be applied in a formal set on machineGood Old-Fashioned AI (GOFAL): intelligent behavior can be captured by rules and logical reasoning.\n\nembodied cognition: study from real enviroment rather than logic inference. can not separate cognition with body.\n\n\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n\nit's hard to define consciousness.(aware of subjective experience, itself, the world.)\nPolite convention: we can not know whether others have mental states, but we have polite conventionhuman has own subjective apparatus to think while machine only runs ode\"\"\\ \n\n \n\n## AIMA 2.1 Agents and Environments\n\nThe agent program implements the agent function\nagent problem is more practical and need more details to take into account.\nagent function is just abstract description\n\n\n \n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n\nrationality: doing the right thing.\nWe use performance measure to evaluate consequences that agent brings.\n\n\n\n\n## AIMA 2.3 The Nature of Environments\n \ntaks environment: PEAS (Performance, Environment, Actuators, Sensors)\n\nProperty of task environment:\nFully observable vs. partially observable\nSingle-agent vs. multiagent\nDeterministic vs. nondeterministic  stochastic(has possibility)\nEpisodic vs. sequential\nStatic vs. dynamic\nDiscrete vs. continuous\nKnown vs. unknown \n  \n\n## AIMA 2.4 The Structure of Agents\n \nagent = architecture+program\ntypes of agents:simple reflex agent\nmodel-based reflex agent\ngoal-based agent\nutility-based agent\nlearning agent(All agents can improve their performance through learning.)\n\ncomponent fo agent : atomic representation, factored representation, structured representation\n\n\n \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* **Percept sequence** - everything from past to present the agent has perceived\n* **Other concept** - your definitions here\n* **Etc.** - your definitions here\n* **Rational agent** - for each step, rational agent should act that maximizes its performance measure. \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\nevironment: fully observable, deterministic\nfour phase problem solving process: goal formulation, problem formulation(abstract model about states and action), search(find a sequence to reach the goal), execution;open-loop system: since solution is guranteed and not change, machine does not need to percept environment.close-loop system: machine need to percept the environment and change its action since the environment may change.(not fully observable or non deterministic0)\nsearch problems and solutions:state space, initial state, goal state, action, transition model, action cost function.\n\nto show the problem, we can use a graph to describe it: arc is action, vertice is point.\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 3.2 Example Problems\n\nstandardized problems: grid world, route finding\nreal world problems: travel-planning Web, TSP(traveling salesperson problem), VLSI, Robot navigation\n\n\n \n\n## AIMA Chapter 3.3 Search Algorithms\n\n\ndifference between state space and search tree: state space displays all possible state, while search tree shows the path between nodes.\n\nBest-first search, every step we choose node with lowest cost function f(n) to check goal and expand.\nfrontier: queue of nodes that need to expand. usually we use a queue to store based on f(n). priority queue, FIFO(BFS),LIFO(DFS)\nexpand: generate its child node to frontier if its child node was never reached, or update if it has a lower path cost than its previous.\n\n\nsearch node : node.STATE, node.Parent, node.Action, node.Path-Cost\n\nSearch tree : has repeated state by cycle(loopy path), might be infinite. has redundant path\n\nhow to reduce redundant path: 1. remember reached states. 2. some problem formulation does not generate or expand repeated state.3. use node.Parent to check whether its Parent == itself. \n\nhow to measure algo performance : completeness, optimality. Time complexity, Space complexity.\n\ndifferent f(n)\n\n\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n Breadth first search: suppose all action has the same cost f(n): the number of actions it takes to reach the node. using FIFO queue is better than priority queue, which can do early goal testrather than late goal test.  always find a solution with a minimal number of action.\nO(b^d), S(b^d)\n\nUniform cost search(Dijkstra's algorithm)  : action have different costs. weighted graph.f(n): path cost\nusing late goal test. test for goals when it expand node not generate node\nnot always find a solution with a minimal number of action but with minimal cost path.\nO(b^(1+⌊C∗/ǫ⌋))(much greater than b^d) When all action costs are equal, b1+⌊C∗/ǫ⌋ is just b^(d+1)C^∗\n\nDepth first search : f(n) negative of the depth\nalways expand deepest node in the frontier first. usually implemented as a tree-like search that not keep reached nodenot complete, not optimal but save space.\nO(b^m)\nS(bm) m is the maximum depth of the tree\nDepth-limited and iterative deepening search\nnot complete, not optimalset a limit depth for DFS, if depth is large than l then cutoff \\ \ncan eliminate cycles by trace the parent chain\nO(b^l) S(b^l) \nIterative deepening search:\niterativly select l for Depth limited search\nO(b^d) S(bd) or O(b^m), S(bm) when there is no solution\nadvantage: complete, optimal, save space\ndisadvantage: does not have reached set, so might viste same state severla times. also has risk to be caught in a loop.N(IDS) = (d)b^1 +(d−1)b^2+(d−2)b^3 · · ·+b^d, therefore won't regenerate too much node to waste.\n\nBidirectional search\nsimulaneously search forward and backward from initial state and goal state.\nb^(d/2) + b^(d/2) is less than b^d\ntry to find two direction's intersection. when A's frontier has a state that is also in B's frontier, the path is connected.\nbut the first solution is not necessarily the optimal. \nit depends on what f(n) it will use. \nif f(n) is path cost, then is bidirectional uniform-cost search, if the cost is the optimal path C^*, node with cost > C*/2 will not be expanded.this method will be optimal.\n\nfor other f(n), we need store solutions, and compare them to find best solution.\n\n\n\n\n\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* **Path** - order/sequence of actions\n* **Solution** - a path from initial to goal state.\n* **Optimal solution** - a solution that has the lowest total cost\n* **Uninformed search** - don't know distance from its current state to goal state. \n\n\n## WARNING: Your definition of 'surely expanded nodes' is too long!\n# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n \n\nheuristic function : h(n) = estimated cost of the cheapest path from the state at node n to a goal state.\n\nGreedy best-first search: \nf(n) = h(n)\nh(n) is not from problem itself but from the world knowledge.\nnot optimal, complete in finite state space, but incomplete in infinite state space.\nalways focus next step, not the whole states. kind of short sighted but is goal guided.it will not expand a node that is not on the solution path, which might fast(always find shorpath) but miss some best path that at first it seems twisting but finally have a good result.worst case : O(|V|), but if good h(n), it might reach O(bm).\n\n\nA* search: \n\nf(n) = g(n) + h(n), estimated cost of the best path that continues from n to a goal.\ncomplete, optimal if h(n) is admissible/optimistic (which means never overestimates the cost to reach the goal)\nAdmissiblity: if h*(n) represent real minimal cost from n to goal, then h(n) <= h*(n)\n\nif for every node and action, h(n) ≤ c(n,a,n′)+h(n′). h(n) is consistent. (triangle inequality)\nconsistent h(x) is admissible but admissible h(x) is not necessarily consistent.\nfor consistent h(x), we don't need to update reached, but just add new node, since every new node is on the optimal path.\neven for inconsistent h(x), we may still have same path if each new path has a lower path cost than the previous.(if we find better pathwe can update in the fronier tracing parent and children)\nnon admissible h(n) not necessarily can not reach a optimal solution, if the optimal solution has cost C∗, and the second-best has cost C2,\\ \nand if h(n) overestimates some costs, but never by more than C2 −C∗, then A∗ is guaranteed to return cost-optimal solutions.\n\nsearch contours: stretch toward the goal and become more narrowly focused around optimal path. (contour lines won't cross each other) line is between two nodeif h(n) is consistent then path cost f(n) will monotonically increase.\nA* might expand some node on the goal contour.\nA* expand no node with f(n) > C*.\n\nA* can prune search node that not lead to optimal solution(for n that f(n)> C*).\nsatisficing search: inadmissible heuristics and weighted A* (because A* expand too much nodes)\nf (n) = g(n)+W ×h(n), W > 1.\nmight overestimate but save time expanding nodes. it focuses more towards the goal than admissible A*\n\nbounded suboptimal search: solution is guaranteed within a constant factor W.\nbounded cost search : search solution that its cost less than specified cost C.\nunbounded cost search(speedy search) : no matter cost is, just find solution. quite like greedy best first search.\n\nIDA,RBFS(backed up value, optimal)\n\n\n\n \n\n## AIMA Chapter 3.6 Heuristic Functions\n \neffective branching factor b∗\nN +1 = 1+b∗+(b∗)2+· · ·+(b∗)d\n\nA well-designed heuristic would have a value of b∗ close to 1, allowing fairly large problems to be solved at reasonable computational cost\n\neffective depth\nO(b^(d−kh) )\n\nh2(n) ≥ h1(n) h2 dominates h1, h2 expand less nodes\n\nrelaxed problem: remove restriction on actions to generate more admissable h(n) which is a supergraph of the original state.\n\npattern database : store subproblem costs to generate h(n)\n\n\n\n\n\n\n\n\n \n\n## Module 4 Lecture Notes\n Your summary here \n\n## Module 4 Definitions\n* **Surely expanded nodes** - if node's f(n) < actual cost(C*), then the node is called surely expanded node which means will be expanded by A*\n* **Optimally efficient** - expand all nodes that are f(n) < actual cost(SEN)\n\n\n# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n \nthree stances for multi-agent : general economy, adversatial agent as a part of environment. model adversarial game tree search.perfect information : fully observable\nzero-sum: one gain, one lose\ngame problem define : initial state, ToMove(the turn for player), action, transition(result), is_terminal, utility.\n\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n move: both players finish one round play\nply: one move by one player.\n\nminimax value is the utility for max player.\n\nstrategy : for Max : Math.max(Min(state)), for Min : Math.min(Max(state))\n\n\nMiniMax : go through whole tree until to the terminal states(leaves), compare leaves value then determine backup value and moveto its parent node. this is a complete, O(b^m),S(bm) if is backtraking then is S(m)  \nDisadvantage : exponential time, which make algo impractical\n\nif is a multiplayer game(>2 players) , we need to store utility value using vector <va,vb,vc>\n\n\n\nalpha-beta Pruning: describe bounds on the backed up values(the worst case think pessimisticlly),can prune entire subtreesalpha : the lowest bound (at least value )along the path for max\\ \nbeta : the highest bound (at most value) along the path for mingenerally, alpha-beta search will prune the remainig branch if the value of the current node is known to be worse than alpha or beta.\nfor max, if alpha(root tree) > beta(subtree) in the path then we can prune the beta subtree.\nfor min, if beta(root tree) < alpha(subtree) in the path, then we can prune the alpha subtree.\n\n\nif done perfectly O(b^(m/2)), braching factor = b^(1/2), randomly (b^(3m/4)) \n\niterative deepening \ntranspositon table that store h(n) to reduce redundant path\n\nA strategy(h(n) estimate ulitilty, wide and shallow tree)\nB strategy(ignore some move looks bad, explore deep and narrow tree)\n\n\n\n \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \n\nreplace the ulility function with evaluation function (g(n)-->h(n)) estimate a state's utility.\nreplace the terminal test by cutoff test(depth limited)\nfor terminal states: EVAL(s,p) = UTILITY(s,p)\nfor nonterminal states: UTILITY(loss, p) ≤ EVAL(s, p) ≤ UTILITY(win, p)\nevaluation calculates many features of the state, using some function to calculate (expected value)possiblity value to win or loss.\nweighted linear function allocate value for every feature and calculate sum: EVAL(s) = w1 f1(s)+w2 f2(s)+···+wnf(s)(assumpthionevery feature is independent) from our experience.\nhow to find a depth to cutoff? sometimes just set a depth then iterative deepen but it might choose wrong move.therefore evaluation function back position should be quiescent that is no pending move (quiescence search)\n\nuse singular extension to mitigate horizon effect\n\n\n\nForward pruning B type, think ahead to eliminate some moves \n\n\n\n\n \n\n## AIMA Chapter 5.5 Stochastic Games\n \nexpectiminimax: we use expected value rather than minimax value to solve stochastic games\nevaluation function should return value that positive linear transformation of probability of wining.\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 Your summary here \n\n## Module 5 Lecture Notes\n \n\n## Module 5 Definitions\n* **Stochastic games** -  uncertain outcome in the playing \n\n\n## WARNING: Your definition of 'k-consistency' is too long!\nWARNING: Your definition of 'bounds - consistent' is too long!\n# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n \n\nfor nomal search problem, we usually treat every state as a black box, but for CSPs problem, we use factored representationin the state: we got variables and try to make every value comply with each others.\ndo not need actions and transition function in the problem description.\n\nenumerate:h(X1,X2),{(3,1), (3,2), (2,1)} or  abbreviation(h(X1,X2),X1 > X2i)\n\nCSP solution: a consistent and complete assignment. it's an NP problem\n\nadvantage of CSP, it can prune large nodes in the search space that atomic state search can notthat is if we find partial assignment violates constraint we can discard any node include that status.also, we can know which variable violate constraints so that we can focus on that variable.\n\n\n\n\ntype of constraints : unary constraint, binary constraint ,higher-order constraint(related variables>2),global constraint(arbitrary constraint,ex All diff)\n\nfinite-domain constraint can be transfered to a set of binary constraints using auxiliary variables\nsometimes we can shift constraints to variables and shift original constraints'values to domain values\n\n\n\n\n\n\n\n\n \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n\n\n\ncompared with atomic search, CSP can discard some value assignment to do some constraint propagation, and also choose some variable assignment. (local consistency)\n\nAC-3 algorithm: queue contains all arcs(in 2 directions), then check every arc whether they are arc consistent. if revise Di, add(Xk,Xi) in the queue, Xk is neighborof Xi not include Xj\n\nfunction AC-3(csp) returns false if an inconsistency is found and true otherwisequeue←a queue of arcs, initially all the arcs in cspwhile queue is not empty do  (Xi, Xj)←POP(queue)  if REVISE(csp, Xi, Xj) then    if size of Di = 0 then return false    for each Xk in Xi.NEIGHBORS - {Xj} do    add (Xk, Xi) to queue  return truefunction REVISE(csp, Xi, Xj) returns true iff we revise the domain of Xi  revised←false  for each x in Di do    if no value y in Dj allows (x,y) to satisfy the constraint between Xi and Xj then    delete x from Di    revised←truereturn revised\nO(cd^3)\n\nfor strongly k-consistency O(d*n^2)\n\n \n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n \nBacktracking Search: after pruning, DFS, only focus on single variables \n\nn variables , domain size d\n\nfunction BACKTRACKING-SEARCH(csp) returns a solution or failure\n  return BACKTRACK(csp, {})\n\nfunction BACKTRACK(csp, assignment) returns a solution or failure\n  if assignment is complete then return assignment\n  var←SELECT-UNASSIGNED-VARIABLE(csp, assignment)\n  for each value in ORDER-DOMAIN-VALUES(csp, var, assignment) do\n    if value is consistent with assignment then\n      add {var = value} to assignment\n      inferences←INFERENCE(csp, var, assignment)\n      if inferences 6= failure then\n        add inferences to csp\n        result←BACKTRACK(csp, assignment)\n        if result 6= failure then return result\n        remove inferences from csp\n      remove {var = value} from assignment\nreturn failure\n\n\n\nIn forward checking, whenever a variable XX is assigned, we establish arc consistency for XX\n\n\n\n\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n MAC do search and inference. AC-3 is juest pure inference.\n\nMAC only queue arc incident on the assigned variable.\n\n \n\n## AIMA Chapter 6.5 The Structure of Problems\n Tree decomposition techniques transform the CSP into a tree of subproblems.\nTree decomposition subproblems are efficient if the tree width of the constraint graph is small \nCutset conditioning save space( linear memory), tree decomosition(exponential memory) save time\n\n\n## Module 6 Lecture Notes\n CSPs represent with a set of variable/value pairs(the conditions for a solution with set of constraints)\nCSP has 2 ruling out variable assignments (choose value assignment, constraint propagation),using search or inference to rule out possible value.\ninference use constraints to rule out(idea is enforcing k-consistency).\n\nBacktracking occurs when no legal assignment can be found for a variable.\nMRV heuristic stands for Minimum Remaining Value, which chooses the variable with the fewest legal values\nThe degree heuristic chooses the variable with the largest number of constraints.\nThe least constraining value heuristic chooses the value that rules out the fewest values for neighboring variables.\nConstraint learning records the conflicts as they are encountered in the search in order to avoid the same conflict later\nSolving an arbitrary CSP takes expoential time in the number of variables, while solving a tree-structued CSP takes time in the number of variables\n\nCutset conditioning is used to reduce a general CSP to a tree structured one \n\n## Module 6 Definitions\n* **Consistent** - does not make conflict with other variables\n* **Complete** - every variable has some value rather than empty set\n* **Precedence constraints** - some variables have order constraint\n* **Preference constraints** - some variables's values are preferred but not must be \n* **Node-consistent** - for a specific variable, its all possible values are meet the unary constraints, even it may violate binary constraints\n* **Arc-consistent** - variable's all values obey binary constraints,(Di,Dj),Di must find a value in Dj which can be related\n* **Csp arc-consistent** -  for every variable in CSP, it is arc-consistent(it and its related variables are mutually arc consistent)\n* **Path-consitency** - find a middle variable m, for every value in variables{Xi,Xj} complys {Xi,Xm} and {Xm,XJ}}\n* **K-consistency** -  for constraint {v1, v2, v3 ,....vk-1}, any consistent value assignment in this set can be consist with kth variable value\n* **Strongly k-consistent** - k consistent, (k-1)consitent, k-2 consistent, 1 consistent\n* **Bounds - consistent** - every variable X, and for both the lower-bound Bounds-consistent and upper-bound values of X, there exists some value of Y that satisfies the constraint between X and Y for every variable Y\n* **Mac** - Maintaing Arc Consistency,recursively propogrates constraints\n\n\n# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n \n\nfunction KB-AGENT(percept) returns an action\n  persistent: KB, a knowledge base\n    t, a counter, initially 0, indicating time\n  TELL(KB,MAKE-PERCEPT-SENTENCE(percept, t))\n  action ← ASK(KB,MAKE-ACTION-QUERY(t))\n  TELL(KB,MAKE-ACTION-SENTENCE(action, t))\n  t ← t + 1\n  return action\n\nusing tell to update KB\nusing ask to reasoning best action, both can include inference.\n\nthe KB agent do three things: 1. Make percept sentence 2. MAKE ACTION QUERY extensive reasoning to make action decision 3. MAKE-ACTION-SENTENCE update KB action  \n\nneed to combine declarative approach and procedural approach.\n\n\n\n\n## AIMA Chapter 7.2 The Wumpus World\n\nwumpus world : Performance measure, Environment, Actuators, Sensors.\nreasoning neighboring square based on its percept and reasoning\nPercept:[Stench,Breeze,Glitter,None,None]\nupdate reasoning information on the map/state\n\nwhat the agent can conclude should be guaranteed to be correct.\n\n\n\n## AIMA Chapter 7.3 Logic\n \n\nhow to make logic representation and logic reasoning?\nsyntax & semantics\nsemantics shoud be either true or false in a specific possible world(which is like context)\n\nIf a sentence α is true in model（possible world）m, we say that m satisfies α or sometimes m is a model of α.\nWe use the notation M(α) to mean the set of all models of α.\n\nα|=β if and only if M(α) ⊆ M(β)  a entails b, a is more stronger assertion.\nM(KB) ⊆ M(α)\n\n\nKB ⊢i α\nα is derived from KB by i” or “i derives α from KB\n\nan inference algorithm is complete if it can derive any sentence that is entailed.\n\n\n\n\n \n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n \n\nfunction TT-ENTAILS?(KB,α) returns true or false\n  inputs: KB, the knowledge base, a sentence in propositional logic\n    α, the query, a sentence in propositional logic\n  symbols←a list of the proposition symbols in KB and α\n  return TT-CHECK-ALL(KB,α, symbols, {})\n\nfunction TT-CHECK-ALL(KB,α, symbols,model) returns true or false\n  if EMPTY?(symbols) then\n    if PL-TRUE?(KB,model) then return PL-TRUE?(α,model)\n    else return true // when KB is false, always return true\n  else\n    P←FIRST(symbols)\n    rest←REST(symbols)\n    return (TT-CHECK-ALL(KB,α, rest,model ∪ {P = true}) and TT-CHECK-ALL(KB,α, rest,model ∪ {P = false }))\n\nthe algorithm is sound and complete\n\n\n \n\n## AIMA 7.5 Propositional Theorem Proving\n \nwe can use search to find conclusion.\nINITIAL STATE: the initial knowledge base.\nACTIONS: the set of actions consists of all the inference rules applied to all the sentences\nthat match the top half of the inference rule.\nRESULT: the result of an action is to add the sentence in the bottom half of the inference\nrule.\nGOAL: the goal is a state that contains the sentence we are trying to prove.\n\nfunction PL-FC-ENTAILS?(KB, q) returns true or false\n  inputs: KB, the knowledge base, a set of propositional definite clauses\n    q, the query, a proposition symbol\n  count←a table, where count[c] is initially the number of symbols in clause c’s premise\n  inferred←a table, where inferred[s] is initially false for all symbols\n  queue←a queue of symbols, initially symbols known to be true in KB\n  while queue is not empty do\n    p←POP(queue)\n    if p = q then return true\n    if inferred[p] = false then\n      inferred[p]←true\n      for each clause c in KB where p is in c.PREMISE do\n        decrement count[c]\n        if count[c] = 0 then add c.CONCLUSION to queue\n  return false\n\nForward chaining is data driven reasoning, derive from KB.\n\nBackward chaining is a form of goal-directed reasoning\n\n\n \n\n## Module 7 Lecture Notes\n Your summary here \n\n## Module 7 Definitions\n* **Knowledge-based agents** - agents use its internal knowledge to reason to make decisions\n* **Knowledge base(kb)** - a set of sentences that are expressed by knoledge representation language.\n* **Axiom** - not concluded by other sentences\n* **Inference** - generate new knowldege from prior internal knowledge\n* **Atomic sentence** - just contain one argument without logic combination.\n* **Validity/taytologies** - if the sentence is true in all possible world\n* **Modus ponens** - if a to b and a are given then we can conclude b.(sufficient)\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "rvnL2yJ7CQOW"
      },
      "source": [
        ""
      ],
      "execution_count": null,
      "outputs": []
    }
  ]
}