{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "FINAL Template_for CIS521_midterm notes.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "brNDGX-kvzds"
      },
      "source": [
        "# Template for Notes for CIS 521 Midterm 1\n",
        "\n",
        "The midterm exam for CIS 521 will be **open notes**. No other matierals are allowed for the exam - you may not use the textbook, the internet, a Python envionement, or communicate with anyone during the exam. \n",
        "\n",
        "This python notebook is where you should save all of your notes.  It provides a structured template that allows you to add summaries for each of the textbook sections that are part of the required reading, plus room for lecture notes and definitions.\n",
        "\n",
        "Your summaries must be written in your own words.  Do not copy and paste from the textbook.  Do not share your notes with classmates, or copy any of your classmates' notes.  "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aPtM8g7R0Pds"
      },
      "source": [
        "# Instructions\n",
        "\n",
        "1. Make a copy of this Google Colab file. From the colab menu, pick **File > Save a copy in Drive**.  That will save a copy of this notebook in your Google drive.\n",
        "2. Go through each section of the notebook, and fill in all the summaries for each chapter and its corresponding sections.  Be sure to save your work frequently!\n",
        "3. Read the notes below about how you can format your summaries.\n",
        "4. In addition to these notes, you are allowed 1 page (both sides) for figures or handwritten notes.\n",
        "5. Submit your version of this notebook to Gradescope before you start the exam.\n",
        "6. If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print: \n",
        "* Run the last cell of this notebook\n",
        "* Click the \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n",
        "\n",
        "## Formatting Notes\n",
        "\n",
        "1. The max length for each section's summary is 500 words / 3000 characters.\n",
        "2. You can also write a 2000 word summary of the lectures for each module.\n",
        "3. You may also write definitions of concepts for each module.  The definitions should be written in your own words (not copy and pasted), and they should be no more than 20 words long for each concept. \n",
        "2. You can use Markdown formatting for your summaries. \n",
        "3. You can use Latex formatting for equations. Put two dollar signs before and after your equation like this: \n",
        "$$ \\epsilon = \\frac{1}{mc^2} $$\n",
        "4. When you write python code or psuedocode algorithms, you should surround it with triple backticks like this:\n",
        "```\n",
        "def function():\n",
        "      print('hello world')\n",
        "```\n",
        "5. Write \\ whenever you want to keep writing on the next line without a newline being inserted."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cw5IpDLCZa4W"
      },
      "source": [
        "## Example summary\n",
        "\n",
        "This is a sample summary of [Section 2.1.1](https://web.stanford.edu/~jurafsky/slp3/2.pdf ) of Jurfasky and Martin's Speech and Language Processing's book\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lzaavW96tcxM",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7e3e005b-eb33-4219-f726-f9e6465e4051"
      },
      "source": [
        "chapter_2_1_example = \"\"\"\n",
        "Regular expressions are an algebraic notation for characterizing \\\n",
        "a set of strings that are useful for searching for a pattern or through a corpus.\\\n",
        "Only the first matching result will be shown. The search string is case sensitive, \\\n",
        "but it can consist of a single character or a sequence of characters. \\\n",
        "While square braces specify a disjunction of characters, the dash can more easily look \\\n",
        "for characters over a range. The caret specifies the non-existence of a character. \\\n",
        "Additionally, the (?) is used to for flexibility on a single character, meaning \\\n",
        "\"the preceding character or nothing\". More importantly, the Kleene star means zero or \\\n",
        "more occurrences of the immediately previous character or regular expression in square braces.\\\n",
        "...\n",
        "\"\"\"\n",
        "\n",
        "length = len(chapter_2_1_example.split(\" \"))\n",
        "print(\"The example summary is {len} words long, so you could write an additional \\\n",
        "{remaining} words.\".format(len=length, remaining=(500-length)))"
      ],
      "execution_count": 116,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The example summary is 116 words long, so you could write an additional 384 words.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "s3Uk9gQTevcj"
      },
      "source": [
        "## Example summary length\n",
        "\n",
        "The maximum summary length for each section is 500 words / 3000 characters.  Hopefully you'll find that to be quite generous. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8DvZ57A-djo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1bd4082f-772d-4f0a-eb79-ca892fccac6a"
      },
      "source": [
        "# This is an example of a 500 word placeholder\n",
        "placeholder = \"\"\"ultrices vitae auctor eu augue ut lectus arcu bibendum at varius \\\n",
        " vel pharetra vel turpis nunc eget lorem dolor sed viverra ipsum nunc aliquet \\\n",
        " bibendum enim facilisis gravida neque convallis a cras semper auctor neque vitae \\\n",
        " tempus quam pellentesque nec nam aliquam sem et tortor consequat id porta nibh \\\n",
        " venenatis cras sed felis eget velit aliquet sagittis id consectetur purus ut \\\n",
        " faucibus pulvinar elementum integer enim neque volutpat ac tincidunt vitae semper \\ \n",
        " quis lectus nulla at volutpat diam ut venenatis tellus in metus vulputate eu \\\n",
        " scelerisque felis imperdiet proin fermentum leo vel orci porta non pulvinar neque \\ \n",
        " laoreet suspendisse interdum consectetur libero id faucibus nisl tincidunt eget \\\n",
        " nullam non nisi est sit amet facilisis magna etiam tempor orci eu lobortis \\\n",
        " elementum nibh tellus molestie nunc non blandit massa enim nec dui nunc mattis \\\n",
        " enim ut tellus elementum sagittis vitae et leo duis ut diam quam nulla porttitor \\\n",
        " massa id neque aliquam vestibulum morbi blandit cursus risus at ultrices mi tempus \\\n",
        " imperdiet nulla malesuada pellentesque elit eget gravida cum sociis natoque \\\n",
        " penatibus et magnis dis parturient montes nascetur ridiculus mus mauris vitae \\\n",
        " ultricies leo integer malesuada nunc vel risus commodo viverra maecenas accumsan \\\n",
        " lacus vel facilisis volutpat est velit egestas dui id ornare arcu odio ut sem nulla \\\n",
        " pharetra diam sit amet nisl suscipit adipiscing bibendum est ultricies integer \\\n",
        " quis auctor elit sed vulputate mi sit amet mauris commodo quis imperdiet massa \\\n",
        " tincidunt nunc pulvinar sapien et ligula ullamcorper malesuada proin libero nunc \\\n",
        " consequat interdum varius sit amet mattis vulputate enim nulla aliquet porttitor \\\n",
        " lacus luctus accumsan tortor posuere ac ut consequat semper viverra nam libero \\\n",
        " justo laoreet sit amet cursus sit amet dictum sit amet justo donec enim diam \\\n",
        " vulputate ut pharetra sit amet aliquam id diam maecenas ultricies mi eget mauris \\\n",
        " pharetra et ultrices neque ornare aenean euismod elementum nisi quis eleifend quam \\\n",
        " adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra justo \\\n",
        " nec ultrices dui sapien eget mi proin sed libero enim sed faucibus turpis in \\\n",
        " eu mi bibendum neque egestas congue quisque egestas diam in arcu cursus euismod \\\n",
        " quis viverra nibh cras pulvinar mattis nunc sed blandit libero volutpat sed cras \\\n",
        " ornare arcu dui vivamus arcu felis bibendum ut tristique et egestas quis ipsum \\\n",
        " suspendisse ultrices gravida dictum fusce ut placerat orci nulla pellentesque \\\n",
        " dignissim enim sit amet venenatis urna cursus eget nunc scelerisque viverra mauris \\\n",
        " in aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod in \\\n",
        " pellentesque massa placerat duis ultricies lacus sed turpis tincidunt id aliquet \\\n",
        " risus feugiat in ante metus dictum at tempor commodo ullamcorper a lacus vestibulum \\\n",
        " sed arcu non odio euismod lacinia at quis risus sed vulputate odio ut enim blandit \\\n",
        " volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque in \\\n",
        " dictum non consectetur a erat nam at lectus urna\"\"\"\n",
        "\n",
        "print(\"The length in words is\", len(placeholder.split(' ')))\n",
        "print(\"The length in characters is\", len(placeholder))"
      ],
      "execution_count": 117,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The length in words is 500\n",
            "The length in characters is 3030\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5yG3-YncJfTB"
      },
      "source": [
        "# Permissions to use your summaries\n",
        "\n",
        "We'd like to use your summaries to help develop better educational resources like [remember.school](https://remember.school) or a question-answering system about the textbook.  \n",
        "\n",
        "1. Please enter your name.  \n",
        "\n",
        "2. If you grant permission for us to use your summaries under a [Creative Commons License](https://creativecommons.org/licenses/by/4.0/), please set ```permission = True```.  If you do not grant permission, please set it to false. Your answer won't affect your grade.\n",
        "\n",
        "3. If you grant us permission, and you'd like to remain anonymous, set ```anonymous = True```.  We'll remove your name before sharing your summaries with anyone. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "2RECnJArJew4"
      },
      "source": [
        "name = \"Abel Chacko\"\n",
        "permission = True\n",
        "anonymous = False"
      ],
      "execution_count": 118,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZZXyrV-xuAp"
      },
      "source": [
        "# Module 1 - Intro to AI"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y2NfE1CKxzS-"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, Chapter 1 “Introduction”, Section 1.1 “What is AI”\n",
        "\n",
        "chapter1_1 = \"\"\" \n",
        "Six disciplines of AI:\\n\n",
        "1. Natural Language processing: commuincating with people\\n\n",
        "2. Knwoledge representation: Store what it hears knows\\n\n",
        "3. Autoamted Reasoning: Answer questions and draw conclusions\\n\n",
        "4. Machine Learning: Adapt\\n\n",
        "5. Computer Vision: percive teh world\\n\n",
        "6. Robotics: manipulate objects and move\\n\n",
        "\n",
        "The turing test was a thought expirement to determine if computers could think.\\n\n",
        "It would interact with irl people and then respond to them.\\n\n",
        "\n",
        "Human thought is broken down in 3 ways:\\n\n",
        "Introspection (thoughts), Pyschological expriments (actions) and brain imaging.\\n\n",
        "The goal of AI is to make agents that help  mankind and society. Human-thought, human-behavior, rational-thought, and rational-behavior\n",
        "are the models considered for AI.\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 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA 4th Edition, Chapter 2 “Intelligent Agents” (whole chapter)\n",
        "chapter2_1 = \"\"\" \"\"\"\n",
        "chapter2_2 = \"\"\" Rather than design perofmrance measure according to how the think the agent should behave \\\n",
        "but rather design it to what you want to actually acheieve. Rationality\\\n",
        "maximizes epxected performance because nothing is omniscient. \"\"\"\n",
        "chapter2_3 = \"\"\" Episodic Vs Sequential\\n\n",
        "Episodic the experince is divide into atomic episodes and agent recives info every epsiode and does actions\\n\n",
        "Sequential: the future states depend on the previous ones.\"\"\"\n",
        "chapter2_4 = \"\"\" A challenge is to have small programs find rational action vs vast table.\n",
        "Simple reflext agent acts based on current precept. Model-based reflex agents consider how the \\\n",
        "environment could change without all the info.Goal based makes decision on getting to\\\n",
        "a goal. Utility based makes deicions based on utility based on action\"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module1_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "\n",
        "# Definitions of concepts from Module 1.\n",
        "# You can define any bolded term in the textbook, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 20 words long.\n",
        "module1_definitions = {\n",
        "\"agent\" : \"anything that can perceive and act in an environment\",\n",
        "'rational agent' : 'agent that tries to select the correct option based on input',\n",
        "'precept sequence' : 'full history of everything the agent has percieved',\n",
        "'limited rationality' : 'choices being made because of limited compute',\n",
        "'agent function' : 'mapping between history and action of precption',\n",
        "'agent program' : 'implementation of the agent function to run',\n",
        "'PEAS' : 'Performance measure, evnironment, acutators, sensors',\n",
        "'Stochastic' : 'nondeterminsim of an enviornemnt that is probablisitic',\n",
        "'transistion model' : 'How agent goes from one state to the next with an action',\n",
        "'Atomic Representation' : 'black box state representation where details are unknown',\n",
        "\"percept\" : \"your definitions here\",\n",
        "\"other concept\" : \"your definitions here\",\n",
        "\"etc.\": \"your definitions here\",\n",
        "}\n",
        "\n"
      ],
      "execution_count": 119,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "elCCgY64spuq"
      },
      "source": [
        "## Preview of your notes for Module 1\n",
        "\n",
        "Here's a preview of your how your notes will be displayed.  At the end of this Python notebook, we'll aggregate your notes for all modules together into a single display.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gYYeNcdM_maE",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "96efded2-cfb3-4acf-852b-1f5232a500ca"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "from IPython.display import display, Markdown, Latex\n",
        "\n",
        "module1_sections = [\n",
        "  (\"AIMA Chapter 1.1 What is AI?\", chapter1_1),\n",
        "  (\"AIMA Chapter 27.1 The Limits of AI\", chapter27_1),\n",
        "  (\"AIMA Chapter 27.1 Can Machines Really Think?\", chapter27_2),\n",
        "  (\"AIMA 2.1 Agents and Environments\", chapter2_1),\n",
        "  (\"AIMA 2.2 Good Behavior: The Concept of Rationality\", chapter2_2),\n",
        "  (\"AIMA 2.3 The Nature of Environments\", chapter2_3),\n",
        "  (\"AIMA 2.4 The Structure of Agents\", chapter2_4),\n",
        "  (\"Module 1 Lecture Notes\", module1_lecture_notes),\n",
        "]\n",
        "\n",
        "\n",
        "def length_check(sections):\n",
        "  warnings = \"\"\n",
        "  for section, summary in sections:\n",
        "    max_word_length = 500\n",
        "    max_character_length = 3000\n",
        "    if \"lecture\" in section.lower():\n",
        "      # It's OK to do longer summaries of the lectures\n",
        "      max_word_length = 2000\n",
        "      max_character_length = 12000  \n",
        "    if (len(summary) > max_character_length or len(summary.split(' ')) > max_word_length):\n",
        "      warnings += \"WARNING: Your summary of '{section}' is too long!\\n\".format(section=section)\n",
        "  return warnings\n",
        "\n",
        "def length_check_definitions(definitions):\n",
        "  warnings = \"\"\n",
        "  for concept, definition in definitions.items():\n",
        "    if(len(definition.split(' ')) > 20):\n",
        "      warnings += \"WARNING: Your definition of '{concept}' is too long!\\n\".format(concept=concept)\n",
        "  return warnings\n",
        "\n",
        "\n",
        "def format_module(module_num, title, sections, definitions, show_placeholder=False):\n",
        "  markdown = \"\"\n",
        "\n",
        "  # Check summary lengths\n",
        "  warnings = length_check(sections)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  # Check definition lengths\n",
        "  warnings = length_check_definitions(definitions)\n",
        "  if warnings != \"\":\n",
        "    markdown += \"## \" + warnings\n",
        "\n",
        "  markdown += \"# Module {num}: {title}\\n\".format(num=module_num, title=title)\n",
        "\n",
        "\n",
        "  for section, summary in sections:\n",
        "    if show_placeholder and summary == \" Your summary here \":\n",
        "      summary = placeholder\n",
        "    markdown += \"## {section}\\n{summary}\\n\\n\".format(section=section, summary=summary)\n",
        "  \n",
        "  markdown += \"## Module {num} Definitions\\n\".format(num=module_num)\n",
        "  for concept, definition in definitions.items():\n",
        "    markdown += \"* **{concept}** - {definition}\\n\".format(concept=concept.capitalize(), definition=definition)\n",
        "  return markdown\n",
        "\n",
        "\n",
        "module1_markdown = format_module(1, \"Rational Agents and Task Environments\", module1_sections, module1_definitions)\n",
        "display(Markdown(module1_markdown))"
      ],
      "execution_count": 120,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n \nSix disciplines of AI:\n\n1. Natural Language processing: commuincating with people\n\n2. Knwoledge representation: Store what it hears knows\n\n3. Autoamted Reasoning: Answer questions and draw conclusions\n\n4. Machine Learning: Adapt\n\n5. Computer Vision: percive teh world\n\n6. Robotics: manipulate objects and move\n\n\nThe turing test was a thought expirement to determine if computers could think.\n\nIt would interact with irl people and then respond to them.\n\n\nHuman thought is broken down in 3 ways:\n\nIntrospection (thoughts), Pyschological expriments (actions) and brain imaging.\n\nThe goal of AI is to make agents that help  mankind and society. Human-thought, human-behavior, rational-thought, and rational-behavior\nare the models considered for AI.\n       \n\n## AIMA Chapter 27.1 The Limits of AI\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n Your summary here \n\n## AIMA 2.1 Agents and Environments\n \n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n Rather than design perofmrance measure according to how the think the agent should behave but rather design it to what you want to actually acheieve. Rationalitymaximizes epxected performance because nothing is omniscient. \n\n## AIMA 2.3 The Nature of Environments\n Episodic Vs Sequential\n\nEpisodic the experince is divide into atomic episodes and agent recives info every epsiode and does actions\n\nSequential: the future states depend on the previous ones.\n\n## AIMA 2.4 The Structure of Agents\n A challenge is to have small programs find rational action vs vast table.\nSimple reflext agent acts based on current precept. Model-based reflex agents consider how the environment could change without all the info.Goal based makes decision on getting toa goal. Utility based makes deicions based on utility based on action\n\n## Module 1 Lecture Notes\n Your summary here \n\n## Module 1 Definitions\n* **Agent** - anything that can perceive and act in an environment\n* **Rational agent** - agent that tries to select the correct option based on input\n* **Precept sequence** - full history of everything the agent has percieved\n* **Limited rationality** - choices being made because of limited compute\n* **Agent function** - mapping between history and action of precption\n* **Agent program** - implementation of the agent function to run\n* **Peas** - Performance measure, evnironment, acutators, sensors\n* **Stochastic** - nondeterminsim of an enviornemnt that is probablisitic\n* **Transistion model** - How agent goes from one state to the next with an action\n* **Atomic representation** - black box state representation where details are unknown\n* **Percept** - your definitions here\n* **Other concept** - your definitions here\n* **Etc.** - your definitions here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9xRbdqDox2zD"
      },
      "source": [
        "#Module 2 - Python"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DpBvu7EMx7sy"
      },
      "source": [
        "# No readings for this module.  Instead you can summarize the lecture instead.\n",
        "\n",
        "# Lecture notes \n",
        "module2_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Each definition should be at most 20 words long.\n",
        "module2_definitions = {\n",
        "\"mutability\" : \"your definition here\",\n",
        "}"
      ],
      "execution_count": 121,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ydOK__lwWgdp",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 210
        },
        "outputId": "6d244783-aa3c-4af1-deee-c46eb3e5a2c7"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "\n",
        "module2_sections = [\n",
        "  (\"Module 2 Lecture Notes\", module2_lecture_notes),\n",
        "]\n",
        "\n",
        "module2_markdown = format_module(2, \"Python\", module2_sections, module2_definitions)\n",
        "display(Markdown(module2_markdown))"
      ],
      "execution_count": 122,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 2: Python\n## Module 2 Lecture Notes\n Your summary here \n\n## Module 2 Definitions\n* **Mutability** - your definition here\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "46MQLR-Gx8dZ"
      },
      "source": [
        "#Module 3 - Search Problems"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BN0b1eVYx-nd"
      },
      "source": [
        "# Russell and Norvig, AIMA 4th Edition, AIMA Chapter 3 “Problem Solving by Search” (3.1-3.4)\n",
        "chapter3_1 = \"\"\" \n",
        "\n",
        "\n",
        "\"\"\"\n",
        "chapter3_2 = \"\"\" \n",
        "\n",
        " \"\"\"\n",
        "chapter3_3 = \"\"\" Graph search checks for redunatn paths, tree search will go down the same paths.\\n\n",
        "Algorithim's performance can be evaultated by:\n",
        "completeness, time complexity, space complexity, and cost optimality.  \n",
        "best-first Search gets nodes based on the minimum eval function.\\n \"\"\"\n",
        "chapter3_4 = \"\"\" \n",
        "Uniform-Cost Search expands to the smallest node value. O(b^(1+[C/e]))\n",
        "Bidirectional search searches from the starting node and goal captures intersection.\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module3_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions of concepts from Module 3.\n",
        "# You can define any bolded term in the textbook, \n",
        "# but you most use your own words for the definitions.\n",
        "# Each definition should be at most 20 words long.\n",
        "module3_definitions = {\n",
        "\"problem-solving agent\" : \"an agent that can formulate a plan via search\",  \n",
        "'action cost function' : 'the value cost of applying an action on a state to reach s',\n",
        "'Tsp' : 'touring problem where all states need at least one vist',\n",
        "}\n",
        "\n"
      ],
      "execution_count": 123,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lvtN3p7ET3Tx",
        "cellView": "form",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 505
        },
        "outputId": "ccd388f9-ffab-4d94-904a-88ed21ca9dd8"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module3_sections = [\n",
        "  (\"AIMA Chapter 3.1 Problem-Solving Agents\", chapter3_1),\n",
        "  (\"AIMA Chapter 3.2 Example Problems\", chapter3_2),\n",
        "  (\"AIMA Chapter 3.3 Search Algorithms\", chapter3_3),\n",
        "  (\"AIMA Chapter 3.4 Uninformed Search Strategies\", chapter3_4),\n",
        "  (\"Module 3 Lecture Notes\", module3_lecture_notes),\n",
        "]\n",
        "\n",
        "module3_markdown = format_module(3, \"Search Problems\", module3_sections, module3_definitions)\n",
        "display(Markdown(module3_markdown))"
      ],
      "execution_count": 124,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n \n\n\n\n\n## AIMA Chapter 3.2 Example Problems\n \n\n \n\n## AIMA Chapter 3.3 Search Algorithms\n Graph search checks for redunatn paths, tree search will go down the same paths.\n\nAlgorithim's performance can be evaultated by:\ncompleteness, time complexity, space complexity, and cost optimality.  \nbest-first Search gets nodes based on the minimum eval function.\n \n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n \nUniform-Cost Search expands to the smallest node value. O(b^(1+[C/e]))\nBidirectional search searches from the starting node and goal captures intersection.\n \n\n## Module 3 Lecture Notes\n Your summary here \n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n* **Action cost function** - the value cost of applying an action on a state to reach s\n* **Tsp** - touring problem where all states need at least one vist\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WHREsHSSyA-h"
      },
      "source": [
        "#Module 4 - Informed Search"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tuFC8w7CyCns"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 3 “Problem Solving by Search” (3.5-3.6)\n",
        "chapter3_5 = \"\"\" \n",
        "Informed search algos have access to heuristic function \\n\n",
        "Greedy-best-first expands with minimal h(n). not complete\\n\n",
        "A* lowest g(n) + h(n), g(n). optimal if h(n) is admissable\\n\n",
        "Weighted A*\\n\n",
        "Beam search keeps k best nodes, limits search\\n\n",
        "IDA* = A* + IDFS; \n",
        "Recursive best first. best first earch recursviley porpagting the best value\\n\n",
        "optimal if heurisitic is optimal. \n",
        "\"\"\"\n",
        "chapter3_6 = \"\"\" \n",
        "Example of a admissible heurisitc is manhattan distance.\\n\n",
        "Heuristic functinos allow for samller uniformend search space. \\n\n",
        "h1 dominates h2 dominations is when h_1(n) > h_2(n) for all n \\n\n",
        "\n",
        "\n",
        "\"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module4_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module4_definitions = { \n",
        "'admisible heuristic' : 'never overestimates acutal cost',\n",
        "}\n"
      ],
      "execution_count": 125,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vqtEs0gHs9sO",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 530
        },
        "cellView": "form",
        "outputId": "aa526257-2cf9-42b8-c7b8-76d20fe77bd3"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module4_sections = [\n",
        "  (\"AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\", chapter3_5),\n",
        "  (\"AIMA Chapter 3.6 Heuristic Functions\", chapter3_6),\n",
        "  (\"Module 4 Lecture Notes\", module4_lecture_notes),\n",
        "]\n",
        "\n",
        "module4_markdown = format_module(4, \"Informed Search\", \n",
        "                         module4_sections, \n",
        "                         module4_definitions)\n",
        "display(Markdown(module4_markdown))"
      ],
      "execution_count": 126,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n \nInformed search algos have access to heuristic function \n\nGreedy-best-first expands with minimal h(n). not complete\n\nA* lowest g(n) + h(n), g(n). optimal if h(n) is admissable\n\nWeighted A*\n\nBeam search keeps k best nodes, limits search\n\nIDA* = A* + IDFS; \nRecursive best first. best first earch recursviley porpagting the best value\n\noptimal if heurisitic is optimal. \n\n\n## AIMA Chapter 3.6 Heuristic Functions\n \nExample of a admissible heurisitc is manhattan distance.\n\nHeuristic functinos allow for samller uniformend search space. \n\nh1 dominates h2 dominations is when h_1(n) > h_2(n) for all n \n\n\n\n\n\n## Module 4 Lecture Notes\n Your summary here \n\n## Module 4 Definitions\n* **Admisible heuristic** - never overestimates acutal cost\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "F3FPMzG9yUls"
      },
      "source": [
        "#Module 5 - Adversarial Search and Games"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iEIOpL7vyWcc"
      },
      "source": [
        "# Russell and Norvig, AIMA chapter 5 \"Adversarial Search\"”\" (5.1-5.3, and 5.5).\n",
        "chapter5_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter5_2 = \"\"\" \n",
        "We can find the optimal strat by doing the minmax of each state\\n\n",
        "Assuming both player play optimally minimax value is the utiltiy of the max palyer for that state\\n\n",
        "Runtime of minMx is O(b^m)\\n\n",
        "Alpha best choice so far any choice for max\n",
        "Beta is the min value for the minium values\n",
        "\"\"\"\n",
        "chapter5_3 = \"\"\" \n",
        "Eval(s,p) give the  estimate of the expected utiltiy value for state and player p\\m\n",
        "The horizon effect can be thwarted with singular extensions \\n\n",
        "Forward prning removes possibly bad moves, decreasing runtime but give non optimal\\n\n",
        "\n",
        " \"\"\"\n",
        "chapter5_5 = \"\"\" Stocastic games chance nodes are needed as wells as max and min nodes.\\n\n",
        "We have to calculate expected value rather than a true minimax. \n",
        "The runtime is O(b^m * n^m) \"\"\"\n",
        "\n",
        "# Russell and Norvig, AIMA Chapter 16 “Making Simple Decisions” (16.1-16.3)\n",
        "chapter16_1 = \"\"\" \n",
        "\n",
        "\n",
        " \"\"\"\n",
        "chapter16_2 = \"\"\" \n",
        "Axioms of utilty theory:\\n\n",
        "Orderabiltiy: a rational agent must perfer one action more else both are equal prob\\n\n",
        "Transitivity: just transitive property\\n\n",
        "Continutiy: \\n\n",
        "Subtitutabiltity: A ~ B same utiltiy cost then can subsitute eachother\\n\n",
        "Monotonicty: A and B have same outcome then it will perfer the higher prop\n",
        "Decomposabiltiy: compund lotteries can be reduced \\n\n",
        "Existence of utlity function: if agent perfernce hold axioms then there is a function U.\\n\n",
        "Expected utility of lottery: sum(v(l) * p(l))\n",
        "\"\"\"\n",
        "chapter16_3 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module5_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module5_definitions = {\n",
        "\"minimax value\" : \"utilty of state for max if both play optimal\",\n",
        "\"Expected utiltiy\" : 'Avg utiliy for outcomes times probablity of outcome',\n",
        "\"imperfect information\" : \"not all infor about the enviromnet\",\n",
        "'perfect info' : 'knowning the state about the enviroment',\n",
        "'zero-sum' : 'gain for one is loss for the other',\n",
        "'Ply' : 'a level of the game tree for one player',\n",
        "'Minimax decision' : 'best choice the MAX player can make to get minimax value',\n",
        "'Back up' :'from the leaves to teh root recusirvely propgating the value',\n",
        "'Killer moves' : 'best move in the game',\n",
        "'tranpostion' : 'getting the same state with differnt moves',\n",
        "'a strategy' : 'depth limted, but see all moves',\n",
        "'b strategy' : 'follow good moves to max depth', \n",
        "'cutoff test' : 'test to determine alpha-beta search should stop',\n",
        "'material value' : 'the worth of each component',\n",
        "'Quiescent' : 'stable state in a game, no moves can be taken',\n",
        "'Horizon effect' : 'using stalling to delay the inevitable',\n",
        "'Singular Extension' : 'choosing the best move when you can',\n",
        "'Retrograde' : 'backwards search by reversing the rules',\n",
        "'Monte carlo tree search' : 'simulation run and the expected value is taken',\n",
        "\n",
        "}\n",
        "\n"
      ],
      "execution_count": 127,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "KUc_LgzDvWf-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "7c51c495-d1c3-4cd5-f9b9-4914ceaa5a18"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module5_sections = [\n",
        "  (\"AIMA Chapter 5.1 Game Theory\", chapter5_1),\n",
        "  (\"AIMA Chapter 5.2 Optimal Decisions in Games\", chapter5_2),\n",
        "  (\"AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\", chapter5_3),\n",
        "  (\"AIMA Chapter 5.5 Stochastic Games\", chapter5_5),\n",
        "  (\"AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\", chapter16_1),\n",
        "  (\"AIMA Chapter 16.2 The Basis of Utility Theory\", chapter16_2),\n",
        "  (\"AIMA Chapter 16.3 Utility Functions\", chapter16_3),\n",
        "  (\"Module 5 Lecture Notes\", module5_lecture_notes),\n",
        "]\n",
        "\n",
        "module5_markdown = format_module(5, \"Adversarial Search and Games\", \n",
        "                         module5_sections, \n",
        "                         module5_definitions)\n",
        "display(Markdown(module5_markdown))"
      ],
      "execution_count": 128,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n \nWe can find the optimal strat by doing the minmax of each state\n\nAssuming both player play optimally minimax value is the utiltiy of the max palyer for that state\n\nRuntime of minMx is O(b^m)\n\nAlpha best choice so far any choice for max\nBeta is the min value for the minium values\n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \nEval(s,p) give the  estimate of the expected utiltiy value for state and player p\\m\nThe horizon effect can be thwarted with singular extensions \n\nForward prning removes possibly bad moves, decreasing runtime but give non optimal\n\n\n \n\n## AIMA Chapter 5.5 Stochastic Games\n Stocastic games chance nodes are needed as wells as max and min nodes.\n\nWe have to calculate expected value rather than a true minimax. \nThe runtime is O(b^m * n^m) \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n \n\n\n \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \nAxioms of utilty theory:\n\nOrderabiltiy: a rational agent must perfer one action more else both are equal prob\n\nTransitivity: just transitive property\n\nContinutiy: \n\nSubtitutabiltity: A ~ B same utiltiy cost then can subsitute eachother\n\nMonotonicty: A and B have same outcome then it will perfer the higher prop\nDecomposabiltiy: compund lotteries can be reduced \n\nExistence of utlity function: if agent perfernce hold axioms then there is a function U.\n\nExpected utility of lottery: sum(v(l) * p(l))\n\n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## Module 5 Lecture Notes\n Your summary here \n\n## Module 5 Definitions\n* **Minimax value** - utilty of state for max if both play optimal\n* **Expected utiltiy** - Avg utiliy for outcomes times probablity of outcome\n* **Imperfect information** - not all infor about the enviromnet\n* **Perfect info** - knowning the state about the enviroment\n* **Zero-sum** - gain for one is loss for the other\n* **Ply** - a level of the game tree for one player\n* **Minimax decision** - best choice the MAX player can make to get minimax value\n* **Back up** - from the leaves to teh root recusirvely propgating the value\n* **Killer moves** - best move in the game\n* **Tranpostion** - getting the same state with differnt moves\n* **A strategy** - depth limted, but see all moves\n* **B strategy** - follow good moves to max depth\n* **Cutoff test** - test to determine alpha-beta search should stop\n* **Material value** - the worth of each component\n* **Quiescent** - stable state in a game, no moves can be taken\n* **Horizon effect** - using stalling to delay the inevitable\n* **Singular extension** - choosing the best move when you can\n* **Retrograde** - backwards search by reversing the rules\n* **Monte carlo tree search** - simulation run and the expected value is taken\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qVSQhTVSyYYO"
      },
      "source": [
        "#Module 6 - \"Constraint Satisfaction Problems\""
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Wm4mfW82yaRH"
      },
      "source": [
        "# Russell and Norvig, AIMA, Chapter 6 “Constraint Satisfaction Problems” (6.1-6.5)\n",
        "chapter6_1 = \"\"\" \n",
        "3 components to csp: X (set of variables),D (set of domains f/variable), C (constraints, that allow \\\n",
        "combinations).\\n \n",
        "Each constraint C_j made up of <scope, relation>\n",
        "pair. EX:D = {1,2,3}, C = <(X_1, X_2), {(2,1), (3,1), (3,2)}>\\n\n",
        "Solving a CSP is an NP-complete task.\\n\n",
        "Representing CSPs as constraint graph is good where the nodes are \\\n",
        "the variables and edges are scopes\\n\n",
        "3 Main Reasons for CSP: \\n\n",
        "1. Easy to make a problem into a csp\n",
        "2. Much research put into csp to make fast and efficent\n",
        "3. Prune stace space(ss) faster than atomic ss searcher\n",
        "sss can only check if goal, but csp cuts down if states are bad\\n\n",
        ".3 The simplest csp are those with discrete finite domains such as\n",
        "with the 8-queens (1..8 limit and discrete).\\n\n",
        "Infinite ex: no deadline on job scheudling, where implicit defintions\\\n",
        "must be used like described in the defintions.\\n\n",
        "solving general nonlinear constraints does not have algorithim,\n",
        "but linear can\\n\n",
        "Continuous domain real world like hubble where power values must\n",
        "match physical laws, best example is linear programming problems\\\n",
        "where constraints are linear (in)equalities.\\n\n",
        "The most common global constraint is Alldiff where a none of the variables\\\n",
        "can be the same ex:sudoku (row, box, col).\\n\n",
        "You can get set of binary constraints if enough auxiliary variables are introduced for \\\n",
        "all finite-domain constraint.\n",
        " We can also do a dual graph transformation where we have 1 variable\\\n",
        "for each constraint in the first graph and one binary constraint for each contraint pair.\\n\n",
        "              \"\"\"\n",
        "chapter6_2 = \"\"\" \n",
        "Constraint Propagation: Inference in CSPs:\n",
        "atomic sss expand nodes to visit a successor while csps has choices based on\n",
        "new variables. Our key idea is local consistency, where each variable is a node\n",
        "and binary constraint edge enforcing local consistency will make the rest of the \n",
        "graph consisent.\\n\n",
        ".1 Node Consistency \\n\n",
        " Say we start with domain {red, green, blue}, if X does not like green we make \n",
        " domain for X, {red, blue} for node consistency.\\n\n",
        " Some CSP will only solve binary constraints expecting the user to elimnate all other constraints\n",
        " because n-ary constraints can be turned into binary.\\n\n",
        ".2 Arc Consistency\\n\n",
        "The most popular arc consistency algorithim is AC-3 which maintains a queue of arcs. \\n\n",
        "AC-3 Pops off abitrary arc X_i/X_j and makes X_i arc-consistent to X_j. If the domain changes of X_i \\\n",
        "we queue all the arcs (X_k, X_i) and continue from there. O(cd^3) c=binary constraints, d=maxsizeof(domain)\\n\n",
        ".3 Path Consistency\\n\n",
        "Path consistency uses the implicit constraints by looking at triples of variables to tighten binary constraints.\\n\n",
        "If we have some X_m that satisfies {X_i, X_m} and {X_m, X_j} for {X_i =a, X_j=b} that satisfy the binary constraint \\\n",
        "then we are path consistent. The term comes from having X_m be the middle node of a path from X_i to X_j.  \\n\n",
        ".4 K-Consistency\\n\n",
        "If we have n nodes that n-consistent we only need to seach d values for each node to find a consistent value so the run time \\\n",
        "is O(n^2 * d). \\n\n",
        "The issue with guarenteeing k-consistency is that the time is exponential to n in he worst case. And that space would\\\n",
        "also run exponential to n. 2-consistency is the most common.\\n\n",
        ".5 Global Constraints\\n\n",
        "A simple way to decetect Alldiff incosistency is that if there are m variables and n values are possible\\\n",
        "where m > n then becuase of pigeonhole there is a value that must be the same.\\n\n",
        "This gives an algorithim, that starts with removing variables that have a size 1 domain and removed this value\\\n",
        "from the domain of all other variables. Continue until singleton values remain, if an empty domain is found then\n",
        "there is an inconsistency.\\n\n",
        "There is also resource constraints which is also known as AtMost constraint. An example is with\\\n",
        "AtMost(10,X_1,X_2,X_3), we check the minium values of each variable and take the sum if the value of the minsum\\\n",
        "is greater than our atmost value then we have an inconsistencny. We can enforce this consistency\\\n",
        "by removing the maximum value of one domain if it is not consistent with the minimum values of other variables\n",
        "For large-resource limited problems with integer values, the domains are represented by upper and lower bounds\n",
        "Ex Flights with capactiy [0, 165] and [0,385], if the flights total need 420 people then our domains become \n",
        "[35, 165] and [255,385] because the lower bounds match with the upper bound of the other.\\n\n",
        ".6 Sudoku\\n\n",
        "Skipping because it's just enforcing Alldiff for box, row and call, with arc consistency\\n\n",
        "255,960 different path constraints for P-3\\n\n",
        "\"\"\"\n",
        "\n",
        "chapter6_3 = \"\"\" \n",
        "After constraint propagation we might still have multiple values, so we have to search for the solution\\n\n",
        "Backtracking search algorithims work on partial assignments.\n",
        "The issue for using standard depth-limited search is that beacuse the branching factor O(nd) at the top level, so \\\n",
        "we would have n!d^n leaves. But we only have d^n possible assignments. We remove the n! factor by understanding that the \\\n",
        "csp's are commutative, at each level we choose a variable to deal with but never backtrack to over our choice\\n\n",
        ".1 Variable and value ordering\\n\n",
        "Neither picking a random variable or in order is optimal for select-unassigned-variable\\\n",
        "The most straight forward idea is to chose the variable with the least legal moves, known\\\n",
        "as minimum-remaning-values heurisitc (fail-first/most constrainted variable)\\ \n",
        "By doing this we will run into failure faster and avoid pointless search\\n\n",
        "Degree heurisitc(DH) helps choosing the first color beacuse MRV doesn't help with that\\\n",
        "DH  tries to reduce the branching factor on the future by picking the variable\\\n",
        "that is involved with the most constraintes on other unassigned variables.\\n\n",
        "The least-constraining-value heuristic is used as the method for selecting values\\\n",
        "after getting a variable. It is to select the value that restricts\\\n",
        "the fewest neighbors in the constraint graph\\n\n",
        "Variables selection is fail-first\\n\n",
        "Value selection is fail-last\\n\n",
        ".2 Interleaving search and inference\\n\n",
        "Forward checking this one of the most simple forms of inference. The algorithim goes\\\n",
        "as such: When x is assigned, for each Y that is in the Arc of X we delete any value from\\\n",
        "Y's domain that would cause X to be inconsistent. For many problems searching is more effecitive\\\n",
        "if we use MRV and forward checking. \\n\n",
        "Forward checking does not detect all inconsistencies because it doesn't look far enough ahead\\n\n",
        "Maintaing Arc Consistency (MAC) finds inconsistencies that forward checking can't find\\\n",
        "because of depth limitations. \\n\n",
        "MAC after a X_i is assigned a value, the inference will call AC-3, but the queue\\\n",
        "will only have the arcs of (X_j, X_i) for unassigned neighbors. And runs AC-3 normally\\\n",
        "if the domain is empty of any variable, it will immediately backtrack. MAC is stronger,\\\n",
        "because forward checkign doesn't propagte constraints when changes are made to the domain.\n",
        ".3 Intelligent backtracking: Looking backward\\n\n",
        "The backtracking-search algorthim when there is failure will back up to the previous variable\\\n",
        "then try a different value this is Chronological backtracking, because most recent decision is changed\\n\n",
        "Backjumping is redudant in a foward-checking search.\n",
        "Sometimes backjumping isn't enough so we have to do conflict-direct backjumping\\\n",
        "which uses a new definition of conflict set that is the set of preecing variables that\\\n",
        "cause a variable to not have a consistent solution\n",
        ".4 Constraint learning\\n\n",
        "Backjumping tells us how far to back up when we reach a contradiction. To avoid running into\\\n",
        "the same problem again we add constraints to not allow the no-good set value to be assigned.\\n\n",
        "\"\"\"\n",
        "chapter6_4 = \"\"\"\n",
        "Local serach algorthims use a complete-state formulation where each state\\\n",
        "assigns value to every variable. Then during the search one variable is changed \\\n",
        "at a time. We randomly chose a conflicted variable and slect a value using the min-conflict\\s\n",
        "heuristic. \\n\n",
        "For the n-queens problem, The run time of min-conflicts is roughly independent of problem size. And min-conflicts\\\n",
        "is effecitve for many CSP's. Hubble Space Telescope uses min-conflicts to reduce \\\n",
        "scheduling time 3weeks to 10 min.\\n\n",
        "With min-conflicts there can be Plateaus of states with the same score. So Pleateua\\\n",
        "search allows us to move sidways to another state to find a way off the plateau. This \\\n",
        "technique is called tabu search. Where we forbid the algorithim from returned to a small list of visted states\\\n",
        "Simulated annealing can also be used\\n\n",
        "Contstraint Weighting focuses the search on important constraints.\\n\n",
        "The constraints are given a numerical weight, which all start at 1. During the search\\\n",
        "The algorithm chooses a variable to change that will result in the lowest total weight of all the \n",
        "inconsistent constraints. Then for all vilated constriantes by the assignemnt the weights are incremented\\nn\n",
        "2 benefits:\n",
        "1. Topography to the plateaus\n",
        "2. Diffcult constraints are given higher weights\n",
        "\"\"\"\n",
        "chapter6_5 = \"\"\" \n",
        "Independence can be found by finding connected components of the constraint graph.\\n\n",
        "The reason why we want to break down our problem is because we can get our run time down to \\\n",
        "O(d^c* n/c) where c is the number of connected components. \\n\n",
        "Constraint graph is a tree when 2 variables are connected by only 1 path. Any tree-strucutred\\\n",
        "CSP(tsCSP) can be solved in linear time. The reason for this is because of direciton arc consistency (DAC).\n",
        "A csp is DAC if in an ordered X_1...X_n iff X_i is  arc-consistent j > i. \\n\n",
        "\n",
        "When solving tsCSP we pick a variable to be our root and then have an ordering. We can use\\\n",
        "toposort to order them. We can ake it arc consistent in O(nd^2). \n",
        "\n",
        ".1 Cutset conditioning\\n\n",
        "One way to reduce a constraint graph to a tree is to give a value to some\\\n",
        "variables so that the remaining variables make a tree.\\n\n",
        "We would need to try each possible value that makes the graph a tree and then run the following\\\n",
        "algorithm.\\n\n",
        "1. We select subset S that allows our graph to be a tree this is the cycle cutset\n",
        "2. For each assignemt for S that satisfies the constraints \n",
        "  a. remove the values from the domains that would cause inconsistents.\n",
        "  b. return the solution if the csp has one with S included\n",
        "the total runtime would be O(d^c *(n-c)d^2). \n",
        "This approach is called cutset conditioning.\n",
        ".2 Tree decomposition\\n\n",
        "Now we can try tree decomposition which transforms the original graph into a tree \\\n",
        "where each node is a set of variables.\n",
        "There are 3 conditions that must be met for a tree decomposition:\n",
        "1. In at least one of the tree nodes, every variable is present\\n\n",
        "2. If two variables are connected by a a contraint then then must appear in at least one node together\\n\n",
        "3. A variable must appear in every node in the path connecting notes if the variable appears in two nodes in the tree\\n\n",
        "\n",
        "The fist 2 conditions are to make sure that constraints and variables are witin the td.\\n\n",
        "The third is to force the variable to have the same value wherever it is.\n",
        "\n",
        "Now we can run Tree-CSP-Solver to get a solution in O(nd^2) time. n is the number of nodes\\n\n",
        "The goal of the decomp is to get as many small subproblems as possible. The tree width of td of a graph\\\n",
        "is the size of hte largest node - 1. The problem can be solved in O(nd^(w+1)).\\\n",
        "The issue is finding the minal tree width decopm is NP-hard.\n",
        ".3 Value symmetry\\n\n",
        "Value symmetry is that for ever consistent oslution we can have d! solutions by permuting\\\n",
        "the solution. So to avoid having to deal with the d!, we have symmetry-breaking constraint.\\n\n",
        "That will allow us to avoid branching. It is NP-hard to eliminate all symmetry, but it is important and effective\n",
        " \"\"\"\n",
        "\n",
        "\n",
        "# Lecture notes \n",
        "module6_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module6_definitions = {\n",
        "\"Contstraint Satisfication Problem\" : '''Problem represented as \n",
        " states having set of variables having values, solved when values for\n",
        " all variables fit contstraint ''',   \n",
        " \"Domain\" : 'Allowable value for for variable X_i',\n",
        " \"Scope\" : 'Variables that are in the constraint',\n",
        " 'Relation' : 'Give the values that the variables in the scope can have',\n",
        " 'Consistent' : 'Legal assignment that does not violate any constraints',\n",
        " 'Complete Assignment' : 'Every variable is assigned a value',\n",
        " 'Solution' : 'Consistent and Complete Assignment ',\n",
        " 'Precidence Constraints' : 'If a task has to happen before another with a duration we have T_1 + d <= T_2',\n",
        " 'Disjunctive Contraint'  : 'When 2 tasks cannot occur at the same time (t + d) < t2 or (t2+d) < t',\n",
        " 'Unary Constraint'       : 'When a constraint is not allow for single variable <X, X!= green>',\n",
        " 'Binary Constriant'      : 'When a constraint relates 2 variables <(X_1, X_2), X_2 != X_1>',\n",
        " 'Binary CSP' : 'CSP that only uses unary and binary constraints',\n",
        " 'Global constraint' : 'constraint that considers an abitrary number of variables',\n",
        " 'Cryptarithmetic puzzle' : 'Each letter represents a different digit',\n",
        " 'Constraint Hypergraph' : 'graph of nodes and hypernodes(squares) that indicate n-ary constraints',\n",
        " 'Perfernce Constraints' : 'Contraint that is allowable, but not optimal',\n",
        " 'Constrained Optimization Problem' : 'CSPs with perfernce solved with optimization, perfernce indicated by cost on variable',\n",
        " 'Constraint propagation': 'reducing legal values using contraints, then reducing the legal values for another variable using new values',\n",
        " 'node-consistent' : 'For the unary constraints, if all values satisfy',\n",
        " 'arc-consistent' : 'Domain satisfies binary constraints',\n",
        " 'k-consistency' : 'If for any k-1 variables, being able to assign the k-th variable to keep everything consistent',\n",
        " 'strongly k-consistent' : '1 to k-consistent',\n",
        " 'bounds-consistent': 'For upper and lower bounds of X there is value between X and Y that satisfies contraints for every Y',\n",
        " 'conflict set' : 'Set of variables and values that conflict with another variable',\n",
        " 'backjumping' : 'backtracking to the most recently assigned in the conflict set',\n",
        " 'Constraint learning' : 'From the conflict set, finding the minimum set of variables that cause a problem',\n",
        " 'no-good' : 'Set of variablese that caused the problem found in constraint learning.',\n",
        "\n",
        "\n",
        "\n",
        "}\n"
      ],
      "execution_count": 129,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "kKWbCsbfxL3R",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "cellView": "form",
        "outputId": "a8bc96c0-6ce7-4dd5-8c66-3de9516148fa"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module6_sections = [\n",
        "  (\"AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\", chapter6_1),\n",
        "  (\"AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\", chapter6_2),\n",
        "  (\"AIMA Chapter 6.3 Backtracking Search for CSPs\", chapter6_3),\n",
        "  (\"AIMA Chapter 6.4 Local Search for CSPs\", chapter6_4),\n",
        "  (\"AIMA Chapter 6.5 The Structure of Problems\", chapter6_5),\n",
        "  (\"Module 6 Lecture Notes\", module6_lecture_notes),\n",
        "]\n",
        "\n",
        "module6_markdown = format_module(6, \"Constraint Satisfaction Problems\", \n",
        "                         module6_sections, \n",
        "                         module6_definitions)\n",
        "display(Markdown(module6_markdown))"
      ],
      "execution_count": 130,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n \n3 components to csp: X (set of variables),D (set of domains f/variable), C (constraints, that allow combinations).\n \nEach constraint C_j made up of <scope, relation>\npair. EX:D = {1,2,3}, C = <(X_1, X_2), {(2,1), (3,1), (3,2)}>\n\nSolving a CSP is an NP-complete task.\n\nRepresenting CSPs as constraint graph is good where the nodes are the variables and edges are scopes\n\n3 Main Reasons for CSP: \n\n1. Easy to make a problem into a csp\n2. Much research put into csp to make fast and efficent\n3. Prune stace space(ss) faster than atomic ss searcher\nsss can only check if goal, but csp cuts down if states are bad\n\n.3 The simplest csp are those with discrete finite domains such as\nwith the 8-queens (1..8 limit and discrete).\n\nInfinite ex: no deadline on job scheudling, where implicit defintionsmust be used like described in the defintions.\n\nsolving general nonlinear constraints does not have algorithim,\nbut linear can\n\nContinuous domain real world like hubble where power values must\nmatch physical laws, best example is linear programming problemswhere constraints are linear (in)equalities.\n\nThe most common global constraint is Alldiff where a none of the variablescan be the same ex:sudoku (row, box, col).\n\nYou can get set of binary constraints if enough auxiliary variables are introduced for all finite-domain constraint.\n We can also do a dual graph transformation where we have 1 variablefor each constraint in the first graph and one binary constraint for each contraint pair.\n\n              \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n \nConstraint Propagation: Inference in CSPs:\natomic sss expand nodes to visit a successor while csps has choices based on\nnew variables. Our key idea is local consistency, where each variable is a node\nand binary constraint edge enforcing local consistency will make the rest of the \ngraph consisent.\n\n.1 Node Consistency \n\n Say we start with domain {red, green, blue}, if X does not like green we make \n domain for X, {red, blue} for node consistency.\n\n Some CSP will only solve binary constraints expecting the user to elimnate all other constraints\n because n-ary constraints can be turned into binary.\n\n.2 Arc Consistency\n\nThe most popular arc consistency algorithim is AC-3 which maintains a queue of arcs. \n\nAC-3 Pops off abitrary arc X_i/X_j and makes X_i arc-consistent to X_j. If the domain changes of X_i we queue all the arcs (X_k, X_i) and continue from there. O(cd^3) c=binary constraints, d=maxsizeof(domain)\n\n.3 Path Consistency\n\nPath consistency uses the implicit constraints by looking at triples of variables to tighten binary constraints.\n\nIf we have some X_m that satisfies {X_i, X_m} and {X_m, X_j} for {X_i =a, X_j=b} that satisfy the binary constraint then we are path consistent. The term comes from having X_m be the middle node of a path from X_i to X_j.  \n\n.4 K-Consistency\n\nIf we have n nodes that n-consistent we only need to seach d values for each node to find a consistent value so the run time is O(n^2 * d). \n\nThe issue with guarenteeing k-consistency is that the time is exponential to n in he worst case. And that space wouldalso run exponential to n. 2-consistency is the most common.\n\n.5 Global Constraints\n\nA simple way to decetect Alldiff incosistency is that if there are m variables and n values are possiblewhere m > n then becuase of pigeonhole there is a value that must be the same.\n\nThis gives an algorithim, that starts with removing variables that have a size 1 domain and removed this valuefrom the domain of all other variables. Continue until singleton values remain, if an empty domain is found then\nthere is an inconsistency.\n\nThere is also resource constraints which is also known as AtMost constraint. An example is withAtMost(10,X_1,X_2,X_3), we check the minium values of each variable and take the sum if the value of the minsumis greater than our atmost value then we have an inconsistencny. We can enforce this consistencyby removing the maximum value of one domain if it is not consistent with the minimum values of other variables\nFor large-resource limited problems with integer values, the domains are represented by upper and lower bounds\nEx Flights with capactiy [0, 165] and [0,385], if the flights total need 420 people then our domains become \n[35, 165] and [255,385] because the lower bounds match with the upper bound of the other.\n\n.6 Sudoku\n\nSkipping because it's just enforcing Alldiff for box, row and call, with arc consistency\n\n255,960 different path constraints for P-3\n\n\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n \nAfter constraint propagation we might still have multiple values, so we have to search for the solution\n\nBacktracking search algorithims work on partial assignments.\nThe issue for using standard depth-limited search is that beacuse the branching factor O(nd) at the top level, so we would have n!d^n leaves. But we only have d^n possible assignments. We remove the n! factor by understanding that the csp's are commutative, at each level we choose a variable to deal with but never backtrack to over our choice\n\n.1 Variable and value ordering\n\nNeither picking a random variable or in order is optimal for select-unassigned-variableThe most straight forward idea is to chose the variable with the least legal moves, knownas minimum-remaning-values heurisitc (fail-first/most constrainted variable)\\ \nBy doing this we will run into failure faster and avoid pointless search\n\nDegree heurisitc(DH) helps choosing the first color beacuse MRV doesn't help with thatDH  tries to reduce the branching factor on the future by picking the variablethat is involved with the most constraintes on other unassigned variables.\n\nThe least-constraining-value heuristic is used as the method for selecting valuesafter getting a variable. It is to select the value that restrictsthe fewest neighbors in the constraint graph\n\nVariables selection is fail-first\n\nValue selection is fail-last\n\n.2 Interleaving search and inference\n\nForward checking this one of the most simple forms of inference. The algorithim goesas such: When x is assigned, for each Y that is in the Arc of X we delete any value fromY's domain that would cause X to be inconsistent. For many problems searching is more effecitiveif we use MRV and forward checking. \n\nForward checking does not detect all inconsistencies because it doesn't look far enough ahead\n\nMaintaing Arc Consistency (MAC) finds inconsistencies that forward checking can't findbecause of depth limitations. \n\nMAC after a X_i is assigned a value, the inference will call AC-3, but the queuewill only have the arcs of (X_j, X_i) for unassigned neighbors. And runs AC-3 normallyif the domain is empty of any variable, it will immediately backtrack. MAC is stronger,because forward checkign doesn't propagte constraints when changes are made to the domain.\n.3 Intelligent backtracking: Looking backward\n\nThe backtracking-search algorthim when there is failure will back up to the previous variablethen try a different value this is Chronological backtracking, because most recent decision is changed\n\nBackjumping is redudant in a foward-checking search.\nSometimes backjumping isn't enough so we have to do conflict-direct backjumpingwhich uses a new definition of conflict set that is the set of preecing variables thatcause a variable to not have a consistent solution\n.4 Constraint learning\n\nBackjumping tells us how far to back up when we reach a contradiction. To avoid running intothe same problem again we add constraints to not allow the no-good set value to be assigned.\n\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n\nLocal serach algorthims use a complete-state formulation where each stateassigns value to every variable. Then during the search one variable is changed at a time. We randomly chose a conflicted variable and slect a value using the min-conflict\\s\nheuristic. \n\nFor the n-queens problem, The run time of min-conflicts is roughly independent of problem size. And min-conflictsis effecitve for many CSP's. Hubble Space Telescope uses min-conflicts to reduce scheduling time 3weeks to 10 min.\n\nWith min-conflicts there can be Plateaus of states with the same score. So Pleateuasearch allows us to move sidways to another state to find a way off the plateau. This technique is called tabu search. Where we forbid the algorithim from returned to a small list of visted statesSimulated annealing can also be used\n\nContstraint Weighting focuses the search on important constraints.\n\nThe constraints are given a numerical weight, which all start at 1. During the searchThe algorithm chooses a variable to change that will result in the lowest total weight of all the \ninconsistent constraints. Then for all vilated constriantes by the assignemnt the weights are incremented\nn\n2 benefits:\n1. Topography to the plateaus\n2. Diffcult constraints are given higher weights\n\n\n## AIMA Chapter 6.5 The Structure of Problems\n \nIndependence can be found by finding connected components of the constraint graph.\n\nThe reason why we want to break down our problem is because we can get our run time down to O(d^c* n/c) where c is the number of connected components. \n\nConstraint graph is a tree when 2 variables are connected by only 1 path. Any tree-strucutredCSP(tsCSP) can be solved in linear time. The reason for this is because of direciton arc consistency (DAC).\nA csp is DAC if in an ordered X_1...X_n iff X_i is  arc-consistent j > i. \n\n\nWhen solving tsCSP we pick a variable to be our root and then have an ordering. We can usetoposort to order them. We can ake it arc consistent in O(nd^2). \n\n.1 Cutset conditioning\n\nOne way to reduce a constraint graph to a tree is to give a value to somevariables so that the remaining variables make a tree.\n\nWe would need to try each possible value that makes the graph a tree and then run the followingalgorithm.\n\n1. We select subset S that allows our graph to be a tree this is the cycle cutset\n2. For each assignemt for S that satisfies the constraints \n  a. remove the values from the domains that would cause inconsistents.\n  b. return the solution if the csp has one with S included\nthe total runtime would be O(d^c *(n-c)d^2). \nThis approach is called cutset conditioning.\n.2 Tree decomposition\n\nNow we can try tree decomposition which transforms the original graph into a tree where each node is a set of variables.\nThere are 3 conditions that must be met for a tree decomposition:\n1. In at least one of the tree nodes, every variable is present\n\n2. If two variables are connected by a a contraint then then must appear in at least one node together\n\n3. A variable must appear in every node in the path connecting notes if the variable appears in two nodes in the tree\n\n\nThe fist 2 conditions are to make sure that constraints and variables are witin the td.\n\nThe third is to force the variable to have the same value wherever it is.\n\nNow we can run Tree-CSP-Solver to get a solution in O(nd^2) time. n is the number of nodes\n\nThe goal of the decomp is to get as many small subproblems as possible. The tree width of td of a graphis the size of hte largest node - 1. The problem can be solved in O(nd^(w+1)).The issue is finding the minal tree width decopm is NP-hard.\n.3 Value symmetry\n\nValue symmetry is that for ever consistent oslution we can have d! solutions by permutingthe solution. So to avoid having to deal with the d!, we have symmetry-breaking constraint.\n\nThat will allow us to avoid branching. It is NP-hard to eliminate all symmetry, but it is important and effective\n \n\n## Module 6 Lecture Notes\n Your summary here \n\n## Module 6 Definitions\n* **Contstraint satisfication problem** - Problem represented as \n states having set of variables having values, solved when values for\n all variables fit contstraint \n* **Domain** - Allowable value for for variable X_i\n* **Scope** - Variables that are in the constraint\n* **Relation** - Give the values that the variables in the scope can have\n* **Consistent** - Legal assignment that does not violate any constraints\n* **Complete assignment** - Every variable is assigned a value\n* **Solution** - Consistent and Complete Assignment \n* **Precidence constraints** - If a task has to happen before another with a duration we have T_1 + d <= T_2\n* **Disjunctive contraint** - When 2 tasks cannot occur at the same time (t + d) < t2 or (t2+d) < t\n* **Unary constraint** - When a constraint is not allow for single variable <X, X!= green>\n* **Binary constriant** - When a constraint relates 2 variables <(X_1, X_2), X_2 != X_1>\n* **Binary csp** - CSP that only uses unary and binary constraints\n* **Global constraint** - constraint that considers an abitrary number of variables\n* **Cryptarithmetic puzzle** - Each letter represents a different digit\n* **Constraint hypergraph** - graph of nodes and hypernodes(squares) that indicate n-ary constraints\n* **Perfernce constraints** - Contraint that is allowable, but not optimal\n* **Constrained optimization problem** - CSPs with perfernce solved with optimization, perfernce indicated by cost on variable\n* **Constraint propagation** - reducing legal values using contraints, then reducing the legal values for another variable using new values\n* **Node-consistent** - For the unary constraints, if all values satisfy\n* **Arc-consistent** - Domain satisfies binary constraints\n* **K-consistency** - If for any k-1 variables, being able to assign the k-th variable to keep everything consistent\n* **Strongly k-consistent** - 1 to k-consistent\n* **Bounds-consistent** - For upper and lower bounds of X there is value between X and Y that satisfies contraints for every Y\n* **Conflict set** - Set of variables and values that conflict with another variable\n* **Backjumping** - backtracking to the most recently assigned in the conflict set\n* **Constraint learning** - From the conflict set, finding the minimum set of variables that cause a problem\n* **No-good** - Set of variablese that caused the problem found in constraint learning.\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RYESi2kMybL8"
      },
      "source": [
        "#Module 7 - Logical Agents"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qIRJ4YYCzNHL"
      },
      "source": [
        "# Russell and Norvig, AIMA Chapter 7 “Logical Agents” (Sections 7.1-7.5)\n",
        "\n",
        "chapter7_1 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_2 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_3 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_4 = \"\"\" Your summary here \"\"\"\n",
        "chapter7_5 = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Lecture notes \n",
        "module7_lecture_notes = \"\"\" Your summary here \"\"\"\n",
        "\n",
        "# Definitions\n",
        "module7_definitions = {\n",
        "\"concept\" : \"definition\",    \n",
        "}\n",
        "\n"
      ],
      "execution_count": 131,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "id": "lXNcHuKjyNXa",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 544
        },
        "outputId": "8236d72a-a811-4d13-8834-3c70df7d6061"
      },
      "source": [
        "#@title Preview of your summary\n",
        "#@markdown You don't need to modify anything in this cell. Just press play.\n",
        "module7_sections = [\n",
        "  (\"AIMA Chapter 7.1 Knowledge-Based Agents\", chapter7_1),\n",
        "  (\"AIMA Chapter 7.2 The Wumpus World\", chapter7_2),\n",
        "  (\"AIMA Chapter 7.3 Logic\", chapter7_3),\n",
        "  (\"AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\", chapter7_4),\n",
        "  (\"AIMA 7.5 Propositional Theorem Proving\", chapter7_5),\n",
        "  (\"Module 7 Lecture Notes\", module7_lecture_notes),\n",
        "]\n",
        "\n",
        "module7_markdown = format_module(7, \"Logical Agents\", \n",
        "                         module7_sections, \n",
        "                         module7_definitions)\n",
        "display(Markdown(module7_markdown))"
      ],
      "execution_count": 132,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n Your summary here \n\n## AIMA Chapter 7.2 The Wumpus World\n Your summary here \n\n## AIMA Chapter 7.3 Logic\n Your summary here \n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n Your summary here \n\n## AIMA 7.5 Propositional Theorem Proving\n Your summary here \n\n## Module 7 Lecture Notes\n Your summary here \n\n## Module 7 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vX7lbnJd4sT5"
      },
      "source": [
        "# Your Exam Notes\n",
        "\n",
        "Here are your full set of exam notes that you can use on your midterm.  Choose **Runtime > Run all**, then your notes will be displayed.\n",
        "\n",
        "If you are taking the exam in person, then you must print a copy of your notes for yourself.   Here's how to print:\n",
        "* Run the cell below. \n",
        "* Click its \"Mirror cell in tab\" button (this is located in the upper right corner of the cell, immediately to the right of the trash can).  This will open the cell.  \n",
        "* In Chrome, you can then print your notes using the **File > Print** option from the browser's menu.  \n",
        "* In the print options, change the layout from Landscape to Portrait. \n",
        "* Clicking the Save, will save a PDF that you can then print.\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "id": "T3cm1WV542_a",
        "outputId": "24c0d90c-be35-4afa-cb35-74639590a6b5"
      },
      "source": [
        "# This will generate the full set of notes that you can use for your exam.\n",
        "full_markdown = \"\\n\\n\".join([module1_markdown, \n",
        "                             module2_markdown, \n",
        "                             module3_markdown, \n",
        "                             module4_markdown, \n",
        "                             module5_markdown,\n",
        "                             module6_markdown,\n",
        "                             module7_markdown,]\n",
        "                       )\n",
        "display(Markdown(full_markdown))"
      ],
      "execution_count": 133,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "text/markdown": "# Module 1: Rational Agents and Task Environments\n## AIMA Chapter 1.1 What is AI?\n \nSix disciplines of AI:\n\n1. Natural Language processing: commuincating with people\n\n2. Knwoledge representation: Store what it hears knows\n\n3. Autoamted Reasoning: Answer questions and draw conclusions\n\n4. Machine Learning: Adapt\n\n5. Computer Vision: percive teh world\n\n6. Robotics: manipulate objects and move\n\n\nThe turing test was a thought expirement to determine if computers could think.\n\nIt would interact with irl people and then respond to them.\n\n\nHuman thought is broken down in 3 ways:\n\nIntrospection (thoughts), Pyschological expriments (actions) and brain imaging.\n\nThe goal of AI is to make agents that help  mankind and society. Human-thought, human-behavior, rational-thought, and rational-behavior\nare the models considered for AI.\n       \n\n## AIMA Chapter 27.1 The Limits of AI\n\n\n## AIMA Chapter 27.1 Can Machines Really Think?\n Your summary here \n\n## AIMA 2.1 Agents and Environments\n \n\n## AIMA 2.2 Good Behavior: The Concept of Rationality\n Rather than design perofmrance measure according to how the think the agent should behave but rather design it to what you want to actually acheieve. Rationalitymaximizes epxected performance because nothing is omniscient. \n\n## AIMA 2.3 The Nature of Environments\n Episodic Vs Sequential\n\nEpisodic the experince is divide into atomic episodes and agent recives info every epsiode and does actions\n\nSequential: the future states depend on the previous ones.\n\n## AIMA 2.4 The Structure of Agents\n A challenge is to have small programs find rational action vs vast table.\nSimple reflext agent acts based on current precept. Model-based reflex agents consider how the environment could change without all the info.Goal based makes decision on getting toa goal. Utility based makes deicions based on utility based on action\n\n## Module 1 Lecture Notes\n Your summary here \n\n## Module 1 Definitions\n* **Agent** - anything that can perceive and act in an environment\n* **Rational agent** - agent that tries to select the correct option based on input\n* **Precept sequence** - full history of everything the agent has percieved\n* **Limited rationality** - choices being made because of limited compute\n* **Agent function** - mapping between history and action of precption\n* **Agent program** - implementation of the agent function to run\n* **Peas** - Performance measure, evnironment, acutators, sensors\n* **Stochastic** - nondeterminsim of an enviornemnt that is probablisitic\n* **Transistion model** - How agent goes from one state to the next with an action\n* **Atomic representation** - black box state representation where details are unknown\n* **Percept** - your definitions here\n* **Other concept** - your definitions here\n* **Etc.** - your definitions here\n\n\n# Module 2: Python\n## Module 2 Lecture Notes\n Your summary here \n\n## Module 2 Definitions\n* **Mutability** - your definition here\n\n\n# Module 3: Search Problems\n## AIMA Chapter 3.1 Problem-Solving Agents\n \n\n\n\n\n## AIMA Chapter 3.2 Example Problems\n \n\n \n\n## AIMA Chapter 3.3 Search Algorithms\n Graph search checks for redunatn paths, tree search will go down the same paths.\n\nAlgorithim's performance can be evaultated by:\ncompleteness, time complexity, space complexity, and cost optimality.  \nbest-first Search gets nodes based on the minimum eval function.\n \n\n## AIMA Chapter 3.4 Uninformed Search Strategies\n \nUniform-Cost Search expands to the smallest node value. O(b^(1+[C/e]))\nBidirectional search searches from the starting node and goal captures intersection.\n \n\n## Module 3 Lecture Notes\n Your summary here \n\n## Module 3 Definitions\n* **Problem-solving agent** - an agent that can formulate a plan via search\n* **Action cost function** - the value cost of applying an action on a state to reach s\n* **Tsp** - touring problem where all states need at least one vist\n\n\n# Module 4: Informed Search\n## AIMA Chapter 3.5 Informed (Heuristic) Search Strategies\n \nInformed search algos have access to heuristic function \n\nGreedy-best-first expands with minimal h(n). not complete\n\nA* lowest g(n) + h(n), g(n). optimal if h(n) is admissable\n\nWeighted A*\n\nBeam search keeps k best nodes, limits search\n\nIDA* = A* + IDFS; \nRecursive best first. best first earch recursviley porpagting the best value\n\noptimal if heurisitic is optimal. \n\n\n## AIMA Chapter 3.6 Heuristic Functions\n \nExample of a admissible heurisitc is manhattan distance.\n\nHeuristic functinos allow for samller uniformend search space. \n\nh1 dominates h2 dominations is when h_1(n) > h_2(n) for all n \n\n\n\n\n\n## Module 4 Lecture Notes\n Your summary here \n\n## Module 4 Definitions\n* **Admisible heuristic** - never overestimates acutal cost\n\n\n# Module 5: Adversarial Search and Games\n## AIMA Chapter 5.1 Game Theory\n Your summary here \n\n## AIMA Chapter 5.2 Optimal Decisions in Games\n \nWe can find the optimal strat by doing the minmax of each state\n\nAssuming both player play optimally minimax value is the utiltiy of the max palyer for that state\n\nRuntime of minMx is O(b^m)\n\nAlpha best choice so far any choice for max\nBeta is the min value for the minium values\n\n\n## AIMA Chapter 5.3 Heuristic Alpha–Beta Tree Search\n \nEval(s,p) give the  estimate of the expected utiltiy value for state and player p\\m\nThe horizon effect can be thwarted with singular extensions \n\nForward prning removes possibly bad moves, decreasing runtime but give non optimal\n\n\n \n\n## AIMA Chapter 5.5 Stochastic Games\n Stocastic games chance nodes are needed as wells as max and min nodes.\n\nWe have to calculate expected value rather than a true minimax. \nThe runtime is O(b^m * n^m) \n\n## AIMA Chapter 16.1 Combining Beliefs and Desires under Uncertainty\n \n\n\n \n\n## AIMA Chapter 16.2 The Basis of Utility Theory\n \nAxioms of utilty theory:\n\nOrderabiltiy: a rational agent must perfer one action more else both are equal prob\n\nTransitivity: just transitive property\n\nContinutiy: \n\nSubtitutabiltity: A ~ B same utiltiy cost then can subsitute eachother\n\nMonotonicty: A and B have same outcome then it will perfer the higher prop\nDecomposabiltiy: compund lotteries can be reduced \n\nExistence of utlity function: if agent perfernce hold axioms then there is a function U.\n\nExpected utility of lottery: sum(v(l) * p(l))\n\n\n## AIMA Chapter 16.3 Utility Functions\n Your summary here \n\n## Module 5 Lecture Notes\n Your summary here \n\n## Module 5 Definitions\n* **Minimax value** - utilty of state for max if both play optimal\n* **Expected utiltiy** - Avg utiliy for outcomes times probablity of outcome\n* **Imperfect information** - not all infor about the enviromnet\n* **Perfect info** - knowning the state about the enviroment\n* **Zero-sum** - gain for one is loss for the other\n* **Ply** - a level of the game tree for one player\n* **Minimax decision** - best choice the MAX player can make to get minimax value\n* **Back up** - from the leaves to teh root recusirvely propgating the value\n* **Killer moves** - best move in the game\n* **Tranpostion** - getting the same state with differnt moves\n* **A strategy** - depth limted, but see all moves\n* **B strategy** - follow good moves to max depth\n* **Cutoff test** - test to determine alpha-beta search should stop\n* **Material value** - the worth of each component\n* **Quiescent** - stable state in a game, no moves can be taken\n* **Horizon effect** - using stalling to delay the inevitable\n* **Singular extension** - choosing the best move when you can\n* **Retrograde** - backwards search by reversing the rules\n* **Monte carlo tree search** - simulation run and the expected value is taken\n\n\n# Module 6: Constraint Satisfaction Problems\n## AIMA Chapter 6.1 Defining Constraint Satisfaction Problems\n \n3 components to csp: X (set of variables),D (set of domains f/variable), C (constraints, that allow combinations).\n \nEach constraint C_j made up of <scope, relation>\npair. EX:D = {1,2,3}, C = <(X_1, X_2), {(2,1), (3,1), (3,2)}>\n\nSolving a CSP is an NP-complete task.\n\nRepresenting CSPs as constraint graph is good where the nodes are the variables and edges are scopes\n\n3 Main Reasons for CSP: \n\n1. Easy to make a problem into a csp\n2. Much research put into csp to make fast and efficent\n3. Prune stace space(ss) faster than atomic ss searcher\nsss can only check if goal, but csp cuts down if states are bad\n\n.3 The simplest csp are those with discrete finite domains such as\nwith the 8-queens (1..8 limit and discrete).\n\nInfinite ex: no deadline on job scheudling, where implicit defintionsmust be used like described in the defintions.\n\nsolving general nonlinear constraints does not have algorithim,\nbut linear can\n\nContinuous domain real world like hubble where power values must\nmatch physical laws, best example is linear programming problemswhere constraints are linear (in)equalities.\n\nThe most common global constraint is Alldiff where a none of the variablescan be the same ex:sudoku (row, box, col).\n\nYou can get set of binary constraints if enough auxiliary variables are introduced for all finite-domain constraint.\n We can also do a dual graph transformation where we have 1 variablefor each constraint in the first graph and one binary constraint for each contraint pair.\n\n              \n\n## AIMA Chapter 6.2 Constraint Propagation: Inference in CSPs\n \nConstraint Propagation: Inference in CSPs:\natomic sss expand nodes to visit a successor while csps has choices based on\nnew variables. Our key idea is local consistency, where each variable is a node\nand binary constraint edge enforcing local consistency will make the rest of the \ngraph consisent.\n\n.1 Node Consistency \n\n Say we start with domain {red, green, blue}, if X does not like green we make \n domain for X, {red, blue} for node consistency.\n\n Some CSP will only solve binary constraints expecting the user to elimnate all other constraints\n because n-ary constraints can be turned into binary.\n\n.2 Arc Consistency\n\nThe most popular arc consistency algorithim is AC-3 which maintains a queue of arcs. \n\nAC-3 Pops off abitrary arc X_i/X_j and makes X_i arc-consistent to X_j. If the domain changes of X_i we queue all the arcs (X_k, X_i) and continue from there. O(cd^3) c=binary constraints, d=maxsizeof(domain)\n\n.3 Path Consistency\n\nPath consistency uses the implicit constraints by looking at triples of variables to tighten binary constraints.\n\nIf we have some X_m that satisfies {X_i, X_m} and {X_m, X_j} for {X_i =a, X_j=b} that satisfy the binary constraint then we are path consistent. The term comes from having X_m be the middle node of a path from X_i to X_j.  \n\n.4 K-Consistency\n\nIf we have n nodes that n-consistent we only need to seach d values for each node to find a consistent value so the run time is O(n^2 * d). \n\nThe issue with guarenteeing k-consistency is that the time is exponential to n in he worst case. And that space wouldalso run exponential to n. 2-consistency is the most common.\n\n.5 Global Constraints\n\nA simple way to decetect Alldiff incosistency is that if there are m variables and n values are possiblewhere m > n then becuase of pigeonhole there is a value that must be the same.\n\nThis gives an algorithim, that starts with removing variables that have a size 1 domain and removed this valuefrom the domain of all other variables. Continue until singleton values remain, if an empty domain is found then\nthere is an inconsistency.\n\nThere is also resource constraints which is also known as AtMost constraint. An example is withAtMost(10,X_1,X_2,X_3), we check the minium values of each variable and take the sum if the value of the minsumis greater than our atmost value then we have an inconsistencny. We can enforce this consistencyby removing the maximum value of one domain if it is not consistent with the minimum values of other variables\nFor large-resource limited problems with integer values, the domains are represented by upper and lower bounds\nEx Flights with capactiy [0, 165] and [0,385], if the flights total need 420 people then our domains become \n[35, 165] and [255,385] because the lower bounds match with the upper bound of the other.\n\n.6 Sudoku\n\nSkipping because it's just enforcing Alldiff for box, row and call, with arc consistency\n\n255,960 different path constraints for P-3\n\n\n\n## AIMA Chapter 6.3 Backtracking Search for CSPs\n \nAfter constraint propagation we might still have multiple values, so we have to search for the solution\n\nBacktracking search algorithims work on partial assignments.\nThe issue for using standard depth-limited search is that beacuse the branching factor O(nd) at the top level, so we would have n!d^n leaves. But we only have d^n possible assignments. We remove the n! factor by understanding that the csp's are commutative, at each level we choose a variable to deal with but never backtrack to over our choice\n\n.1 Variable and value ordering\n\nNeither picking a random variable or in order is optimal for select-unassigned-variableThe most straight forward idea is to chose the variable with the least legal moves, knownas minimum-remaning-values heurisitc (fail-first/most constrainted variable)\\ \nBy doing this we will run into failure faster and avoid pointless search\n\nDegree heurisitc(DH) helps choosing the first color beacuse MRV doesn't help with thatDH  tries to reduce the branching factor on the future by picking the variablethat is involved with the most constraintes on other unassigned variables.\n\nThe least-constraining-value heuristic is used as the method for selecting valuesafter getting a variable. It is to select the value that restrictsthe fewest neighbors in the constraint graph\n\nVariables selection is fail-first\n\nValue selection is fail-last\n\n.2 Interleaving search and inference\n\nForward checking this one of the most simple forms of inference. The algorithim goesas such: When x is assigned, for each Y that is in the Arc of X we delete any value fromY's domain that would cause X to be inconsistent. For many problems searching is more effecitiveif we use MRV and forward checking. \n\nForward checking does not detect all inconsistencies because it doesn't look far enough ahead\n\nMaintaing Arc Consistency (MAC) finds inconsistencies that forward checking can't findbecause of depth limitations. \n\nMAC after a X_i is assigned a value, the inference will call AC-3, but the queuewill only have the arcs of (X_j, X_i) for unassigned neighbors. And runs AC-3 normallyif the domain is empty of any variable, it will immediately backtrack. MAC is stronger,because forward checkign doesn't propagte constraints when changes are made to the domain.\n.3 Intelligent backtracking: Looking backward\n\nThe backtracking-search algorthim when there is failure will back up to the previous variablethen try a different value this is Chronological backtracking, because most recent decision is changed\n\nBackjumping is redudant in a foward-checking search.\nSometimes backjumping isn't enough so we have to do conflict-direct backjumpingwhich uses a new definition of conflict set that is the set of preecing variables thatcause a variable to not have a consistent solution\n.4 Constraint learning\n\nBackjumping tells us how far to back up when we reach a contradiction. To avoid running intothe same problem again we add constraints to not allow the no-good set value to be assigned.\n\n\n\n## AIMA Chapter 6.4 Local Search for CSPs\n\nLocal serach algorthims use a complete-state formulation where each stateassigns value to every variable. Then during the search one variable is changed at a time. We randomly chose a conflicted variable and slect a value using the min-conflict\\s\nheuristic. \n\nFor the n-queens problem, The run time of min-conflicts is roughly independent of problem size. And min-conflictsis effecitve for many CSP's. Hubble Space Telescope uses min-conflicts to reduce scheduling time 3weeks to 10 min.\n\nWith min-conflicts there can be Plateaus of states with the same score. So Pleateuasearch allows us to move sidways to another state to find a way off the plateau. This technique is called tabu search. Where we forbid the algorithim from returned to a small list of visted statesSimulated annealing can also be used\n\nContstraint Weighting focuses the search on important constraints.\n\nThe constraints are given a numerical weight, which all start at 1. During the searchThe algorithm chooses a variable to change that will result in the lowest total weight of all the \ninconsistent constraints. Then for all vilated constriantes by the assignemnt the weights are incremented\nn\n2 benefits:\n1. Topography to the plateaus\n2. Diffcult constraints are given higher weights\n\n\n## AIMA Chapter 6.5 The Structure of Problems\n \nIndependence can be found by finding connected components of the constraint graph.\n\nThe reason why we want to break down our problem is because we can get our run time down to O(d^c* n/c) where c is the number of connected components. \n\nConstraint graph is a tree when 2 variables are connected by only 1 path. Any tree-strucutredCSP(tsCSP) can be solved in linear time. The reason for this is because of direciton arc consistency (DAC).\nA csp is DAC if in an ordered X_1...X_n iff X_i is  arc-consistent j > i. \n\n\nWhen solving tsCSP we pick a variable to be our root and then have an ordering. We can usetoposort to order them. We can ake it arc consistent in O(nd^2). \n\n.1 Cutset conditioning\n\nOne way to reduce a constraint graph to a tree is to give a value to somevariables so that the remaining variables make a tree.\n\nWe would need to try each possible value that makes the graph a tree and then run the followingalgorithm.\n\n1. We select subset S that allows our graph to be a tree this is the cycle cutset\n2. For each assignemt for S that satisfies the constraints \n  a. remove the values from the domains that would cause inconsistents.\n  b. return the solution if the csp has one with S included\nthe total runtime would be O(d^c *(n-c)d^2). \nThis approach is called cutset conditioning.\n.2 Tree decomposition\n\nNow we can try tree decomposition which transforms the original graph into a tree where each node is a set of variables.\nThere are 3 conditions that must be met for a tree decomposition:\n1. In at least one of the tree nodes, every variable is present\n\n2. If two variables are connected by a a contraint then then must appear in at least one node together\n\n3. A variable must appear in every node in the path connecting notes if the variable appears in two nodes in the tree\n\n\nThe fist 2 conditions are to make sure that constraints and variables are witin the td.\n\nThe third is to force the variable to have the same value wherever it is.\n\nNow we can run Tree-CSP-Solver to get a solution in O(nd^2) time. n is the number of nodes\n\nThe goal of the decomp is to get as many small subproblems as possible. The tree width of td of a graphis the size of hte largest node - 1. The problem can be solved in O(nd^(w+1)).The issue is finding the minal tree width decopm is NP-hard.\n.3 Value symmetry\n\nValue symmetry is that for ever consistent oslution we can have d! solutions by permutingthe solution. So to avoid having to deal with the d!, we have symmetry-breaking constraint.\n\nThat will allow us to avoid branching. It is NP-hard to eliminate all symmetry, but it is important and effective\n \n\n## Module 6 Lecture Notes\n Your summary here \n\n## Module 6 Definitions\n* **Contstraint satisfication problem** - Problem represented as \n states having set of variables having values, solved when values for\n all variables fit contstraint \n* **Domain** - Allowable value for for variable X_i\n* **Scope** - Variables that are in the constraint\n* **Relation** - Give the values that the variables in the scope can have\n* **Consistent** - Legal assignment that does not violate any constraints\n* **Complete assignment** - Every variable is assigned a value\n* **Solution** - Consistent and Complete Assignment \n* **Precidence constraints** - If a task has to happen before another with a duration we have T_1 + d <= T_2\n* **Disjunctive contraint** - When 2 tasks cannot occur at the same time (t + d) < t2 or (t2+d) < t\n* **Unary constraint** - When a constraint is not allow for single variable <X, X!= green>\n* **Binary constriant** - When a constraint relates 2 variables <(X_1, X_2), X_2 != X_1>\n* **Binary csp** - CSP that only uses unary and binary constraints\n* **Global constraint** - constraint that considers an abitrary number of variables\n* **Cryptarithmetic puzzle** - Each letter represents a different digit\n* **Constraint hypergraph** - graph of nodes and hypernodes(squares) that indicate n-ary constraints\n* **Perfernce constraints** - Contraint that is allowable, but not optimal\n* **Constrained optimization problem** - CSPs with perfernce solved with optimization, perfernce indicated by cost on variable\n* **Constraint propagation** - reducing legal values using contraints, then reducing the legal values for another variable using new values\n* **Node-consistent** - For the unary constraints, if all values satisfy\n* **Arc-consistent** - Domain satisfies binary constraints\n* **K-consistency** - If for any k-1 variables, being able to assign the k-th variable to keep everything consistent\n* **Strongly k-consistent** - 1 to k-consistent\n* **Bounds-consistent** - For upper and lower bounds of X there is value between X and Y that satisfies contraints for every Y\n* **Conflict set** - Set of variables and values that conflict with another variable\n* **Backjumping** - backtracking to the most recently assigned in the conflict set\n* **Constraint learning** - From the conflict set, finding the minimum set of variables that cause a problem\n* **No-good** - Set of variablese that caused the problem found in constraint learning.\n\n\n# Module 7: Logical Agents\n## AIMA Chapter 7.1 Knowledge-Based Agents\n Your summary here \n\n## AIMA Chapter 7.2 The Wumpus World\n Your summary here \n\n## AIMA Chapter 7.3 Logic\n Your summary here \n\n## AIMA Chapter 7.4 Propositional Logic: A Very Simple Logic\n Your summary here \n\n## AIMA 7.5 Propositional Theorem Proving\n Your summary here \n\n## Module 7 Lecture Notes\n Your summary here \n\n## Module 7 Definitions\n* **Concept** - definition\n",
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "metadata": {}
        }
      ]
    }
  ]
}