{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "brNDGX-kvzds"
   },
   "source": [
    "# Template for Notes for CIS 521 Midterm 1\n",
    "\n",
    "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
    "\n",
    "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
    "\n",
    "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "aPtM8g7R0Pds"
   },
   "source": [
    "# Instructions\n",
    "\n",
    "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
    "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
    "3. Read the notes below about how you can format your summaries.\n",
    "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
    "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
    "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
    "* Run the last cell of this notebook\n",
    "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
    "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
    "* In the print options, change the layout from Landscape to Portrait. \n",
    "* Clicking the Save, will save a PDF that you can then print.\n",
    "\n",
    "## Formatting Notes\n",
    "\n",
    "1. The max length for each section's summary is 500 words / 3000 characters.\n",
    "2. You can also write a 2000 word summary of the lectures for each module.\n",
    "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
    "2. You can use Markdown formatting for your summaries. \n",
    "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
    "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
    "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
    "```\n",
    "def function():\n",
    "      print('hello world')\n",
    "```\n",
    "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "cw5IpDLCZa4W"
   },
   "source": [
    "## Example summary\n",
    "\n",
    "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 0
    },
    "id": "lzaavW96tcxM",
    "outputId": "fec3b4ea-468f-4442-ca8f-8358b870b7a6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The example summary is 116 words long, so you could write an additional 384 words.\n"
     ]
    }
   ],
   "source": [
    "chapter_2_1_example = \"\"\"\n",
    "Regular expressions are an algebraic notation for characterizing \\\n",
    "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
    "Only the first matching result will be shown. The search string is case sensitive, \\\n",
    "but it can consist of a single character or a sequence of characters. \\\n",
    "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
    "for characters over a range. The caret specifies the non-existence of a character. \\\n",
    "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
    "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
    "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
    "...\n",
    "\"\"\"\n",
    "\n",
    "length = len(chapter_2_1_example.split(\" \"))\n",
    "print(\"The example summary is {len} words long, so you could write an additional \\\n",
    "{remaining} words.\".format(len=length, remaining=(500-length)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "s3Uk9gQTevcj"
   },
   "source": [
    "## Example summary length\n",
    "\n",
    "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "8DvZ57A-djo1",
    "outputId": "ef81cd11-e574-43c8-fb57-4c2e2e3d803c"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The length in words is 500\n",
      "The length in characters is 3030\n"
     ]
    }
   ],
   "source": [
    "# This is an example of a 500 word placeholder\n",
    "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
    " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
    " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
    " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
    " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
    " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
    " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
    " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
    " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
    " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
    " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
    " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
    " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
    " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
    " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
    " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
    " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
    " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
    " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
    " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
    " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
    " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
    " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
    " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
    " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
    " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
    " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
    " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
    " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
    " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
    " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
    " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
    " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
    " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
    " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
    " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
    " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
    " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
    "\n",
    "print(\"The length in words is\", len(placeholder.split(' ')))\n",
    "print(\"The length in characters is\", len(placeholder))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5yG3-YncJfTB"
   },
   "source": [
    "# Permissions to use your summaries\n",
    "\n",
    "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
    "\n",
    "1. Please enter your name.  \n",
    "\n",
    "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
    "\n",
    "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "2RECnJArJew4"
   },
   "outputs": [],
   "source": [
    "name = \"\"\n",
    "permission = True\n",
    "anonymous = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "GZZXyrV-xuAp"
   },
   "source": [
    "# Module 1 - Intro to AI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "id": "Y2NfE1CKxzS-"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA 4th Edition, Chapter 1 “Introduction”, Section 1.1 “What is AI”\n",
    "\n",
    "chapter1_1 = \"\"\"\n",
    "1. Total Turing test: NLP, knowledge presentation, automated reasoning, ML, computer vision, robotics. \n",
    "2. Human methods of thinking: introspection, psychological experiments, brain imaging. \n",
    "3. Four views of AI: thinking/acting humanly/rationally\n",
    "4. Agent (agent function) = program + (runs on) architecture (physical)\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",
    "chapter27_2 = \"\"\" \"\"\"\n",
    "\n",
    "# Russell and Norvig, AIMA 4th Edition, Chapter 2 “Intelligent Agents” (whole chapter)\n",
    "chapter2_1 = \"\"\" \"\"\"\n",
    "chapter2_2 = \"\"\" \"\"\"\n",
    "chapter2_3 = \"\"\" \"\"\"\n",
    "chapter2_4 = \"\"\" \"\"\"\n",
    "\n",
    "# Lecture notes \n",
    "module1_lecture_notes = \"\"\"\n",
    "1. Rational means doing the right thing, but does not guarantee success. \n",
    "2. Types of environments: fully/partially observable, non-/deterministic, episodic/sequential, static/dynamic, discrete/continuous, single/multi-agent. \n",
    "\"\"\"\n",
    "\n",
    "\n",
    "# Definitions of concepts from Module 1.\n",
    "# You can define any bolded term in the textbook, \n",
    "# but you most use your own words for the definitions.\n",
    "# Each definition should be at most 20 words long.\n",
    "module1_definitions = {\n",
    "\"agent\" : \"anything that perceives its environment through **sensors** and acts on its environment through **actuators**\",\n",
    "\"rational agent\" : \"anything that acts to achieve the best (expected) outcome\",\n",
    "\"percept\" : \"perceptual inputs of the agent\",\n",
    "\"agent function\" : \"agent (specification), = agent program + physical architecture\",\n",
    "\"relax agent\" : \"act based on current percept only\",\n",
    "\"problem solving agent\" : \"plan ahead and consider a sequence of actions from a start/current state to a goal state (search)\"\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "elCCgY64spuq"
   },
   "source": [
    "## Preview of your notes for Module 1\n",
    "\n",
    "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 721
    },
    "id": "gYYeNcdM_maE",
    "outputId": "ef0b5ba8-48b5-4b26-ed2b-9e308b60c281"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 1: Rational Agents and Task Environments\n",
       "## AIMA Chapter 1.1 What is AI?\n",
       "\n",
       "1. Total Turing test: NLP, knowledge presentation, automated reasoning, ML, computer vision, robotics. \n",
       "2. Human methods of thinking: introspection, psychological experiments, brain imaging. \n",
       "3. Four views of AI: thinking/acting humanly/rationally\n",
       "4. Agent (agent function) = program + (runs on) architecture (physical)\n",
       "\n",
       "\n",
       "## AIMA Chapter 27.1 The Limits of AI\n",
       " \n",
       "\n",
       "## AIMA Chapter 27.1 Can Machines Really Think?\n",
       " \n",
       "\n",
       "## AIMA 2.1 Agents and Environments\n",
       " \n",
       "\n",
       "## AIMA 2.2 Good Behavior: The Concept of Rationality\n",
       " \n",
       "\n",
       "## AIMA 2.3 The Nature of Environments\n",
       " \n",
       "\n",
       "## AIMA 2.4 The Structure of Agents\n",
       " \n",
       "\n",
       "## Module 1 Lecture Notes\n",
       "\n",
       "1. Rational means doing the right thing, but does not guarantee success. \n",
       "2. Types of environments: fully/partially observable, non-/deterministic, episodic/sequential, static/dynamic, discrete/continuous, single/multi-agent. \n",
       "\n",
       "\n",
       "## Module 1 Definitions\n",
       "* **Agent** - anything that perceives its environment through **sensors** and acts on its environment through **actuators**\n",
       "* **Rational agent** - anything that acts to achieve the best (expected) outcome\n",
       "* **Percept** - perceptual inputs of the agent\n",
       "* **Agent function** - agent (specification), = agent program + physical architecture\n",
       "* **Relax agent** - act based on current percept only\n",
       "* **Problem solving agent** - plan ahead and consider a sequence of actions from a start/current state to a goal state (search)\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "from IPython.display import display, Markdown, Latex\n",
    "\n",
    "module1_sections = [\n",
    "  (\"AIMA Chapter 1.1 What is AI?\", chapter1_1),\n",
    "  (\"AIMA Chapter 27.1 The Limits of AI\", chapter27_1),\n",
    "  (\"AIMA Chapter 27.1 Can Machines Really Think?\", chapter27_2),\n",
    "  (\"AIMA 2.1 Agents and Environments\", chapter2_1),\n",
    "  (\"AIMA 2.2 Good Behavior: The Concept of Rationality\", chapter2_2),\n",
    "  (\"AIMA 2.3 The Nature of Environments\", chapter2_3),\n",
    "  (\"AIMA 2.4 The Structure of Agents\", chapter2_4),\n",
    "  (\"Module 1 Lecture Notes\", module1_lecture_notes),\n",
    "]\n",
    "\n",
    "\n",
    "def length_check(sections):\n",
    "  warnings = \"\"\n",
    "  for section, summary in sections:\n",
    "    max_word_length = 500\n",
    "    max_character_length = 3000\n",
    "    if \"lecture\" in section.lower():\n",
    "      # It's OK to do longer summaries of the lectures\n",
    "      max_word_length = 2000\n",
    "      max_character_length = 12000  \n",
    "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
    "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
    "  return warnings\n",
    "\n",
    "def length_check_definitions(definitions):\n",
    "  warnings = \"\"\n",
    "  for concept, definition in definitions.items():\n",
    "    if(len(definition.split(' ')) > 20):\n",
    "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
    "  return warnings\n",
    "\n",
    "\n",
    "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
    "  markdown = \"\"\n",
    "\n",
    "  # Check summary lengths\n",
    "  warnings = length_check(sections)\n",
    "  if warnings != \"\":\n",
    "    markdown += \"## \" + warnings\n",
    "\n",
    "  # Check definition lengths\n",
    "  warnings = length_check_definitions(definitions)\n",
    "  if warnings != \"\":\n",
    "    markdown += \"## \" + warnings\n",
    "\n",
    "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
    "\n",
    "\n",
    "  for section, summary in sections:\n",
    "    if show_placeholder and summary == \" Your summary here \":\n",
    "      summary = placeholder\n",
    "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
    "  \n",
    "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
    "  for concept, definition in definitions.items():\n",
    "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
    "  return markdown\n",
    "\n",
    "\n",
    "module1_markdown = format_module(1, \"Rational Agents and Task Environments\", module1_sections, module1_definitions)\n",
    "display(Markdown(module1_markdown))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9xRbdqDox2zD"
   },
   "source": [
    "#Module 2 - Python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "DpBvu7EMx7sy"
   },
   "outputs": [],
   "source": [
    "# No readings for this module.  Instead you can summarize the lecture instead.\n",
    "\n",
    "# Lecture notes \n",
    "module2_lecture_notes = \"\"\" \n",
    "| type | mutable | hashable |\n",
    "| :--- | ---: | ---: |\n",
    "| string | no | yes |\n",
    "| tuple | no | yes |\n",
    "| frozenset | no | yes |\n",
    "| list | yes | no |\n",
    "| dict (set) | yes | no |\n",
    "\n",
    "1. [:] creates a (shallow copy) of a seq. \n",
    "2. list.sort(func) sorts the list by func (compare(x,y) returns 1 (prior), -1, or 0).\n",
    "3. For strings, \\n\n",
    "  a. s.split(key) splits by key, returns a list of strings \\n\n",
    "  b. key.join(list) merges a list of strings (linked by key), returns a string \\n\n",
    "  c. s.capitalize(), s.upper() \\n\n",
    "  d. s.strip(key or [keys]) removes key(s) in the head or tail of the string (default: space and \\\\n). \\n\n",
    "4. No function overloading in python. \n",
    "5. *args: a tuple of arguments. \n",
    "6. **kwargs: a dict of arguments. \n",
    "7. [expression **for** name **in** list **if** filter]\n",
    "\"\"\"\n",
    "# Each definition should be at most 20 words long.\n",
    "module2_definitions = {\n",
    "\"mutability\" : \"allow the value (stored in memory) to be updated\",\n",
    "\"hashability\" : \"can have a hash value associated with it --> can be used as a key for a dict\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 597
    },
    "id": "ydOK__lwWgdp",
    "outputId": "dd65f4af-8b28-499a-afc0-12482ed7c7ca"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 2: Python\n",
       "## Module 2 Lecture Notes\n",
       " \n",
       "| type | mutable | hashable |\n",
       "| :--- | ---: | ---: |\n",
       "| string | no | yes |\n",
       "| tuple | no | yes |\n",
       "| frozenset | no | yes |\n",
       "| list | yes | no |\n",
       "| dict (set) | yes | no |\n",
       "\n",
       "1. [:] creates a (shallow copy) of a seq. \n",
       "2. list.sort(func) sorts the list by func (compare(x,y) returns 1 (prior), -1, or 0).\n",
       "3. For strings, \n",
       "\n",
       "  a. s.split(key) splits by key, returns a list of strings \n",
       "\n",
       "  b. key.join(list) merges a list of strings (linked by key), returns a string \n",
       "\n",
       "  c. s.capitalize(), s.upper() \n",
       "\n",
       "  d. s.strip(key or [keys]) removes key(s) in the head or tail of the string (default: space and \\n). \n",
       "\n",
       "4. No function overloading in python. \n",
       "5. *args: a tuple of arguments. \n",
       "6. **kwargs: a dict of arguments. \n",
       "7. [expression **for** name **in** list **if** filter]\n",
       "\n",
       "\n",
       "## Module 2 Definitions\n",
       "* **Mutability** - allow the value (stored in memory) to be updated\n",
       "* **Hashability** - can have a hash value associated with it --> can be used as a key for a dict\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "\n",
    "module2_sections = [\n",
    "  (\"Module 2 Lecture Notes\", module2_lecture_notes),\n",
    "]\n",
    "\n",
    "module2_markdown = format_module(2, \"Python\", module2_sections, module2_definitions)\n",
    "display(Markdown(module2_markdown))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "46MQLR-Gx8dZ"
   },
   "source": [
    "#Module 3 - Search Problems"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "BN0b1eVYx-nd"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 3 “Problem Solving by Search” (3.1-3.4)\n",
    "chapter3_1 = \"\"\"\n",
    "***Episodic, single agent, fully observable, deterministic, static, discrete, known environment***\n",
    "\n",
    "1. Problem-solving agents use **atomic** representations (not considering internal structure)\n",
    "2. Search problem : state space, initial state, goal states, actions, transition model (describes what each action does), action cost function\n",
    "\"\"\"\n",
    "\n",
    "chapter3_2 = \"\"\"\n",
    "1. Standardized problem can be solved by various methods (to compare the performance). \n",
    "2. Real world problem is idiosyncratic (异质的). It is these solutions that people actually use. \n",
    "\"\"\"\n",
    "\n",
    "chapter3_3 = \"\"\"\n",
    "1. Reached state: has a node. Expanded state: done node.successors(). \n",
    "2. Best-first search\n",
    "- evaluation function f(n)\n",
    "- ***expand the node with minimum f(n)***\n",
    "```\n",
    "def bestfirstsearch(problem, f):\n",
    "    state = initial\n",
    "    frontier = PriorityQueue()\n",
    "    frontier.put(0, state)\n",
    "    reached = {initial:0}\n",
    "    while not frontier.empty():\n",
    "      current = frontier.get()[1]\n",
    "      if current.is_solved():\n",
    "        return solution\n",
    "      for action, successor in current.successors():\n",
    "        newcost = reached[current.state] + delta_cost\n",
    "        if successor.state not in reached or newcost < reached[successor.state]:\n",
    "          reached[successor.state] = newcost\n",
    "          frontier.put((f(successor), successor))\n",
    "    return failure\n",
    "```\n",
    "\n",
    "3. Graph search checks for redundant paths (tree search doesn't). \n",
    "\n",
    "\"\"\"\n",
    "chapter3_4 = \"\"\"\n",
    "| Algorithm | Optimal | Complete | Time Complexity | Space Complexity |\n",
    "| :--- | :---: | :---: | :---: | :---: |\n",
    "| DFS | N | N | O(branching^maxdepth) | O(b*m) |\n",
    "| Depth-limited | N | N | O(b^limit) | O(b*l) | \n",
    "| IDDFS | Y | Y | O(b^d) | O(b*d) | \n",
    "| BFS | Y | Y | O(branching^depth) | O(b^d) |\n",
    "| Uniform-cost | Y | Y | O(b^(1+C/e)) | O(b^(1+C/e)) |\n",
    "| Bidirectional | Y | Y | O(b^d/2) | O(b^d/2) |\n",
    "\n",
    "In above table b is finite (otherwise all incomplete), m can be infinite. \n",
    "\n",
    "e is the lower bound of action cost. \n",
    "\n",
    "1. Uniform-cost search (Dijkstra if without goal) is best-first search with path-cost as f(n) (uniform total cost). BFS is when path-costs are equal. \n",
    "2. Depth-limited search pseudocode\n",
    "```\n",
    "def dls(problem, l, actions):\n",
    "    if l <= 0 or len(actions) >= l: \n",
    "      return\n",
    "    copy_p = copy(problem)\n",
    "    for action in actions:\n",
    "      copy_p.perform_move(action)\n",
    "    if copy_p.is_solved():\n",
    "      yield actions\n",
    "    for action, successor in copy_p.successors(): # 其实只需要action\n",
    "      yield from dls(problem, actions+[action])\n",
    "```\n",
    "3. In DLS if l<d incomplete. If l>d not optimal. \n",
    "4. In bidirectional search we need to keep track of two frontiers. \n",
    "\"\"\"\n",
    "\n",
    "# Lecture notes \n",
    "module3_lecture_notes = \"\"\"\n",
    "1. Tree/Graph search: the only difference is that graph search keeps track of \"visited\" set, and only adds successor node to the \\\n",
    "frontier if it's unvisited.  \n",
    "2. BFS vs DFS: \\n\n",
    "a. Use DFS if space is restricted / long solutions / wrong paths terminated quickly / search can be fine-tuned (微调) quickly \\n\n",
    "b. Use BFS if infinite depth / short solutions / can quickly discard unlikely paths\n",
    "\"\"\"\n",
    "\n",
    "# Definitions of concepts from Module 3.\n",
    "# You can define any bolded term in the textbook, \n",
    "# but you most use your own words for the definitions.\n",
    "# Each definition should be at most 20 words long.\n",
    "module3_definitions = {\n",
    "\"problem-solving agent\" : \"an agent that can formulate a plan via search\", \n",
    "\"path\" : \"a sequence of actions\",    \n",
    "\"solution\" : \"a path from the initial state to a goal state\",\n",
    "\"optimal solution\" : \"lowest path cost\",\n",
    "\"search problem\" : \"the process of finding a solution\",\n",
    "\"open-loop\" : \"once solution found, the agent can ignore the environment and just execute the solution to reach the goal\",\n",
    "\"search algorithm\" : \"input: a search problem, return: a solution or failure\", \n",
    "\"completeness\" : \"guarantee to find a solution if there is one, otherwise report failure\", \n",
    "\"optimality\" : \"able to find an optimal solution\",\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1575
    },
    "id": "lvtN3p7ET3Tx",
    "outputId": "b5e7ff38-e2b4-42ed-a7db-4920bceef282"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 3: Search Problems\n",
       "## AIMA Chapter 3.1 Problem-Solving Agents\n",
       "\n",
       "***Episodic, single agent, fully observable, deterministic, static, discrete, known environment***\n",
       "\n",
       "1. Problem-solving agents use **atomic** representations (not considering internal structure)\n",
       "2. Search problem : state space, initial state, goal states, actions, transition model (describes what each action does), action cost function\n",
       "\n",
       "\n",
       "## AIMA Chapter 3.2 Example Problems\n",
       "\n",
       "1. Standardized problem can be solved by various methods (to compare the performance). \n",
       "2. Real world problem is idiosyncratic (异质的). It is these solutions that people actually use. \n",
       "\n",
       "\n",
       "## AIMA Chapter 3.3 Search Algorithms\n",
       "\n",
       "1. Reached state: has a node. Expanded state: done node.successors(). \n",
       "2. Best-first search\n",
       "- evaluation function f(n)\n",
       "- ***expand the node with minimum f(n)***\n",
       "```\n",
       "def bestfirstsearch(problem, f):\n",
       "    state = initial\n",
       "    frontier = PriorityQueue()\n",
       "    frontier.put(0, state)\n",
       "    reached = {initial:0}\n",
       "    while not frontier.empty():\n",
       "      current = frontier.get()[1]\n",
       "      if current.is_solved():\n",
       "        return solution\n",
       "      for action, successor in current.successors():\n",
       "        newcost = reached[current.state] + delta_cost\n",
       "        if successor.state not in reached or newcost < reached[successor.state]:\n",
       "          reached[successor.state] = newcost\n",
       "          frontier.put((f(successor), successor))\n",
       "    return failure\n",
       "```\n",
       "\n",
       "3. Graph search checks for redundant paths (tree search doesn't). \n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 3.4 Uninformed Search Strategies\n",
       "\n",
       "| Algorithm | Optimal | Complete | Time Complexity | Space Complexity |\n",
       "| :--- | :---: | :---: | :---: | :---: |\n",
       "| DFS | N | N | O(branching^maxdepth) | O(b*m) |\n",
       "| Depth-limited | N | N | O(b^limit) | O(b*l) | \n",
       "| IDDFS | Y | Y | O(b^d) | O(b*d) | \n",
       "| BFS | Y | Y | O(branching^depth) | O(b^d) |\n",
       "| Uniform-cost | Y | Y | O(b^(1+C/e)) | O(b^(1+C/e)) |\n",
       "| Bidirectional | Y | Y | O(b^d/2) | O(b^d/2) |\n",
       "\n",
       "In above table b is finite (otherwise all incomplete), m can be infinite. \n",
       "\n",
       "e is the lower bound of action cost. \n",
       "\n",
       "1. Uniform-cost search (Dijkstra if without goal) is best-first search with path-cost as f(n) (uniform total cost). BFS is when path-costs are equal. \n",
       "2. Depth-limited search pseudocode\n",
       "```\n",
       "def dls(problem, l, actions):\n",
       "    if l <= 0 or len(actions) >= l: \n",
       "      return\n",
       "    copy_p = copy(problem)\n",
       "    for action in actions:\n",
       "      copy_p.perform_move(action)\n",
       "    if copy_p.is_solved():\n",
       "      yield actions\n",
       "    for action, successor in copy_p.successors(): # 其实只需要action\n",
       "      yield from dls(problem, actions+[action])\n",
       "```\n",
       "3. In DLS if l<d incomplete. If l>d not optimal. \n",
       "4. In bidirectional search we need to keep track of two frontiers. \n",
       "\n",
       "\n",
       "## Module 3 Lecture Notes\n",
       "\n",
       "1. Tree/Graph search: the only difference is that graph search keeps track of \"visited\" set, and only adds successor node to the frontier if it's unvisited.  \n",
       "2. BFS vs DFS: \n",
       "\n",
       "a. Use DFS if space is restricted / long solutions / wrong paths terminated quickly / search can be fine-tuned (微调) quickly \n",
       "\n",
       "b. Use BFS if infinite depth / short solutions / can quickly discard unlikely paths\n",
       "\n",
       "\n",
       "## Module 3 Definitions\n",
       "* **Problem-solving agent** - an agent that can formulate a plan via search\n",
       "* **Path** - a sequence of actions\n",
       "* **Solution** - a path from the initial state to a goal state\n",
       "* **Optimal solution** - lowest path cost\n",
       "* **Search problem** - the process of finding a solution\n",
       "* **Open-loop** - once solution found, the agent can ignore the environment and just execute the solution to reach the goal\n",
       "* **Search algorithm** - input: a search problem, return: a solution or failure\n",
       "* **Completeness** - guarantee to find a solution if there is one, otherwise report failure\n",
       "* **Optimality** - able to find an optimal solution\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "module3_sections = [\n",
    "  (\"AIMA Chapter 3.1 Problem-Solving Agents\", chapter3_1),\n",
    "  (\"AIMA Chapter 3.2 Example Problems\", chapter3_2),\n",
    "  (\"AIMA Chapter 3.3 Search Algorithms\", chapter3_3),\n",
    "  (\"AIMA Chapter 3.4 Uninformed Search Strategies\", chapter3_4),\n",
    "  (\"Module 3 Lecture Notes\", module3_lecture_notes),\n",
    "]\n",
    "\n",
    "module3_markdown = format_module(3, \"Search Problems\", module3_sections, module3_definitions)\n",
    "display(Markdown(module3_markdown))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WHREsHSSyA-h"
   },
   "source": [
    "#Module 4 - Informed Search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "tuFC8w7CyCns"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA Chapter 3 “Problem Solving by Search” (3.5-3.6)\n",
    "chapter3_5 = \"\"\"\n",
    "The only difference between un-/informed search strategy is informed search has heuristic(s).\n",
    "\n",
    "**Heuristic function** hints where the goal is. \n",
    "\n",
    "| Algorithm | Optimal | Complete | Time Complexity | Space Complexity |\n",
    "| :--- | :---: | :---: | :---: | :---: |\n",
    "| Greedy best-first search | N | Y | O(b*m) to O(V) | O(b*m) to O(V) |\n",
    "| A* search | Y if h is admissible | Y | | |\n",
    "\n",
    "\n",
    "1. Greedy best-first search is best-first search where f(n) = h(n). At each move it tries to go as close to the goal as possible. \n",
    "2. Uniform-cost search is ... where f(n) = g(n).\n",
    "3. A* search, f(n) = g(n) + h(n). g(n) is the actual cost from initial state to the node n (cost so far). \\\n",
    "f(n) is estimated cost from initial state through node n to a goal. \n",
    "4. **Consistent heuristic --> admissible.**\n",
    "5. A* prunes away nodes not necessary for finding an optimal solution. \n",
    "6. The main issue with A* is its use of memory. \n",
    "\"\"\"\n",
    "\n",
    "chapter3_6 = \"\"\"\n",
    "***Smaller h(n) --> more possible to be admissible, but slower.***\n",
    "\n",
    "***Larger h(n) --> less possible to be admissible, but faster.***\n",
    "\n",
    "1. Domination. h2 dominates h1 iff h2(n)>=h1(n) for each n. h2 is more efficient than h1. \n",
    "2. The cost of an optimal solution to a relaxed problem is a consistent heuristic for the original problem. \n",
    "3. Lower effective branching factor --> higher efficiency. \n",
    "\"\"\"\n",
    "\n",
    "\n",
    "# Lecture notes \n",
    "module4_lecture_notes = \"\"\"\n",
    "1. 0 <= admissible h(n) <= h*(n) true optimal cost. \n",
    "2. Manhattan distance and Euclidean distance are admissible heuristics. \n",
    "3. A* search pseudocode: \n",
    "```\n",
    "def astar(problem):\n",
    "    frontier = PriorityQueue()\n",
    "    frontier.put(0, initial)\n",
    "    actual_costs = {initial:0}\n",
    "    while not frontier.empty():\n",
    "      current = frontier.get()[1]\n",
    "      if current.is_solved():\n",
    "        return solution\n",
    "      for action, successor in current.successors():\n",
    "        newcost = actual_costs[current] + deltacost\n",
    "        if successor not in actual_costs or newcost < actual_costs[successor]:\n",
    "          actual_costs[successor] = newcost\n",
    "        frontier.put((newcost+h(successor), successor))\n",
    "```\n",
    "\"\"\"\n",
    "\n",
    "# Definitions\n",
    "module4_definitions = {\n",
    "\"heuristic function h(n)\" : \"estimated cost of the cheapest path from node *n* to a goal state\",    \n",
    "\"admissibility\" : \"**(optimistic)** never overestimate the cost to reach a goal\", \n",
    "\"consistency\" : \"(for a heuristic) h(n) <= cost(n to n' through action) + h(n', successor of n)\",\n",
    "\"optimally efficient\" : \"A* with a consistent heuristic\",\n",
    "\"satisficing solution\" : \"not optimal but good enough\", \n",
    "\"weighted A* search\" : \"f(n) = g(n) + W*h(n), W>1\", \n",
    "\"Beam search\" : \"limits the size of the frontier\", \n",
    "\"IDA*\" : \"Iterative-deepening A* search\", \n",
    "\"RBFS recursive best-first search\" : \"remember f-value, if excceeds the bound, choose the alternative\", \n",
    "\"MA* /SMA*\" : \"(simplified) memory-bounded A*\", \n",
    "\"effective branching factor\" : \"# of nodes used / depth reached (for finding a soluition)\", \n",
    "\"relaxed problem\" : \"a problem with fewer restrictions on actions\", \n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1114
    },
    "id": "vqtEs0gHs9sO",
    "outputId": "8b6ca034-ae7e-4c76-cc7b-8852b72c2720"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 4: Informed Search\n",
       "## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n",
       "\n",
       "The only difference between un-/informed search strategy is informed search has heuristic(s).\n",
       "\n",
       "**Heuristic function** hints where the goal is. \n",
       "\n",
       "| Algorithm | Optimal | Complete | Time Complexity | Space Complexity |\n",
       "| :--- | :---: | :---: | :---: | :---: |\n",
       "| Greedy best-first search | N | Y | O(b*m) to O(V) | O(b*m) to O(V) |\n",
       "| A* search | Y if h is admissible | Y | | |\n",
       "\n",
       "\n",
       "1. Greedy best-first search is best-first search where f(n) = h(n). At each move it tries to go as close to the goal as possible. \n",
       "2. Uniform-cost search is ... where f(n) = g(n).\n",
       "3. A* search, f(n) = g(n) + h(n). g(n) is the actual cost from initial state to the node n (cost so far). f(n) is estimated cost from initial state through node n to a goal. \n",
       "4. **Consistent heuristic --> admissible.**\n",
       "5. A* prunes away nodes not necessary for finding an optimal solution. \n",
       "6. The main issue with A* is its use of memory. \n",
       "\n",
       "\n",
       "## AIMA Chapter 3.6 Heuristic Functions\n",
       "\n",
       "***Smaller h(n) --> more possible to be admissible, but slower.***\n",
       "\n",
       "***Larger h(n) --> less possible to be admissible, but faster.***\n",
       "\n",
       "1. Domination. h2 dominates h1 iff h2(n)>=h1(n) for each n. h2 is more efficient than h1. \n",
       "2. The cost of an optimal solution to a relaxed problem is a consistent heuristic for the original problem. \n",
       "3. Lower effective branching factor --> higher efficiency. \n",
       "\n",
       "\n",
       "## Module 4 Lecture Notes\n",
       "\n",
       "1. 0 <= admissible h(n) <= h*(n) true optimal cost. \n",
       "2. Manhattan distance and Euclidean distance are admissible heuristics. \n",
       "3. A* search pseudocode: \n",
       "```\n",
       "def astar(problem):\n",
       "    frontier = PriorityQueue()\n",
       "    frontier.put(0, initial)\n",
       "    actual_costs = {initial:0}\n",
       "    while not frontier.empty():\n",
       "      current = frontier.get()[1]\n",
       "      if current.is_solved():\n",
       "        return solution\n",
       "      for action, successor in current.successors():\n",
       "        newcost = actual_costs[current] + deltacost\n",
       "        if successor not in actual_costs or newcost < actual_costs[successor]:\n",
       "          actual_costs[successor] = newcost\n",
       "        frontier.put((newcost+h(successor), successor))\n",
       "```\n",
       "\n",
       "\n",
       "## Module 4 Definitions\n",
       "* **Heuristic function h(n)** - estimated cost of the cheapest path from node *n* to a goal state\n",
       "* **Admissibility** - **(optimistic)** never overestimate the cost to reach a goal\n",
       "* **Consistency** - (for a heuristic) h(n) <= cost(n to n' through action) + h(n', successor of n)\n",
       "* **Optimally efficient** - A* with a consistent heuristic\n",
       "* **Satisficing solution** - not optimal but good enough\n",
       "* **Weighted a* search** - f(n) = g(n) + W*h(n), W>1\n",
       "* **Beam search** - limits the size of the frontier\n",
       "* **Ida*** - Iterative-deepening A* search\n",
       "* **Rbfs recursive best-first search** - remember f-value, if excceeds the bound, choose the alternative\n",
       "* **Ma* /sma*** - (simplified) memory-bounded A*\n",
       "* **Effective branching factor** - # of nodes used / depth reached (for finding a soluition)\n",
       "* **Relaxed problem** - a problem with fewer restrictions on actions\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "module4_sections = [\n",
    "  (\"AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\", chapter3_5),\n",
    "  (\"AIMA Chapter 3.6 Heuristic Functions\", chapter3_6),\n",
    "  (\"Module 4 Lecture Notes\", module4_lecture_notes),\n",
    "]\n",
    "\n",
    "module4_markdown = format_module(4, \"Informed Search\", \n",
    "                         module4_sections, \n",
    "                         module4_definitions)\n",
    "display(Markdown(module4_markdown))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "F3FPMzG9yUls"
   },
   "source": [
    "#Module 5 - Adversarial Search and Games"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "iEIOpL7vyWcc"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA chapter 5 \"Adversarial Search\"”\" (5.1-5.3, and 5.5).\n",
    "chapter5_1 = \"\"\"\n",
    "***Competitive environment***\n",
    "\n",
    "***Deterministic, two-player, turn-taking, perfect information, zero-sum games***\n",
    "1. Game definition: initial state, turn (who moves), actions (clear set), transition model, terminal states, utility function (well-defined outcomes). \n",
    "2. Utility function is also called an objective / payoff function. \n",
    "3. Complete game ree: a search tree of every seq of moves to terminal states. \n",
    "\"\"\"\n",
    "\n",
    "chapter5_2 = \"\"\"\n",
    "minimax(s) =\n",
    "- utility(s, max)  if s.is_terminal() \n",
    "- max_{su \\in s.successors()} (minimax(su)) if turn = max \n",
    "- min_{su \\in s.successors()} (minimax(su)) if turn = min \n",
    "1. Optimal play for MAX assumes that MIN also plays optimally. If not, MAX can be better, but probably not optimal. \n",
    "2. Minimax performs DFS for the game tree. Time complexity = O(b^m). Space complexity = O(b*m). \n",
    "3. <u>Alpha and beta in alpha-beta pruning are **inherited from the parent**, 之后再按规则update回parent. Each node has outcome (**back-up value**, optimal value of its children), and alpha and beta. </u>\n",
    "4. **Only alpha is updated when the we moves. Only beta is updated when the rival moves.** Updating order is the same as DFS. (<u>Inherit both alpha and beta, but only update one.</u>)\n",
    "5. **Pruning is triggered when MIN moves but outcome < alpha, or when MAX moves but outcome > beta.** \n",
    "\"\"\"\n",
    "\n",
    "chapter5_3 = \"\"\"\n",
    "1. Apply a evaluation function to evaluate nonterminal nodes (to avoid search till the terminal). Replace the terminal test by **cutoff test** (return True if real terminal). \n",
    "2. Evaluation function should be \\n\n",
    "- fast\n",
    "- strongly correlated with chances of winning (e.g. expected value)\n",
    "3. Cutting off search. Evaluation function should be applied only to quiescent states. \n",
    "\n",
    "\"\"\"\n",
    "chapter5_5 = \"\"\"\n",
    "expectiminimax(s) =\n",
    "- utility(s, max)  if s.is_terminal() \n",
    "- max_{su \\in s.successors()} (expectiminimax(su)) if turn = max \n",
    "- min_{su \\in s.successors()} (expectiminimax(su)) if turn = min \n",
    "- Expectation_r (expectiminimax(s, r)) if turn = chance\n",
    "\n",
    "where r represents a possible outcome.\n",
    "1. Game tree includes **chance nodes** layer between each MIN layer and MAX layer. \n",
    "2. Minimax values are expected value of a position (expectiminimax value). \n",
    "\"\"\"\n",
    "\n",
    "# Russell and Norvig, AIMA Chapter 16 “Making Simple Decisions” (16.1-16.3)\n",
    "chapter16_1 = \"\"\"\n",
    "1. Principle of MEU (maximum expected utility): rational agents choose actions maximizing expected utility. \n",
    "2. If an agent acts to maximize a utility function that correctly reflects the performance measure, the \\\n",
    "the agent will achieve the highest **possible** performance score. \n",
    "\"\"\"\n",
    "\n",
    "chapter16_2 = \"\"\"\n",
    "Axioms of utility theory. Here, >, <, and = represent domination relationships. \\n \n",
    "- Orderability: A>B or B>A else A=B. \n",
    "- Transitivity: A>B and B>C then A>C. \n",
    "- Continuity: A>B>C then p*A+(1-p)*C = B for some p.\n",
    "- Substitutability: A=(>)B then p*A+(1-p)*C =(>) p*B+(1-p)*C for any p.\n",
    "- Monotonicity: A>B then (p>q iff p*A+(1-p)*B > q*A+(1-q)*B)\n",
    "- Decomposability: p*A+(1-p)*(q*B+(1-q)*C) = p*A+(1-p)*q*B+(1-p)*(1-q)*C\n",
    "\"\"\"\n",
    "chapter16_3 = \"\"\"\n",
    "1. Risk averse, risk-seeking, certainty equivalent (risk-neutral).\n",
    "2. Decision theory is normative theory (what should do). On the other hand, descriptive theory is about how agents actually act. \n",
    "\"\"\"\n",
    "\n",
    "# Lecture notes \n",
    "module5_lecture_notes = \"\"\"\n",
    "Expectimax: compute the average score under optimal play (take expected utility). It is used when the opponent randomize actions. \n",
    "\"\"\"\n",
    "\n",
    "# Definitions\n",
    "module5_definitions = {\n",
    "\"Type A strategy\" : \"considers wide but shallow cases in a game tree\", \n",
    "\"Type B strategy\" : \"considers narrow but deep cases in a game tree\",     \n",
    "\"quiescent\" : \"休眠的, positions in which no pending moves will hugely change the (next) evaluation\", \n",
    "\"horizon effect\" : \"opponent's move can seriously damage mine and is unavoidable, but can be avoided temporarily\",\n",
    "\"forward pruning\" : \"prunes probably poor moves (prunes more than alpha-beta)\", \n",
    "\"ambiguity aversion\" : \"inconsistent risk preference for people\",\n",
    "\"framing effect\" : \"same information, different statement, then different decision\", \n",
    "\"stochastic game\" : \"game including uncertainty\"\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1519
    },
    "id": "KUc_LgzDvWf-",
    "outputId": "cefd7f46-a5b9-40c5-aa90-7885ab33bf49"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 5: Adversarial Search and Games\n",
       "## AIMA Chapter 5.1 Game Theory\n",
       "\n",
       "***Competitive environment***\n",
       "\n",
       "***Deterministic, two-player, turn-taking, perfect information, zero-sum games***\n",
       "1. Game definition: initial state, turn (who moves), actions (clear set), transition model, terminal states, utility function (well-defined outcomes). \n",
       "2. Utility function is also called an objective / payoff function. \n",
       "3. Complete game ree: a search tree of every seq of moves to terminal states. \n",
       "\n",
       "\n",
       "## AIMA Chapter 5.2 Optimal Decisions in Games\n",
       "\n",
       "minimax(s) =\n",
       "- utility(s, max)  if s.is_terminal() \n",
       "- max_{su \\in s.successors()} (minimax(su)) if turn = max \n",
       "- min_{su \\in s.successors()} (minimax(su)) if turn = min \n",
       "1. Optimal play for MAX assumes that MIN also plays optimally. If not, MAX can be better, but probably not optimal. \n",
       "2. Minimax performs DFS for the game tree. Time complexity = O(b^m). Space complexity = O(b*m). \n",
       "3. <u>Alpha and beta in alpha-beta pruning are **inherited from the parent**, 之后再按规则update回parent. Each node has outcome (**back-up value**, optimal value of its children), and alpha and beta. </u>\n",
       "4. **Only alpha is updated when the we moves. Only beta is updated when the rival moves.** Updating order is the same as DFS. (<u>Inherit both alpha and beta, but only update one.</u>)\n",
       "5. **Pruning is triggered when MIN moves but outcome < alpha, or when MAX moves but outcome > beta.** \n",
       "\n",
       "\n",
       "## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n",
       "\n",
       "1. Apply a evaluation function to evaluate nonterminal nodes (to avoid search till the terminal). Replace the terminal test by **cutoff test** (return True if real terminal). \n",
       "2. Evaluation function should be \n",
       "\n",
       "- fast\n",
       "- strongly correlated with chances of winning (e.g. expected value)\n",
       "3. Cutting off search. Evaluation function should be applied only to quiescent states. \n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 5.5 Stochastic Games\n",
       "\n",
       "expectiminimax(s) =\n",
       "- utility(s, max)  if s.is_terminal() \n",
       "- max_{su \\in s.successors()} (expectiminimax(su)) if turn = max \n",
       "- min_{su \\in s.successors()} (expectiminimax(su)) if turn = min \n",
       "- Expectation_r (expectiminimax(s, r)) if turn = chance\n",
       "\n",
       "where r represents a possible outcome.\n",
       "1. Game tree includes **chance nodes** layer between each MIN layer and MAX layer. \n",
       "2. Minimax values are expected value of a position (expectiminimax value). \n",
       "\n",
       "\n",
       "## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n",
       "\n",
       "1. Principle of MEU (maximum expected utility): rational agents choose actions maximizing expected utility. \n",
       "2. If an agent acts to maximize a utility function that correctly reflects the performance measure, the the agent will achieve the highest **possible** performance score. \n",
       "\n",
       "\n",
       "## AIMA Chapter 16.2 The Basis of Utility Theory\n",
       "\n",
       "Axioms of utility theory. Here, >, <, and = represent domination relationships. \n",
       " \n",
       "- Orderability: A>B or B>A else A=B. \n",
       "- Transitivity: A>B and B>C then A>C. \n",
       "- Continuity: A>B>C then p*A+(1-p)*C = B for some p.\n",
       "- Substitutability: A=(>)B then p*A+(1-p)*C =(>) p*B+(1-p)*C for any p.\n",
       "- Monotonicity: A>B then (p>q iff p*A+(1-p)*B > q*A+(1-q)*B)\n",
       "- Decomposability: p*A+(1-p)*(q*B+(1-q)*C) = p*A+(1-p)*q*B+(1-p)*(1-q)*C\n",
       "\n",
       "\n",
       "## AIMA Chapter 16.3 Utility Functions\n",
       "\n",
       "1. Risk averse, risk-seeking, certainty equivalent (risk-neutral).\n",
       "2. Decision theory is normative theory (what should do). On the other hand, descriptive theory is about how agents actually act. \n",
       "\n",
       "\n",
       "## Module 5 Lecture Notes\n",
       "\n",
       "Expectimax: compute the average score under optimal play (take expected utility). It is used when the opponent randomize actions. \n",
       "\n",
       "\n",
       "## Module 5 Definitions\n",
       "* **Type a strategy** - considers wide but shallow cases in a game tree\n",
       "* **Type b strategy** - considers narrow but deep cases in a game tree\n",
       "* **Quiescent** - 休眠的, positions in which no pending moves will hugely change the (next) evaluation\n",
       "* **Horizon effect** - opponent's move can seriously damage mine and is unavoidable, but can be avoided temporarily\n",
       "* **Forward pruning** - prunes probably poor moves (prunes more than alpha-beta)\n",
       "* **Ambiguity aversion** - inconsistent risk preference for people\n",
       "* **Framing effect** - same information, different statement, then different decision\n",
       "* **Stochastic game** - game including uncertainty\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "module5_sections = [\n",
    "  (\"AIMA Chapter 5.1 Game Theory\", chapter5_1),\n",
    "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter5_2),\n",
    "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter5_3),\n",
    "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter5_5),\n",
    "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
    "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
    "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
    "  (\"Module 5 Lecture Notes\", module5_lecture_notes),\n",
    "]\n",
    "\n",
    "module5_markdown = format_module(5, \"Adversarial Search and Games\", \n",
    "                         module5_sections, \n",
    "                         module5_definitions)\n",
    "display(Markdown(module5_markdown))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "qVSQhTVSyYYO"
   },
   "source": [
    "#Module 6 - \"Constraint Satisfaction Problems\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "Wm4mfW82yaRH"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA, Chapter 6 “Constraint Satisfaction Problems” (6.1-6.5)\n",
    "chapter6_1 = \"\"\"\n",
    "1. CSP search use general heuristics (rather than domain-specific). Actions and transition model are derived from problem description. \n",
    "2. CSP definition: set of variables, set of domains, set of constraints ((included variable, relation) pair). \n",
    "3. **A is consistent with B means for all values in A.domain there exists at least one value in B.domain that makes the constraint satisfied.** \n",
    "4. Advantages of CSP form: \\n\n",
    "- Represents many problems. \n",
    "- Solvers are fast and efficient. \n",
    "- Quickly pruning (atomic state-space searcher cannot). No need to check expansions of wrong partial assignments. \n",
    "5. No algorithm can solve general nonlinear constraints CSPs on integer variables. \n",
    "6. Constraint hypergraph consists of ordinary nodes and hypernodes (represent n-ary constraints for n>3, linked with each constrained node). \n",
    "7. Constrained optimization problem introduces costs of variable assignment. \n",
    "\"\"\"\n",
    "\n",
    "chapter6_2 = \"\"\"\n",
    "1. Through hypergraph, one can transform all n-ary constraints into binary ones. \n",
    "2. AC-3 pseudocode\n",
    "```\n",
    "def ac3(csp):\n",
    "    frontier = Queue()\n",
    "    for arc in ARCS: \n",
    "      frontier.put(arc)\n",
    "    while not frontier.empty():\n",
    "      current_arc = frontier.get() # current_arc is (Xi, Xj)\n",
    "      if current_arc[0].adjust(current_arc[1]): # if reduce the domain of current_arc[0]\n",
    "        # adjust current_arc[0] to be arc-consistent with current_arc[1] \n",
    "        # adjust above removes value in current_arc[0].domain if there is no consistent value in current_arc[1].domain\n",
    "        if current_arc[0].domain.empty():\n",
    "          return False\n",
    "        for arc in ARCS that arc[1] == current_arc[0]:\n",
    "          frontier.put(arc)\n",
    "    return True\n",
    "```\n",
    "\"\"\"\n",
    "\n",
    "chapter6_3 = \"\"\"\n",
    "1. Backtracking search does DFS. When value choice leads to failure, it returns to the state before the choice (and makes another choice). \\\n",
    "This is done by two \"add\"s and two \"remove\"s. \n",
    "```\n",
    "def backtrack(csp, assignment):\n",
    "    ...\n",
    "    add {variable=value} to assignment\n",
    "    inference impose some-consistency\n",
    "    if inference != failure:\n",
    "      add inference to csp\n",
    "      result = backtrack(csp, assignment)\n",
    "      if result != failure:\n",
    "        return result\n",
    "      remove inference from csp\n",
    "    remove {variable=value} from assignment\n",
    "```\n",
    "This is **chronological backtracking**. \n",
    "\n",
    "2. Order of value assignment \\n\n",
    "(1) Most constrained variable. (MRV minimum-remaining-values heuristic, fail-first)\\n\n",
    "(2) Most constraining variable. (degree heuristic) \\n\n",
    "(3) Least constraining value. \n",
    "3. **Forward checking** is one of the simplest form of inference. Whenever a variable is assigned, it establishes arc-consistency for it. (**no propagation**)\n",
    "4. **MAC** Maintaining Arc Consistency algorithm uses AC-3 as inference. The difference is that MAC starts from neighbors of the assigned value (not all arcs are in queue at first). \n",
    "5. Compared to Backtracking, Backjumping revisit the variable responsible for assigning the conflictive value (most recent in the conflict set). Simple backjumping is redundant for \\\n",
    "forward checking (then also for consistency of higher levels). \n",
    "6. Constraint learning finds a minimum conflict set (**no-goods**) and tries to avoid them in further search (e.g. add new constraints). \n",
    "\"\"\"\n",
    "\n",
    "chapter6_4 = \"\"\"\n",
    "1. Local search definition: with a initial assignment, change the values to get close to a solution. \n",
    "2. **Min-conflicts heuristic** minimizes number of conflicts. It assigns value causing least conflicts to a conflictive variable each time. \n",
    "3. Local search (usually) make less changes to existing state in less amount of time than backtracking. \n",
    "\"\"\"\n",
    "\n",
    "chapter6_5 = \"\"\"\n",
    "1. Tree-structured constraint graph: only one path between any two variables. \n",
    "2. Topological sort picks an arbitraty variable to be the root of the tree (to convert tree-structured CSP graph into the form of tree).\n",
    "3. Two ways of reducing a general CSP to a tree: cutset conditioning and tree decomposition. \n",
    "4. **Cutset conditioning algorithm** \n",
    "- Separate a cycle cutset *S* from CSP (so that the graph becomes a tree). \n",
    "- For a solution of *S*, remove inconsistent values from domains of remaining variables. \n",
    "- If the remaining CSP has a solution, return with *S* assignment, otherwise repeat (2)-(3). \n",
    "\n",
    "Time complexity (total) (d is domain size, c is size of *S*, n is size of original CSP)\n",
    "$$\n",
    "O(d^c\\cdot(n-c)d^2)\n",
    "$$\n",
    "Space complexity\n",
    "$$\n",
    "O(n)\n",
    "$$\n",
    "\n",
    "5. **Tree decomposition requirement**\n",
    "- Every variable in the original CSP appears in at least one tree node. \n",
    "- If two variables connected by a constraint, they (and the constraint) appear together in at least one tree node. \n",
    "- If one variable appears in two nodes, it appears in every node along the path of the two nodes. \n",
    "\n",
    "Time complexity **after decomposition**\n",
    "$$\n",
    "O(nd^2)\n",
    "$$\n",
    "Time complexity (total) (w is tree-width of graph)\n",
    "$$\n",
    "O(nd^{w+1})\n",
    "$$\n",
    "Space complexity\n",
    "$$\n",
    "O(n^w)\n",
    "$$\n",
    "\n",
    "But finding decomposition with minimal tree width is NP-hard. \n",
    "\"\"\"\n",
    "\n",
    "\n",
    "# Lecture notes \n",
    "module6_lecture_notes = \"\"\"\n",
    "1. Enforcing K-consistency doesn't guarantee to solve a CSP. \n",
    "2. CSP solvers use search (assigning a value) and inference (constraint propagation). \n",
    "3. AC-3 time complexity (worst case, complete graph)\n",
    "$$\n",
    "O(n^2d^3)\n",
    "$$\n",
    "Planar (二维) constraint grpha case\n",
    "$$\n",
    "O(nd^3)\n",
    "$$\n",
    "\"\"\"\n",
    "\n",
    "# Definitions\n",
    "module6_definitions = {\n",
    "\"Factored representation for states\" : \"a set of variables with values\", \n",
    "\"consistent/legal assignment\" : \"doesn't violate any constraints (see above 6.1)\", \n",
    "\"complete assignment\" : \"every variable is assigned a value\", \n",
    "\"solution to CSP\" : \"a consistent, complete assignment\", \n",
    "\"partial assignment\" : \"incomplete assignment, some variables unassigned\", \n",
    "\"partial solution\" : \"consistent partial assignment\", \n",
    "\"constraint graph\" : \"nodes are variables, edges are constraints (linking any two variables involved)\", \n",
    "\"linear constraint\" : \"variables appear only in linear forms\", \n",
    "\"unary constraint\" : \"constraint involving only one variable\", \n",
    "\"binary constraint\" : \"constraint involving only two variables\", \n",
    "\"binary CSP\" : \"CSP with only unary and binary constraints\",\n",
    "\"global constraint\" : \"constraint involving arbitrary number of variables (**need not involve all the variables**)\",\n",
    "\"preference constraint\" : \"indicate preference of solutions (not absolute constraints)\", \n",
    "\"COP\" : \"constrained optimization problem, CSP with preferences\", \n",
    "\"constraint propagation\" : \"use constraints to reduce the domains\", \n",
    "\"local consistency\" : \"consistent in some **part** of the graph\", \n",
    "\"node consistency\" : \"all values in domain satisfy **unary** constraints for each variable\", \n",
    "\"arc consistency\" : \"all values in domain satisfy **binary** constraints for each variable\",\n",
    "\"path consistency\" : \"a third variable is consistent with a two-variable set\", \n",
    "\"consistency for CSP\" : \"the CSP is some-consistent iff all variables satisfy some-consistency\", \n",
    "\"k-consistency (for CSP)\" : \"any *k*th variable is consistent with any (k-1)-variable set\", \n",
    "\"strong k-consistency (for CSP)\": \"k, (k-1), ..., 1-consistent\", \n",
    "\"commutativity\" : \"the order of application of any given set of actions does not matter\", \n",
    "\"conflict-directed backjumping\" : \"backjumping where conflict set of a variable is preceding varaibles that cause inconsistency of it and subsequent variables\", \n",
    "\"directional arc consistency (for CSP)\" : \"for X1, ..., Xn, every Xi is arc-consistent with Xj for each j>i\",\n",
    "\"tree-width of a tree decomposition\" : \"size of the largest node - 1\",\n",
    "\"tree-width of the graph\" : \"min(tree-widths of tree decompositions)\"\n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 2538
    },
    "id": "kKWbCsbfxL3R",
    "outputId": "751538cc-0936-4e1e-aede-08b044b315d5"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 6: Constraint Satisfaction Problems\n",
       "## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n",
       "\n",
       "1. CSP search use general heuristics (rather than domain-specific). Actions and transition model are derived from problem description. \n",
       "2. CSP definition: set of variables, set of domains, set of constraints ((included variable, relation) pair). \n",
       "3. **A is consistent with B means for all values in A.domain there exists at least one value in B.domain that makes the constraint satisfied.** \n",
       "4. Advantages of CSP form: \n",
       "\n",
       "- Represents many problems. \n",
       "- Solvers are fast and efficient. \n",
       "- Quickly pruning (atomic state-space searcher cannot). No need to check expansions of wrong partial assignments. \n",
       "5. No algorithm can solve general nonlinear constraints CSPs on integer variables. \n",
       "6. Constraint hypergraph consists of ordinary nodes and hypernodes (represent n-ary constraints for n>3, linked with each constrained node). \n",
       "7. Constrained optimization problem introduces costs of variable assignment. \n",
       "\n",
       "\n",
       "## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n",
       "\n",
       "1. Through hypergraph, one can transform all n-ary constraints into binary ones. \n",
       "2. AC-3 pseudocode\n",
       "```\n",
       "def ac3(csp):\n",
       "    frontier = Queue()\n",
       "    for arc in ARCS: \n",
       "      frontier.put(arc)\n",
       "    while not frontier.empty():\n",
       "      current_arc = frontier.get() # current_arc is (Xi, Xj)\n",
       "      if current_arc[0].adjust(current_arc[1]): # if reduce the domain of current_arc[0]\n",
       "        # adjust current_arc[0] to be arc-consistent with current_arc[1] \n",
       "        # adjust above removes value in current_arc[0].domain if there is no consistent value in current_arc[1].domain\n",
       "        if current_arc[0].domain.empty():\n",
       "          return False\n",
       "        for arc in ARCS that arc[1] == current_arc[0]:\n",
       "          frontier.put(arc)\n",
       "    return True\n",
       "```\n",
       "\n",
       "\n",
       "## AIMA Chapter 6.3 Backtracking Search for CSPs\n",
       "\n",
       "1. Backtracking search does DFS. When value choice leads to failure, it returns to the state before the choice (and makes another choice). This is done by two \"add\"s and two \"remove\"s. \n",
       "```\n",
       "def backtrack(csp, assignment):\n",
       "    ...\n",
       "    add {variable=value} to assignment\n",
       "    inference impose some-consistency\n",
       "    if inference != failure:\n",
       "      add inference to csp\n",
       "      result = backtrack(csp, assignment)\n",
       "      if result != failure:\n",
       "        return result\n",
       "      remove inference from csp\n",
       "    remove {variable=value} from assignment\n",
       "```\n",
       "This is **chronological backtracking**. \n",
       "\n",
       "2. Order of value assignment \n",
       "\n",
       "(1) Most constrained variable. (MRV minimum-remaining-values heuristic, fail-first)\n",
       "\n",
       "(2) Most constraining variable. (degree heuristic) \n",
       "\n",
       "(3) Least constraining value. \n",
       "3. **Forward checking** is one of the simplest form of inference. Whenever a variable is assigned, it establishes arc-consistency for it. (**no propagation**)\n",
       "4. **MAC** Maintaining Arc Consistency algorithm uses AC-3 as inference. The difference is that MAC starts from neighbors of the assigned value (not all arcs are in queue at first). \n",
       "5. Compared to Backtracking, Backjumping revisit the variable responsible for assigning the conflictive value (most recent in the conflict set). Simple backjumping is redundant for forward checking (then also for consistency of higher levels). \n",
       "6. Constraint learning finds a minimum conflict set (**no-goods**) and tries to avoid them in further search (e.g. add new constraints). \n",
       "\n",
       "\n",
       "## AIMA Chapter 6.4 Local Search for CSPs\n",
       "\n",
       "1. Local search definition: with a initial assignment, change the values to get close to a solution. \n",
       "2. **Min-conflicts heuristic** minimizes number of conflicts. It assigns value causing least conflicts to a conflictive variable each time. \n",
       "3. Local search (usually) make less changes to existing state in less amount of time than backtracking. \n",
       "\n",
       "\n",
       "## AIMA Chapter 6.5 The Structure of Problems\n",
       "\n",
       "1. Tree-structured constraint graph: only one path between any two variables. \n",
       "2. Topological sort picks an arbitraty variable to be the root of the tree (to convert tree-structured CSP graph into the form of tree).\n",
       "3. Two ways of reducing a general CSP to a tree: cutset conditioning and tree decomposition. \n",
       "4. **Cutset conditioning algorithm** \n",
       "- Separate a cycle cutset *S* from CSP (so that the graph becomes a tree). \n",
       "- For a solution of *S*, remove inconsistent values from domains of remaining variables. \n",
       "- If the remaining CSP has a solution, return with *S* assignment, otherwise repeat (2)-(3). \n",
       "\n",
       "Time complexity (total) (d is domain size, c is size of *S*, n is size of original CSP)\n",
       "$$\n",
       "O(d^c\\cdot(n-c)d^2)\n",
       "$$\n",
       "Space complexity\n",
       "$$\n",
       "O(n)\n",
       "$$\n",
       "\n",
       "5. **Tree decomposition requirement**\n",
       "- Every variable in the original CSP appears in at least one tree node. \n",
       "- If two variables connected by a constraint, they (and the constraint) appear together in at least one tree node. \n",
       "- If one variable appears in two nodes, it appears in every node along the path of the two nodes. \n",
       "\n",
       "Time complexity **after decomposition**\n",
       "$$\n",
       "O(nd^2)\n",
       "$$\n",
       "Time complexity (total) (w is tree-width of graph)\n",
       "$$\n",
       "O(nd^{w+1})\n",
       "$$\n",
       "Space complexity\n",
       "$$\n",
       "O(n^w)\n",
       "$$\n",
       "\n",
       "But finding decomposition with minimal tree width is NP-hard. \n",
       "\n",
       "\n",
       "## Module 6 Lecture Notes\n",
       "\n",
       "1. Enforcing K-consistency doesn't guarantee to solve a CSP. \n",
       "2. CSP solvers use search (assigning a value) and inference (constraint propagation). \n",
       "3. AC-3 time complexity (worst case, complete graph)\n",
       "$$\n",
       "O(n^2d^3)\n",
       "$$\n",
       "Planar (二维) constraint grpha case\n",
       "$$\n",
       "O(nd^3)\n",
       "$$\n",
       "\n",
       "\n",
       "## Module 6 Definitions\n",
       "* **Factored representation for states** - a set of variables with values\n",
       "* **Consistent/legal assignment** - doesn't violate any constraints (see above 6.1)\n",
       "* **Complete assignment** - every variable is assigned a value\n",
       "* **Solution to csp** - a consistent, complete assignment\n",
       "* **Partial assignment** - incomplete assignment, some variables unassigned\n",
       "* **Partial solution** - consistent partial assignment\n",
       "* **Constraint graph** - nodes are variables, edges are constraints (linking any two variables involved)\n",
       "* **Linear constraint** - variables appear only in linear forms\n",
       "* **Unary constraint** - constraint involving only one variable\n",
       "* **Binary constraint** - constraint involving only two variables\n",
       "* **Binary csp** - CSP with only unary and binary constraints\n",
       "* **Global constraint** - constraint involving arbitrary number of variables (**need not involve all the variables**)\n",
       "* **Preference constraint** - indicate preference of solutions (not absolute constraints)\n",
       "* **Cop** - constrained optimization problem, CSP with preferences\n",
       "* **Constraint propagation** - use constraints to reduce the domains\n",
       "* **Local consistency** - consistent in some **part** of the graph\n",
       "* **Node consistency** - all values in domain satisfy **unary** constraints for each variable\n",
       "* **Arc consistency** - all values in domain satisfy **binary** constraints for each variable\n",
       "* **Path consistency** - a third variable is consistent with a two-variable set\n",
       "* **Consistency for csp** - the CSP is some-consistent iff all variables satisfy some-consistency\n",
       "* **K-consistency (for csp)** - any *k*th variable is consistent with any (k-1)-variable set\n",
       "* **Strong k-consistency (for csp)** - k, (k-1), ..., 1-consistent\n",
       "* **Commutativity** - the order of application of any given set of actions does not matter\n",
       "* **Conflict-directed backjumping** - backjumping where conflict set of a variable is preceding varaibles that cause inconsistency of it and subsequent variables\n",
       "* **Directional arc consistency (for csp)** - for X1, ..., Xn, every Xi is arc-consistent with Xj for each j>i\n",
       "* **Tree-width of a tree decomposition** - size of the largest node - 1\n",
       "* **Tree-width of the graph** - min(tree-widths of tree decompositions)\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "module6_sections = [\n",
    "  (\"AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\", chapter6_1),\n",
    "  (\"AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\", chapter6_2),\n",
    "  (\"AIMA Chapter 6.3 Backtracking Search for CSPs\", chapter6_3),\n",
    "  (\"AIMA Chapter 6.4 Local Search for CSPs\", chapter6_4),\n",
    "  (\"AIMA Chapter 6.5 The Structure of Problems\", chapter6_5),\n",
    "  (\"Module 6 Lecture Notes\", module6_lecture_notes),\n",
    "]\n",
    "\n",
    "module6_markdown = format_module(6, \"Constraint Satisfaction Problems\", \n",
    "                         module6_sections, \n",
    "                         module6_definitions)\n",
    "display(Markdown(module6_markdown))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RYESi2kMybL8"
   },
   "source": [
    "#Module 7 - Logical Agents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "id": "qIRJ4YYCzNHL"
   },
   "outputs": [],
   "source": [
    "# Russell and Norvig, AIMA Chapter 7 “Logical Agents” (Sections 7.1-7.5)\n",
    "\n",
    "chapter7_1 = \"\"\"\n",
    "1. Declarative approach is telling the agent what it needs to **know** so that it knows how to operate in the environment. \n",
    "2. Procedural approach is telling the agent what it needs to **do** specifically (behaviors). \n",
    "\"\"\"\n",
    "chapter7_2 = \"\"\"\n",
    "1. Task environment definition (review): performance measure, environment, actuators, sensors. \n",
    "2. A sentence *s* is true in model *m* <--> *m* satisfies *s* <--> *m* is a model of *s*. \n",
    "3. *M(s)* represents the set of all models of *s*.\n",
    "4. Entailment of sentences: a |= b iff M(a) belongs to M(b) (similar to -->). \n",
    "5. Inference: KB |=i a iff a is derived from KB by inference algorithm i.\n",
    "\"\"\"\n",
    "\n",
    "chapter7_3 = \"\"\"\n",
    "Learning means deriving knowledge from perceptual experience. \n",
    "\"\"\"\n",
    "\n",
    "chapter7_4 = \"\"\"\n",
    "| Terminology | Explanation |\n",
    "| :--- | ---: |\n",
    "| conjunction | and | \n",
    "| disjunction | or |\n",
    "| implication | (premise, antecedent) --> (conclusion, consequent) |\n",
    "| biconditional | iff, <--> |\n",
    "\"\"\"\n",
    "chapter7_5 = \"\"\"\n",
    "| Terminology and laws | Explanation |\n",
    "| :--- | ---: |\n",
    "| Logical equivalence | <--> of sentences, equal truth values (following \"=\") |\n",
    "| (a and b) = (b and a) | commutativity of and | \n",
    "| (a or b) = (b or a) | commutativity of or | \n",
    "| ((a and b) and c) = (a and (b and c)) | associativity of and |\n",
    "| ((a or b) or c) = (a or (b or c)) | associativity of or |\n",
    "| not(not a) = a | double-negation elimination |\n",
    "| (a --> b) = ((not b) --> (not a)) | contraposition |\n",
    "| (a --> b) = ((not a) or b) | implication elimination |\n",
    "| (a <--> b) = ((a --> b) and (b --> a)) | biconditional elimination |\n",
    "| not(a and b) = (not a) or (not b) | De Morgan |\n",
    "| not(a or b) = (not a) and (not b) | De Morgan |\n",
    "| a and (b or c) = (a and b) or (a and c) | distributivity of and over or |\n",
    "| a or (b and c) = (a or b) and (a or c) | distributivity of or over and |\n",
    "\n",
    "1. Validity: true in all models. Valid sentences are called tautologies. \n",
    "2. a |= b iff (a --> b) is valid. \n",
    "3. Satisfiability: true in some model(s).\n",
    "4. Proof problem definition: initial state (KB), actions, result, goal.  \n",
    "\n",
    "| Terminology | Explanation |\n",
    "| :--- | ---: |\n",
    "| CNF | 合取范式, linked by and |\n",
    "| DNF | 析取范式, linked by or |\n",
    "| DefiniteClauseForm | Fact or (symbol_1 and ... and symbol_n) --> symbol |\n",
    "| GoalClauseForm | (symbol_1 and ... and symbol_n) --> False |\n",
    "| HornClauseForm | DefiniteClauseForm or GoalClauseForm |\n",
    "\n",
    "5. Forward chaining (is sound and complete) conducts reasoning until the query is added or no further inferences.\n",
    "6. Backward chaining algorithm works backward from the query, and is a form of goal-directed reasoning. \n",
    "\"\"\"\n",
    "\n",
    "# Lecture notes \n",
    "module7_lecture_notes = \"\"\"\n",
    "Inference rules\n",
    "$$ {sentence_1 given, sentence_2 given, ...} $$ \n",
    "$$ ------------------- $$\n",
    "$$ {sentence_1 inferred, sentence_2 inferred, ...} $$\n",
    "\n",
    "Resolution algorithm is proof by contradiction. e.g. to show KB |= a we show KB and (not a) is unsatisfiable. \n",
    "\"\"\"\n",
    "\n",
    "# Definitions\n",
    "module7_definitions = {\n",
    "\"knowledge-based agents\" : \"uses **reasoning** over an internal representation of knowledge\", \n",
    "\"knowledge base\" : \"a set of sentences (in the representation language)\", \n",
    "\"axiom\" : \"knowledge that is given (not derived)\", \n",
    "\"semantics/meaning\" : \"defines the truth of each sentences in each model (possible world)\",\n",
    "\"sound/truth-preserving inference algorithm\" : \"derives only entailed sentences\",\n",
    "\"complete inference algorithm\" : \"can derive any entailed sentence\", \n",
    "\"monotonicity\" : \"the set of entailed sentences is non-decreasing as information added to KB\",\n",
    "}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "cellView": "form",
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 1465
    },
    "id": "lXNcHuKjyNXa",
    "outputId": "156d1da9-301c-4de7-ec85-990253aabb64"
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 7: Logical Agents\n",
       "## AIMA Chapter 7.1 Knowledge-Based Agents\n",
       "\n",
       "1. Declarative approach is telling the agent what it needs to **know** so that it knows how to operate in the environment. \n",
       "2. Procedural approach is telling the agent what it needs to **do** specifically (behaviors). \n",
       "\n",
       "\n",
       "## AIMA Chapter 7.2 The Wumpus World\n",
       "\n",
       "1. Task environment definition (review): performance measure, environment, actuators, sensors. \n",
       "2. A sentence *s* is true in model *m* <--> *m* satisfies *s* <--> *m* is a model of *s*. \n",
       "3. *M(s)* represents the set of all models of *s*.\n",
       "4. Entailment of sentences: a |= b iff M(a) belongs to M(b) (similar to -->). \n",
       "5. Inference: KB |=i a iff a is derived from KB by inference algorithm i.\n",
       "\n",
       "\n",
       "## AIMA Chapter 7.3 Logic\n",
       "\n",
       "Learning means deriving knowledge from perceptual experience. \n",
       "\n",
       "\n",
       "## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n",
       "\n",
       "| Terminology | Explanation |\n",
       "| :--- | ---: |\n",
       "| conjunction | and | \n",
       "| disjunction | or |\n",
       "| implication | (premise, antecedent) --> (conclusion, consequent) |\n",
       "| biconditional | iff, <--> |\n",
       "\n",
       "\n",
       "## AIMA 7.5 Propositional Theorem Proving\n",
       "\n",
       "| Terminology and laws | Explanation |\n",
       "| :--- | ---: |\n",
       "| Logical equivalence | <--> of sentences, equal truth values (following \"=\") |\n",
       "| (a and b) = (b and a) | commutativity of and | \n",
       "| (a or b) = (b or a) | commutativity of or | \n",
       "| ((a and b) and c) = (a and (b and c)) | associativity of and |\n",
       "| ((a or b) or c) = (a or (b or c)) | associativity of or |\n",
       "| not(not a) = a | double-negation elimination |\n",
       "| (a --> b) = ((not b) --> (not a)) | contraposition |\n",
       "| (a --> b) = ((not a) or b) | implication elimination |\n",
       "| (a <--> b) = ((a --> b) and (b --> a)) | biconditional elimination |\n",
       "| not(a and b) = (not a) or (not b) | De Morgan |\n",
       "| not(a or b) = (not a) and (not b) | De Morgan |\n",
       "| a and (b or c) = (a and b) or (a and c) | distributivity of and over or |\n",
       "| a or (b and c) = (a or b) and (a or c) | distributivity of or over and |\n",
       "\n",
       "1. Validity: true in all models. Valid sentences are called tautologies. \n",
       "2. a |= b iff (a --> b) is valid. \n",
       "3. Satisfiability: true in some model(s).\n",
       "4. Proof problem definition: initial state (KB), actions, result, goal.  \n",
       "\n",
       "| Terminology | Explanation |\n",
       "| :--- | ---: |\n",
       "| CNF | 合取范式, linked by and |\n",
       "| DNF | 析取范式, linked by or |\n",
       "| DefiniteClauseForm | Fact or (symbol_1 and ... and symbol_n) --> symbol |\n",
       "| GoalClauseForm | (symbol_1 and ... and symbol_n) --> False |\n",
       "| HornClauseForm | DefiniteClauseForm or GoalClauseForm |\n",
       "\n",
       "5. Forward chaining (is sound and complete) conducts reasoning until the query is added or no further inferences.\n",
       "6. Backward chaining algorithm works backward from the query, and is a form of goal-directed reasoning. \n",
       "\n",
       "\n",
       "## Module 7 Lecture Notes\n",
       "\n",
       "Inference rules\n",
       "$$ {sentence_1 given, sentence_2 given, ...} $$ \n",
       "$$ ------------------- $$\n",
       "$$ {sentence_1 inferred, sentence_2 inferred, ...} $$\n",
       "\n",
       "Resolution algorithm is proof by contradiction. e.g. to show KB |= a we show KB and (not a) is unsatisfiable. \n",
       "\n",
       "\n",
       "## Module 7 Definitions\n",
       "* **Knowledge-based agents** - uses **reasoning** over an internal representation of knowledge\n",
       "* **Knowledge base** - a set of sentences (in the representation language)\n",
       "* **Axiom** - knowledge that is given (not derived)\n",
       "* **Semantics/meaning** - defines the truth of each sentences in each model (possible world)\n",
       "* **Sound/truth-preserving inference algorithm** - derives only entailed sentences\n",
       "* **Complete inference algorithm** - can derive any entailed sentence\n",
       "* **Monotonicity** - the set of entailed sentences is non-decreasing as information added to KB\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#@title Preview of your summary\n",
    "#@markdown You don't need to modify anything in this cell. Just press play.\n",
    "module7_sections = [\n",
    "  (\"AIMA Chapter 7.1 Knowledge-Based Agents\", chapter7_1),\n",
    "  (\"AIMA Chapter 7.2 The Wumpus World\", chapter7_2),\n",
    "  (\"AIMA Chapter 7.3 Logic\", chapter7_3),\n",
    "  (\"AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\", chapter7_4),\n",
    "  (\"AIMA 7.5 Propositional Theorem Proving\", chapter7_5),\n",
    "  (\"Module 7 Lecture Notes\", module7_lecture_notes),\n",
    "]\n",
    "\n",
    "module7_markdown = format_module(7, \"Logical Agents\", \n",
    "                         module7_sections, \n",
    "                         module7_definitions)\n",
    "display(Markdown(module7_markdown))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vX7lbnJd4sT5"
   },
   "source": [
    "# Your Exam Notes\n",
    "\n",
    "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
    "\n",
    "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
    "* Run the cell below. \n",
    "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
    "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
    "* In the print options, change the layout from Landscape to Portrait. \n",
    "* Clicking the Save, will save a PDF that you can then print.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/",
     "height": 9392
    },
    "id": "T3cm1WV542_a",
    "outputId": "dffa6180-2f20-46ab-c6a9-941937afa768",
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "# Module 1: Rational Agents and Task Environments\n",
       "## AIMA Chapter 1.1 What is AI?\n",
       "\n",
       "1. Total Turing test: NLP, knowledge presentation, automated reasoning, ML, computer vision, robotics. \n",
       "2. Human methods of thinking: introspection, psychological experiments, brain imaging. \n",
       "3. Four views of AI: thinking/acting humanly/rationally\n",
       "4. Agent (agent function) = program + (runs on) architecture (physical)\n",
       "\n",
       "\n",
       "## AIMA Chapter 27.1 The Limits of AI\n",
       " \n",
       "\n",
       "## AIMA Chapter 27.1 Can Machines Really Think?\n",
       " \n",
       "\n",
       "## AIMA 2.1 Agents and Environments\n",
       " \n",
       "\n",
       "## AIMA 2.2 Good Behavior: The Concept of Rationality\n",
       " \n",
       "\n",
       "## AIMA 2.3 The Nature of Environments\n",
       " \n",
       "\n",
       "## AIMA 2.4 The Structure of Agents\n",
       " \n",
       "\n",
       "## Module 1 Lecture Notes\n",
       "\n",
       "1. Rational means doing the right thing, but does not guarantee success. \n",
       "2. Types of environments: fully/partially observable, non-/deterministic, episodic/sequential, static/dynamic, discrete/continuous, single/multi-agent. \n",
       "\n",
       "\n",
       "## Module 1 Definitions\n",
       "* **Agent** - anything that perceives its environment through **sensors** and acts on its environment through **actuators**\n",
       "* **Rational agent** - anything that acts to achieve the best (expected) outcome\n",
       "* **Percept** - perceptual inputs of the agent\n",
       "* **Agent function** - agent (specification), = agent program + physical architecture\n",
       "* **Relax agent** - act based on current percept only\n",
       "* **Problem solving agent** - plan ahead and consider a sequence of actions from a start/current state to a goal state (search)\n",
       "\n",
       "\n",
       "# Module 2: Python\n",
       "## Module 2 Lecture Notes\n",
       " \n",
       "| type | mutable | hashable |\n",
       "| :--- | ---: | ---: |\n",
       "| string | no | yes |\n",
       "| tuple | no | yes |\n",
       "| frozenset | no | yes |\n",
       "| list | yes | no |\n",
       "| dict (set) | yes | no |\n",
       "\n",
       "1. [:] creates a (shallow copy) of a seq. \n",
       "2. list.sort(func) sorts the list by func (compare(x,y) returns 1 (prior), -1, or 0).\n",
       "3. For strings, \n",
       "\n",
       "  a. s.split(key) splits by key, returns a list of strings \n",
       "\n",
       "  b. key.join(list) merges a list of strings (linked by key), returns a string \n",
       "\n",
       "  c. s.capitalize(), s.upper() \n",
       "\n",
       "  d. s.strip(key or [keys]) removes key(s) in the head or tail of the string (default: space and \\n). \n",
       "\n",
       "4. No function overloading in python. \n",
       "5. *args: a tuple of arguments. \n",
       "6. **kwargs: a dict of arguments. \n",
       "7. [expression **for** name **in** list **if** filter]\n",
       "\n",
       "\n",
       "## Module 2 Definitions\n",
       "* **Mutability** - allow the value (stored in memory) to be updated\n",
       "* **Hashability** - can have a hash value associated with it --> can be used as a key for a dict\n",
       "\n",
       "\n",
       "# Module 3: Search Problems\n",
       "## AIMA Chapter 3.1 Problem-Solving Agents\n",
       "\n",
       "***Episodic, single agent, fully observable, deterministic, static, discrete, known environment***\n",
       "\n",
       "1. Problem-solving agents use **atomic** representations (not considering internal structure)\n",
       "2. Search problem : state space, initial state, goal states, actions, transition model (describes what each action does), action cost function\n",
       "\n",
       "\n",
       "## AIMA Chapter 3.2 Example Problems\n",
       "\n",
       "1. Standardized problem can be solved by various methods (to compare the performance). \n",
       "2. Real world problem is idiosyncratic (异质的). It is these solutions that people actually use. \n",
       "\n",
       "\n",
       "## AIMA Chapter 3.3 Search Algorithms\n",
       "\n",
       "1. Reached state: has a node. Expanded state: done node.successors(). \n",
       "2. Best-first search\n",
       "- evaluation function f(n)\n",
       "- ***expand the node with minimum f(n)***\n",
       "```\n",
       "def bestfirstsearch(problem, f):\n",
       "    state = initial\n",
       "    frontier = PriorityQueue()\n",
       "    frontier.put(0, state)\n",
       "    reached = {initial:0}\n",
       "    while not frontier.empty():\n",
       "      current = frontier.get()[1]\n",
       "      if current.is_solved():\n",
       "        return solution\n",
       "      for action, successor in current.successors():\n",
       "        newcost = reached[current.state] + delta_cost\n",
       "        if successor.state not in reached or newcost < reached[successor.state]:\n",
       "          reached[successor.state] = newcost\n",
       "          frontier.put((f(successor), successor))\n",
       "    return failure\n",
       "```\n",
       "\n",
       "3. Graph search checks for redundant paths (tree search doesn't). \n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 3.4 Uninformed Search Strategies\n",
       "\n",
       "| Algorithm | Optimal | Complete | Time Complexity | Space Complexity |\n",
       "| :--- | :---: | :---: | :---: | :---: |\n",
       "| DFS | N | N | O(branching^maxdepth) | O(b*m) |\n",
       "| Depth-limited | N | N | O(b^limit) | O(b*l) | \n",
       "| IDDFS | Y | Y | O(b^d) | O(b*d) | \n",
       "| BFS | Y | Y | O(branching^depth) | O(b^d) |\n",
       "| Uniform-cost | Y | Y | O(b^(1+C/e)) | O(b^(1+C/e)) |\n",
       "| Bidirectional | Y | Y | O(b^d/2) | O(b^d/2) |\n",
       "\n",
       "In above table b is finite (otherwise all incomplete), m can be infinite. \n",
       "\n",
       "e is the lower bound of action cost. \n",
       "\n",
       "1. Uniform-cost search (Dijkstra if without goal) is best-first search with path-cost as f(n) (uniform total cost). BFS is when path-costs are equal. \n",
       "2. Depth-limited search pseudocode\n",
       "```\n",
       "def dls(problem, l, actions):\n",
       "    if l <= 0 or len(actions) >= l: \n",
       "      return\n",
       "    copy_p = copy(problem)\n",
       "    for action in actions:\n",
       "      copy_p.perform_move(action)\n",
       "    if copy_p.is_solved():\n",
       "      yield actions\n",
       "    for action, successor in copy_p.successors(): # 其实只需要action\n",
       "      yield from dls(problem, actions+[action])\n",
       "```\n",
       "3. In DLS if l<d incomplete. If l>d not optimal. \n",
       "4. In bidirectional search we need to keep track of two frontiers. \n",
       "\n",
       "\n",
       "## Module 3 Lecture Notes\n",
       "\n",
       "1. Tree/Graph search: the only difference is that graph search keeps track of \"visited\" set, and only adds successor node to the frontier if it's unvisited.  \n",
       "2. BFS vs DFS: \n",
       "\n",
       "a. Use DFS if space is restricted / long solutions / wrong paths terminated quickly / search can be fine-tuned (微调) quickly \n",
       "\n",
       "b. Use BFS if infinite depth / short solutions / can quickly discard unlikely paths\n",
       "\n",
       "\n",
       "## Module 3 Definitions\n",
       "* **Problem-solving agent** - an agent that can formulate a plan via search\n",
       "* **Path** - a sequence of actions\n",
       "* **Solution** - a path from the initial state to a goal state\n",
       "* **Optimal solution** - lowest path cost\n",
       "* **Search problem** - the process of finding a solution\n",
       "* **Open-loop** - once solution found, the agent can ignore the environment and just execute the solution to reach the goal\n",
       "* **Search algorithm** - input: a search problem, return: a solution or failure\n",
       "* **Completeness** - guarantee to find a solution if there is one, otherwise report failure\n",
       "* **Optimality** - able to find an optimal solution\n",
       "\n",
       "\n",
       "# Module 4: Informed Search\n",
       "## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n",
       "\n",
       "The only difference between un-/informed search strategy is informed search has heuristic(s).\n",
       "\n",
       "**Heuristic function** hints where the goal is. \n",
       "\n",
       "| Algorithm | Optimal | Complete | Time Complexity | Space Complexity |\n",
       "| :--- | :---: | :---: | :---: | :---: |\n",
       "| Greedy best-first search | N | Y | O(b*m) to O(V) | O(b*m) to O(V) |\n",
       "| A* search | Y if h is admissible | Y | | |\n",
       "\n",
       "\n",
       "1. Greedy best-first search is best-first search where f(n) = h(n). At each move it tries to go as close to the goal as possible. \n",
       "2. Uniform-cost search is ... where f(n) = g(n).\n",
       "3. A* search, f(n) = g(n) + h(n). g(n) is the actual cost from initial state to the node n (cost so far). f(n) is estimated cost from initial state through node n to a goal. \n",
       "4. **Consistent heuristic --> admissible.**\n",
       "5. A* prunes away nodes not necessary for finding an optimal solution. \n",
       "6. The main issue with A* is its use of memory. \n",
       "\n",
       "\n",
       "## AIMA Chapter 3.6 Heuristic Functions\n",
       "\n",
       "***Smaller h(n) --> more possible to be admissible, but slower.***\n",
       "\n",
       "***Larger h(n) --> less possible to be admissible, but faster.***\n",
       "\n",
       "1. Domination. h2 dominates h1 iff h2(n)>=h1(n) for each n. h2 is more efficient than h1. \n",
       "2. The cost of an optimal solution to a relaxed problem is a consistent heuristic for the original problem. \n",
       "3. Lower effective branching factor --> higher efficiency. \n",
       "\n",
       "\n",
       "## Module 4 Lecture Notes\n",
       "\n",
       "1. 0 <= admissible h(n) <= h*(n) true optimal cost. \n",
       "2. Manhattan distance and Euclidean distance are admissible heuristics. \n",
       "3. A* search pseudocode: \n",
       "```\n",
       "def astar(problem):\n",
       "    frontier = PriorityQueue()\n",
       "    frontier.put(0, initial)\n",
       "    actual_costs = {initial:0}\n",
       "    while not frontier.empty():\n",
       "      current = frontier.get()[1]\n",
       "      if current.is_solved():\n",
       "        return solution\n",
       "      for action, successor in current.successors():\n",
       "        newcost = actual_costs[current] + deltacost\n",
       "        if successor not in actual_costs or newcost < actual_costs[successor]:\n",
       "          actual_costs[successor] = newcost\n",
       "        frontier.put((newcost+h(successor), successor))\n",
       "```\n",
       "\n",
       "\n",
       "## Module 4 Definitions\n",
       "* **Heuristic function h(n)** - estimated cost of the cheapest path from node *n* to a goal state\n",
       "* **Admissibility** - **(optimistic)** never overestimate the cost to reach a goal\n",
       "* **Consistency** - (for a heuristic) h(n) <= cost(n to n' through action) + h(n', successor of n)\n",
       "* **Optimally efficient** - A* with a consistent heuristic\n",
       "* **Satisficing solution** - not optimal but good enough\n",
       "* **Weighted a* search** - f(n) = g(n) + W*h(n), W>1\n",
       "* **Beam search** - limits the size of the frontier\n",
       "* **Ida*** - Iterative-deepening A* search\n",
       "* **Rbfs recursive best-first search** - remember f-value, if excceeds the bound, choose the alternative\n",
       "* **Ma* /sma*** - (simplified) memory-bounded A*\n",
       "* **Effective branching factor** - # of nodes used / depth reached (for finding a soluition)\n",
       "* **Relaxed problem** - a problem with fewer restrictions on actions\n",
       "\n",
       "\n",
       "# Module 5: Adversarial Search and Games\n",
       "## AIMA Chapter 5.1 Game Theory\n",
       "\n",
       "***Competitive environment***\n",
       "\n",
       "***Deterministic, two-player, turn-taking, perfect information, zero-sum games***\n",
       "1. Game definition: initial state, turn (who moves), actions (clear set), transition model, terminal states, utility function (well-defined outcomes). \n",
       "2. Utility function is also called an objective / payoff function. \n",
       "3. Complete game ree: a search tree of every seq of moves to terminal states. \n",
       "\n",
       "\n",
       "## AIMA Chapter 5.2 Optimal Decisions in Games\n",
       "\n",
       "minimax(s) =\n",
       "- utility(s, max)  if s.is_terminal() \n",
       "- max_{su \\in s.successors()} (minimax(su)) if turn = max \n",
       "- min_{su \\in s.successors()} (minimax(su)) if turn = min \n",
       "1. Optimal play for MAX assumes that MIN also plays optimally. If not, MAX can be better, but probably not optimal. \n",
       "2. Minimax performs DFS for the game tree. Time complexity = O(b^m). Space complexity = O(b*m). \n",
       "3. <u>Alpha and beta in alpha-beta pruning are **inherited from the parent**, 之后再按规则update回parent. Each node has outcome (**back-up value**, optimal value of its children), and alpha and beta. </u>\n",
       "4. **Only alpha is updated when the we moves. Only beta is updated when the rival moves.** Updating order is the same as DFS. (<u>Inherit both alpha and beta, but only update one.</u>)\n",
       "5. **Pruning is triggered when MIN moves but outcome < alpha, or when MAX moves but outcome > beta.** \n",
       "\n",
       "\n",
       "## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n",
       "\n",
       "1. Apply a evaluation function to evaluate nonterminal nodes (to avoid search till the terminal). Replace the terminal test by **cutoff test** (return True if real terminal). \n",
       "2. Evaluation function should be \n",
       "\n",
       "- fast\n",
       "- strongly correlated with chances of winning (e.g. expected value)\n",
       "3. Cutting off search. Evaluation function should be applied only to quiescent states. \n",
       "\n",
       "\n",
       "\n",
       "## AIMA Chapter 5.5 Stochastic Games\n",
       "\n",
       "expectiminimax(s) =\n",
       "- utility(s, max)  if s.is_terminal() \n",
       "- max_{su \\in s.successors()} (expectiminimax(su)) if turn = max \n",
       "- min_{su \\in s.successors()} (expectiminimax(su)) if turn = min \n",
       "- Expectation_r (expectiminimax(s, r)) if turn = chance\n",
       "\n",
       "where r represents a possible outcome.\n",
       "1. Game tree includes **chance nodes** layer between each MIN layer and MAX layer. \n",
       "2. Minimax values are expected value of a position (expectiminimax value). \n",
       "\n",
       "\n",
       "## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n",
       "\n",
       "1. Principle of MEU (maximum expected utility): rational agents choose actions maximizing expected utility. \n",
       "2. If an agent acts to maximize a utility function that correctly reflects the performance measure, the the agent will achieve the highest **possible** performance score. \n",
       "\n",
       "\n",
       "## AIMA Chapter 16.2 The Basis of Utility Theory\n",
       "\n",
       "Axioms of utility theory. Here, >, <, and = represent domination relationships. \n",
       " \n",
       "- Orderability: A>B or B>A else A=B. \n",
       "- Transitivity: A>B and B>C then A>C. \n",
       "- Continuity: A>B>C then p*A+(1-p)*C = B for some p.\n",
       "- Substitutability: A=(>)B then p*A+(1-p)*C =(>) p*B+(1-p)*C for any p.\n",
       "- Monotonicity: A>B then (p>q iff p*A+(1-p)*B > q*A+(1-q)*B)\n",
       "- Decomposability: p*A+(1-p)*(q*B+(1-q)*C) = p*A+(1-p)*q*B+(1-p)*(1-q)*C\n",
       "\n",
       "\n",
       "## AIMA Chapter 16.3 Utility Functions\n",
       "\n",
       "1. Risk averse, risk-seeking, certainty equivalent (risk-neutral).\n",
       "2. Decision theory is normative theory (what should do). On the other hand, descriptive theory is about how agents actually act. \n",
       "\n",
       "\n",
       "## Module 5 Lecture Notes\n",
       "\n",
       "Expectimax: compute the average score under optimal play (take expected utility). It is used when the opponent randomize actions. \n",
       "\n",
       "\n",
       "## Module 5 Definitions\n",
       "* **Type a strategy** - considers wide but shallow cases in a game tree\n",
       "* **Type b strategy** - considers narrow but deep cases in a game tree\n",
       "* **Quiescent** - 休眠的, positions in which no pending moves will hugely change the (next) evaluation\n",
       "* **Horizon effect** - opponent's move can seriously damage mine and is unavoidable, but can be avoided temporarily\n",
       "* **Forward pruning** - prunes probably poor moves (prunes more than alpha-beta)\n",
       "* **Ambiguity aversion** - inconsistent risk preference for people\n",
       "* **Framing effect** - same information, different statement, then different decision\n",
       "* **Stochastic game** - game including uncertainty\n",
       "\n",
       "\n",
       "# Module 6: Constraint Satisfaction Problems\n",
       "## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n",
       "\n",
       "1. CSP search use general heuristics (rather than domain-specific). Actions and transition model are derived from problem description. \n",
       "2. CSP definition: set of variables, set of domains, set of constraints ((included variable, relation) pair). \n",
       "3. **A is consistent with B means for all values in A.domain there exists at least one value in B.domain that makes the constraint satisfied.** \n",
       "4. Advantages of CSP form: \n",
       "\n",
       "- Represents many problems. \n",
       "- Solvers are fast and efficient. \n",
       "- Quickly pruning (atomic state-space searcher cannot). No need to check expansions of wrong partial assignments. \n",
       "5. No algorithm can solve general nonlinear constraints CSPs on integer variables. \n",
       "6. Constraint hypergraph consists of ordinary nodes and hypernodes (represent n-ary constraints for n>3, linked with each constrained node). \n",
       "7. Constrained optimization problem introduces costs of variable assignment. \n",
       "\n",
       "\n",
       "## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n",
       "\n",
       "1. Through hypergraph, one can transform all n-ary constraints into binary ones. \n",
       "2. AC-3 pseudocode\n",
       "```\n",
       "def ac3(csp):\n",
       "    frontier = Queue()\n",
       "    for arc in ARCS: \n",
       "      frontier.put(arc)\n",
       "    while not frontier.empty():\n",
       "      current_arc = frontier.get() # current_arc is (Xi, Xj)\n",
       "      if current_arc[0].adjust(current_arc[1]): # if reduce the domain of current_arc[0]\n",
       "        # adjust current_arc[0] to be arc-consistent with current_arc[1] \n",
       "        # adjust above removes value in current_arc[0].domain if there is no consistent value in current_arc[1].domain\n",
       "        if current_arc[0].domain.empty():\n",
       "          return False\n",
       "        for arc in ARCS that arc[1] == current_arc[0]:\n",
       "          frontier.put(arc)\n",
       "    return True\n",
       "```\n",
       "\n",
       "\n",
       "## AIMA Chapter 6.3 Backtracking Search for CSPs\n",
       "\n",
       "1. Backtracking search does DFS. When value choice leads to failure, it returns to the state before the choice (and makes another choice). This is done by two \"add\"s and two \"remove\"s. \n",
       "```\n",
       "def backtrack(csp, assignment):\n",
       "    ...\n",
       "    add {variable=value} to assignment\n",
       "    inference impose some-consistency\n",
       "    if inference != failure:\n",
       "      add inference to csp\n",
       "      result = backtrack(csp, assignment)\n",
       "      if result != failure:\n",
       "        return result\n",
       "      remove inference from csp\n",
       "    remove {variable=value} from assignment\n",
       "```\n",
       "This is **chronological backtracking**. \n",
       "\n",
       "2. Order of value assignment \n",
       "\n",
       "(1) Most constrained variable. (MRV minimum-remaining-values heuristic, fail-first)\n",
       "\n",
       "(2) Most constraining variable. (degree heuristic) \n",
       "\n",
       "(3) Least constraining value. \n",
       "3. **Forward checking** is one of the simplest form of inference. Whenever a variable is assigned, it establishes arc-consistency for it. (**no propagation**)\n",
       "4. **MAC** Maintaining Arc Consistency algorithm uses AC-3 as inference. The difference is that MAC starts from neighbors of the assigned value (not all arcs are in queue at first). \n",
       "5. Compared to Backtracking, Backjumping revisit the variable responsible for assigning the conflictive value (most recent in the conflict set). Simple backjumping is redundant for forward checking (then also for consistency of higher levels). \n",
       "6. Constraint learning finds a minimum conflict set (**no-goods**) and tries to avoid them in further search (e.g. add new constraints). \n",
       "\n",
       "\n",
       "## AIMA Chapter 6.4 Local Search for CSPs\n",
       "\n",
       "1. Local search definition: with a initial assignment, change the values to get close to a solution. \n",
       "2. **Min-conflicts heuristic** minimizes number of conflicts. It assigns value causing least conflicts to a conflictive variable each time. \n",
       "3. Local search (usually) make less changes to existing state in less amount of time than backtracking. \n",
       "\n",
       "\n",
       "## AIMA Chapter 6.5 The Structure of Problems\n",
       "\n",
       "1. Tree-structured constraint graph: only one path between any two variables. \n",
       "2. Topological sort picks an arbitraty variable to be the root of the tree (to convert tree-structured CSP graph into the form of tree).\n",
       "3. Two ways of reducing a general CSP to a tree: cutset conditioning and tree decomposition. \n",
       "4. **Cutset conditioning algorithm** \n",
       "- Separate a cycle cutset *S* from CSP (so that the graph becomes a tree). \n",
       "- For a solution of *S*, remove inconsistent values from domains of remaining variables. \n",
       "- If the remaining CSP has a solution, return with *S* assignment, otherwise repeat (2)-(3). \n",
       "\n",
       "Time complexity (total) (d is domain size, c is size of *S*, n is size of original CSP)\n",
       "$$\n",
       "O(d^c\\cdot(n-c)d^2)\n",
       "$$\n",
       "Space complexity\n",
       "$$\n",
       "O(n)\n",
       "$$\n",
       "\n",
       "5. **Tree decomposition requirement**\n",
       "- Every variable in the original CSP appears in at least one tree node. \n",
       "- If two variables connected by a constraint, they (and the constraint) appear together in at least one tree node. \n",
       "- If one variable appears in two nodes, it appears in every node along the path of the two nodes. \n",
       "\n",
       "Time complexity **after decomposition**\n",
       "$$\n",
       "O(nd^2)\n",
       "$$\n",
       "Time complexity (total) (w is tree-width of graph)\n",
       "$$\n",
       "O(nd^{w+1})\n",
       "$$\n",
       "Space complexity\n",
       "$$\n",
       "O(n^w)\n",
       "$$\n",
       "\n",
       "But finding decomposition with minimal tree width is NP-hard. \n",
       "\n",
       "\n",
       "## Module 6 Lecture Notes\n",
       "\n",
       "1. Enforcing K-consistency doesn't guarantee to solve a CSP. \n",
       "2. CSP solvers use search (assigning a value) and inference (constraint propagation). \n",
       "3. AC-3 time complexity (worst case, complete graph)\n",
       "$$\n",
       "O(n^2d^3)\n",
       "$$\n",
       "Planar (二维) constraint grpha case\n",
       "$$\n",
       "O(nd^3)\n",
       "$$\n",
       "\n",
       "\n",
       "## Module 6 Definitions\n",
       "* **Factored representation for states** - a set of variables with values\n",
       "* **Consistent/legal assignment** - doesn't violate any constraints (see above 6.1)\n",
       "* **Complete assignment** - every variable is assigned a value\n",
       "* **Solution to csp** - a consistent, complete assignment\n",
       "* **Partial assignment** - incomplete assignment, some variables unassigned\n",
       "* **Partial solution** - consistent partial assignment\n",
       "* **Constraint graph** - nodes are variables, edges are constraints (linking any two variables involved)\n",
       "* **Linear constraint** - variables appear only in linear forms\n",
       "* **Unary constraint** - constraint involving only one variable\n",
       "* **Binary constraint** - constraint involving only two variables\n",
       "* **Binary csp** - CSP with only unary and binary constraints\n",
       "* **Global constraint** - constraint involving arbitrary number of variables (**need not involve all the variables**)\n",
       "* **Preference constraint** - indicate preference of solutions (not absolute constraints)\n",
       "* **Cop** - constrained optimization problem, CSP with preferences\n",
       "* **Constraint propagation** - use constraints to reduce the domains\n",
       "* **Local consistency** - consistent in some **part** of the graph\n",
       "* **Node consistency** - all values in domain satisfy **unary** constraints for each variable\n",
       "* **Arc consistency** - all values in domain satisfy **binary** constraints for each variable\n",
       "* **Path consistency** - a third variable is consistent with a two-variable set\n",
       "* **Consistency for csp** - the CSP is some-consistent iff all variables satisfy some-consistency\n",
       "* **K-consistency (for csp)** - any *k*th variable is consistent with any (k-1)-variable set\n",
       "* **Strong k-consistency (for csp)** - k, (k-1), ..., 1-consistent\n",
       "* **Commutativity** - the order of application of any given set of actions does not matter\n",
       "* **Conflict-directed backjumping** - backjumping where conflict set of a variable is preceding varaibles that cause inconsistency of it and subsequent variables\n",
       "* **Directional arc consistency (for csp)** - for X1, ..., Xn, every Xi is arc-consistent with Xj for each j>i\n",
       "* **Tree-width of a tree decomposition** - size of the largest node - 1\n",
       "* **Tree-width of the graph** - min(tree-widths of tree decompositions)\n",
       "\n",
       "\n",
       "# Module 7: Logical Agents\n",
       "## AIMA Chapter 7.1 Knowledge-Based Agents\n",
       "\n",
       "1. Declarative approach is telling the agent what it needs to **know** so that it knows how to operate in the environment. \n",
       "2. Procedural approach is telling the agent what it needs to **do** specifically (behaviors). \n",
       "\n",
       "\n",
       "## AIMA Chapter 7.2 The Wumpus World\n",
       "\n",
       "1. Task environment definition (review): performance measure, environment, actuators, sensors. \n",
       "2. A sentence *s* is true in model *m* <--> *m* satisfies *s* <--> *m* is a model of *s*. \n",
       "3. *M(s)* represents the set of all models of *s*.\n",
       "4. Entailment of sentences: a |= b iff M(a) belongs to M(b) (similar to -->). \n",
       "5. Inference: KB |=i a iff a is derived from KB by inference algorithm i.\n",
       "\n",
       "\n",
       "## AIMA Chapter 7.3 Logic\n",
       "\n",
       "Learning means deriving knowledge from perceptual experience. \n",
       "\n",
       "\n",
       "## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n",
       "\n",
       "| Terminology | Explanation |\n",
       "| :--- | ---: |\n",
       "| conjunction | and | \n",
       "| disjunction | or |\n",
       "| implication | (premise, antecedent) --> (conclusion, consequent) |\n",
       "| biconditional | iff, <--> |\n",
       "\n",
       "\n",
       "## AIMA 7.5 Propositional Theorem Proving\n",
       "\n",
       "| Terminology and laws | Explanation |\n",
       "| :--- | ---: |\n",
       "| Logical equivalence | <--> of sentences, equal truth values (following \"=\") |\n",
       "| (a and b) = (b and a) | commutativity of and | \n",
       "| (a or b) = (b or a) | commutativity of or | \n",
       "| ((a and b) and c) = (a and (b and c)) | associativity of and |\n",
       "| ((a or b) or c) = (a or (b or c)) | associativity of or |\n",
       "| not(not a) = a | double-negation elimination |\n",
       "| (a --> b) = ((not b) --> (not a)) | contraposition |\n",
       "| (a --> b) = ((not a) or b) | implication elimination |\n",
       "| (a <--> b) = ((a --> b) and (b --> a)) | biconditional elimination |\n",
       "| not(a and b) = (not a) or (not b) | De Morgan |\n",
       "| not(a or b) = (not a) and (not b) | De Morgan |\n",
       "| a and (b or c) = (a and b) or (a and c) | distributivity of and over or |\n",
       "| a or (b and c) = (a or b) and (a or c) | distributivity of or over and |\n",
       "\n",
       "1. Validity: true in all models. Valid sentences are called tautologies. \n",
       "2. a |= b iff (a --> b) is valid. \n",
       "3. Satisfiability: true in some model(s).\n",
       "4. Proof problem definition: initial state (KB), actions, result, goal.  \n",
       "\n",
       "| Terminology | Explanation |\n",
       "| :--- | ---: |\n",
       "| CNF | 合取范式, linked by and |\n",
       "| DNF | 析取范式, linked by or |\n",
       "| DefiniteClauseForm | Fact or (symbol_1 and ... and symbol_n) --> symbol |\n",
       "| GoalClauseForm | (symbol_1 and ... and symbol_n) --> False |\n",
       "| HornClauseForm | DefiniteClauseForm or GoalClauseForm |\n",
       "\n",
       "5. Forward chaining (is sound and complete) conducts reasoning until the query is added or no further inferences.\n",
       "6. Backward chaining algorithm works backward from the query, and is a form of goal-directed reasoning. \n",
       "\n",
       "\n",
       "## Module 7 Lecture Notes\n",
       "\n",
       "Inference rules\n",
       "$$ {sentence_1 given, sentence_2 given, ...} $$ \n",
       "$$ ------------------- $$\n",
       "$$ {sentence_1 inferred, sentence_2 inferred, ...} $$\n",
       "\n",
       "Resolution algorithm is proof by contradiction. e.g. to show KB |= a we show KB and (not a) is unsatisfiable. \n",
       "\n",
       "\n",
       "## Module 7 Definitions\n",
       "* **Knowledge-based agents** - uses **reasoning** over an internal representation of knowledge\n",
       "* **Knowledge base** - a set of sentences (in the representation language)\n",
       "* **Axiom** - knowledge that is given (not derived)\n",
       "* **Semantics/meaning** - defines the truth of each sentences in each model (possible world)\n",
       "* **Sound/truth-preserving inference algorithm** - derives only entailed sentences\n",
       "* **Complete inference algorithm** - can derive any entailed sentence\n",
       "* **Monotonicity** - the set of entailed sentences is non-decreasing as information added to KB\n"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# This will generate the full set of notes that you can use for your exam.\n",
    "full_markdown = \"\\n\\n\".join([module1_markdown, \n",
    "                             module2_markdown, \n",
    "                             module3_markdown, \n",
    "                             module4_markdown, \n",
    "                             module5_markdown,\n",
    "                             module6_markdown,\n",
    "                             module7_markdown,]\n",
    "                       )\n",
    "display(Markdown(full_markdown))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fmKl3HJdZmkI"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "CIS421 Midterm Notes",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
