{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Copy of 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": "f9856cb1-b927-424d-d421-44c0c3ba4f1a"
      },
      "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": 48,
      "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": "37bbad9f-622c-4834-85d2-c441ff627c01"
      },
      "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": 49,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"\"\n",
        "permission = True\n",
        "anonymous = True"
      ],
      "execution_count": 50,
      "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 = \"\"\"\n",
        "* AI is a rational agent that aims to reach the best expected outcome\n",
        "* make correct inferences/ decide whether an action is best\n",
        "* do the right thing - depends on how we human define right thing\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",
        "* Turing test: focus on whether machines can perform well on open-ended behavioral tasks,\n",
        "* instead of asking philosophical questions (e.g. whether machines can think)\n",
        "\"\"\"\n",
        "chapter27_2 = \"\"\"\n",
        "* No need to ask the question whether Machines Can Think according to Edsger Dijkstra\n",
        "* The Chinese room - generate intelligent Chinese response by following\n",
        "* the rule book written in English without knowing Chinese\n",
        "\"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA 4th Edition, Chapter 2 “Intelligent Agents” (whole chapter)\n",
        "chapter2_1 = \"\"\"\n",
        "* An agent’s choice of action depends on its knowledge \n",
        "* and its percept sequence till the current moment\n",
        "\"\"\"\n",
        "chapter2_2 = \"\"\"\n",
        "* Whether an agent is rational/does the right thing is evaluated with \n",
        "* consequentialism - the consequence of its behaviors\n",
        "* Four factors to decide what is rational: \n",
        "* 1. performance measure (defines the criterion of success)\n",
        "* 2. agents’ prior knowledge about its environment\n",
        "* 3. agent’s possible actions\n",
        "* 4. agent’s percept sequence till the moment\n",
        "* omniscience agent: knows the actual outcome of actions, acts accordingly\n",
        "* omniscience is impossible in real life\n",
        "\"\"\"\n",
        "chapter2_3 = \"\"\"\n",
        "* properties of task environmnets: \n",
        "* fully observable vs. partially observable\n",
        "* single-agent vs. multiagent; competitive vs. cooperative\n",
        "* deterministic vs. nondeterministic\n",
        "* episodic vs. sequential\n",
        "* static vs. dynamic\n",
        "* discrete vs. continuous\n",
        "* known vs. unknown\n",
        "\"\"\"\n",
        "chapter2_4 = \"\"\"\n",
        "* Types of agents: simple reflex, model-based, goal-based, utility-based\n",
        "* Agents improve their performance via learning\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module1_lecture_notes = \"\"\"\n",
        "* four views of AI: think humanly, think rationally, act humanly, act rationally\n",
        "* agent: anything that \n",
        "* 1. perceives its environment through sensors\n",
        "* 2. act upon its environment through actuators\n",
        "* e.g. human agent: eyes, ears (sensors), hands, legs, mouth (actuators);\n",
        "* robotic agent: cameras, infrared range finders (sensors), motors (actuators)\n",
        "* humans, robots, softbots, thermostats are all considered as agents\n",
        "* percept: the agent’s perceptual inputs at any moment\n",
        "* agent = architecture + program\n",
        "* rational agent: perceives environment and acts rationally (does the right thing)\n",
        "* We defined a performance measure to check if the agent is acting rationally\n",
        "* ROT for performance measures: \n",
        "* what you want to be achieved > how you think the agent should behave\n",
        "* rationality != omniscience; rationality != guaranteed success\n",
        "* complete rationality is not achievable due to computational limitations\n",
        "* rational agents select actions to maximize the expected value \n",
        "* (no need to know what the actual outcome will be)\n",
        "* hardest environment: continuous, partially observable, stochastic, multi-agent\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 1.\n",
        "# You can define any bolded term in the textbook, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 20 words long.\n",
        "module1_definitions = {\n",
        "\"agent\" : \"anything that can perceive and act in an environment\",\n",
        "\"percept\" : \"what the agent has perceived\",\n",
        "\"value alignment problem\": \"machine’s values/ objectives = human’s\",\n",
        "\"weak AI\": \"machines act as if intelligent\",\n",
        "\"strong AI\": \"can solve a wide variety of tasks just like human\",\n",
        "\"Turing test\": \"whether AI can pass a behavioral test\",\n",
        "\"percept sequence\": \"a complete history of things the agent has perceived\",\n",
        "\"agent function\": \"an abstract math description\",\n",
        "\"agent program\": \"a concrete/physical implementation\",\n",
        "\"rational agent\": \"selects action expected to maximize performance from percept sequence & knowledge\",\n",
        "\"omniscience\": \"knows everything\",\n",
        "\"autonomy\": \"learn to compensate for partial/incorrect prior knowledge\",\n",
        "\"PEAS\": \"performance measure, environment, actuators, sensors\",\n",
        "\"fully vs. partially observable\": \"whether agent’s sensors give it access to complete state of environment continually\",\n",
        "\"unobservable\": \"no sensors\",\n",
        "\"deterministic vs. nondeterministic\": \"whether next state fully determined by current state and actions taken\",\n",
        "\"stochastic\": \"random; explicitly deals with quantified probabilities\",\n",
        "\"episodic\": \"agent’s experience divided into episodes (next episode doesn’t depend on the previous)\",\n",
        "\"sequential\": \"future decisions depend on current decision\",\n",
        "\"static vs. dynamic\": \"whether environment can be changed by agent’s actions\",\n",
        "\"simple reflex agents\": \"choose action based on the current percept and ignores rest of percept history\",\n",
        "\"model-based reflex agents\": \"deal with partial observability by tracking part it can’t see now; maintains internal state from percept history\",\n",
        "\"goal-based agents\": \"w/ goal information that describes desirable situations and selects actions to achieve goal\",\n",
        "\"utility-based agents\": \"select actions to maximize expected utility\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 51,
      "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": "2b813c4b-e7a1-4f5c-8297-b3f5870fce3d"
      },
      "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": 52,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n\n* AI is a rational agent that aims to reach the best expected outcome\n* make correct inferences/ decide whether an action is best\n* do the right thing - depends on how we human define right thing\n\n\n## AIMA Chapter 27.1 The Limits of AI\n\n* Turing test: focus on whether machines can perform well on open-ended behavioral tasks,\n* instead of asking philosophical questions (e.g. whether machines can think)\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n\n* No need to ask the question whether Machines Can Think according to Edsger Dijkstra\n* The Chinese room - generate intelligent Chinese response by following\n* the rule book written in English without knowing Chinese\n\n\n## AIMA 2.1 Agents and Environments\n\n* An agent’s choice of action depends on its knowledge \n* and its percept sequence till the current moment\n\n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n\n* Whether an agent is rational/does the right thing is evaluated with \n* consequentialism - the consequence of its behaviors\n* Four factors to decide what is rational: \n* 1. performance measure (defines the criterion of success)\n* 2. agents’ prior knowledge about its environment\n* 3. agent’s possible actions\n* 4. agent’s percept sequence till the moment\n* omniscience agent: knows the actual outcome of actions, acts accordingly\n* omniscience is impossible in real life\n\n\n## AIMA 2.3 The Nature of Environments\n\n* properties of task environmnets: \n* fully observable vs. partially observable\n* single-agent vs. multiagent; competitive vs. cooperative\n* deterministic vs. nondeterministic\n* episodic vs. sequential\n* static vs. dynamic\n* discrete vs. continuous\n* known vs. unknown\n\n\n## AIMA 2.4 The Structure of Agents\n\n* Types of agents: simple reflex, model-based, goal-based, utility-based\n* Agents improve their performance via learning\n\n\n## Module 1 Lecture Notes\n\n* four views of AI: think humanly, think rationally, act humanly, act rationally\n* agent: anything that \n* 1. perceives its environment through sensors\n* 2. act upon its environment through actuators\n* e.g. human agent: eyes, ears (sensors), hands, legs, mouth (actuators);\n* robotic agent: cameras, infrared range finders (sensors), motors (actuators)\n* humans, robots, softbots, thermostats are all considered as agents\n* percept: the agent’s perceptual inputs at any moment\n* agent = architecture + program\n* rational agent: perceives environment and acts rationally (does the right thing)\n* We defined a performance measure to check if the agent is acting rationally\n* ROT for performance measures: \n* what you want to be achieved > how you think the agent should behave\n* rationality != omniscience; rationality != guaranteed success\n* complete rationality is not achievable due to computational limitations\n* rational agents select actions to maximize the expected value \n* (no need to know what the actual outcome will be)\n* hardest environment: continuous, partially observable, stochastic, multi-agent\n\n\n## Module 1 Definitions\n* **Agent** - anything that can perceive and act in an environment\n* **Percept** - what the agent has perceived\n* **Value alignment problem** - machine’s values/ objectives = human’s\n* **Weak ai** - machines act as if intelligent\n* **Strong ai** - can solve a wide variety of tasks just like human\n* **Turing test** - whether AI can pass a behavioral test\n* **Percept sequence** - a complete history of things the agent has perceived\n* **Agent function** - an abstract math description\n* **Agent program** - a concrete/physical implementation\n* **Rational agent** - selects action expected to maximize performance from percept sequence & knowledge\n* **Omniscience** - knows everything\n* **Autonomy** - learn to compensate for partial/incorrect prior knowledge\n* **Peas** - performance measure, environment, actuators, sensors\n* **Fully vs. partially observable** - whether agent’s sensors give it access to complete state of environment continually\n* **Unobservable** - no sensors\n* **Deterministic vs. nondeterministic** - whether next state fully determined by current state and actions taken\n* **Stochastic** - random; explicitly deals with quantified probabilities\n* **Episodic** - agent’s experience divided into episodes (next episode doesn’t depend on the previous)\n* **Sequential** - future decisions depend on current decision\n* **Static vs. dynamic** - whether environment can be changed by agent’s actions\n* **Simple reflex agents** - choose action based on the current percept and ignores rest of percept history\n* **Model-based reflex agents** - deal with partial observability by tracking part it can’t see now; maintains internal state from percept history\n* **Goal-based agents** - w/ goal information that describes desirable situations and selects actions to achieve goal\n* **Utility-based agents** - select actions to maximize expected utility\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 = \"\"\"\n",
        "* developed by Guido van Rossum in 1989\n",
        "* inspired by ABC language\n",
        "* positive features: fast development, portable, various built-in types, \n",
        "* large collection of support libraries\n",
        "* all data is treated as objects; \n",
        "* an object gets deleted once it becomes unreachable (by garbage collection)\n",
        "* strong typing: each object has a fixed type\n",
        "* dynamic typing: variables come into existence when first assigned; \n",
        "* type errors only caught at runtime\n",
        "* strings are immutable; lists are mutable\n",
        "* sequence types: tuple, string, list\n",
        "* Tuple: cannot be modified once created; \n",
        "* items can be of mixed types (including collection types)\n",
        "* Strings: unicode; use 2-byte characters\n",
        "* Dictionaries: unordered; keys must be immutable\n",
        "* Function multiple return: return type is a tuple\n",
        "* Python does not allow function overloading; \n",
        "* each function is specified by its name alone \n",
        "* no two functions can have the same name even they have different parameters\n",
        "* operator overloading is possible\n",
        "* *args: accept a variable number of non-keyword arguments for a function\n",
        "```\n",
        "def print_everything(*args):\n",
        "\t#args is a tuple of arguments passed to the fn\n",
        "\tprint(args) \n",
        "print_everything('a', 'b', 'c’) # ('a', 'b', 'c’) \n",
        "lst = ['a', 'b', 'c’] \n",
        "print_everything(*lst) # ('a', 'b', 'c’) \n",
        "```\n",
        "* kwargs: accept a variable number of keyword arguments for a function\n",
        "```\n",
        "def print_keyword_args(**kwargs):\n",
        "  # kwargs is a dict of the keyword args passed to the fn \n",
        "\tprint(kwargs) \n",
        "print_keyword_args(first_name=\"John\", last_name=\"Doe\") \n",
        "# {'first_name': 'John', 'last_name': 'Doe’} \n",
        "my_dict = {'first_name': 'Wei', 'last_name': 'Xu’} \n",
        "print_keyword_args(**my_dict)\n",
        "# {'first_name': 'Wei', 'last_name': 'Xu'} \n",
        "```\n",
        "* functions are first-class objects\n",
        "* a class can extend another class \n",
        "* no ‘extends’ keyword like java & supports multiple-inheritance\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 20 words long.\n",
        "module2_definitions = {\n",
        "\"mutability\" : \"whether values of an object can be changed\",\n",
        "\"REPL\": \"read-evaluate-print loop\"\n",
        "}"
      ],
      "execution_count": 53,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 886
        },
        "outputId": "ebfc51fd-a8eb-4b91-b4dd-289ed49de8f4"
      },
      "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": 54,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 2: Python\n## Module 2 Lecture Notes\n\n* developed by Guido van Rossum in 1989\n* inspired by ABC language\n* positive features: fast development, portable, various built-in types, \n* large collection of support libraries\n* all data is treated as objects; \n* an object gets deleted once it becomes unreachable (by garbage collection)\n* strong typing: each object has a fixed type\n* dynamic typing: variables come into existence when first assigned; \n* type errors only caught at runtime\n* strings are immutable; lists are mutable\n* sequence types: tuple, string, list\n* Tuple: cannot be modified once created; \n* items can be of mixed types (including collection types)\n* Strings: unicode; use 2-byte characters\n* Dictionaries: unordered; keys must be immutable\n* Function multiple return: return type is a tuple\n* Python does not allow function overloading; \n* each function is specified by its name alone \n* no two functions can have the same name even they have different parameters\n* operator overloading is possible\n* *args: accept a variable number of non-keyword arguments for a function\n```\ndef print_everything(*args):\n\t#args is a tuple of arguments passed to the fn\n\tprint(args) \nprint_everything('a', 'b', 'c’) # ('a', 'b', 'c’) \nlst = ['a', 'b', 'c’] \nprint_everything(*lst) # ('a', 'b', 'c’) \n```\n* kwargs: accept a variable number of keyword arguments for a function\n```\ndef print_keyword_args(**kwargs):\n  # kwargs is a dict of the keyword args passed to the fn \n\tprint(kwargs) \nprint_keyword_args(first_name=\"John\", last_name=\"Doe\") \n# {'first_name': 'John', 'last_name': 'Doe’} \nmy_dict = {'first_name': 'Wei', 'last_name': 'Xu’} \nprint_keyword_args(**my_dict)\n# {'first_name': 'Wei', 'last_name': 'Xu'} \n```\n* functions are first-class objects\n* a class can extend another class \n* no ‘extends’ keyword like java & supports multiple-inheritance\n\n\n## Module 2 Definitions\n* **Mutability** - whether values of an object can be changed\n* **Repl** - read-evaluate-print loop\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",
        "* search problem: state space, initial state, actions, \n",
        "* transition model, goal states, action cost\n",
        "\"\"\"\n",
        "chapter3_2 = \"\"\"\n",
        "* route-finding problem\n",
        "* touring problem - e.g. traveling salesperson problem\n",
        "* VLSI layout problem\n",
        "* robot navigation\n",
        "* automatic assembly sequencing\n",
        "\"\"\"\n",
        "chapter3_3 = \"\"\"\n",
        "* best-first search (graph)\n",
        "* node data structure: state, parent, action, path-cost\n",
        "* graph search checks for redundant paths\n",
        "* tree search does not check for redundant paths\n",
        "* measuring performance: completeness, cost optimality, \n",
        "* time complexity, space complexity\n",
        "\"\"\"\n",
        "chapter3_4 = \"\"\"\n",
        "* given no clue about the distance between its current state and the goals\n",
        "* Breadth-first search (BFS) has both time and space complexity of O(b^d)\n",
        "* Dijkstra’s algorithm - uniform-cost search\n",
        "* Uniform-cost search is complete and cost-optimal\n",
        "* Depth-first search (DFS) - always expands deepest node in frontier, \n",
        "* not cost-optimal (returns first solution, not guaranteed cheapest)\n",
        "* DFS is not complete because it can get stuck in an infinite path\n",
        "* backtracking: a variant of DFS (less memory)\n",
        "* depth-limited search - time complexity O(b^l) l = depth limit; \n",
        "* space complexity O(bl); can fail if the choice for l is bad\n",
        "* iterative deepening search - O(bd) space & O(b^d) time when there’s a solution, \n",
        "* O(bm) space & O(b^m) time when no solution on finite state space\n",
        "* depth-limited search & iterative deepening search: \n",
        "* optimal when actions have same cost\n",
        "* bidirectional search: searches forward from initial state and backwards from \n",
        "* goal state at the same time, hoping they will meet (b^(d/2) * b^(d/2) < b^d )\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module3_lecture_notes = \"\"\"\n",
        "* simple reflex agent: selects an action based on current percept \n",
        "* & ignore the rest of the percept history\n",
        "* problem-solving agent: plans ahead \n",
        "* & considers a sequence of actions forming a path to goal\n",
        "* solution: a sequence of actions from initial state to goal state\n",
        "* uninformed search: all non-goal nodes in frontier look equally good\n",
        "* informed search: some non-goal nodes are better than others\n",
        "* time/space complexity variables: \n",
        "* b - maximum branching factor of search tree\n",
        "* d - depth of shallowest goal node\n",
        "* m - maximum length of any path in state space (can be infinity)\n",
        "* BFS: expands shallowest unexpanded node; frontier is FIFO\n",
        "* DFS: expands deepest unexpanded node; frontier if LIFO\n",
        "* Use DFS when space is restructured | many possible solutions with long paths \n",
        "* | wrong paths terminated quickly | searched can be fine-tuned quickly\n",
        "* Use BFS when there can be infinite paths | some solutions have short paths \n",
        "* | can quickly discard unlikely paths\n",
        "\"\"\"\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",
        "\"state space\": \"possible states of the environment\",\n",
        "\"search algorithm\": \"input - search problem; output: solution/report failure\",\n",
        "\"depth (d)\": \"number of actions in the optimal solution\",\n",
        "\"m\": \"maximum number of actions in all path/ maximum depth of search tree\",\n",
        "\"branching factor (b)\": \"number of successors for each node considered\",\n",
        "\"l\": \"depth limit\",\n",
        "\"frontier\": \"states available for expanding\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 55,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "37c96597-f4ee-41a7-95f3-9a4d91d613a5"
      },
      "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": 56,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n\n* search problem: state space, initial state, actions, \n* transition model, goal states, action cost\n\n\n## AIMA Chapter 3.2 Example Problems\n\n* route-finding problem\n* touring problem - e.g. traveling salesperson problem\n* VLSI layout problem\n* robot navigation\n* automatic assembly sequencing\n\n\n## AIMA Chapter 3.3 Search Algorithms\n\n* best-first search (graph)\n* node data structure: state, parent, action, path-cost\n* graph search checks for redundant paths\n* tree search does not check for redundant paths\n* measuring performance: completeness, cost optimality, \n* time complexity, space complexity\n\n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n\n* given no clue about the distance between its current state and the goals\n* Breadth-first search (BFS) has both time and space complexity of O(b^d)\n* Dijkstra’s algorithm - uniform-cost search\n* Uniform-cost search is complete and cost-optimal\n* Depth-first search (DFS) - always expands deepest node in frontier, \n* not cost-optimal (returns first solution, not guaranteed cheapest)\n* DFS is not complete because it can get stuck in an infinite path\n* backtracking: a variant of DFS (less memory)\n* depth-limited search - time complexity O(b^l) l = depth limit; \n* space complexity O(bl); can fail if the choice for l is bad\n* iterative deepening search - O(bd) space & O(b^d) time when there’s a solution, \n* O(bm) space & O(b^m) time when no solution on finite state space\n* depth-limited search & iterative deepening search: \n* optimal when actions have same cost\n* bidirectional search: searches forward from initial state and backwards from \n* goal state at the same time, hoping they will meet (b^(d/2) * b^(d/2) < b^d )\n\n\n## Module 3 Lecture Notes\n\n* simple reflex agent: selects an action based on current percept \n* & ignore the rest of the percept history\n* problem-solving agent: plans ahead \n* & considers a sequence of actions forming a path to goal\n* solution: a sequence of actions from initial state to goal state\n* uninformed search: all non-goal nodes in frontier look equally good\n* informed search: some non-goal nodes are better than others\n* time/space complexity variables: \n* b - maximum branching factor of search tree\n* d - depth of shallowest goal node\n* m - maximum length of any path in state space (can be infinity)\n* BFS: expands shallowest unexpanded node; frontier is FIFO\n* DFS: expands deepest unexpanded node; frontier if LIFO\n* Use DFS when space is restructured | many possible solutions with long paths \n* | wrong paths terminated quickly | searched can be fine-tuned quickly\n* Use BFS when there can be infinite paths | some solutions have short paths \n* | can quickly discard unlikely paths\n\n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n* **State space** - possible states of the environment\n* **Search algorithm** - input - search problem; output: solution/report failure\n* **Depth (d)** - number of actions in the optimal solution\n* **M** - maximum number of actions in all path/ maximum depth of search tree\n* **Branching factor (b)** - number of successors for each node considered\n* **L** - depth limit\n* **Frontier** - states available for expanding\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",
        "* Greedy best-first search: f(n) = h(n)\n",
        "* A* serach: f(n) = g(n) + h(n)\n",
        "* A* if cost=optimal if the heuristic is admissible\n",
        "* A* prunes unnecessary nodes when finding the optimal solution\n",
        "* memory-bounded search:\n",
        "* beam search: limits size of frontier; e.g. keeps only k best nodes\n",
        "* Iterative-deepening A* search (IDA*): \n",
        "* similar to iterative-deepening search to DFS\n",
        "* Recursive best-first search (RBFS): \n",
        "* mimics standard best-first search while using linear space\n",
        "\"\"\"\n",
        "chapter3_6 = \"\"\"\n",
        "* quality of the heuristic function decides the performance of \n",
        "* the heuristic search algorithm\n",
        "* ways to find a good heuristic: relaxing problem definition, \n",
        "* storing precomputed solution costs, defining landmarks, \n",
        "* learning from experience of similar problems\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module4_lecture_notes = \"\"\"\n",
        "* Search strategy: order of tree expansion; \n",
        "* impelled by different queue structures (LIFO, FIFO, priority)\n",
        "* dimensions for evaluation: completeness, optimality, time/space complexity\n",
        "* time complexity: number of nodes generated\n",
        "* space complexity: number of nodes in memory at the same time\n",
        "* heuristic knowledge: useful, not necessarily correct\n",
        "* key concept of A* search: admissible heuristics\n",
        "* How to find an admissible heuristic: \n",
        "* find the cost of an optimal solution to a relaxed problem\n",
        "* dominance: if h2(n) >= h1(n) for all n (both admissible), then h2 dominates h1\n",
        "* h2 is optimistic but more accurate than h1 -> h2 is better for search\n",
        "* A heuristic h is admissible if 0 <= h(n) <= h*(n), \n",
        "* h * (n) = true cost to nearest goal\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module4_definitions = {\n",
        "\"heuristic function\": \"estimates the lowest cost from current node to goal\",\n",
        "\"g(n)\": \"path cost from initial state to node n\",\n",
        "\"h(n)\": \"estimated cost of shortest path from node n to goal\",\n",
        "\"f(n)\": \"estimated cost of best path from node n to goal\",\n",
        "\"admissible\": \"never overestimates the path cost to goal; optimistic\",\n",
        "\"monotonic\": \"cost always increases along a path\",\n",
        "\"relaxed problem\": \"a problem with fewer restrictions on the actions than the original problem\"   \n",
        "}\n",
        "\n"
      ],
      "execution_count": 57,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 881
        },
        "cellView": "form",
        "outputId": "8532e598-317c-4e5d-c3a1-bfd84fed9fa5"
      },
      "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": 58,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n\n* Greedy best-first search: f(n) = h(n)\n* A* serach: f(n) = g(n) + h(n)\n* A* if cost=optimal if the heuristic is admissible\n* A* prunes unnecessary nodes when finding the optimal solution\n* memory-bounded search:\n* beam search: limits size of frontier; e.g. keeps only k best nodes\n* Iterative-deepening A* search (IDA*): \n* similar to iterative-deepening search to DFS\n* Recursive best-first search (RBFS): \n* mimics standard best-first search while using linear space\n\n\n## AIMA Chapter 3.6 Heuristic Functions\n\n* quality of the heuristic function decides the performance of \n* the heuristic search algorithm\n* ways to find a good heuristic: relaxing problem definition, \n* storing precomputed solution costs, defining landmarks, \n* learning from experience of similar problems\n\n\n## Module 4 Lecture Notes\n\n* Search strategy: order of tree expansion; \n* impelled by different queue structures (LIFO, FIFO, priority)\n* dimensions for evaluation: completeness, optimality, time/space complexity\n* time complexity: number of nodes generated\n* space complexity: number of nodes in memory at the same time\n* heuristic knowledge: useful, not necessarily correct\n* key concept of A* search: admissible heuristics\n* How to find an admissible heuristic: \n* find the cost of an optimal solution to a relaxed problem\n* dominance: if h2(n) >= h1(n) for all n (both admissible), then h2 dominates h1\n* h2 is optimistic but more accurate than h1 -> h2 is better for search\n* A heuristic h is admissible if 0 <= h(n) <= h*(n), \n* h * (n) = true cost to nearest goal\n\n\n## Module 4 Definitions\n* **Heuristic function** - estimates the lowest cost from current node to goal\n* **G(n)** - path cost from initial state to node n\n* **H(n)** - estimated cost of shortest path from node n to goal\n* **F(n)** - estimated cost of best path from node n to goal\n* **Admissible** - never overestimates the path cost to goal; optimistic\n* **Monotonic** - cost always increases along a path\n* **Relaxed problem** - a problem with fewer restrictions on the actions than the original problem\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",
        "* Elements in a game: initial state, whose turn it is, \n",
        "* set of legal moves in state, transition model, terminal test\n",
        "\"\"\"\n",
        "chapter5_2 = \"\"\"\n",
        "* ply: one move by one player\n",
        "* pruning: no need to examine every state\n",
        "\"\"\"\n",
        "chapter5_3 = \"\"\"\n",
        "* EVAL(s, p): heuristic evaluation function; \n",
        "* returns expected utility of state s to player p\n",
        "* Beam search is one approach of forward pruning\n",
        "\"\"\"\n",
        "chapter5_5 = \"\"\"\n",
        "* Stochastic games: unpredictable\n",
        "* A chance node is evaluated by computing the average utility of its children\n",
        "\"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 16 “Making Simple Decisions” (16.1-16.3)\n",
        "chapter16_1 = \"\"\"\n",
        "* Maximum expected utility (MEU): \n",
        "* rational agent should select the action which maximizes its expected utility\n",
        "\"\"\"\n",
        "chapter16_2 = \"\"\"\n",
        "* Orderability: given two lotteries, agent must either prefer on \n",
        "* or view them as equally preferable; cannot avoid deciding\n",
        "* Transitivity: prefers A to B & prefers B to C -> must prefer A to C\n",
        "* Continuity\n",
        "* Substitutability\n",
        "* Monotonicity: if agent prefers outcome A to outcome B, \n",
        "* then it must prefer the lottery with higher probability for A\n",
        "* Decomposability: reduce compound lotteries to simpler lotteries \n",
        "* using laws of probability \n",
        "\"\"\"\n",
        "chapter16_3 = \"\"\"\n",
        "* QALY: quality-adjusted life year\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module5_lecture_notes = \"\"\"\n",
        "* Simplest game environment: multi-agent, static, discrete, \n",
        "* fully observable, strategic\n",
        "* Static: no change while an agent is deliberating\n",
        "* Discrete: a finite set of percepts & actions\n",
        "* Fully observable: agent has the complete state of the environment via its sensors\n",
        "* Strategic: next state determined by current state \n",
        "* & agent’s action & other agent’s action\n",
        "* Evaluation function f(n); zero-sum assumption -> \n",
        "* f(n) > 0 if MAX is winning at n\n",
        "* f(n) = 0 if tied at n\n",
        "* f(n) < 0 if MIN is winning at n\n",
        "* alpha-beta pruning: \n",
        "* a (alpha): MAX’s current lower bound on MAX’s outcome; \n",
        "* MAX will never allow a move that leads to a worse score (for MAX) than a \n",
        "* b (beta): MIN’s current upper bound on MIN’S outcome; \n",
        "* MIN will never allow a move that leads to a better score (for MAX) than b\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module5_definitions = {\n",
        "\"perfect information\": \"fully observable\",\n",
        "\"zero-sum\": \"no win-win; good for one player is bad for the other player\",\n",
        "\"stochastic games\": \"randomly determined; unpredictable\",\n",
        "\"expected utility\": \"the avg. utility of all outcomes weighted by probability of each outcome\",\n",
        "\"optimizer’s curse\": \"the best choice’s estimated expected utility tends to be very high\",\n",
        "\"normative theory\": \"describes how the rational agent is supposed to act\",\n",
        "\"descriptive theory\": \"describes how the rational agent actually acts\" \n",
        "}\n",
        "\n"
      ],
      "execution_count": 59,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "cf33d53f-e706-412f-e4d0-d056a2b5ea9c"
      },
      "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": 60,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n\n* Elements in a game: initial state, whose turn it is, \n* set of legal moves in state, transition model, terminal test\n\n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n\n* ply: one move by one player\n* pruning: no need to examine every state\n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n\n* EVAL(s, p): heuristic evaluation function; \n* returns expected utility of state s to player p\n* Beam search is one approach of forward pruning\n\n\n## AIMA Chapter 5.5 Stochastic Games\n\n* Stochastic games: unpredictable\n* A chance node is evaluated by computing the average utility of its children\n\n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n\n* Maximum expected utility (MEU): \n* rational agent should select the action which maximizes its expected utility\n\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n\n* Orderability: given two lotteries, agent must either prefer on \n* or view them as equally preferable; cannot avoid deciding\n* Transitivity: prefers A to B & prefers B to C -> must prefer A to C\n* Continuity\n* Substitutability\n* Monotonicity: if agent prefers outcome A to outcome B, \n* then it must prefer the lottery with higher probability for A\n* Decomposability: reduce compound lotteries to simpler lotteries \n* using laws of probability \n\n\n## AIMA Chapter 16.3 Utility Functions\n\n* QALY: quality-adjusted life year\n\n\n## Module 5 Lecture Notes\n\n* Simplest game environment: multi-agent, static, discrete, \n* fully observable, strategic\n* Static: no change while an agent is deliberating\n* Discrete: a finite set of percepts & actions\n* Fully observable: agent has the complete state of the environment via its sensors\n* Strategic: next state determined by current state \n* & agent’s action & other agent’s action\n* Evaluation function f(n); zero-sum assumption -> \n* f(n) > 0 if MAX is winning at n\n* f(n) = 0 if tied at n\n* f(n) < 0 if MIN is winning at n\n* alpha-beta pruning: \n* a (alpha): MAX’s current lower bound on MAX’s outcome; \n* MAX will never allow a move that leads to a worse score (for MAX) than a \n* b (beta): MIN’s current upper bound on MIN’S outcome; \n* MIN will never allow a move that leads to a better score (for MAX) than b\n\n\n## Module 5 Definitions\n* **Perfect information** - fully observable\n* **Zero-sum** - no win-win; good for one player is bad for the other player\n* **Stochastic games** - randomly determined; unpredictable\n* **Expected utility** - the avg. utility of all outcomes weighted by probability of each outcome\n* **Optimizer’s curse** - the best choice’s estimated expected utility tends to be very high\n* **Normative theory** - describes how the rational agent is supposed to act\n* **Descriptive theory** - describes how the rational agent actually acts\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",
        "* three components of CSP: X, D, C\n",
        "* X: a set of variables\n",
        "* D: a set of domains, one domain for each variable\n",
        "* C: a set of constraints \n",
        "* CSP solves the problem of assigning values to variables\n",
        "* a consistent assignment is one that does not violate any constraints\n",
        "* a complete assignment is one where each variable is assigned a value\n",
        "* a solution to CSP is consistent and complete\n",
        "* a partial assignment is one where some variables remind unassigned\n",
        "* a partial solution is a consistent partial assignment\n",
        "* solving a CSP is an NP-complete problem\n",
        "\"\"\"\n",
        "chapter6_2 = \"\"\"\n",
        "* Constraint propagation: reduce number of legal values for a variable \n",
        "* using constraints -> reduce for other variables\n",
        "* Node-consistent: all values in a variable’s domain satisfy its unary constraints \n",
        "* Arc-consistency: binary\n",
        "* Path-consistency: tightens binary constraints; \n",
        "* looks at triples of variables to infer implicit constraints\n",
        "\"\"\"\n",
        "chapter6_3 = \"\"\"\n",
        "* Commutativity: a crucial property of CSP; \n",
        "* order of any set of actions does not matter\n",
        "* Forward checking: when X is assigned, it established arc consistency; \n",
        "* for each unassigned Y connected to X by a constraint, \n",
        "* remove all inconsistent values from Y’s domain according to the value of X\n",
        "* MAC: maintaining arc consistency\n",
        "\"\"\"\n",
        "chapter6_4 = \"\"\"\n",
        "* min-conflicts heuristic: select value resulting in min numbers of conflicts\n",
        "\"\"\"\n",
        "chapter6_5 = \"\"\"\n",
        "* Cutset conditioning:\n",
        "* 1. Select a subset S (cycle cutset) of CSP’s variables \n",
        "* so that the constraint graph becomes a tree after the removal\n",
        "* 2. Find all possible assignments to the variables in S \n",
        "* which satisfies all constraints, and for each: remove all values inconsistent \n",
        "* with the assignment for S from domains of remaining variables & return a \n",
        "* solution with the assignment for S if the remaining CSP has a solution\n",
        "* Tree decomposition: turn original graph into a tree \n",
        "* each node in the tree is a set of variables)\n",
        "* Three requirements of tree decomposition:\n",
        "* 1. For each variable in the original problem, \n",
        "* it is guaranteed that it appears in at least one node in the tree\n",
        "* 2. Two variables (if connected by a constraint in original problem) \n",
        "* must appear together (with the constraint) in at least one node in the tree\n",
        "* 3. A variable appears in two nodes in tree -> must appear in each node \n",
        "* along the path that connects these nodes\n",
        "* tree width (tree decomposition): ones less than size of largest node\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module6_lecture_notes = \"\"\"\n",
        "* Benefits of CSP: clean specification (convert problem to CSP & solve with \n",
        "* general approach), “knows” what variables violate constraints, \n",
        "* automatically prunes branches that violate constraints\n",
        "* varieties of constraints:\n",
        "* 1. Unary: involves a single variable (e.g. SA != green)\n",
        "* 2. Binary: involves a pair of variables (e.g. SA != WA)\n",
        "* 3. High-order: involves 3 or more variables\n",
        "* 4. Preference: soft constraints (e.g. red is better than green)\n",
        "* express CSP as a search problem:\n",
        "* 1. Initial state: empty assignment {}\n",
        "* 2. Successors: assign a value to any unassigned variable given there’s no conflict\n",
        "* 3. Goal: the current assignment is complete\n",
        "* 4. Path cost: constant cost for each step\n",
        "* Use DFS for solving CSP because solution always found at depth n for n variables\n",
        "* Heuristics to improve backtracking: most constrained variable, \n",
        "* most constraining variable (if ties), least constraining value \n",
        "* (order of trying a variable’s values), forward checking (detect failure early)\n",
        "* Inference in CSPs: constraint propagation \n",
        "* node consistency (unary constraints), arc consistency (binary constraints)\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module6_definitions = {\n",
        "\"inference\": \"rules out certain variable assignments using constraints\",\n",
        "\"backtracking search\": \"commonly used to solve CSPs; a form of DFS\"  \n",
        "}\n"
      ],
      "execution_count": 61,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "b7a6e8a5-b2c2-42ab-9633-03dc14cbf1f0"
      },
      "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": 62,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n\n* three components of CSP: X, D, C\n* X: a set of variables\n* D: a set of domains, one domain for each variable\n* C: a set of constraints \n* CSP solves the problem of assigning values to variables\n* a consistent assignment is one that does not violate any constraints\n* a complete assignment is one where each variable is assigned a value\n* a solution to CSP is consistent and complete\n* a partial assignment is one where some variables remind unassigned\n* a partial solution is a consistent partial assignment\n* solving a CSP is an NP-complete problem\n\n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n\n* Constraint propagation: reduce number of legal values for a variable \n* using constraints -> reduce for other variables\n* Node-consistent: all values in a variable’s domain satisfy its unary constraints \n* Arc-consistency: binary\n* Path-consistency: tightens binary constraints; \n* looks at triples of variables to infer implicit constraints\n\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n\n* Commutativity: a crucial property of CSP; \n* order of any set of actions does not matter\n* Forward checking: when X is assigned, it established arc consistency; \n* for each unassigned Y connected to X by a constraint, \n* remove all inconsistent values from Y’s domain according to the value of X\n* MAC: maintaining arc consistency\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n\n* min-conflicts heuristic: select value resulting in min numbers of conflicts\n\n\n## AIMA Chapter 6.5 The Structure of Problems\n\n* Cutset conditioning:\n* 1. Select a subset S (cycle cutset) of CSP’s variables \n* so that the constraint graph becomes a tree after the removal\n* 2. Find all possible assignments to the variables in S \n* which satisfies all constraints, and for each: remove all values inconsistent \n* with the assignment for S from domains of remaining variables & return a \n* solution with the assignment for S if the remaining CSP has a solution\n* Tree decomposition: turn original graph into a tree \n* each node in the tree is a set of variables)\n* Three requirements of tree decomposition:\n* 1. For each variable in the original problem, \n* it is guaranteed that it appears in at least one node in the tree\n* 2. Two variables (if connected by a constraint in original problem) \n* must appear together (with the constraint) in at least one node in the tree\n* 3. A variable appears in two nodes in tree -> must appear in each node \n* along the path that connects these nodes\n* tree width (tree decomposition): ones less than size of largest node\n\n\n## Module 6 Lecture Notes\n\n* Benefits of CSP: clean specification (convert problem to CSP & solve with \n* general approach), “knows” what variables violate constraints, \n* automatically prunes branches that violate constraints\n* varieties of constraints:\n* 1. Unary: involves a single variable (e.g. SA != green)\n* 2. Binary: involves a pair of variables (e.g. SA != WA)\n* 3. High-order: involves 3 or more variables\n* 4. Preference: soft constraints (e.g. red is better than green)\n* express CSP as a search problem:\n* 1. Initial state: empty assignment {}\n* 2. Successors: assign a value to any unassigned variable given there’s no conflict\n* 3. Goal: the current assignment is complete\n* 4. Path cost: constant cost for each step\n* Use DFS for solving CSP because solution always found at depth n for n variables\n* Heuristics to improve backtracking: most constrained variable, \n* most constraining variable (if ties), least constraining value \n* (order of trying a variable’s values), forward checking (detect failure early)\n* Inference in CSPs: constraint propagation \n* node consistency (unary constraints), arc consistency (binary constraints)\n\n\n## Module 6 Definitions\n* **Inference** - rules out certain variable assignments using constraints\n* **Backtracking search** - commonly used to solve CSPs; a form of DFS\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",
        "* Declarative: start with empty knowledge base, tell the agent sentences \n",
        "* it needs to know one by one, until the agent knows what to do\n",
        "* Procedural: encode deserted behaviors as code directly\n",
        "* A successful agent combines declarative & procedural approaches in its design\n",
        "\"\"\"\n",
        "chapter7_2 = \"\"\"\n",
        "* Wumpus world: a cave with rooms connected by passageways; \n",
        "* there’s a wumpus somewhere in the cave; the agent has only one arrow \n",
        "* and can shoot the wumpus; some rooms can trap anyone who go into the rooms \n",
        "* (except for the wumpus) with bottomless pits; \n",
        "* reward: find a heap of gold in this environment\n",
        "\"\"\"\n",
        "chapter7_3 = \"\"\"\n",
        "* possible world -> model\n",
        "* logical entailment between sentences: a |= b\n",
        "\"\"\"\n",
        "chapter7_4 = \"\"\"\n",
        "* atomic sentences consist of only one proposition symbol\n",
        "\"\"\"\n",
        "chapter7_5 = \"\"\"\n",
        "* Define a proof problem:\n",
        "* 1. initial state: initial knowledge base\n",
        "* 2. actions: all inference rules applied to all sentences \n",
        "* matching top half of inference rule\n",
        "* 3. result: add the sentence in bottom half of inference rule\n",
        "* 4. goal: a state containing the target sentence / \n",
        "* Ground resolution theorem: a set of clauses is unsatisfiable -> \n",
        "* resolution closure of the set of clauses contains the empty clause\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module7_lecture_notes = \"\"\"\n",
        "* KB consists of sentences in the representation language\n",
        "* Representation language has a syntax to specify well-formed sentences\n",
        "* Logic defines semantics (meaning) of the sentences\n",
        "* semantics defines the truth of each sentence with respect to a model\n",
        "* logic connective: not, and, or, implies, if and only if\n",
        "* Complex sentences are constructed from simpler sentences using \n",
        "* parenthesis and logical connectives\n",
        "* monotonicity -> soundness\n",
        "* Conjunctive Normal Form (CNF)\n",
        "* Definite clause is the disjunction of literals where only one is positive\n",
        "* Horn clause is the disjunction of literals where at most one is positive \n",
        "* (includes definite clauses)\n",
        "* Forward chaining: a form of data-driven reasoning; \n",
        "* agent starts with known data, adds premises as new percepts come in, \n",
        "* and apply forward chaining algorithm to derive new conclusions incrementally\n",
        "* Backward chaining: goes backwards from a query; for a false query, \n",
        "* if all premises of one of the implications in the KB whose conclusion \n",
        "* is the query, then the query is true\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module7_definitions = {\n",
        "\"axiom\": \"a sentence that is given; not derived from other sentences\",\n",
        "\"inference\": \"derive new sentences from old sentences\",\n",
        "\"semantics\": \"the meaning of sentences\",\n",
        "\"positive literal\": \"an atomic sentence\",\n",
        "\"negative literal\": \"a negated atomic sentence\",\n",
        "\"literal\": \"positive literal | negative literal\",\n",
        "\"validity\": \"if a sentence is true in all models\",\n",
        "\"tautology\": \"valid sentence that is necessarily true\",\n",
        "\"satisfiability\": \"if a sentence is true in (satisfied by) some model\",\n",
        "\"reductio ad absurdum\": \"reduction to an absurd thing; proof by refutation/ contradiction\",\n",
        "\"soundness\": \"the inference algorithm only derives entailed sentences\",\n",
        "\"completeness\": \"the inference algorithm can derive all entailed sentences\",\n",
        "\"logical equivalence\": \"two sentences are true in the same set of models\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 63,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "8c9c60fe-7488-4a78-96c8-a785a8644708"
      },
      "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": 64,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n\n* Declarative: start with empty knowledge base, tell the agent sentences \n* it needs to know one by one, until the agent knows what to do\n* Procedural: encode deserted behaviors as code directly\n* A successful agent combines declarative & procedural approaches in its design\n\n\n## AIMA Chapter 7.2 The Wumpus World\n\n* Wumpus world: a cave with rooms connected by passageways; \n* there’s a wumpus somewhere in the cave; the agent has only one arrow \n* and can shoot the wumpus; some rooms can trap anyone who go into the rooms \n* (except for the wumpus) with bottomless pits; \n* reward: find a heap of gold in this environment\n\n\n## AIMA Chapter 7.3 Logic\n\n* possible world -> model\n* logical entailment between sentences: a |= b\n\n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n\n* atomic sentences consist of only one proposition symbol\n\n\n## AIMA 7.5 Propositional Theorem Proving\n\n* Define a proof problem:\n* 1. initial state: initial knowledge base\n* 2. actions: all inference rules applied to all sentences \n* matching top half of inference rule\n* 3. result: add the sentence in bottom half of inference rule\n* 4. goal: a state containing the target sentence / \n* Ground resolution theorem: a set of clauses is unsatisfiable -> \n* resolution closure of the set of clauses contains the empty clause\n\n\n## Module 7 Lecture Notes\n\n* KB consists of sentences in the representation language\n* Representation language has a syntax to specify well-formed sentences\n* Logic defines semantics (meaning) of the sentences\n* semantics defines the truth of each sentence with respect to a model\n* logic connective: not, and, or, implies, if and only if\n* Complex sentences are constructed from simpler sentences using \n* parenthesis and logical connectives\n* monotonicity -> soundness\n* Conjunctive Normal Form (CNF)\n* Definite clause is the disjunction of literals where only one is positive\n* Horn clause is the disjunction of literals where at most one is positive \n* (includes definite clauses)\n* Forward chaining: a form of data-driven reasoning; \n* agent starts with known data, adds premises as new percepts come in, \n* and apply forward chaining algorithm to derive new conclusions incrementally\n* Backward chaining: goes backwards from a query; for a false query, \n* if all premises of one of the implications in the KB whose conclusion \n* is the query, then the query is true\n\n\n## Module 7 Definitions\n* **Axiom** - a sentence that is given; not derived from other sentences\n* **Inference** - derive new sentences from old sentences\n* **Semantics** - the meaning of sentences\n* **Positive literal** - an atomic sentence\n* **Negative literal** - a negated atomic sentence\n* **Literal** - positive literal | negative literal\n* **Validity** - if a sentence is true in all models\n* **Tautology** - valid sentence that is necessarily true\n* **Satisfiability** - if a sentence is true in (satisfied by) some model\n* **Reductio ad absurdum** - reduction to an absurd thing; proof by refutation/ contradiction\n* **Soundness** - the inference algorithm only derives entailed sentences\n* **Completeness** - the inference algorithm can derive all entailed sentences\n* **Logical equivalence** - two sentences are true in the same set of models\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "1124e88f-ea14-4e4d-be13-ec76d5d76937"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module1_markdown, \n",
        "                             module2_markdown, \n",
        "                             module3_markdown, \n",
        "                             module4_markdown, \n",
        "                             module5_markdown,\n",
        "                             module6_markdown,\n",
        "                             module7_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": 65,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n\n* AI is a rational agent that aims to reach the best expected outcome\n* make correct inferences/ decide whether an action is best\n* do the right thing - depends on how we human define right thing\n\n\n## AIMA Chapter 27.1 The Limits of AI\n\n* Turing test: focus on whether machines can perform well on open-ended behavioral tasks,\n* instead of asking philosophical questions (e.g. whether machines can think)\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n\n* No need to ask the question whether Machines Can Think according to Edsger Dijkstra\n* The Chinese room - generate intelligent Chinese response by following\n* the rule book written in English without knowing Chinese\n\n\n## AIMA 2.1 Agents and Environments\n\n* An agent’s choice of action depends on its knowledge \n* and its percept sequence till the current moment\n\n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n\n* Whether an agent is rational/does the right thing is evaluated with \n* consequentialism - the consequence of its behaviors\n* Four factors to decide what is rational: \n* 1. performance measure (defines the criterion of success)\n* 2. agents’ prior knowledge about its environment\n* 3. agent’s possible actions\n* 4. agent’s percept sequence till the moment\n* omniscience agent: knows the actual outcome of actions, acts accordingly\n* omniscience is impossible in real life\n\n\n## AIMA 2.3 The Nature of Environments\n\n* properties of task environmnets: \n* fully observable vs. partially observable\n* single-agent vs. multiagent; competitive vs. cooperative\n* deterministic vs. nondeterministic\n* episodic vs. sequential\n* static vs. dynamic\n* discrete vs. continuous\n* known vs. unknown\n\n\n## AIMA 2.4 The Structure of Agents\n\n* Types of agents: simple reflex, model-based, goal-based, utility-based\n* Agents improve their performance via learning\n\n\n## Module 1 Lecture Notes\n\n* four views of AI: think humanly, think rationally, act humanly, act rationally\n* agent: anything that \n* 1. perceives its environment through sensors\n* 2. act upon its environment through actuators\n* e.g. human agent: eyes, ears (sensors), hands, legs, mouth (actuators);\n* robotic agent: cameras, infrared range finders (sensors), motors (actuators)\n* humans, robots, softbots, thermostats are all considered as agents\n* percept: the agent’s perceptual inputs at any moment\n* agent = architecture + program\n* rational agent: perceives environment and acts rationally (does the right thing)\n* We defined a performance measure to check if the agent is acting rationally\n* ROT for performance measures: \n* what you want to be achieved > how you think the agent should behave\n* rationality != omniscience; rationality != guaranteed success\n* complete rationality is not achievable due to computational limitations\n* rational agents select actions to maximize the expected value \n* (no need to know what the actual outcome will be)\n* hardest environment: continuous, partially observable, stochastic, multi-agent\n\n\n## Module 1 Definitions\n* **Agent** - anything that can perceive and act in an environment\n* **Percept** - what the agent has perceived\n* **Value alignment problem** - machine’s values/ objectives = human’s\n* **Weak ai** - machines act as if intelligent\n* **Strong ai** - can solve a wide variety of tasks just like human\n* **Turing test** - whether AI can pass a behavioral test\n* **Percept sequence** - a complete history of things the agent has perceived\n* **Agent function** - an abstract math description\n* **Agent program** - a concrete/physical implementation\n* **Rational agent** - selects action expected to maximize performance from percept sequence & knowledge\n* **Omniscience** - knows everything\n* **Autonomy** - learn to compensate for partial/incorrect prior knowledge\n* **Peas** - performance measure, environment, actuators, sensors\n* **Fully vs. partially observable** - whether agent’s sensors give it access to complete state of environment continually\n* **Unobservable** - no sensors\n* **Deterministic vs. nondeterministic** - whether next state fully determined by current state and actions taken\n* **Stochastic** - random; explicitly deals with quantified probabilities\n* **Episodic** - agent’s experience divided into episodes (next episode doesn’t depend on the previous)\n* **Sequential** - future decisions depend on current decision\n* **Static vs. dynamic** - whether environment can be changed by agent’s actions\n* **Simple reflex agents** - choose action based on the current percept and ignores rest of percept history\n* **Model-based reflex agents** - deal with partial observability by tracking part it can’t see now; maintains internal state from percept history\n* **Goal-based agents** - w/ goal information that describes desirable situations and selects actions to achieve goal\n* **Utility-based agents** - select actions to maximize expected utility\n\n\n# Module 2: Python\n## Module 2 Lecture Notes\n\n* developed by Guido van Rossum in 1989\n* inspired by ABC language\n* positive features: fast development, portable, various built-in types, \n* large collection of support libraries\n* all data is treated as objects; \n* an object gets deleted once it becomes unreachable (by garbage collection)\n* strong typing: each object has a fixed type\n* dynamic typing: variables come into existence when first assigned; \n* type errors only caught at runtime\n* strings are immutable; lists are mutable\n* sequence types: tuple, string, list\n* Tuple: cannot be modified once created; \n* items can be of mixed types (including collection types)\n* Strings: unicode; use 2-byte characters\n* Dictionaries: unordered; keys must be immutable\n* Function multiple return: return type is a tuple\n* Python does not allow function overloading; \n* each function is specified by its name alone \n* no two functions can have the same name even they have different parameters\n* operator overloading is possible\n* *args: accept a variable number of non-keyword arguments for a function\n```\ndef print_everything(*args):\n\t#args is a tuple of arguments passed to the fn\n\tprint(args) \nprint_everything('a', 'b', 'c’) # ('a', 'b', 'c’) \nlst = ['a', 'b', 'c’] \nprint_everything(*lst) # ('a', 'b', 'c’) \n```\n* kwargs: accept a variable number of keyword arguments for a function\n```\ndef print_keyword_args(**kwargs):\n  # kwargs is a dict of the keyword args passed to the fn \n\tprint(kwargs) \nprint_keyword_args(first_name=\"John\", last_name=\"Doe\") \n# {'first_name': 'John', 'last_name': 'Doe’} \nmy_dict = {'first_name': 'Wei', 'last_name': 'Xu’} \nprint_keyword_args(**my_dict)\n# {'first_name': 'Wei', 'last_name': 'Xu'} \n```\n* functions are first-class objects\n* a class can extend another class \n* no ‘extends’ keyword like java & supports multiple-inheritance\n\n\n## Module 2 Definitions\n* **Mutability** - whether values of an object can be changed\n* **Repl** - read-evaluate-print loop\n\n\n# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n\n* search problem: state space, initial state, actions, \n* transition model, goal states, action cost\n\n\n## AIMA Chapter 3.2 Example Problems\n\n* route-finding problem\n* touring problem - e.g. traveling salesperson problem\n* VLSI layout problem\n* robot navigation\n* automatic assembly sequencing\n\n\n## AIMA Chapter 3.3 Search Algorithms\n\n* best-first search (graph)\n* node data structure: state, parent, action, path-cost\n* graph search checks for redundant paths\n* tree search does not check for redundant paths\n* measuring performance: completeness, cost optimality, \n* time complexity, space complexity\n\n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n\n* given no clue about the distance between its current state and the goals\n* Breadth-first search (BFS) has both time and space complexity of O(b^d)\n* Dijkstra’s algorithm - uniform-cost search\n* Uniform-cost search is complete and cost-optimal\n* Depth-first search (DFS) - always expands deepest node in frontier, \n* not cost-optimal (returns first solution, not guaranteed cheapest)\n* DFS is not complete because it can get stuck in an infinite path\n* backtracking: a variant of DFS (less memory)\n* depth-limited search - time complexity O(b^l) l = depth limit; \n* space complexity O(bl); can fail if the choice for l is bad\n* iterative deepening search - O(bd) space & O(b^d) time when there’s a solution, \n* O(bm) space & O(b^m) time when no solution on finite state space\n* depth-limited search & iterative deepening search: \n* optimal when actions have same cost\n* bidirectional search: searches forward from initial state and backwards from \n* goal state at the same time, hoping they will meet (b^(d/2) * b^(d/2) < b^d )\n\n\n## Module 3 Lecture Notes\n\n* simple reflex agent: selects an action based on current percept \n* & ignore the rest of the percept history\n* problem-solving agent: plans ahead \n* & considers a sequence of actions forming a path to goal\n* solution: a sequence of actions from initial state to goal state\n* uninformed search: all non-goal nodes in frontier look equally good\n* informed search: some non-goal nodes are better than others\n* time/space complexity variables: \n* b - maximum branching factor of search tree\n* d - depth of shallowest goal node\n* m - maximum length of any path in state space (can be infinity)\n* BFS: expands shallowest unexpanded node; frontier is FIFO\n* DFS: expands deepest unexpanded node; frontier if LIFO\n* Use DFS when space is restructured | many possible solutions with long paths \n* | wrong paths terminated quickly | searched can be fine-tuned quickly\n* Use BFS when there can be infinite paths | some solutions have short paths \n* | can quickly discard unlikely paths\n\n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n* **State space** - possible states of the environment\n* **Search algorithm** - input - search problem; output: solution/report failure\n* **Depth (d)** - number of actions in the optimal solution\n* **M** - maximum number of actions in all path/ maximum depth of search tree\n* **Branching factor (b)** - number of successors for each node considered\n* **L** - depth limit\n* **Frontier** - states available for expanding\n\n\n# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n\n* Greedy best-first search: f(n) = h(n)\n* A* serach: f(n) = g(n) + h(n)\n* A* if cost=optimal if the heuristic is admissible\n* A* prunes unnecessary nodes when finding the optimal solution\n* memory-bounded search:\n* beam search: limits size of frontier; e.g. keeps only k best nodes\n* Iterative-deepening A* search (IDA*): \n* similar to iterative-deepening search to DFS\n* Recursive best-first search (RBFS): \n* mimics standard best-first search while using linear space\n\n\n## AIMA Chapter 3.6 Heuristic Functions\n\n* quality of the heuristic function decides the performance of \n* the heuristic search algorithm\n* ways to find a good heuristic: relaxing problem definition, \n* storing precomputed solution costs, defining landmarks, \n* learning from experience of similar problems\n\n\n## Module 4 Lecture Notes\n\n* Search strategy: order of tree expansion; \n* impelled by different queue structures (LIFO, FIFO, priority)\n* dimensions for evaluation: completeness, optimality, time/space complexity\n* time complexity: number of nodes generated\n* space complexity: number of nodes in memory at the same time\n* heuristic knowledge: useful, not necessarily correct\n* key concept of A* search: admissible heuristics\n* How to find an admissible heuristic: \n* find the cost of an optimal solution to a relaxed problem\n* dominance: if h2(n) >= h1(n) for all n (both admissible), then h2 dominates h1\n* h2 is optimistic but more accurate than h1 -> h2 is better for search\n* A heuristic h is admissible if 0 <= h(n) <= h*(n), \n* h * (n) = true cost to nearest goal\n\n\n## Module 4 Definitions\n* **Heuristic function** - estimates the lowest cost from current node to goal\n* **G(n)** - path cost from initial state to node n\n* **H(n)** - estimated cost of shortest path from node n to goal\n* **F(n)** - estimated cost of best path from node n to goal\n* **Admissible** - never overestimates the path cost to goal; optimistic\n* **Monotonic** - cost always increases along a path\n* **Relaxed problem** - a problem with fewer restrictions on the actions than the original problem\n\n\n# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n\n* Elements in a game: initial state, whose turn it is, \n* set of legal moves in state, transition model, terminal test\n\n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n\n* ply: one move by one player\n* pruning: no need to examine every state\n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n\n* EVAL(s, p): heuristic evaluation function; \n* returns expected utility of state s to player p\n* Beam search is one approach of forward pruning\n\n\n## AIMA Chapter 5.5 Stochastic Games\n\n* Stochastic games: unpredictable\n* A chance node is evaluated by computing the average utility of its children\n\n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n\n* Maximum expected utility (MEU): \n* rational agent should select the action which maximizes its expected utility\n\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n\n* Orderability: given two lotteries, agent must either prefer on \n* or view them as equally preferable; cannot avoid deciding\n* Transitivity: prefers A to B & prefers B to C -> must prefer A to C\n* Continuity\n* Substitutability\n* Monotonicity: if agent prefers outcome A to outcome B, \n* then it must prefer the lottery with higher probability for A\n* Decomposability: reduce compound lotteries to simpler lotteries \n* using laws of probability \n\n\n## AIMA Chapter 16.3 Utility Functions\n\n* QALY: quality-adjusted life year\n\n\n## Module 5 Lecture Notes\n\n* Simplest game environment: multi-agent, static, discrete, \n* fully observable, strategic\n* Static: no change while an agent is deliberating\n* Discrete: a finite set of percepts & actions\n* Fully observable: agent has the complete state of the environment via its sensors\n* Strategic: next state determined by current state \n* & agent’s action & other agent’s action\n* Evaluation function f(n); zero-sum assumption -> \n* f(n) > 0 if MAX is winning at n\n* f(n) = 0 if tied at n\n* f(n) < 0 if MIN is winning at n\n* alpha-beta pruning: \n* a (alpha): MAX’s current lower bound on MAX’s outcome; \n* MAX will never allow a move that leads to a worse score (for MAX) than a \n* b (beta): MIN’s current upper bound on MIN’S outcome; \n* MIN will never allow a move that leads to a better score (for MAX) than b\n\n\n## Module 5 Definitions\n* **Perfect information** - fully observable\n* **Zero-sum** - no win-win; good for one player is bad for the other player\n* **Stochastic games** - randomly determined; unpredictable\n* **Expected utility** - the avg. utility of all outcomes weighted by probability of each outcome\n* **Optimizer’s curse** - the best choice’s estimated expected utility tends to be very high\n* **Normative theory** - describes how the rational agent is supposed to act\n* **Descriptive theory** - describes how the rational agent actually acts\n\n\n# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n\n* three components of CSP: X, D, C\n* X: a set of variables\n* D: a set of domains, one domain for each variable\n* C: a set of constraints \n* CSP solves the problem of assigning values to variables\n* a consistent assignment is one that does not violate any constraints\n* a complete assignment is one where each variable is assigned a value\n* a solution to CSP is consistent and complete\n* a partial assignment is one where some variables remind unassigned\n* a partial solution is a consistent partial assignment\n* solving a CSP is an NP-complete problem\n\n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n\n* Constraint propagation: reduce number of legal values for a variable \n* using constraints -> reduce for other variables\n* Node-consistent: all values in a variable’s domain satisfy its unary constraints \n* Arc-consistency: binary\n* Path-consistency: tightens binary constraints; \n* looks at triples of variables to infer implicit constraints\n\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n\n* Commutativity: a crucial property of CSP; \n* order of any set of actions does not matter\n* Forward checking: when X is assigned, it established arc consistency; \n* for each unassigned Y connected to X by a constraint, \n* remove all inconsistent values from Y’s domain according to the value of X\n* MAC: maintaining arc consistency\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n\n* min-conflicts heuristic: select value resulting in min numbers of conflicts\n\n\n## AIMA Chapter 6.5 The Structure of Problems\n\n* Cutset conditioning:\n* 1. Select a subset S (cycle cutset) of CSP’s variables \n* so that the constraint graph becomes a tree after the removal\n* 2. Find all possible assignments to the variables in S \n* which satisfies all constraints, and for each: remove all values inconsistent \n* with the assignment for S from domains of remaining variables & return a \n* solution with the assignment for S if the remaining CSP has a solution\n* Tree decomposition: turn original graph into a tree \n* each node in the tree is a set of variables)\n* Three requirements of tree decomposition:\n* 1. For each variable in the original problem, \n* it is guaranteed that it appears in at least one node in the tree\n* 2. Two variables (if connected by a constraint in original problem) \n* must appear together (with the constraint) in at least one node in the tree\n* 3. A variable appears in two nodes in tree -> must appear in each node \n* along the path that connects these nodes\n* tree width (tree decomposition): ones less than size of largest node\n\n\n## Module 6 Lecture Notes\n\n* Benefits of CSP: clean specification (convert problem to CSP & solve with \n* general approach), “knows” what variables violate constraints, \n* automatically prunes branches that violate constraints\n* varieties of constraints:\n* 1. Unary: involves a single variable (e.g. SA != green)\n* 2. Binary: involves a pair of variables (e.g. SA != WA)\n* 3. High-order: involves 3 or more variables\n* 4. Preference: soft constraints (e.g. red is better than green)\n* express CSP as a search problem:\n* 1. Initial state: empty assignment {}\n* 2. Successors: assign a value to any unassigned variable given there’s no conflict\n* 3. Goal: the current assignment is complete\n* 4. Path cost: constant cost for each step\n* Use DFS for solving CSP because solution always found at depth n for n variables\n* Heuristics to improve backtracking: most constrained variable, \n* most constraining variable (if ties), least constraining value \n* (order of trying a variable’s values), forward checking (detect failure early)\n* Inference in CSPs: constraint propagation \n* node consistency (unary constraints), arc consistency (binary constraints)\n\n\n## Module 6 Definitions\n* **Inference** - rules out certain variable assignments using constraints\n* **Backtracking search** - commonly used to solve CSPs; a form of DFS\n\n\n# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n\n* Declarative: start with empty knowledge base, tell the agent sentences \n* it needs to know one by one, until the agent knows what to do\n* Procedural: encode deserted behaviors as code directly\n* A successful agent combines declarative & procedural approaches in its design\n\n\n## AIMA Chapter 7.2 The Wumpus World\n\n* Wumpus world: a cave with rooms connected by passageways; \n* there’s a wumpus somewhere in the cave; the agent has only one arrow \n* and can shoot the wumpus; some rooms can trap anyone who go into the rooms \n* (except for the wumpus) with bottomless pits; \n* reward: find a heap of gold in this environment\n\n\n## AIMA Chapter 7.3 Logic\n\n* possible world -> model\n* logical entailment between sentences: a |= b\n\n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n\n* atomic sentences consist of only one proposition symbol\n\n\n## AIMA 7.5 Propositional Theorem Proving\n\n* Define a proof problem:\n* 1. initial state: initial knowledge base\n* 2. actions: all inference rules applied to all sentences \n* matching top half of inference rule\n* 3. result: add the sentence in bottom half of inference rule\n* 4. goal: a state containing the target sentence / \n* Ground resolution theorem: a set of clauses is unsatisfiable -> \n* resolution closure of the set of clauses contains the empty clause\n\n\n## Module 7 Lecture Notes\n\n* KB consists of sentences in the representation language\n* Representation language has a syntax to specify well-formed sentences\n* Logic defines semantics (meaning) of the sentences\n* semantics defines the truth of each sentence with respect to a model\n* logic connective: not, and, or, implies, if and only if\n* Complex sentences are constructed from simpler sentences using \n* parenthesis and logical connectives\n* monotonicity -> soundness\n* Conjunctive Normal Form (CNF)\n* Definite clause is the disjunction of literals where only one is positive\n* Horn clause is the disjunction of literals where at most one is positive \n* (includes definite clauses)\n* Forward chaining: a form of data-driven reasoning; \n* agent starts with known data, adds premises as new percepts come in, \n* and apply forward chaining algorithm to derive new conclusions incrementally\n* Backward chaining: goes backwards from a query; for a false query, \n* if all premises of one of the implications in the KB whose conclusion \n* is the query, then the query is true\n\n\n## Module 7 Definitions\n* **Axiom** - a sentence that is given; not derived from other sentences\n* **Inference** - derive new sentences from old sentences\n* **Semantics** - the meaning of sentences\n* **Positive literal** - an atomic sentence\n* **Negative literal** - a negated atomic sentence\n* **Literal** - positive literal | negative literal\n* **Validity** - if a sentence is true in all models\n* **Tautology** - valid sentence that is necessarily true\n* **Satisfiability** - if a sentence is true in (satisfied by) some model\n* **Reductio ad absurdum** - reduction to an absurd thing; proof by refutation/ contradiction\n* **Soundness** - the inference algorithm only derives entailed sentences\n* **Completeness** - the inference algorithm can derive all entailed sentences\n* **Logical equivalence** - two sentences are true in the same set of models\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}