{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "tthang-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": "ba7c92f1-1765-4166-a83f-8dfe50a56b53"
      },
      "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": 19,
      "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": "1ce281c3-ef4d-404b-e13e-b657e3d5b009"
      },
      "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": 20,
      "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": 21,
      "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 = \"\"\" 2 dimensions: human vs rational and thought vs behavior\n",
        "1. Acting humanly: turing test = can human tell if it's from a computer vs person? Computer would need NLP, knowledge representation, automated\n",
        "reasoning, machine learning to pass. Total turing test requires interaction with objects and people in real world --> robot will need computer vision, speech recognition, and robotics\\n\n",
        "2. Thinking humanly: cognitive modeling - introspection, psychological experiments, brain imaging\\n\n",
        "3. Thinking rationally: laws of thought - syllogisms and logic + probability, emphasis on correct inference \\n\n",
        "4. Acting rationally: rational agent - 2 advantages: more general than \"laws of thought\" & more amedable to scientific development \\n\n",
        "We want agents that are provably beneficial to humans\n",
        "\"\"\" \n",
        "\n",
        "# Russell and Norvig, AIMA 4th Edition, Chapter 27 “Philosophical Foundations”, Sections 27.1 “The Limits of AI” and 27.2 “Can Machines Really Think?”\n",
        "chapter27_1 = \"\"\" \n",
        "weak AI: machines act as if they were intelligent vs strong AI: actually consciously thinking\n",
        "\"\"\"\n",
        "chapter27_2 = \"\"\" \n",
        "Chinese room argument by John Searle - application of rules to input symbols isn't \n",
        "true intelligence\n",
        "\"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA 4th Edition, Chapter 2 “Intelligent Agents” (whole chapter)\n",
        "chapter2_1 = \"\"\" An agent's choice of action can depends on its built-in knowledge and the entire percept sequence observed to date (not the future).\n",
        "Math speak: agent's behavior is described by the agent function that maps percept sequence to action. Internally, the agent function will be implemented by an agent program.\n",
        "Agent function is an abstract math description, agent program is a concrete implementation\"\"\"\n",
        "chapter2_2 = \"\"\" \n",
        "Performace measures: general rule = design according to what one wants to be achieved in the environment, rather than how one thinks \n",
        "the agent should behave. \\n\n",
        "Rationality vs omniscience - rationality is not perfection. Doing actions to modify future percepts = information gathering ie. exploration \\n\n",
        "rational agent should be autonomous \"\"\"\n",
        "chapter2_3 = \"\"\" \n",
        "task enviroments = \"problems\" to which rational agents are the \"solution\" \\n\n",
        "Specifying task environment: PEAS (performance, envirnment, actuators, sensors) \\n\n",
        "Fully = agent's sensors give access to complete state of environment at each point in time vs. partially observable \\n\n",
        "Single vs Multiagent: key distinction is whether B's behavior is best described as maximizing a performance measure whose value depends on A's behavior \\n\n",
        "Deterministic = next state of environment completely determined by current state + action vs Nondeterministic \\n\n",
        "Episodic vs. Sequential = current action affect future decisions \\n\n",
        "Static [crossword] vs dynamic [taxi] vs semidynamic [chess]= environment doesn't change with time but performace score does \\n\n",
        "Known vs Unknown: agent's state of knowledge about the law of physics of the environment. ie. solitaire = known but partially observable \\n\n",
        "The hardest case is partially observable, multiagent, nondeterministic, sequential, dynamic, continuous, and unknown\"\"\"\n",
        "chapter2_4 = \"\"\"\n",
        "agent = architecture (device with sensors and actuators) + program (implements agent function)\\n\n",
        "table driven approach - doom to fail cuz contains too many entries $\\sum|P|^t$ \\n\n",
        "1. Simple reflex agents: select actions on the crrent percept. Condition-action rule. Problem of infinite loops in partialy observable \n",
        "environments --> escape by randomize its action \\n\n",
        "2. Model-based reflex agent: handle partial observability by keep track of part of the world it can't see now = internal state. \n",
        "Updating internal state requires info about how the world changes over time (transition model) + how the state of the world is reflected in the agent's percepts (sensor model)\\n\n",
        "3. Goal-based agent: search and planning. Appear less efficient but more flexible \\n\n",
        "4. Utility-based agent: internal utility function matches external performance measure\\n\n",
        "Learning agent: learning element (for making improvements), performance element* (select external action), critic (give feedback),\n",
        "problem generator (suggest actions that will lead to new experience) \\n\n",
        "State representation: atomic, factored (each stte has fixed set of variables or attributes, value), \n",
        "structured\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module1_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 1.\n",
        "# You can define any bolded term in the textbook, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 20 words long.\n",
        "module1_definitions = {\n",
        "\"rationality\": \"doing the right thing --> standard model\",\n",
        "\"cognitive science\": \"interdisciplinary field that brings together AI computer models and psychology to model human minds\",\n",
        "\"value alignment problem\": \"the objective put into the machine has to aligh with humans' value\",\n",
        "\"agent\" : \"anything that can perceive (through sensors) and act (through actuators) in an environment\",\n",
        "\"rational agent\" : \"select action to maximize expected performance measure, given the percept sequence and built-in knowledge\",\n",
        "\"percept\" : \"the content that agent's sensors perceive\",\n",
        "\"consequentialism\" : \"evaluate agent's behavior by its consequences\",\n",
        "\"omniscience\": \"know the actual outcome of its action and act accordingly, but impoassible in reality\",\n",
        "\"autonomy\": \"learn to compensate for partial or incorrect prior knowledge\",\n",
        "\"stochastic\": \"explicitly deal with probability vs nondeterministic (possibility not quantified)\",\n",
        "\"transition model\": \"knowledge about how the world works\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 22,
      "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": "b11c4b65-d18d-4e83-eeba-ce59576e68c3"
      },
      "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": 23,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n 2 dimensions: human vs rational and thought vs behavior\n1. Acting humanly: turing test = can human tell if it's from a computer vs person? Computer would need NLP, knowledge representation, automated\nreasoning, machine learning to pass. Total turing test requires interaction with objects and people in real world --> robot will need computer vision, speech recognition, and robotics\n\n2. Thinking humanly: cognitive modeling - introspection, psychological experiments, brain imaging\n\n3. Thinking rationally: laws of thought - syllogisms and logic + probability, emphasis on correct inference \n\n4. Acting rationally: rational agent - 2 advantages: more general than \"laws of thought\" & more amedable to scientific development \n\nWe want agents that are provably beneficial to humans\n\n\n## AIMA Chapter 27.1 The Limits of AI\n \nweak AI: machines act as if they were intelligent vs strong AI: actually consciously thinking\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n \nChinese room argument by John Searle - application of rules to input symbols isn't \ntrue intelligence\n\n\n## AIMA 2.1 Agents and Environments\n An agent's choice of action can depends on its built-in knowledge and the entire percept sequence observed to date (not the future).\nMath speak: agent's behavior is described by the agent function that maps percept sequence to action. Internally, the agent function will be implemented by an agent program.\nAgent function is an abstract math description, agent program is a concrete implementation\n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n \nPerformace measures: general rule = design according to what one wants to be achieved in the environment, rather than how one thinks \nthe agent should behave. \n\nRationality vs omniscience - rationality is not perfection. Doing actions to modify future percepts = information gathering ie. exploration \n\nrational agent should be autonomous \n\n## AIMA 2.3 The Nature of Environments\n \ntask enviroments = \"problems\" to which rational agents are the \"solution\" \n\nSpecifying task environment: PEAS (performance, envirnment, actuators, sensors) \n\nFully = agent's sensors give access to complete state of environment at each point in time vs. partially observable \n\nSingle vs Multiagent: key distinction is whether B's behavior is best described as maximizing a performance measure whose value depends on A's behavior \n\nDeterministic = next state of environment completely determined by current state + action vs Nondeterministic \n\nEpisodic vs. Sequential = current action affect future decisions \n\nStatic [crossword] vs dynamic [taxi] vs semidynamic [chess]= environment doesn't change with time but performace score does \n\nKnown vs Unknown: agent's state of knowledge about the law of physics of the environment. ie. solitaire = known but partially observable \n\nThe hardest case is partially observable, multiagent, nondeterministic, sequential, dynamic, continuous, and unknown\n\n## AIMA 2.4 The Structure of Agents\n\nagent = architecture (device with sensors and actuators) + program (implements agent function)\n\ntable driven approach - doom to fail cuz contains too many entries $\\sum|P|^t$ \n\n1. Simple reflex agents: select actions on the crrent percept. Condition-action rule. Problem of infinite loops in partialy observable \nenvironments --> escape by randomize its action \n\n2. Model-based reflex agent: handle partial observability by keep track of part of the world it can't see now = internal state. \nUpdating internal state requires info about how the world changes over time (transition model) + how the state of the world is reflected in the agent's percepts (sensor model)\n\n3. Goal-based agent: search and planning. Appear less efficient but more flexible \n\n4. Utility-based agent: internal utility function matches external performance measure\n\nLearning agent: learning element (for making improvements), performance element* (select external action), critic (give feedback),\nproblem generator (suggest actions that will lead to new experience) \n\nState representation: atomic, factored (each stte has fixed set of variables or attributes, value), \nstructured\n\n\n## Module 1 Lecture Notes\n Your summary here \n\n## Module 1 Definitions\n* **Rationality** - doing the right thing --> standard model\n* **Cognitive science** - interdisciplinary field that brings together AI computer models and psychology to model human minds\n* **Value alignment problem** - the objective put into the machine has to aligh with humans' value\n* **Agent** - anything that can perceive (through sensors) and act (through actuators) in an environment\n* **Rational agent** - select action to maximize expected performance measure, given the percept sequence and built-in knowledge\n* **Percept** - the content that agent's sensors perceive\n* **Consequentialism** - evaluate agent's behavior by its consequences\n* **Omniscience** - know the actual outcome of its action and act accordingly, but impoassible in reality\n* **Autonomy** - learn to compensate for partial or incorrect prior knowledge\n* **Stochastic** - explicitly deal with probability vs nondeterministic (possibility not quantified)\n* **Transition model** - knowledge about how the world works\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",
        "- list(range(1,101)) = a single line of code to create a list containing values from 1 to 100, [1, 2, …, 100] \\n\n",
        "- mlist[:][0] ->[:] creates a copy of the list, which means we are modifying the copy but not the original.\n",
        "- tuple, strings are immutable\n",
        "- list is mutable\n",
        "- no function overloading in python, function is specified by its name alone. BUT \n",
        "operator overloading (+,==,-) is possible\n",
        "- *args: accept a variable number of non-keyword arguments\n",
        "- **kwargs: accept a variable number of keyword arguments ie. **my_dict\n",
        "\"\"\"\n",
        "\n",
        "# Each definition should be at most 20 words long.\n",
        "module2_definitions = {\n",
        "\"mutability\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 24,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 348
        },
        "outputId": "2b767897-5737-4496-c272-61d77a872f1d"
      },
      "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": 25,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 2: Python\n## Module 2 Lecture Notes\n \n- list(range(1,101)) = a single line of code to create a list containing values from 1 to 100, [1, 2, …, 100] \n\n- mlist[:][0] ->[:] creates a copy of the list, which means we are modifying the copy but not the original.\n- tuple, strings are immutable\n- list is mutable\n- no function overloading in python, function is specified by its name alone. BUT \noperator overloading (+,==,-) is possible\n- *args: accept a variable number of non-keyword arguments\n- **kwargs: accept a variable number of keyword arguments ie. **my_dict\n\n\n## Module 2 Definitions\n* **Mutability** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 3 - Search Problems"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 3 “Problem Solving by Search” (3.1-3.4)\n",
        "chapter3_1 = \"\"\" Assume agent has access to info about the world. 4 phase problem-solving process \\n\n",
        "1. Goal formulation\n",
        "2. Problem formulation\n",
        "3. Search: find sequence of actions that reaches the goal = solution\n",
        "4. Execution \\n\n",
        "In a fully observable, deterministic, known environment, the solution to any problem is a fixed sequence of actions \\n\n",
        "Search problem: state space, intitial state, goal states, actions, transition model, action cost function\n",
        "  \"\"\"\n",
        "chapter3_2 = \"\"\"\n",
        "Standardized [grid world, sokoban puzzle, sliding tiles] vs real world problems\n",
        "[touring problem, traveling salesperson, robot]\"\"\"\n",
        "chapter3_3 = \"\"\" \n",
        "- node = state in state space\n",
        "- edge = actions\n",
        "- root = initial state\n",
        "\n",
        "frontier separates two regions of the state-space graph: an interior region\n",
        "where every state has been expanded, and an exterior region of states that have not yet\n",
        "been reached \\n\n",
        "best-first search: choose node on frontier with minimum value of evaluation function, f(n). \n",
        "Return either solution node or failure. Use priority queue (min cost). Reached is a mapping from states to nodes \\n\n",
        "Remember redundant path: \n",
        "1. remember all previously reached states [best-first search] \n",
        "2. not worry about repeating the past: graph search [checks redundant path], tree-like search [doesn't check]\n",
        "3. check just for cycles: takes constant time for small cycles\"\"\"\n",
        "chapter3_4 = \"\"\" access only the problem description\n",
        "1. Breadth-first search: best-first search where f(n) is the depth of the node, FIFO queue, early goal test\n",
        "2. Uniform-cost search (Dijkstra): f(n) is cost of path from root to current node. Late goal test\n",
        "3. Depth-first search: can use best-first search where f(n) is negative of the depth BUT usually implemented as a tree search\n",
        "that doesn't keep table of reached states. Can get stuck in an infinite loop in cyclic state spaces or go down infinite path.\n",
        "Much smaller memory need. Backtracking search adapted from DFS with even less memory req.\n",
        "4. Depth-limited and iterative deepening: Each iteration generates a new level, similar to BFS\n",
        "but BFS stores all nodes in memory, while ids repeats the previous levels - saving memory at the cost of more time\n",
        "5. Bidirectional: searches forward from the initial state and backwards from the goal state(s)\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module3_lecture_notes = \"\"\" When correct action is not obvious, an agent needs to plan ahead = consider sequence of actions \n",
        "that form a path to a goal state. We call that agent a problem-solving agent, and the process is called search.\n",
        "Use atomic representation \"\"\"\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",
        "\"open-loop\": \"systems that can ignore the percept - break the loop between agent and environment\",   \n",
        "\"optimal solution\": \"has lowest path cost\",   \n",
        "\"FIFO queue\": \"use in BFS\",   \n",
        "\"LIFO queue\": \"(stack) use in DFS\",\n",
        "\"redundant path\": \"less than optimal way to get to the same state, ie. different side of circle\",\n",
        "\"completeness\": \"algorithm guarantees to find a solution if there is one, and correctly report failure if there isn't\",\n",
        "\"early goal test\": \"check if a node is a solution when it is generated\",\n",
        "\"late goal test\": \"wait until a node is popped of the queue to check, used in best-first search\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 26,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "83fab24d-8c9f-43bb-b388-7fa8481bbf1a"
      },
      "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": 27,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n Assume agent has access to info about the world. 4 phase problem-solving process \n\n1. Goal formulation\n2. Problem formulation\n3. Search: find sequence of actions that reaches the goal = solution\n4. Execution \n\nIn a fully observable, deterministic, known environment, the solution to any problem is a fixed sequence of actions \n\nSearch problem: state space, intitial state, goal states, actions, transition model, action cost function\n  \n\n## AIMA Chapter 3.2 Example Problems\n\nStandardized [grid world, sokoban puzzle, sliding tiles] vs real world problems\n[touring problem, traveling salesperson, robot]\n\n## AIMA Chapter 3.3 Search Algorithms\n \n- node = state in state space\n- edge = actions\n- root = initial state\n\nfrontier separates two regions of the state-space graph: an interior region\nwhere every state has been expanded, and an exterior region of states that have not yet\nbeen reached \n\nbest-first search: choose node on frontier with minimum value of evaluation function, f(n). \nReturn either solution node or failure. Use priority queue (min cost). Reached is a mapping from states to nodes \n\nRemember redundant path: \n1. remember all previously reached states [best-first search] \n2. not worry about repeating the past: graph search [checks redundant path], tree-like search [doesn't check]\n3. check just for cycles: takes constant time for small cycles\n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n access only the problem description\n1. Breadth-first search: best-first search where f(n) is the depth of the node, FIFO queue, early goal test\n2. Uniform-cost search (Dijkstra): f(n) is cost of path from root to current node. Late goal test\n3. Depth-first search: can use best-first search where f(n) is negative of the depth BUT usually implemented as a tree search\nthat doesn't keep table of reached states. Can get stuck in an infinite loop in cyclic state spaces or go down infinite path.\nMuch smaller memory need. Backtracking search adapted from DFS with even less memory req.\n4. Depth-limited and iterative deepening: Each iteration generates a new level, similar to BFS\nbut BFS stores all nodes in memory, while ids repeats the previous levels - saving memory at the cost of more time\n5. Bidirectional: searches forward from the initial state and backwards from the goal state(s)\n\n\n## Module 3 Lecture Notes\n When correct action is not obvious, an agent needs to plan ahead = consider sequence of actions \nthat form a path to a goal state. We call that agent a problem-solving agent, and the process is called search.\nUse atomic representation \n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n* **Open-loop** - systems that can ignore the percept - break the loop between agent and environment\n* **Optimal solution** - has lowest path cost\n* **Fifo queue** - use in BFS\n* **Lifo queue** - (stack) use in DFS\n* **Redundant path** - less than optimal way to get to the same state, ie. different side of circle\n* **Completeness** - algorithm guarantees to find a solution if there is one, and correctly report failure if there isn't\n* **Early goal test** - check if a node is a solution when it is generated\n* **Late goal test** - wait until a node is popped of the queue to check, used in best-first search\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 4 - Informed Search"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 3 “Problem Solving by Search” (3.5-3.6)\n",
        "chapter3_5 = \"\"\" \n",
        "1. Greedy best-first search: expands first the node with lowest h(n) ie. straight line distance. \n",
        "Not optimal. Time and space $O(|V|)$, but can reach $O(bm)$ with good h(n)\n",
        "2. A* search: $f(n)=g(n)+h(n)$. Cost optimal. Heuristic is optimal and consistent $h(n)\\leq c(n,a,n')+h(n')$.\n",
        "Every consistent heuristic is admissible & first time we reach a state it will be on an optimal path - never \n",
        "have to change the frontier\n",
        "3. Satisficing search: inadmissible heuristics = accept suboptimal/good enough solution for faster search. \n",
        "weighted A*: $f(n)=g(n)+W\\cdot h(n), W>1$\n",
        "4. Memory-bounded search: save memory from duplication of nodes in frontier and reached.\n",
        "Reference counts = #times a state has been reach, remove from reached table when no more was to reach the state.\n",
        "- Beam search: limit frontier size, keep only k nodes with best f-scores or keep nodes with f-score within $\\delta$ of best f-score.\n",
        "Incomplete & suboptimal but fast\n",
        "- IDA*: not keep all reached states. The cutoff is f-cost at each iteration\n",
        "- Recursive best-first: use linear space, use f_limit variable to keep track of f-value of best alternative path = remembers f-value of \n",
        "best leaf in the forgotten subtree(backed-up value). Somewhat more efficient that IDA* but excessive node regeneration.\n",
        "RBFS is optimal with admissible h\n",
        "- MA* & SMA*: robust & optimal. Given enough time, they can solve problems for which A* runs out of memory. \n",
        "Expanding best leaf til full memory, back up value of forgotten nodes to its parent\n",
        "5. Bidirectional heuristic search\n",
        "\"\"\"\n",
        "chapter3_6 = \"\"\"\n",
        "Quality of heuristic: \n",
        "- effective branching factor b*: $N+1=1+b+b^2+...+b^d$. Good if close to 1\n",
        "- effective depth: reduce by constant $k_h$. Cost is now $O(b^{d-k_h})$\n",
        "- $h_2$ dominates $h_1$, $h_2\\geq h_1$\n",
        "- composite heuristic = max(all h)\n",
        "\n",
        "Relaxed problem = problem with fewer restrictions on the actions. The state-space graph of the relaxed problem is a supergraph of\n",
        "the original state space because the removal of restrictions creates added edges in the graph.\n",
        "The cost of an optimal solution to a relaxed problem is an admissible heuristic for the original problem. \\n\n",
        "A program called ABSOLVER can generate heuristics automatically from problem definitions. \\n\n",
        "- Generating h from subproblems: pattern databases\n",
        "- landmarks: precomputation of some optimal path costs\n",
        "- Learn how to search better? metalevel state space: each state in metalevel space captures internal (computational)\n",
        "state of a program that is searching in ordinary(object-level) state space\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module4_lecture_notes = \"\"\" Informed search uses domain-specific hints about the location of goals - \n",
        "heuristic function h(n) = estimated cost of the cheapest path from node to goal state \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module4_definitions = {\n",
        "\"admissible heuristic\" : \"h that never overstimates cost to reach a goal = optimistic\",    \n",
        "\"optimally efficient\" : \"any algo that uses the same h must expand all nodes surely expanded by A*\",    \n",
        "\"speedy search\" : \"a version of greedy best-first search [unbounded cost] with h = est. #actions to reach goal, regardless of cost\",    \n",
        "\"bounded supoptimal search\" : \"look for solution that is within a constant factor W of optimal cost\",    \n",
        "\"effective branching factor\" : \"branching factor that a uniform tree with dept d would need to contain N+1 nodes\"   \n",
        "}\n",
        "\n"
      ],
      "execution_count": 28,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 904
        },
        "cellView": "form",
        "outputId": "b778b9d6-1329-493e-8905-73e464d8270b"
      },
      "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": 29,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n \n1. Greedy best-first search: expands first the node with lowest h(n) ie. straight line distance. \nNot optimal. Time and space $O(|V|)$, but can reach $O(bm)$ with good h(n)\n2. A* search: $f(n)=g(n)+h(n)$. Cost optimal. Heuristic is optimal and consistent $h(n)\\leq c(n,a,n')+h(n')$.\nEvery consistent heuristic is admissible & first time we reach a state it will be on an optimal path - never \nhave to change the frontier\n3. Satisficing search: inadmissible heuristics = accept suboptimal/good enough solution for faster search. \nweighted A*: $f(n)=g(n)+W\\cdot h(n), W>1$\n4. Memory-bounded search: save memory from duplication of nodes in frontier and reached.\nReference counts = #times a state has been reach, remove from reached table when no more was to reach the state.\n- Beam search: limit frontier size, keep only k nodes with best f-scores or keep nodes with f-score within $\\delta$ of best f-score.\nIncomplete & suboptimal but fast\n- IDA*: not keep all reached states. The cutoff is f-cost at each iteration\n- Recursive best-first: use linear space, use f_limit variable to keep track of f-value of best alternative path = remembers f-value of \nbest leaf in the forgotten subtree(backed-up value). Somewhat more efficient that IDA* but excessive node regeneration.\nRBFS is optimal with admissible h\n- MA* & SMA*: robust & optimal. Given enough time, they can solve problems for which A* runs out of memory. \nExpanding best leaf til full memory, back up value of forgotten nodes to its parent\n5. Bidirectional heuristic search\n\n\n## AIMA Chapter 3.6 Heuristic Functions\n\nQuality of heuristic: \n- effective branching factor b*: $N+1=1+b+b^2+...+b^d$. Good if close to 1\n- effective depth: reduce by constant $k_h$. Cost is now $O(b^{d-k_h})$\n- $h_2$ dominates $h_1$, $h_2\\geq h_1$\n- composite heuristic = max(all h)\n\nRelaxed problem = problem with fewer restrictions on the actions. The state-space graph of the relaxed problem is a supergraph of\nthe original state space because the removal of restrictions creates added edges in the graph.\nThe cost of an optimal solution to a relaxed problem is an admissible heuristic for the original problem. \n\nA program called ABSOLVER can generate heuristics automatically from problem definitions. \n\n- Generating h from subproblems: pattern databases\n- landmarks: precomputation of some optimal path costs\n- Learn how to search better? metalevel state space: each state in metalevel space captures internal (computational)\nstate of a program that is searching in ordinary(object-level) state space\n\n\n## Module 4 Lecture Notes\n Informed search uses domain-specific hints about the location of goals - \nheuristic function h(n) = estimated cost of the cheapest path from node to goal state \n\n## Module 4 Definitions\n* **Admissible heuristic** - h that never overstimates cost to reach a goal = optimistic\n* **Optimally efficient** - any algo that uses the same h must expand all nodes surely expanded by A*\n* **Speedy search** - a version of greedy best-first search [unbounded cost] with h = est. #actions to reach goal, regardless of cost\n* **Bounded supoptimal search** - look for solution that is within a constant factor W of optimal cost\n* **Effective branching factor** - branching factor that a uniform tree with dept d would need to contain N+1 nodes\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",
        "perfect information (fully-observable), zero-sum games \\n\n",
        "- optimal strategy determined by working out the minimax value of each state in the tree\n",
        "- utility of being in that state, assume that both players play optimally\n",
        "\"\"\"\n",
        "chapter5_2 = \"\"\" \n",
        "- starts with MAX, minimax algo performs a depth-first exploration\n",
        "- time $O(b^m)$, space $O(bm)$ with m is max depth of tree, b is legal moves at each point\n",
        "- multiplayer: backed-up value of a node is the utility\n",
        "vector of the successor state with the highest value for the player choosing at n\n",
        "Alpha-beta pruning\n",
        "- $\\\\alpha$: value of the best (highest-value) choice we have found so far at any choice\n",
        "point along the path for MAX [at least]\n",
        "- $\\\\beta$: value of the best (lowest-value) choice we have found so far at any choice\n",
        "point along the path for MIN [at most]\n",
        "- if $v \\geq \\\\beta, v \\leq \\\\alpha$ then prune/cut off search\n",
        "- depends on order. With perfect ordering, need to examine $O(b^{m/2})$ nodes, effective\n",
        "branching factor is now $\\sqrt(b)$ instead of b. With random ordering, $O(b^{3m/4})$ nodes\n",
        "- can use IDS to find killer moves (best moves)\n",
        " \"\"\"\n",
        "chapter5_3 = \"\"\" \n",
        "With limited computation time, we can cut off the serach early. Replace utility function with eval, cutoff test instead of terminal test\n",
        "- UTILITY(loss, p) ≤ EVAL(s, p) ≤ UTILITY(win, p)\n",
        "- expected value/material value calculated from features of the state\n",
        "Cutting off search\n",
        "- modify ab pruning to call heuristic EVAL function when it's appropriate to cut search\n",
        "- should only applied to quiescent position - no pending moves ie. capture the queen\n",
        "- horizon effect: when the program is facing an opponent's move that can cause serious damage/unavoidable but \n",
        "can be temporily avoided using delay tactics - allow singular extensions to mitigate the effect\n",
        "Forward pruning: type B strategy\n",
        "- similar to human chess players: save computation time at risk of error\n",
        "- beam search\n",
        "- ProbCut: ab search that prunes nodes that are probably outside the window\n",
        "- late move reduction: assume ordering is good. Reduce depth of later moves\n",
        "\"\"\"\n",
        "chapter5_5 = \"\"\" \n",
        "Ex. backgammon\n",
        "- game tree includes chance nodes alongside MIN and MAX nodes\n",
        "- calculate expected value of a position = expectiminimax value: average over all possible outcomes of the chance nodes\n",
        "- expectiminimax considers all the possible dice-roll sequences, it will take $O(b^m n^m)$ time, with n = #distinct rolls\n",
        "\"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 16 “Making Simple Decisions” (16.1-16.3)\n",
        "chapter16_1 = \"\"\" \n",
        "- Uncertainty about the current state s, $P(RESULT(a) = s′)=\\sum_s P(s)P(s'∣s,a)$\n",
        "- agent's preference captured by a utility function -> expected utility \n",
        "- principle of maximum expected untility(MEU): rational agent should choose\n",
        "the action that maximizes the agent’s expected utility\n",
        "\"\"\"\n",
        "chapter16_2 = \"\"\" \n",
        "Constraints on rational preferences: leads to utility...axioms\n",
        "- agent needs only a preferenc eraning on states - numbers don't matter: value function/ordinal utility function\n",
        "\"\"\"\n",
        "chapter16_3 = \"\"\" \n",
        "preference elicitation: presenting choices to the human and\n",
        "using the observed preferences to pin down the underlying utility function\n",
        "\n",
        " \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module5_lecture_notes = \"\"\" \n",
        "Competitive environment: move = action, position = state\n",
        "- initial state, to-move(s), actions(s), result(s,a) transition model, is-terminal(s),\n",
        "utility(s,p) or objective/payoff function\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module5_definitions = {\n",
        "\"ply\" : \"one move by one player = one level deeper in the game tree\",  \n",
        "\"transpositions\" : \"repeated states occur cuz different permutations of moves end up in the same position -> keep transposition table\",    \n",
        "\"type A strategy\" : \"consider all possible moves (wide) at shallow depth\",    \n",
        "\"type B strategy\" : \"ignores moves that seem bad, deep but narrow\",\n",
        "\"policy\" : \"mapping from every state to best move for the state\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 30,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "fd9d46b4-9495-45f1-b32a-7d41ca60cc24"
      },
      "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": 31,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n \nperfect information (fully-observable), zero-sum games \n\n- optimal strategy determined by working out the minimax value of each state in the tree\n- utility of being in that state, assume that both players play optimally\n\n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n \n- starts with MAX, minimax algo performs a depth-first exploration\n- time $O(b^m)$, space $O(bm)$ with m is max depth of tree, b is legal moves at each point\n- multiplayer: backed-up value of a node is the utility\nvector of the successor state with the highest value for the player choosing at n\nAlpha-beta pruning\n- $\\alpha$: value of the best (highest-value) choice we have found so far at any choice\npoint along the path for MAX [at least]\n- $\\beta$: value of the best (lowest-value) choice we have found so far at any choice\npoint along the path for MIN [at most]\n- if $v \\geq \\beta, v \\leq \\alpha$ then prune/cut off search\n- depends on order. With perfect ordering, need to examine $O(b^{m/2})$ nodes, effective\nbranching factor is now $\\sqrt(b)$ instead of b. With random ordering, $O(b^{3m/4})$ nodes\n- can use IDS to find killer moves (best moves)\n \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \nWith limited computation time, we can cut off the serach early. Replace utility function with eval, cutoff test instead of terminal test\n- UTILITY(loss, p) ≤ EVAL(s, p) ≤ UTILITY(win, p)\n- expected value/material value calculated from features of the state\nCutting off search\n- modify ab pruning to call heuristic EVAL function when it's appropriate to cut search\n- should only applied to quiescent position - no pending moves ie. capture the queen\n- horizon effect: when the program is facing an opponent's move that can cause serious damage/unavoidable but \ncan be temporily avoided using delay tactics - allow singular extensions to mitigate the effect\nForward pruning: type B strategy\n- similar to human chess players: save computation time at risk of error\n- beam search\n- ProbCut: ab search that prunes nodes that are probably outside the window\n- late move reduction: assume ordering is good. Reduce depth of later moves\n\n\n## AIMA Chapter 5.5 Stochastic Games\n \nEx. backgammon\n- game tree includes chance nodes alongside MIN and MAX nodes\n- calculate expected value of a position = expectiminimax value: average over all possible outcomes of the chance nodes\n- expectiminimax considers all the possible dice-roll sequences, it will take $O(b^m n^m)$ time, with n = #distinct rolls\n\n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n \n- Uncertainty about the current state s, $P(RESULT(a) = s′)=\\sum_s P(s)P(s'∣s,a)$\n- agent's preference captured by a utility function -> expected utility \n- principle of maximum expected untility(MEU): rational agent should choose\nthe action that maximizes the agent’s expected utility\n\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \nConstraints on rational preferences: leads to utility...axioms\n- agent needs only a preferenc eraning on states - numbers don't matter: value function/ordinal utility function\n\n\n## AIMA Chapter 16.3 Utility Functions\n \npreference elicitation: presenting choices to the human and\nusing the observed preferences to pin down the underlying utility function\n\n \n\n## Module 5 Lecture Notes\n \nCompetitive environment: move = action, position = state\n- initial state, to-move(s), actions(s), result(s,a) transition model, is-terminal(s),\nutility(s,p) or objective/payoff function\n\n\n## Module 5 Definitions\n* **Ply** - one move by one player = one level deeper in the game tree\n* **Transpositions** - repeated states occur cuz different permutations of moves end up in the same position -> keep transposition table\n* **Type a strategy** - consider all possible moves (wide) at shallow depth\n* **Type b strategy** - ignores moves that seem bad, deep but narrow\n* **Policy** - mapping from every state to best move for the state\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",
        "3 components\n",
        "1. X is a set of variables\n",
        "2. D is a set of domains, one for each variable\n",
        "3. C is a set of constraints that specify allowable combinations of values\"\"\"\n",
        "chapter6_2 = \"\"\" \n",
        "CSP algo has choices: generate successors by choosing a new variable assignmnent or \n",
        "do inference/constraint propagation (use constraints to reduce #legal values for a variable).\n",
        "Constraint propagation may be intertwined with search, or it may be done as a\n",
        "preprocessing step. \\n\n",
        "Most popular algo for enforcing arc consistency, AC-3: \n",
        "Place all the arcs in a queue. Pop arcs $(X_i,X_j)$. For each arc, remove inconsistent values. \n",
        "If we change the values of a node $D_i$, add its arcs $(X_k,X_i)$ to the queue. Terminate when the queue is empty.\n",
        "New CSP will be faster to search. Each arc can be inserted to queue only d times.\n",
        "Checking arc consistency can be done in $O(d^2)$, so we get $O(cd^3)$ worst-case time, with\n",
        "c binary constraints(arcs) \\n\n",
        "K-consistency: for any set of variables and for any consistent assignment to those\n",
        "variables, a consistent value can always be assigned to any k_th variable.\n",
        "A CSP is strongly k-consistent if it is k-consistent and also (k-1)-consistent, \n",
        "(k-2)consistent, all the way down to 1-consistent. Total runtime $O(n^2d)$.\n",
        "BUT any algorithm for establishing n-consistency must take time/space exponential in n\n",
        " \"\"\"\n",
        "chapter6_3 = \"\"\" \n",
        "backtracking search algorithms that work on partial assignments. Notice the tree has\n",
        "$n!\\cdot d^n$ leaves, despite $d^n$ possible complete assignments.\n",
        "BACKTRACKING-SEARCH keeps only a single representation of a state (assignment)\n",
        "and alters that representation rather than creating new ones.\\n\n",
        "Commutativity property of CSPs: the order of application of any given set of actions does not matter.\n",
        "1. variable and value ordering: \n",
        "- choose the variable with the fewest “legal” values—\n",
        "minimum-remaining-values(MRV) heuristic/most-constrained/fail-first\n",
        "- degree heuristics: (if ties:) Most constraining variable\n",
        "- Least-constraining-value\n",
        "2. Interleaving search and inference: \n",
        "- simplest form = forward checking = \n",
        "delete from Y’s domain any value that is inconsistent with the value chosen for X\n",
        "- MAC(maintaining arc consistency): call AC-3 start on arcs $(X_j,X_i)$ for all\n",
        "$X_j$ that are unassigned variables that are neighbors of $X_i$\n",
        "- MAC recursively propagates constraints, whereas forward checking does not\n",
        "3. Intelligent backtracking: conflict set, backjumping method\n",
        "4. constraint learning: record no-good \n",
        "\"\"\"\n",
        "chapter6_4 = \"\"\" \n",
        "- min-conflicts heuristics\n",
        "- tabu search: : keeping a small list of recently visited states and forbidding the algorithm to return\n",
        "to those states\n",
        "- constraint weighting: concentrate the search on important constraints\n",
        " \"\"\"\n",
        "chapter6_5 = \"\"\" \n",
        "independent subproblems, by finding connected components of the constraint graph\n",
        "- reduce work from exponential $O(d^n)$ to linear $O(d^cn/c)$\n",
        "Any tree-structured CSP can be solved in linear time in the #of variables. Directional\n",
        "arc consistency(DAC)/topological sort ordering. Time $O(nd^2)$\\n\n",
        "Reducing constraint graphs to trees:\n",
        "1. cutset conditioning: assigning values to some variables so that the remaining variables form a tree.\n",
        "If the cycle cutset has size c, runtime is $O(d^c(n-c)d^2)$\n",
        "2. tree decomposition: Time $O(nd^{w+1})$ [polynomial time]\n",
        "- Every variable in the original problem appears in at least one of the tree nodes.\n",
        "- If two variables are connected by a constraint in the original problem, they must appear\n",
        "together (along with the constraint) in at least one of the tree nodes.\n",
        "- If a variable appears in two nodes in the tree, it must appear in every node along the\n",
        "path connecting those nodes\n",
        "- In choosing a decomposition, make subproblems as small as possible = \n",
        "tree width of a tree decomposition of a graph is\n",
        "one less than the size of the largest node\n",
        "- Note $w<c+1$. Time consideration favors tree decomposition, but\n",
        "cycle-cutset approach can be executed in linear memory, while tree decomposition\n",
        "requires memory exponential in w\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module6_lecture_notes = \"\"\"\n",
        "Break the black box (atomic representation) by using a factored representation: a set of variables, with a value. \n",
        "A problem is solved when each variable has a value that satisfies all constraints.\n",
        "CSPs have the additional advantage that the\n",
        "actions and transition model can be deduced from the problem description. Solving CSPs is an NP complete problem\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module6_definitions = {\n",
        "\"consistent assignment\" : \"(or legal assignment) an assignment that doesn't violate any constraints\",\n",
        "\"complete assignment\" : \"every variable is assigned a value\",\n",
        "\"solution\" : \"consistent, complete assignment\",\n",
        "\"global constraint\" : \"constraint involving an arbitrary number of variables\",\n",
        "\"tree width\" : \"min width among all its tree decompositions\",\n",
        "\"symmetry-breaking constraint\" : \"impose an ordering to make only one of d! solutions possible\"\n",
        "}\n"
      ],
      "execution_count": 32,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "8e991f1e-0f87-405d-c387-f431c0a352a3"
      },
      "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": 33,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n\n3 components\n1. X is a set of variables\n2. D is a set of domains, one for each variable\n3. C is a set of constraints that specify allowable combinations of values\n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n \nCSP algo has choices: generate successors by choosing a new variable assignmnent or \ndo inference/constraint propagation (use constraints to reduce #legal values for a variable).\nConstraint propagation may be intertwined with search, or it may be done as a\npreprocessing step. \n\nMost popular algo for enforcing arc consistency, AC-3: \nPlace all the arcs in a queue. Pop arcs $(X_i,X_j)$. For each arc, remove inconsistent values. \nIf we change the values of a node $D_i$, add its arcs $(X_k,X_i)$ to the queue. Terminate when the queue is empty.\nNew CSP will be faster to search. Each arc can be inserted to queue only d times.\nChecking arc consistency can be done in $O(d^2)$, so we get $O(cd^3)$ worst-case time, with\nc binary constraints(arcs) \n\nK-consistency: for any set of variables and for any consistent assignment to those\nvariables, a consistent value can always be assigned to any k_th variable.\nA CSP is strongly k-consistent if it is k-consistent and also (k-1)-consistent, \n(k-2)consistent, all the way down to 1-consistent. Total runtime $O(n^2d)$.\nBUT any algorithm for establishing n-consistency must take time/space exponential in n\n \n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n \nbacktracking search algorithms that work on partial assignments. Notice the tree has\n$n!\\cdot d^n$ leaves, despite $d^n$ possible complete assignments.\nBACKTRACKING-SEARCH keeps only a single representation of a state (assignment)\nand alters that representation rather than creating new ones.\n\nCommutativity property of CSPs: the order of application of any given set of actions does not matter.\n1. variable and value ordering: \n- choose the variable with the fewest “legal” values—\nminimum-remaining-values(MRV) heuristic/most-constrained/fail-first\n- degree heuristics: (if ties:) Most constraining variable\n- Least-constraining-value\n2. Interleaving search and inference: \n- simplest form = forward checking = \ndelete from Y’s domain any value that is inconsistent with the value chosen for X\n- MAC(maintaining arc consistency): call AC-3 start on arcs $(X_j,X_i)$ for all\n$X_j$ that are unassigned variables that are neighbors of $X_i$\n- MAC recursively propagates constraints, whereas forward checking does not\n3. Intelligent backtracking: conflict set, backjumping method\n4. constraint learning: record no-good \n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n \n- min-conflicts heuristics\n- tabu search: : keeping a small list of recently visited states and forbidding the algorithm to return\nto those states\n- constraint weighting: concentrate the search on important constraints\n \n\n## AIMA Chapter 6.5 The Structure of Problems\n \nindependent subproblems, by finding connected components of the constraint graph\n- reduce work from exponential $O(d^n)$ to linear $O(d^cn/c)$\nAny tree-structured CSP can be solved in linear time in the #of variables. Directional\narc consistency(DAC)/topological sort ordering. Time $O(nd^2)$\n\nReducing constraint graphs to trees:\n1. cutset conditioning: assigning values to some variables so that the remaining variables form a tree.\nIf the cycle cutset has size c, runtime is $O(d^c(n-c)d^2)$\n2. tree decomposition: Time $O(nd^{w+1})$ [polynomial time]\n- Every variable in the original problem appears in at least one of the tree nodes.\n- If two variables are connected by a constraint in the original problem, they must appear\ntogether (along with the constraint) in at least one of the tree nodes.\n- If a variable appears in two nodes in the tree, it must appear in every node along the\npath connecting those nodes\n- In choosing a decomposition, make subproblems as small as possible = \ntree width of a tree decomposition of a graph is\none less than the size of the largest node\n- Note $w<c+1$. Time consideration favors tree decomposition, but\ncycle-cutset approach can be executed in linear memory, while tree decomposition\nrequires memory exponential in w\n\n\n## Module 6 Lecture Notes\n\nBreak the black box (atomic representation) by using a factored representation: a set of variables, with a value. \nA problem is solved when each variable has a value that satisfies all constraints.\nCSPs have the additional advantage that the\nactions and transition model can be deduced from the problem description. Solving CSPs is an NP complete problem\n\n## Module 6 Definitions\n* **Consistent assignment** - (or legal assignment) an assignment that doesn't violate any constraints\n* **Complete assignment** - every variable is assigned a value\n* **Solution** - consistent, complete assignment\n* **Global constraint** - constraint involving an arbitrary number of variables\n* **Tree width** - min width among all its tree decompositions\n* **Symmetry-breaking constraint** - impose an ordering to make only one of d! solutions possible\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",
        "ASK and TELL: inference - deriving new sentences from old. Each time an agent is called\n",
        "1. TELLs the knowledge base what it perceives\n",
        "2. ASKs the knowledge base what action it should perform\n",
        "3. TELLs the knowledge base which action was chosen, and returns the action so that\n",
        "it can be executed \\n\n",
        "Declarative approach to system building: agent designer can TELL sentences one by one until the\n",
        "agent knows how to operate in its environment. \\n\n",
        "Procedural approach encodes desired behaviors directly as program code.\n",
        "\"\"\"\n",
        "chapter7_2 = \"\"\" \n",
        "Deterministic, discrete, static, single-agent (wumpus doesn't move). Sequential,\n",
        "partially observable. Transitiona model is unknown: doesn't know which Forward action is fatal \"\"\"\n",
        "chapter7_3 = \"\"\" \n",
        "- If a sentence $\\\\alpha $ is true in model m, we say m satisfies $\\\\alpha$ or m is a model of $\\\\alpha$. \n",
        "Notation $M(\\\\alpha)$ means the set of all models of $\\\\alpha$\n",
        "- Entailment $A \\models B$ iff in every model in which $\\\\alpha$ is true, $\\\\beta$ is also true.\n",
        "$A \\models B$ iff $M(\\\\alpha)\\subseteq M(\\\\beta)$. $\\\\alpha$ is a stronger assertion = rules out more possible worlds.\n",
        "- Entailment is like the needle [alpha] being in the haystack [KB], inference is like finding it\n",
        "- $KB \\models_i \\\\alpha$: alpha is derived from KB by i or i derives alpha from KB\n",
        "- Sound/truth-preserving: Inference algo that derives only entailed sentences \n",
        "- Completeness: inference algo is complete if it can derive any sentence that is entailed\n",
        "- Grounding: connection bw logical reasoning processes and the real environment\n",
        "\"\"\"\n",
        "chapter7_4 = \"\"\" \n",
        "Inference procedure\n",
        "- model-checking approach: enumerate the models and check that alpha is true in every model in which KB is true\n",
        "- general algo for deciding entailment: TL-Entails (like backtracking-search) performs\n",
        "recursive enumeration of finite space of assignments to symbols. The algo is sound & complete.\n",
        "Time complexity $O(2^n)$, space $O(n)$ bc. enumeration is depth-first\n",
        "\"\"\"\n",
        "chapter7_5 = \"\"\"\n",
        "Theorem proving = applying rules of inference directly to the\n",
        "sentences in our knowledge base to construct a proof of the desired sentence without\n",
        "consulting models.\n",
        "- Logical equivalence $A\\equiv B$: true in the same set of models. Each of them entails the other.\n",
        "- Validity: true in all models, tautologies\n",
        "- Satisfiability: true in, or satisfied by, some model. SAT problem = problem of determining satisfiability\n",
        "of sentences in propositional logic - first problem proved to be np-complete. A is valid iff $\\\\neg A$ is unsatisfiable.\n",
        "Also, contradiction: $A \\models B$ iff $A \\land \\\\neg B$\n",
        "- Monotonicity: if $KB \\models \\\\alpha$, then $KB \\land \\\\beta \\models \\\\alpha$ \\n\n",
        "Inference and proofs\n",
        "- Modus Ponens: $\\\\frac{A\\\\implies B,A}{B}$\n",
        "- And-Elimination: $\\\\frac{A\\land B}{B}$ \\n\n",
        "Proof by resolution... \\n\n",
        "Conjunctive normal form: eliminate $\\iff$, elimninate $\\\\implies$, move $\\\\neg$ inwards(De Morgan), \n",
        "distribute $\\lor$ over $\\land$ whenever possible. The form (..v..) $\\land$ (..v.v.) \\n\n",
        "- Completeness theorem for resolution - Ground resolution theorem: If a set of clauses is unsatisfiable, \n",
        "then the resolution closure of those clauses contains the empty clause\n",
        "- Definite clause: disjunction of literals of which exactly one is positive\n",
        "- Horn clauses: disjunction of literals of which at most one is positive. Horn clauses are closed\n",
        "under resolution. Goal clauses-no positive \\n\n",
        "Forward & Backward chaining: run in linear time\n",
        "- Forward: determines if a single proposition symbol q is entailed by a KB of definite clauses\n",
        "- Backward: If q is known to be true, then no work needed. Otherwise, the algorithm finds\n",
        "those implications in the knowledge base whose conclusion is q. It's a form of \n",
        "goal-directed reasoning. Cost often less than linear\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module7_lecture_notes = \"\"\" \n",
        "Knowledge-based agents use a process of reasoning over an internal representation of\n",
        "knowledge to decide what actions to take. Knowledge base (KB) is a set of sentences \n",
        "in a knowledge representation language and represents some assertion about the world\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "# Definitions\n",
        "module7_definitions = {\n",
        "\"axiom\" : \"given sentence, not derived from other sentences\",\n",
        "\"syntax\": \"structure of sentences\",\n",
        "\"inference\" : \"process of deriving new sentences from old ones\",\n",
        "\"semantics\" : \"meaning of sentences, which defines the truth with respect to each possible world(model)\",\n",
        "\"entailment\" : \"a sentence follows logically from another one\",    \n",
        "\"reductio ad absurdum\" : \"proof by contradiction/refutation\", \n",
        "\"clause\" : \"disjunction of literals, with a single literal can be viewed as unit clause\", \n",
        "\"resolution closure(RC)\" : \"set of all clauses derivable by repeated application of resolution rule\"\n",
        "}\n",
        "\n"
      ],
      "execution_count": 34,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "05813a55-2aee-4072-877e-667813e624d2"
      },
      "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": 35,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n \nASK and TELL: inference - deriving new sentences from old. Each time an agent is called\n1. TELLs the knowledge base what it perceives\n2. ASKs the knowledge base what action it should perform\n3. TELLs the knowledge base which action was chosen, and returns the action so that\nit can be executed \n\nDeclarative approach to system building: agent designer can TELL sentences one by one until the\nagent knows how to operate in its environment. \n\nProcedural approach encodes desired behaviors directly as program code.\n\n\n## AIMA Chapter 7.2 The Wumpus World\n \nDeterministic, discrete, static, single-agent (wumpus doesn't move). Sequential,\npartially observable. Transitiona model is unknown: doesn't know which Forward action is fatal \n\n## AIMA Chapter 7.3 Logic\n \n- If a sentence $\\alpha $ is true in model m, we say m satisfies $\\alpha$ or m is a model of $\\alpha$. \nNotation $M(\\alpha)$ means the set of all models of $\\alpha$\n- Entailment $A \\models B$ iff in every model in which $\\alpha$ is true, $\\beta$ is also true.\n$A \\models B$ iff $M(\\alpha)\\subseteq M(\\beta)$. $\\alpha$ is a stronger assertion = rules out more possible worlds.\n- Entailment is like the needle [alpha] being in the haystack [KB], inference is like finding it\n- $KB \\models_i \\alpha$: alpha is derived from KB by i or i derives alpha from KB\n- Sound/truth-preserving: Inference algo that derives only entailed sentences \n- Completeness: inference algo is complete if it can derive any sentence that is entailed\n- Grounding: connection bw logical reasoning processes and the real environment\n\n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n \nInference procedure\n- model-checking approach: enumerate the models and check that alpha is true in every model in which KB is true\n- general algo for deciding entailment: TL-Entails (like backtracking-search) performs\nrecursive enumeration of finite space of assignments to symbols. The algo is sound & complete.\nTime complexity $O(2^n)$, space $O(n)$ bc. enumeration is depth-first\n\n\n## AIMA 7.5 Propositional Theorem Proving\n\nTheorem proving = applying rules of inference directly to the\nsentences in our knowledge base to construct a proof of the desired sentence without\nconsulting models.\n- Logical equivalence $A\\equiv B$: true in the same set of models. Each of them entails the other.\n- Validity: true in all models, tautologies\n- Satisfiability: true in, or satisfied by, some model. SAT problem = problem of determining satisfiability\nof sentences in propositional logic - first problem proved to be np-complete. A is valid iff $\\neg A$ is unsatisfiable.\nAlso, contradiction: $A \\models B$ iff $A \\land \\neg B$\n- Monotonicity: if $KB \\models \\alpha$, then $KB \\land \\beta \\models \\alpha$ \n\nInference and proofs\n- Modus Ponens: $\\frac{A\\implies B,A}{B}$\n- And-Elimination: $\\frac{A\\land B}{B}$ \n\nProof by resolution... \n\nConjunctive normal form: eliminate $\\iff$, elimninate $\\implies$, move $\\neg$ inwards(De Morgan), \ndistribute $\\lor$ over $\\land$ whenever possible. The form (..v..) $\\land$ (..v.v.) \n\n- Completeness theorem for resolution - Ground resolution theorem: If a set of clauses is unsatisfiable, \nthen the resolution closure of those clauses contains the empty clause\n- Definite clause: disjunction of literals of which exactly one is positive\n- Horn clauses: disjunction of literals of which at most one is positive. Horn clauses are closed\nunder resolution. Goal clauses-no positive \n\nForward & Backward chaining: run in linear time\n- Forward: determines if a single proposition symbol q is entailed by a KB of definite clauses\n- Backward: If q is known to be true, then no work needed. Otherwise, the algorithm finds\nthose implications in the knowledge base whose conclusion is q. It's a form of \ngoal-directed reasoning. Cost often less than linear\n\n\n\n## Module 7 Lecture Notes\n \nKnowledge-based agents use a process of reasoning over an internal representation of\nknowledge to decide what actions to take. Knowledge base (KB) is a set of sentences \nin a knowledge representation language and represents some assertion about the world\n\n\n\n## Module 7 Definitions\n* **Axiom** - given sentence, not derived from other sentences\n* **Syntax** - structure of sentences\n* **Inference** - process of deriving new sentences from old ones\n* **Semantics** - meaning of sentences, which defines the truth with respect to each possible world(model)\n* **Entailment** - a sentence follows logically from another one\n* **Reductio ad absurdum** - proof by contradiction/refutation\n* **Clause** - disjunction of literals, with a single literal can be viewed as unit clause\n* **Resolution closure(rc)** - set of all clauses derivable by repeated application of resolution rule\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": "419b95b1-9eb4-41c5-c12b-94449791ae03"
      },
      "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": 36,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n 2 dimensions: human vs rational and thought vs behavior\n1. Acting humanly: turing test = can human tell if it's from a computer vs person? Computer would need NLP, knowledge representation, automated\nreasoning, machine learning to pass. Total turing test requires interaction with objects and people in real world --> robot will need computer vision, speech recognition, and robotics\n\n2. Thinking humanly: cognitive modeling - introspection, psychological experiments, brain imaging\n\n3. Thinking rationally: laws of thought - syllogisms and logic + probability, emphasis on correct inference \n\n4. Acting rationally: rational agent - 2 advantages: more general than \"laws of thought\" & more amedable to scientific development \n\nWe want agents that are provably beneficial to humans\n\n\n## AIMA Chapter 27.1 The Limits of AI\n \nweak AI: machines act as if they were intelligent vs strong AI: actually consciously thinking\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n \nChinese room argument by John Searle - application of rules to input symbols isn't \ntrue intelligence\n\n\n## AIMA 2.1 Agents and Environments\n An agent's choice of action can depends on its built-in knowledge and the entire percept sequence observed to date (not the future).\nMath speak: agent's behavior is described by the agent function that maps percept sequence to action. Internally, the agent function will be implemented by an agent program.\nAgent function is an abstract math description, agent program is a concrete implementation\n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n \nPerformace measures: general rule = design according to what one wants to be achieved in the environment, rather than how one thinks \nthe agent should behave. \n\nRationality vs omniscience - rationality is not perfection. Doing actions to modify future percepts = information gathering ie. exploration \n\nrational agent should be autonomous \n\n## AIMA 2.3 The Nature of Environments\n \ntask enviroments = \"problems\" to which rational agents are the \"solution\" \n\nSpecifying task environment: PEAS (performance, envirnment, actuators, sensors) \n\nFully = agent's sensors give access to complete state of environment at each point in time vs. partially observable \n\nSingle vs Multiagent: key distinction is whether B's behavior is best described as maximizing a performance measure whose value depends on A's behavior \n\nDeterministic = next state of environment completely determined by current state + action vs Nondeterministic \n\nEpisodic vs. Sequential = current action affect future decisions \n\nStatic [crossword] vs dynamic [taxi] vs semidynamic [chess]= environment doesn't change with time but performace score does \n\nKnown vs Unknown: agent's state of knowledge about the law of physics of the environment. ie. solitaire = known but partially observable \n\nThe hardest case is partially observable, multiagent, nondeterministic, sequential, dynamic, continuous, and unknown\n\n## AIMA 2.4 The Structure of Agents\n\nagent = architecture (device with sensors and actuators) + program (implements agent function)\n\ntable driven approach - doom to fail cuz contains too many entries $\\sum|P|^t$ \n\n1. Simple reflex agents: select actions on the crrent percept. Condition-action rule. Problem of infinite loops in partialy observable \nenvironments --> escape by randomize its action \n\n2. Model-based reflex agent: handle partial observability by keep track of part of the world it can't see now = internal state. \nUpdating internal state requires info about how the world changes over time (transition model) + how the state of the world is reflected in the agent's percepts (sensor model)\n\n3. Goal-based agent: search and planning. Appear less efficient but more flexible \n\n4. Utility-based agent: internal utility function matches external performance measure\n\nLearning agent: learning element (for making improvements), performance element* (select external action), critic (give feedback),\nproblem generator (suggest actions that will lead to new experience) \n\nState representation: atomic, factored (each stte has fixed set of variables or attributes, value), \nstructured\n\n\n## Module 1 Lecture Notes\n Your summary here \n\n## Module 1 Definitions\n* **Rationality** - doing the right thing --> standard model\n* **Cognitive science** - interdisciplinary field that brings together AI computer models and psychology to model human minds\n* **Value alignment problem** - the objective put into the machine has to aligh with humans' value\n* **Agent** - anything that can perceive (through sensors) and act (through actuators) in an environment\n* **Rational agent** - select action to maximize expected performance measure, given the percept sequence and built-in knowledge\n* **Percept** - the content that agent's sensors perceive\n* **Consequentialism** - evaluate agent's behavior by its consequences\n* **Omniscience** - know the actual outcome of its action and act accordingly, but impoassible in reality\n* **Autonomy** - learn to compensate for partial or incorrect prior knowledge\n* **Stochastic** - explicitly deal with probability vs nondeterministic (possibility not quantified)\n* **Transition model** - knowledge about how the world works\n\n\n# Module 2: Python\n## Module 2 Lecture Notes\n \n- list(range(1,101)) = a single line of code to create a list containing values from 1 to 100, [1, 2, …, 100] \n\n- mlist[:][0] ->[:] creates a copy of the list, which means we are modifying the copy but not the original.\n- tuple, strings are immutable\n- list is mutable\n- no function overloading in python, function is specified by its name alone. BUT \noperator overloading (+,==,-) is possible\n- *args: accept a variable number of non-keyword arguments\n- **kwargs: accept a variable number of keyword arguments ie. **my_dict\n\n\n## Module 2 Definitions\n* **Mutability** - your definition here\n\n\n# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n Assume agent has access to info about the world. 4 phase problem-solving process \n\n1. Goal formulation\n2. Problem formulation\n3. Search: find sequence of actions that reaches the goal = solution\n4. Execution \n\nIn a fully observable, deterministic, known environment, the solution to any problem is a fixed sequence of actions \n\nSearch problem: state space, intitial state, goal states, actions, transition model, action cost function\n  \n\n## AIMA Chapter 3.2 Example Problems\n\nStandardized [grid world, sokoban puzzle, sliding tiles] vs real world problems\n[touring problem, traveling salesperson, robot]\n\n## AIMA Chapter 3.3 Search Algorithms\n \n- node = state in state space\n- edge = actions\n- root = initial state\n\nfrontier separates two regions of the state-space graph: an interior region\nwhere every state has been expanded, and an exterior region of states that have not yet\nbeen reached \n\nbest-first search: choose node on frontier with minimum value of evaluation function, f(n). \nReturn either solution node or failure. Use priority queue (min cost). Reached is a mapping from states to nodes \n\nRemember redundant path: \n1. remember all previously reached states [best-first search] \n2. not worry about repeating the past: graph search [checks redundant path], tree-like search [doesn't check]\n3. check just for cycles: takes constant time for small cycles\n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n access only the problem description\n1. Breadth-first search: best-first search where f(n) is the depth of the node, FIFO queue, early goal test\n2. Uniform-cost search (Dijkstra): f(n) is cost of path from root to current node. Late goal test\n3. Depth-first search: can use best-first search where f(n) is negative of the depth BUT usually implemented as a tree search\nthat doesn't keep table of reached states. Can get stuck in an infinite loop in cyclic state spaces or go down infinite path.\nMuch smaller memory need. Backtracking search adapted from DFS with even less memory req.\n4. Depth-limited and iterative deepening: Each iteration generates a new level, similar to BFS\nbut BFS stores all nodes in memory, while ids repeats the previous levels - saving memory at the cost of more time\n5. Bidirectional: searches forward from the initial state and backwards from the goal state(s)\n\n\n## Module 3 Lecture Notes\n When correct action is not obvious, an agent needs to plan ahead = consider sequence of actions \nthat form a path to a goal state. We call that agent a problem-solving agent, and the process is called search.\nUse atomic representation \n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n* **Open-loop** - systems that can ignore the percept - break the loop between agent and environment\n* **Optimal solution** - has lowest path cost\n* **Fifo queue** - use in BFS\n* **Lifo queue** - (stack) use in DFS\n* **Redundant path** - less than optimal way to get to the same state, ie. different side of circle\n* **Completeness** - algorithm guarantees to find a solution if there is one, and correctly report failure if there isn't\n* **Early goal test** - check if a node is a solution when it is generated\n* **Late goal test** - wait until a node is popped of the queue to check, used in best-first search\n\n\n# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n \n1. Greedy best-first search: expands first the node with lowest h(n) ie. straight line distance. \nNot optimal. Time and space $O(|V|)$, but can reach $O(bm)$ with good h(n)\n2. A* search: $f(n)=g(n)+h(n)$. Cost optimal. Heuristic is optimal and consistent $h(n)\\leq c(n,a,n')+h(n')$.\nEvery consistent heuristic is admissible & first time we reach a state it will be on an optimal path - never \nhave to change the frontier\n3. Satisficing search: inadmissible heuristics = accept suboptimal/good enough solution for faster search. \nweighted A*: $f(n)=g(n)+W\\cdot h(n), W>1$\n4. Memory-bounded search: save memory from duplication of nodes in frontier and reached.\nReference counts = #times a state has been reach, remove from reached table when no more was to reach the state.\n- Beam search: limit frontier size, keep only k nodes with best f-scores or keep nodes with f-score within $\\delta$ of best f-score.\nIncomplete & suboptimal but fast\n- IDA*: not keep all reached states. The cutoff is f-cost at each iteration\n- Recursive best-first: use linear space, use f_limit variable to keep track of f-value of best alternative path = remembers f-value of \nbest leaf in the forgotten subtree(backed-up value). Somewhat more efficient that IDA* but excessive node regeneration.\nRBFS is optimal with admissible h\n- MA* & SMA*: robust & optimal. Given enough time, they can solve problems for which A* runs out of memory. \nExpanding best leaf til full memory, back up value of forgotten nodes to its parent\n5. Bidirectional heuristic search\n\n\n## AIMA Chapter 3.6 Heuristic Functions\n\nQuality of heuristic: \n- effective branching factor b*: $N+1=1+b+b^2+...+b^d$. Good if close to 1\n- effective depth: reduce by constant $k_h$. Cost is now $O(b^{d-k_h})$\n- $h_2$ dominates $h_1$, $h_2\\geq h_1$\n- composite heuristic = max(all h)\n\nRelaxed problem = problem with fewer restrictions on the actions. The state-space graph of the relaxed problem is a supergraph of\nthe original state space because the removal of restrictions creates added edges in the graph.\nThe cost of an optimal solution to a relaxed problem is an admissible heuristic for the original problem. \n\nA program called ABSOLVER can generate heuristics automatically from problem definitions. \n\n- Generating h from subproblems: pattern databases\n- landmarks: precomputation of some optimal path costs\n- Learn how to search better? metalevel state space: each state in metalevel space captures internal (computational)\nstate of a program that is searching in ordinary(object-level) state space\n\n\n## Module 4 Lecture Notes\n Informed search uses domain-specific hints about the location of goals - \nheuristic function h(n) = estimated cost of the cheapest path from node to goal state \n\n## Module 4 Definitions\n* **Admissible heuristic** - h that never overstimates cost to reach a goal = optimistic\n* **Optimally efficient** - any algo that uses the same h must expand all nodes surely expanded by A*\n* **Speedy search** - a version of greedy best-first search [unbounded cost] with h = est. #actions to reach goal, regardless of cost\n* **Bounded supoptimal search** - look for solution that is within a constant factor W of optimal cost\n* **Effective branching factor** - branching factor that a uniform tree with dept d would need to contain N+1 nodes\n\n\n# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n \nperfect information (fully-observable), zero-sum games \n\n- optimal strategy determined by working out the minimax value of each state in the tree\n- utility of being in that state, assume that both players play optimally\n\n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n \n- starts with MAX, minimax algo performs a depth-first exploration\n- time $O(b^m)$, space $O(bm)$ with m is max depth of tree, b is legal moves at each point\n- multiplayer: backed-up value of a node is the utility\nvector of the successor state with the highest value for the player choosing at n\nAlpha-beta pruning\n- $\\alpha$: value of the best (highest-value) choice we have found so far at any choice\npoint along the path for MAX [at least]\n- $\\beta$: value of the best (lowest-value) choice we have found so far at any choice\npoint along the path for MIN [at most]\n- if $v \\geq \\beta, v \\leq \\alpha$ then prune/cut off search\n- depends on order. With perfect ordering, need to examine $O(b^{m/2})$ nodes, effective\nbranching factor is now $\\sqrt(b)$ instead of b. With random ordering, $O(b^{3m/4})$ nodes\n- can use IDS to find killer moves (best moves)\n \n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \nWith limited computation time, we can cut off the serach early. Replace utility function with eval, cutoff test instead of terminal test\n- UTILITY(loss, p) ≤ EVAL(s, p) ≤ UTILITY(win, p)\n- expected value/material value calculated from features of the state\nCutting off search\n- modify ab pruning to call heuristic EVAL function when it's appropriate to cut search\n- should only applied to quiescent position - no pending moves ie. capture the queen\n- horizon effect: when the program is facing an opponent's move that can cause serious damage/unavoidable but \ncan be temporily avoided using delay tactics - allow singular extensions to mitigate the effect\nForward pruning: type B strategy\n- similar to human chess players: save computation time at risk of error\n- beam search\n- ProbCut: ab search that prunes nodes that are probably outside the window\n- late move reduction: assume ordering is good. Reduce depth of later moves\n\n\n## AIMA Chapter 5.5 Stochastic Games\n \nEx. backgammon\n- game tree includes chance nodes alongside MIN and MAX nodes\n- calculate expected value of a position = expectiminimax value: average over all possible outcomes of the chance nodes\n- expectiminimax considers all the possible dice-roll sequences, it will take $O(b^m n^m)$ time, with n = #distinct rolls\n\n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n \n- Uncertainty about the current state s, $P(RESULT(a) = s′)=\\sum_s P(s)P(s'∣s,a)$\n- agent's preference captured by a utility function -> expected utility \n- principle of maximum expected untility(MEU): rational agent should choose\nthe action that maximizes the agent’s expected utility\n\n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \nConstraints on rational preferences: leads to utility...axioms\n- agent needs only a preferenc eraning on states - numbers don't matter: value function/ordinal utility function\n\n\n## AIMA Chapter 16.3 Utility Functions\n \npreference elicitation: presenting choices to the human and\nusing the observed preferences to pin down the underlying utility function\n\n \n\n## Module 5 Lecture Notes\n \nCompetitive environment: move = action, position = state\n- initial state, to-move(s), actions(s), result(s,a) transition model, is-terminal(s),\nutility(s,p) or objective/payoff function\n\n\n## Module 5 Definitions\n* **Ply** - one move by one player = one level deeper in the game tree\n* **Transpositions** - repeated states occur cuz different permutations of moves end up in the same position -> keep transposition table\n* **Type a strategy** - consider all possible moves (wide) at shallow depth\n* **Type b strategy** - ignores moves that seem bad, deep but narrow\n* **Policy** - mapping from every state to best move for the state\n\n\n# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n\n3 components\n1. X is a set of variables\n2. D is a set of domains, one for each variable\n3. C is a set of constraints that specify allowable combinations of values\n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n \nCSP algo has choices: generate successors by choosing a new variable assignmnent or \ndo inference/constraint propagation (use constraints to reduce #legal values for a variable).\nConstraint propagation may be intertwined with search, or it may be done as a\npreprocessing step. \n\nMost popular algo for enforcing arc consistency, AC-3: \nPlace all the arcs in a queue. Pop arcs $(X_i,X_j)$. For each arc, remove inconsistent values. \nIf we change the values of a node $D_i$, add its arcs $(X_k,X_i)$ to the queue. Terminate when the queue is empty.\nNew CSP will be faster to search. Each arc can be inserted to queue only d times.\nChecking arc consistency can be done in $O(d^2)$, so we get $O(cd^3)$ worst-case time, with\nc binary constraints(arcs) \n\nK-consistency: for any set of variables and for any consistent assignment to those\nvariables, a consistent value can always be assigned to any k_th variable.\nA CSP is strongly k-consistent if it is k-consistent and also (k-1)-consistent, \n(k-2)consistent, all the way down to 1-consistent. Total runtime $O(n^2d)$.\nBUT any algorithm for establishing n-consistency must take time/space exponential in n\n \n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n \nbacktracking search algorithms that work on partial assignments. Notice the tree has\n$n!\\cdot d^n$ leaves, despite $d^n$ possible complete assignments.\nBACKTRACKING-SEARCH keeps only a single representation of a state (assignment)\nand alters that representation rather than creating new ones.\n\nCommutativity property of CSPs: the order of application of any given set of actions does not matter.\n1. variable and value ordering: \n- choose the variable with the fewest “legal” values—\nminimum-remaining-values(MRV) heuristic/most-constrained/fail-first\n- degree heuristics: (if ties:) Most constraining variable\n- Least-constraining-value\n2. Interleaving search and inference: \n- simplest form = forward checking = \ndelete from Y’s domain any value that is inconsistent with the value chosen for X\n- MAC(maintaining arc consistency): call AC-3 start on arcs $(X_j,X_i)$ for all\n$X_j$ that are unassigned variables that are neighbors of $X_i$\n- MAC recursively propagates constraints, whereas forward checking does not\n3. Intelligent backtracking: conflict set, backjumping method\n4. constraint learning: record no-good \n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n \n- min-conflicts heuristics\n- tabu search: : keeping a small list of recently visited states and forbidding the algorithm to return\nto those states\n- constraint weighting: concentrate the search on important constraints\n \n\n## AIMA Chapter 6.5 The Structure of Problems\n \nindependent subproblems, by finding connected components of the constraint graph\n- reduce work from exponential $O(d^n)$ to linear $O(d^cn/c)$\nAny tree-structured CSP can be solved in linear time in the #of variables. Directional\narc consistency(DAC)/topological sort ordering. Time $O(nd^2)$\n\nReducing constraint graphs to trees:\n1. cutset conditioning: assigning values to some variables so that the remaining variables form a tree.\nIf the cycle cutset has size c, runtime is $O(d^c(n-c)d^2)$\n2. tree decomposition: Time $O(nd^{w+1})$ [polynomial time]\n- Every variable in the original problem appears in at least one of the tree nodes.\n- If two variables are connected by a constraint in the original problem, they must appear\ntogether (along with the constraint) in at least one of the tree nodes.\n- If a variable appears in two nodes in the tree, it must appear in every node along the\npath connecting those nodes\n- In choosing a decomposition, make subproblems as small as possible = \ntree width of a tree decomposition of a graph is\none less than the size of the largest node\n- Note $w<c+1$. Time consideration favors tree decomposition, but\ncycle-cutset approach can be executed in linear memory, while tree decomposition\nrequires memory exponential in w\n\n\n## Module 6 Lecture Notes\n\nBreak the black box (atomic representation) by using a factored representation: a set of variables, with a value. \nA problem is solved when each variable has a value that satisfies all constraints.\nCSPs have the additional advantage that the\nactions and transition model can be deduced from the problem description. Solving CSPs is an NP complete problem\n\n## Module 6 Definitions\n* **Consistent assignment** - (or legal assignment) an assignment that doesn't violate any constraints\n* **Complete assignment** - every variable is assigned a value\n* **Solution** - consistent, complete assignment\n* **Global constraint** - constraint involving an arbitrary number of variables\n* **Tree width** - min width among all its tree decompositions\n* **Symmetry-breaking constraint** - impose an ordering to make only one of d! solutions possible\n\n\n# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n \nASK and TELL: inference - deriving new sentences from old. Each time an agent is called\n1. TELLs the knowledge base what it perceives\n2. ASKs the knowledge base what action it should perform\n3. TELLs the knowledge base which action was chosen, and returns the action so that\nit can be executed \n\nDeclarative approach to system building: agent designer can TELL sentences one by one until the\nagent knows how to operate in its environment. \n\nProcedural approach encodes desired behaviors directly as program code.\n\n\n## AIMA Chapter 7.2 The Wumpus World\n \nDeterministic, discrete, static, single-agent (wumpus doesn't move). Sequential,\npartially observable. Transitiona model is unknown: doesn't know which Forward action is fatal \n\n## AIMA Chapter 7.3 Logic\n \n- If a sentence $\\alpha $ is true in model m, we say m satisfies $\\alpha$ or m is a model of $\\alpha$. \nNotation $M(\\alpha)$ means the set of all models of $\\alpha$\n- Entailment $A \\models B$ iff in every model in which $\\alpha$ is true, $\\beta$ is also true.\n$A \\models B$ iff $M(\\alpha)\\subseteq M(\\beta)$. $\\alpha$ is a stronger assertion = rules out more possible worlds.\n- Entailment is like the needle [alpha] being in the haystack [KB], inference is like finding it\n- $KB \\models_i \\alpha$: alpha is derived from KB by i or i derives alpha from KB\n- Sound/truth-preserving: Inference algo that derives only entailed sentences \n- Completeness: inference algo is complete if it can derive any sentence that is entailed\n- Grounding: connection bw logical reasoning processes and the real environment\n\n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n \nInference procedure\n- model-checking approach: enumerate the models and check that alpha is true in every model in which KB is true\n- general algo for deciding entailment: TL-Entails (like backtracking-search) performs\nrecursive enumeration of finite space of assignments to symbols. The algo is sound & complete.\nTime complexity $O(2^n)$, space $O(n)$ bc. enumeration is depth-first\n\n\n## AIMA 7.5 Propositional Theorem Proving\n\nTheorem proving = applying rules of inference directly to the\nsentences in our knowledge base to construct a proof of the desired sentence without\nconsulting models.\n- Logical equivalence $A\\equiv B$: true in the same set of models. Each of them entails the other.\n- Validity: true in all models, tautologies\n- Satisfiability: true in, or satisfied by, some model. SAT problem = problem of determining satisfiability\nof sentences in propositional logic - first problem proved to be np-complete. A is valid iff $\\neg A$ is unsatisfiable.\nAlso, contradiction: $A \\models B$ iff $A \\land \\neg B$\n- Monotonicity: if $KB \\models \\alpha$, then $KB \\land \\beta \\models \\alpha$ \n\nInference and proofs\n- Modus Ponens: $\\frac{A\\implies B,A}{B}$\n- And-Elimination: $\\frac{A\\land B}{B}$ \n\nProof by resolution... \n\nConjunctive normal form: eliminate $\\iff$, elimninate $\\implies$, move $\\neg$ inwards(De Morgan), \ndistribute $\\lor$ over $\\land$ whenever possible. The form (..v..) $\\land$ (..v.v.) \n\n- Completeness theorem for resolution - Ground resolution theorem: If a set of clauses is unsatisfiable, \nthen the resolution closure of those clauses contains the empty clause\n- Definite clause: disjunction of literals of which exactly one is positive\n- Horn clauses: disjunction of literals of which at most one is positive. Horn clauses are closed\nunder resolution. Goal clauses-no positive \n\nForward & Backward chaining: run in linear time\n- Forward: determines if a single proposition symbol q is entailed by a KB of definite clauses\n- Backward: If q is known to be true, then no work needed. Otherwise, the algorithm finds\nthose implications in the knowledge base whose conclusion is q. It's a form of \ngoal-directed reasoning. Cost often less than linear\n\n\n\n## Module 7 Lecture Notes\n \nKnowledge-based agents use a process of reasoning over an internal representation of\nknowledge to decide what actions to take. Knowledge base (KB) is a set of sentences \nin a knowledge representation language and represents some assertion about the world\n\n\n\n## Module 7 Definitions\n* **Axiom** - given sentence, not derived from other sentences\n* **Syntax** - structure of sentences\n* **Inference** - process of deriving new sentences from old ones\n* **Semantics** - meaning of sentences, which defines the truth with respect to each possible world(model)\n* **Entailment** - a sentence follows logically from another one\n* **Reductio ad absurdum** - proof by contradiction/refutation\n* **Clause** - disjunction of literals, with a single literal can be viewed as unit clause\n* **Resolution closure(rc)** - set of all clauses derivable by repeated application of resolution rule\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}