{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "040f1c5f",
   "metadata": {},
   "source": [
    "# 🧩 Constraint solving in Python\n",
    "\n",
    "In the chapter [Logic](https://ai.kuleuven.be/aivooriedereen/en/logic), you wrote rules down in logic and let a solver find the possible worlds in which they all hold. This notebook shows what that looks like in code. You describe *what* a good solution looks like, and the solver figures out *how* to find one.\n",
    "\n",
    "You will do that twice:\n",
    "\n",
    "1. 🎁 to draw names for Secret Santa, with the rules of your own group of friends;\n",
    "2. 🗓️ to build a full week of lectures for a small faculty, with rules for students, teachers and rooms, and wishes that pull in different directions.\n",
    "\n",
    "**Prior knowledge**: the chapter [Logic](https://ai.kuleuven.be/aivooriedereen/en/logic), in particular the parts on [SAT solvers](https://ai.kuleuven.be/aivooriedereen/en/logic#sat-solver) and [constraint problems](https://ai.kuleuven.be/aivooriedereen/en/logic#constraint-satisfaction-problems). You don't need any programming experience: you can run the whole notebook without changing a single line, and the exercises only ask you to change small pieces.\n",
    "\n",
    "**Estimated time**: about 45 minutes, without the exercises.\n",
    "\n",
    "*This notebook is part of [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en) (KU Leuven). The latest version is always at [ai.kuleuven.be/aivooriedereen/en/notebook/constraint-solving](https://ai.kuleuven.be/aivooriedereen/en/notebook/constraint-solving), and you can open it directly in [Google Colab](https://colab.research.google.com/drive/1gbgw4qjbUQxacrcRsuCjMwyst7JTcXyA?usp=sharing).*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c754f33",
   "metadata": {},
   "source": [
    "## 🚀 First time in a notebook?\n",
    "\n",
    "Then the short [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains everything step by step. The most important things:\n",
    "\n",
    "1. **Make your own copy**: *File → Save a copy in Drive* (in the menu at the top left), and work in that copy.\n",
    "2. **Run a cell** by clicking in it and pressing **Shift+Enter**, or with the ▶ button to its left. The result appears below the cell.\n",
    "3. **Run the cells in order, from top to bottom**, because a cell uses what the cells above it made. Does something behave strangely? Choose *Runtime → Restart session* and run everything again from the top.\n",
    "\n",
    "**Prefer not to use Google?** Download [the notebook file](https://ai.kuleuven.be/aivooriedereen/notebooks/constraint-solving.ipynb) and open it in [Jupyter](https://jupyter.org/install) or [Visual Studio Code](https://code.visualstudio.com/docs/datascience/jupyter-notebooks)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ee3a5cc",
   "metadata": {},
   "source": [
    "## 🐍 Python in this notebook\n",
    "\n",
    "New to Python? The [introductory notebook](https://ai.kuleuven.be/aivooriedereen/en/notebook/python-basics) explains the basics: variables, lists, dictionaries, loops and functions. On top of those, this notebook uses:\n",
    "\n",
    "| Code | Meaning |\n",
    "| --- | --- |\n",
    "| `f\"{person} buys a present\"` | An **f-string**: Python fills in the value of `person` between the braces, for example `\"Anna buys a present\"`. |\n",
    "| `[2 * n for n in numbers]` | A list built in one line: every number in `numbers`, doubled. Add `if ...` at the end to keep only some items. You will see this a lot inside `cp.sum([...])`. |\n",
    "| `buys_for[\"Anna\", \"Bram\"]` | A **dictionary** that you look up with two names instead of one, like a row and a column in a table. Later on, `when[\"Calculus\", \"Mon\", \"08:30\"]` takes three. |\n",
    "| `me = \"Anna\"  # @param [...]` | A comment that Colab turns into an input next to the code: a text field, a dropdown or a slider. In other notebook programs it is just a comment. |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16610862",
   "metadata": {},
   "source": [
    "## 📦 Install the solver\n",
    "\n",
    "You will use [CPMpy](https://cpmpy.readthedocs.io), a free Python library developed at KU Leuven. You write the rules in Python, and CPMpy passes them on to a solver that searches for a solution. The cell below installs CPMpy and two solvers: OR-Tools, the fastest, and Z3, for computers that have no version of OR-Tools (such as Windows laptops with an ARM processor). On such a computer, the last line ends with an error: no problem, the notebook then uses Z3. The installation takes about half a minute."
   ]
  },
  {
   "cell_type": "code",
   "id": "fcdb3b42",
   "metadata": {},
   "source": [
    "# Colab comes with HiGHS, another solver that can't be loaded together with OR-Tools: remove it first\n",
    "%pip uninstall --quiet --yes highspy\n",
    "# CPMpy itself (--no-deps: without OR-Tools for now, see the last line)\n",
    "%pip install --quiet --no-deps cpmpy==1.1.0\n",
    "# what CPMpy and this notebook use, including the solver Z3\n",
    "%pip install --quiet numpy packaging pandas z3-solver\n",
    "# the fastest solver, OR-Tools (an error here means your computer has no version of it)\n",
    "%pip install --quiet ortools"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "65e296c6",
   "metadata": {},
   "source": [
    "import cpmpy as cp\n",
    "from cpmpy.tools.explain import mus\n",
    "\n",
    "# the solver for the rest of the notebook: OR-Tools if it is installed, otherwise Z3\n",
    "SOLVER = \"ortools\" if cp.SolverLookup.lookup(\"ortools\").supported() else \"z3\"\n",
    "print(\"Solver:\", SOLVER)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "60edd31b",
   "metadata": {},
   "source": [
    "## 🎁 Secret Santa\n",
    "\n",
    "Christmas is coming, and with it **Secret Santa** (in Flanders: *lootjes trekken*): everyone in a group of friends draws a name and secretly buys a present for that person. Drawing names from a hat works fine, until the group adds rules: couples don't want to draw each other, and whoever draws their own name has to start over. A solver takes all those rules into account at once.\n",
    "\n",
    "The group: the four friends from the party in the chapter, Anna, Bram, Caroline and David, and four more: Eric, Freya, Gilles and Helena.\n",
    "\n",
    "### 🔣 One proposition per pair\n",
    "\n",
    "As in the chapter, you start with **propositions**: statements that are true or false. Here you need one for every pair of friends, such as *\"Anna buys a present for Bram\"*. With eight friends, that makes 8 × 8 = 64 propositions.\n",
    "\n",
    "`cp.boolvar` creates such a proposition (a *Boolean variable*: true or false, but the solver still has to decide which). The dictionary `buys_for` stores them all, so that `buys_for[\"Anna\", \"Bram\"]` is the proposition *\"Anna buys a present for Bram\"*."
   ]
  },
  {
   "cell_type": "code",
   "id": "02e0fce2",
   "metadata": {},
   "source": [
    "people = [\"Anna\", \"Bram\", \"Caroline\", \"David\", \"Eric\", \"Freya\", \"Gilles\", \"Helena\"]\n",
    "\n",
    "buys_for = {}\n",
    "for giver in people:\n",
    "    for receiver in people:\n",
    "        # the proposition \"giver buys a present for receiver\": true or false\n",
    "        buys_for[giver, receiver] = cp.boolvar(name=f\"{giver}→{receiver}\")\n",
    "\n",
    "print(len(buys_for), \"propositions, for example\", buys_for[\"Anna\", \"Bram\"])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "78482869",
   "metadata": {},
   "source": [
    "Most CPMpy code, like [its documentation](https://cpmpy.readthedocs.io/en/latest/modeling.html), makes a matrix of variables here instead: `buys_for = cp.boolvar(shape=(8, 8))`, with a row for every giver and a column for every receiver. That one line replaces both loops, and `buys_for[0, :]` gives you the whole row of Anna at once. But you then have to look everything up by number, with `buys_for[0, 1]` for *\"Anna buys a present for Bram\"*, and remember who is who. This notebook uses names because they read more easily.\n",
    "\n",
    "### 📜 The rules\n",
    "\n",
    "Rules are formulas over these propositions. CPMpy writes the operators from the chapter like this, with `A` and `B` two propositions:\n",
    "\n",
    "| Logic | CPMpy | Meaning |\n",
    "| --- | --- | --- |\n",
    "| $\\lnot A$ | `~A` | not A |\n",
    "| ${A \\land B}$ | `A & B` | A and B |\n",
    "| ${A \\lor B}$ | `A \\| B` | A or B (or both) |\n",
    "| ${A \\to B}$ | `A.implies(B)` | if A, then B |\n",
    "| | `cp.sum([A, B, C]) == 1` | exactly one of A, B and C is true |\n",
    "| | `cp.sum([A, B, C]) <= 1` | at most one of them is true |\n",
    "\n",
    "The last two rows count: `cp.sum` adds up propositions, with true as 1 and false as 0. You could write *\"exactly one\"* with the operators alone, but that takes a pile of clauses (see [translating to propositional logic](https://ai.kuleuven.be/aivooriedereen/en/logic#translation-to-propositional-logic) in the chapter); the solver understands the count directly.\n",
    "\n",
    "The draw has six rules. The first three make it a valid draw; the last three are wishes of the group, with a \"not\", an \"if ... then\" and an \"or\", just like the rules of the party in the chapter:\n",
    "\n",
    "1. Everyone buys exactly one present.\n",
    "2. Everyone gets exactly one present.\n",
    "3. Nobody draws their own name.\n",
    "4. Couples don't draw each other: they buy each other a present anyway. Anna and Bram are a couple, just like in the chapter, and so are Freya and Gilles.\n",
    "5. No swaps: if Caroline buys for David, David doesn't buy for Caroline, so that no two friends simply trade presents with each other. That is an implication for every pair.\n",
    "6. Gilles is new in the group. Apart from Freya, he only knows Anna, David and Helena well, so he buys for one of those three. That is a clause, just like *\"Caroline or David comes\"* in the chapter.\n",
    "\n",
    "`cp.Model()` makes an empty **model**, and `santa += ...` adds a rule to it. The comments in the code refer to the rules by their number."
   ]
  },
  {
   "cell_type": "code",
   "id": "c80c0562",
   "metadata": {},
   "source": [
    "santa = cp.Model()\n",
    "for person in people:\n",
    "    # Rule 1: everyone buys exactly one present\n",
    "    santa += (cp.sum([buys_for[person, receiver] for receiver in people]) == 1)\n",
    "    # Rule 2: everyone gets exactly one present\n",
    "    santa += (cp.sum([buys_for[giver, person] for giver in people]) == 1)\n",
    "    # Rule 3: nobody draws their own name\n",
    "    santa += ~buys_for[person, person]\n",
    "\n",
    "# Rule 4: couples don't draw each other\n",
    "santa += ~buys_for[\"Anna\", \"Bram\"] & ~buys_for[\"Bram\", \"Anna\"]\n",
    "santa += ~buys_for[\"Freya\", \"Gilles\"] & ~buys_for[\"Gilles\", \"Freya\"]\n",
    "\n",
    "# Rule 5: no swaps\n",
    "for a in people:\n",
    "    for b in people:\n",
    "        if a < b:  # alphabetical order: every pair once\n",
    "            santa += buys_for[a, b].implies(~buys_for[b, a])\n",
    "\n",
    "# Rule 6: Gilles buys for Anna, David or Helena\n",
    "santa += buys_for[\"Gilles\", \"Anna\"] | buys_for[\"Gilles\", \"David\"] | buys_for[\"Gilles\", \"Helena\"]\n",
    "\n",
    "print(len(santa.constraints), \"rules, for example:\")\n",
    "print(santa.constraints[0])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "43297bd5",
   "metadata": {},
   "source": [
    "### 🎲 Let the solver draw\n",
    "\n",
    "Now ask the solver for a solution of the model: a value, true or false, for every proposition, such that all rules hold. In the words of the chapter: a possible world. `solve()` gives back `True` if it found one, and from then on `.value()` gives the value of each proposition in that world. There are thousands of valid draws; the solver gives back the first one it finds."
   ]
  },
  {
   "cell_type": "code",
   "id": "e1959f36",
   "metadata": {},
   "source": [
    "if santa.solve(solver=SOLVER):\n",
    "    for giver in people:\n",
    "        for receiver in people:\n",
    "            if buys_for[giver, receiver].value():\n",
    "                print(f\"🎁 {giver} buys a present for {receiver}\")\n",
    "else:\n",
    "    print(\"No draw satisfies all rules.\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "48254d47",
   "metadata": {},
   "source": [
    "**Try it yourself**\n",
    "\n",
    "- Use it for your own group: change the names in `people` and rules 4 to 6, and run the cells again from 🔣 One proposition per pair.\n",
    "- Add a rule that clashes with rule 4: `santa += buys_for[\"Anna\", \"Bram\"]`, and run the draw again. What does the solver say? Run the cell with the rules again to get rid of it.\n",
    "- Add a rule of your own: nobody draws the same person as last year. If Anna drew Caroline last year: `santa += ~buys_for[\"Anna\", \"Caroline\"]`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3dff4f97",
   "metadata": {},
   "source": [
    "## 🗓️ A timetable for a whole faculty\n",
    "\n",
    "Secret Santa had 64 propositions and a few dozen rules. A weekly timetable for a faculty is the same kind of puzzle, only bigger: every course needs its lectures, nobody can be in two places at once, every lecture needs a room, and everyone has wishes on top of that. Universities, schools and hospitals use solvers like this one for their timetables.\n",
    "\n",
    "### 📋 The faculty\n",
    "\n",
    "A small, made-up faculty:\n",
    "\n",
    "- 🗓️ a week of 5 days, each with 4 time slots of two hours: at 08:30, 10:30, 13:30 and 15:30;\n",
    "- 🏛️ 4 rooms, from Aula A with 250 seats to Room D with 50;\n",
    "- 🎓 6 student groups, such as *Engineering 1*: the 130 first-year engineering students;\n",
    "- 📚 15 courses, each with a teacher, a number of lectures a week and the groups that follow it. Some courses are shared: all first-year students follow Calculus together.\n",
    "\n",
    "All data is in the cell below, so you can change it later: add a course, or make a room smaller. The lines below the data look up, for every course, how many students follow it, and list the courses of every group and every teacher. The table at the end shows the courses."
   ]
  },
  {
   "cell_type": "code",
   "id": "a8dd3aca",
   "metadata": {},
   "source": [
    "import pandas as pd\n",
    "from IPython.display import HTML\n",
    "\n",
    "DAYS = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\"]\n",
    "TIMES = [\"08:30\", \"10:30\", \"13:30\", \"15:30\"]\n",
    "ROOMS = {\"Aula A\": 250, \"Aula B\": 150, \"Room C\": 80, \"Room D\": 50}  # room: seats\n",
    "GROUPS = {\"Engineering 1\": 130, \"Computer Science 1\": 70, \"Chemistry 1\": 40,  # group: students\n",
    "          \"Engineering 2\": 110, \"Computer Science 2\": 60, \"Chemistry 2\": 35}\n",
    "COURSES = [\n",
    "    # course                 teacher     lectures a week, followed by\n",
    "    (\"Calculus\",             \"Peeters\",  3, [\"Engineering 1\", \"Computer Science 1\", \"Chemistry 1\"]),\n",
    "    (\"Linear Algebra\",       \"Jacobs\",   2, [\"Engineering 1\", \"Computer Science 1\"]),\n",
    "    (\"Physics\",              \"Janssens\", 2, [\"Engineering 1\", \"Chemistry 1\"]),\n",
    "    (\"Programming\",          \"Maes\",     2, [\"Engineering 1\", \"Computer Science 1\"]),\n",
    "    (\"General Chemistry\",    \"Mertens\",  2, [\"Engineering 1\", \"Chemistry 1\"]),\n",
    "    (\"Discrete Mathematics\", \"Peeters\",  2, [\"Computer Science 1\"]),\n",
    "    (\"Organic Chemistry\",    \"Willems\",  2, [\"Chemistry 1\"]),\n",
    "    (\"Mechanics\",            \"Janssens\", 2, [\"Engineering 2\"]),\n",
    "    (\"Electronics\",          \"Claes\",    2, [\"Engineering 2\"]),\n",
    "    (\"Thermodynamics\",       \"Goossens\", 2, [\"Engineering 2\", \"Chemistry 2\"]),\n",
    "    (\"Statistics\",           \"Wouters\",  2, [\"Engineering 2\", \"Computer Science 2\", \"Chemistry 2\"]),\n",
    "    (\"Algorithms\",           \"Maes\",     2, [\"Computer Science 2\"]),\n",
    "    (\"Databases\",            \"Claes\",    1, [\"Computer Science 2\"]),\n",
    "    (\"Analytical Chemistry\", \"Willems\",  2, [\"Chemistry 2\"]),\n",
    "    (\"Ethics\",               \"De Smet\",  1, [\"Engineering 2\", \"Computer Science 2\", \"Chemistry 2\"]),\n",
    "]\n",
    "\n",
    "courses = []             # the names of all courses\n",
    "teacher = {}             # teacher[\"Calculus\"] is \"Peeters\"\n",
    "lectures = {}            # lectures[\"Calculus\"] is 3\n",
    "students = {}            # students[\"Calculus\"] is 240: all students of its groups together\n",
    "courses_of_group = {}    # courses_of_group[\"Engineering 1\"]: the courses that group follows\n",
    "courses_of_teacher = {}  # courses_of_teacher[\"Peeters\"]: the courses Peeters teaches\n",
    "for course, prof, number, groups in COURSES:\n",
    "    courses.append(course)\n",
    "    teacher[course] = prof\n",
    "    lectures[course] = number\n",
    "    students[course] = sum([GROUPS[group] for group in groups])\n",
    "    for group in groups:\n",
    "        courses_of_group.setdefault(group, []).append(course)  # setdefault: start an empty list the first time\n",
    "    courses_of_teacher.setdefault(prof, []).append(course)\n",
    "\n",
    "print(len(courses), \"courses,\", sum(lectures.values()), \"lectures a week\")\n",
    "overview = pd.DataFrame(COURSES, columns=[\"course\", \"teacher\", \"lectures a week\", \"followed by\"]).set_index(\"course\")\n",
    "overview[\"students\"] = [students[course] for course in courses]\n",
    "HTML(overview.to_html())"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "cb2d14f4",
   "metadata": {},
   "source": [
    "### 🔣 Propositions: when and where\n",
    "\n",
    "Two kinds of propositions describe a timetable:\n",
    "\n",
    "- `when[course, day, time]`: *\"Calculus has a lecture on Monday at 08:30\"*. That's 15 courses × 5 days × 4 time slots = 300 propositions.\n",
    "- `where[course, room]`: *\"Calculus is taught in Aula A\"*, in the same room all week. That's 15 × 4 = 60 propositions.\n",
    "\n",
    "A solution makes each of these 360 propositions true or false. That gives $2^{360}$ candidate timetables, a number with 109 digits. No truth table will ever list them all, but the solver doesn't need one."
   ]
  },
  {
   "cell_type": "code",
   "id": "6f460e1f",
   "metadata": {},
   "source": [
    "when = {}\n",
    "for course in courses:\n",
    "    for day in DAYS:\n",
    "        for time in TIMES:\n",
    "            when[course, day, time] = cp.boolvar(name=f\"{course} {day} {time}\")\n",
    "\n",
    "where = {}\n",
    "for course in courses:\n",
    "    for room in ROOMS:\n",
    "        where[course, room] = cp.boolvar(name=f\"{course} in {room}\")\n",
    "\n",
    "print(len(when) + len(where), \"propositions\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "31bf4000",
   "metadata": {},
   "source": [
    "### 🧰 Helper functions\n",
    "\n",
    "- `count_lectures(course_list, days, times)` counts the lectures of some courses on some days and times. Most rules below are a condition on such a count: Calculus has 3 lectures a week, *Engineering 1* has at most 1 lecture on Monday at 08:30, and so on.\n",
    "- `rule(sentence, formula)` gives a formula a sentence in plain language, with CPMpy's `set_description`. `print` then shows the sentence, and `repr` still the formula. That will let the solver explain itself in sentences later on.\n",
    "- `solve(model)` asks the solver for a timetable that satisfies all rules of the model.\n",
    "- `show_week(group)` shows the week of one student group, and `show_faculty()` the week of the whole faculty, with a row for every time slot and room. Every lecture shows its teacher, its room with the number of students next to the number of seats (in red if they don't fit), and the groups that follow it. A red block means that a group has two lectures at once.\n",
    "\n",
    "Only the code of `count_lectures` and `rule` matters for what follows. For the other functions, it's enough to know what they do."
   ]
  },
  {
   "cell_type": "code",
   "id": "4c727a75",
   "metadata": {},
   "source": [
    "def count_lectures(course_list, days, times):\n",
    "    \"\"\"How many lectures of these courses fall on these days, at these times?\"\"\"\n",
    "    return cp.sum([when[course, day, time] for course in course_list for day in days for time in times])\n",
    "\n",
    "\n",
    "def rule(sentence, formula):\n",
    "    \"\"\"A formula with a sentence: print(...) now shows the sentence, repr(...) still the formula.\"\"\"\n",
    "    formula.set_description(sentence)\n",
    "    return formula\n",
    "\n",
    "\n",
    "def solve(model, penalty=None, seconds=30):\n",
    "    \"\"\"Look for a timetable that satisfies all rules of the model (and has the lowest penalty, if you give one).\"\"\"\n",
    "    attempt = model.copy()  # a copy, so that the penalty doesn't stay in the model\n",
    "    if penalty is not None:\n",
    "        attempt.minimize(penalty)\n",
    "    found = attempt.solve(solver=SOLVER, time_limit=seconds)\n",
    "    if not found:\n",
    "        print(\"❌ No timetable satisfies all\", len(model.constraints), \"rules.\")\n",
    "    elif penalty is None:\n",
    "        print(\"✅ A timetable that satisfies all\", len(model.constraints), \"rules.\")\n",
    "    elif attempt.status().exitstatus.name == \"OPTIMAL\":\n",
    "        print(\"✅ The best possible timetable: a penalty of\", penalty.value(), \"points.\")\n",
    "    else:\n",
    "        print(\"✅ The best timetable found in\", seconds, \"seconds: a penalty of\", penalty.value(), \"points.\")\n",
    "\n",
    "\n",
    "COLORS = [\"#dbeafe\", \"#dcfce7\", \"#fef9c3\", \"#ffedd5\", \"#f3e8ff\", \"#cffafe\", \"#fce7f3\", \"#e0e7ff\",\n",
    "          \"#ecfccb\", \"#fae8ff\", \"#ccfbf1\", \"#fef3c7\", \"#e0f2fe\", \"#d1fae5\", \"#ede9fe\"]\n",
    "# Every style sits on the element itself, so that a dark notebook theme can't change it\n",
    "CELL = \"border: 1px solid #9ca3af; padding: 2px; width: 104px; vertical-align: top; text-align: center\"\n",
    "HEAD = \"padding: 4px 8px; text-align: center\"\n",
    "\n",
    "\n",
    "def room_of(course):\n",
    "    \"\"\"The room the solver gave this course, or None if it has no room yet.\"\"\"\n",
    "    for room in ROOMS:\n",
    "        if where[course, room].value():\n",
    "            return room\n",
    "    return None\n",
    "\n",
    "\n",
    "def lecture(course, clash=False):\n",
    "    \"\"\"One lecture as a colored block: course, teacher, room: students/seats, groups.\"\"\"\n",
    "    room = room_of(course)\n",
    "    if room is None:  # no rooms yet\n",
    "        seats = f\"{students[course]} students\"\n",
    "    elif students[course] > ROOMS[room]:  # not enough seats: in red\n",
    "        seats = f\"{room}: <b style='color: #b91c1c'>{students[course]}/{ROOMS[room]}</b>\"\n",
    "    else:\n",
    "        seats = f\"{room}: {students[course]}/{ROOMS[room]}\"\n",
    "    # the groups that follow the course, with short names (Eng 1, CS 1, Chem 1, ...) that never break\n",
    "    groups = [g for g in GROUPS if course in courses_of_group[g]]\n",
    "    groups = \" · \".join(g.replace(\"Engineering\", \"Eng\").replace(\"Computer Science\", \"CS\")\n",
    "                        .replace(\"Chemistry\", \"Chem\").replace(\" \", \"&nbsp;\") for g in groups)\n",
    "    color = \"#fecaca\" if clash else COLORS[courses.index(course) % len(COLORS)]  # red: two lectures at once\n",
    "    return (f\"<div style='background: {color}; color: #111827; padding: 3px 4px; margin: 1px 0; font-size: 11.5px; \"\n",
    "            f\"line-height: 1.3; text-align: center'><b>{course}</b><br>Prof. {teacher[course]}<br>{seats}<br>\"\n",
    "            f\"<span style='color: #374151; font-size: 10.5px'>{groups}</span></div>\")\n",
    "\n",
    "\n",
    "def table(title, header, rows):\n",
    "    \"\"\"An HTML table with a title above it.\"\"\"\n",
    "    caption = (f\"<caption style='font-size: 15px; font-weight: bold; padding: 6px'>{title}<br>\"\n",
    "               \"<span style='font-size: 12px; font-weight: normal'>\"\n",
    "               \"per lecture: course, teacher, room: students/seats, groups</span></caption>\")\n",
    "    return HTML(f\"<table style='border-collapse: collapse; font-family: Helvetica, Arial, sans-serif'>\"\n",
    "                f\"{caption}{header}{rows}</table>\")\n",
    "\n",
    "\n",
    "def show_week(group):\n",
    "    \"\"\"The week of one student group: the times as rows, the days as columns.\"\"\"\n",
    "    rows = \"\"\n",
    "    for time in TIMES:\n",
    "        cells = \"\"\n",
    "        for day in DAYS:\n",
    "            here = [course for course in courses_of_group[group] if when[course, day, time].value()]\n",
    "            blocks = \"\".join(lecture(course, clash=len(here) > 1) for course in here)\n",
    "            cells += f\"<td style='{CELL}; height: 72px'>{blocks}</td>\"\n",
    "        rows += f\"<tr><th style='{HEAD}'>{time}</th>{cells}</tr>\"\n",
    "    header = f\"<tr><th style='{HEAD}'></th>\" + \"\".join(f\"<th style='{HEAD}'>{day}</th>\" for day in DAYS) + \"</tr>\"\n",
    "    return table(f\"Week of {group}\", header, rows)\n",
    "\n",
    "\n",
    "def show_faculty():\n",
    "    \"\"\"The week of the whole faculty: a row for every time slot and room, the days as columns.\"\"\"\n",
    "    rows = \"\"\n",
    "    for time in TIMES:\n",
    "        for room in ROOMS:\n",
    "            cells = \"\"\n",
    "            for day in DAYS:\n",
    "                here = [course for course in courses if when[course, day, time].value() and room_of(course) == room]\n",
    "                cells += f\"<td style='{CELL}'>{''.join(lecture(course) for course in here)}</td>\"\n",
    "            time_cell = f\"<th style='{HEAD}' rowspan='{len(ROOMS)}'>{time}</th>\" if room == list(ROOMS)[0] else \"\"\n",
    "            rows += f\"<tr>{time_cell}<th style='{HEAD}; font-weight: normal'>{room}</th>{cells}</tr>\"\n",
    "    header = f\"<tr><th style='{HEAD}'></th><th style='{HEAD}'></th>\" + \"\".join(f\"<th style='{HEAD}'>{day}</th>\" for day in DAYS) + \"</tr>\"\n",
    "    return table(\"Week of the whole faculty\", header, rows)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "25e39681",
   "metadata": {},
   "source": [
    "### 1️⃣ Every course gets its lectures\n",
    "\n",
    "Start with a new model, with one rule per course: Calculus has 3 lectures a week, Physics 2, and so on. There will be many more rules than for Secret Santa, so every rule gets a sentence with the function `rule`."
   ]
  },
  {
   "cell_type": "code",
   "id": "abed8f41",
   "metadata": {},
   "source": [
    "lecture_rules = cp.Model()\n",
    "for course in courses:\n",
    "    lecture_rules += rule(f\"{course} has {lectures[course]} lectures a week\",\n",
    "                          count_lectures([course], DAYS, TIMES) == lectures[course])\n",
    "\n",
    "solve(lecture_rules)\n",
    "show_week(\"Engineering 1\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ae019bfe",
   "metadata": {},
   "source": [
    "The solver did exactly what you asked, and nothing more: every course has the right number of lectures, but *Engineering 1* has several lectures at the same time (the red blocks), and no course has a room. Nobody told the solver that's a problem. That's typical: the most obvious rules are the ones you forget to write down.\n",
    "\n",
    "### 2️⃣ All the other rules\n",
    "\n",
    "A real timetable needs a few more rules:\n",
    "\n",
    "- a student group follows at most one lecture at a time, and a teacher teaches at most one;\n",
    "- a course has at most one lecture a day: three lectures of Calculus on a single Monday would be too much;\n",
    "- every course gets one room for the whole week, with enough seats for all its students;\n",
    "- a room hosts at most one lecture at a time. Calculus has a lecture in Aula A on Monday at 08:30 if `when[\"Calculus\", \"Mon\", \"08:30\"]` and `where[\"Calculus\", \"Aula A\"]` are both true: `when[...] & where[...]`;\n",
    "- and a wish of a teacher: Prof. Maes can't teach on Wednesdays, so the number of lectures of Maes's courses on Wednesday has to be 0.\n",
    "\n",
    "The function `at_most_one_at_a_time` makes a formula for every one of the 20 moments of the week, and `cp.all` combines those into one rule that holds if all of them do."
   ]
  },
  {
   "cell_type": "code",
   "id": "d6268e00",
   "metadata": {},
   "source": [
    "def at_most_one_at_a_time(course_list):\n",
    "    \"\"\"A formula: at every moment of the week, at most one of these courses has a lecture.\"\"\"\n",
    "    moments = []\n",
    "    for day in DAYS:\n",
    "        for time in TIMES:\n",
    "            moments.append(count_lectures(course_list, [day], [time]) <= 1)\n",
    "    return cp.all(moments)\n",
    "\n",
    "\n",
    "timetable = lecture_rules.copy()  # a copy of the rules so far, with all the other rules on top\n",
    "\n",
    "# nobody in two places at once\n",
    "for group in GROUPS:\n",
    "    timetable += rule(f\"{group} follows at most one lecture at a time\",\n",
    "                      at_most_one_at_a_time(courses_of_group[group]))\n",
    "for prof in courses_of_teacher:\n",
    "    timetable += rule(f\"Prof. {prof} teaches at most one lecture at a time\",\n",
    "                      at_most_one_at_a_time(courses_of_teacher[prof]))\n",
    "\n",
    "# at most one lecture of a course a day\n",
    "for course in courses:\n",
    "    timetable += rule(f\"{course} has at most one lecture a day\",\n",
    "                      cp.all([count_lectures([course], [day], TIMES) <= 1 for day in DAYS]))\n",
    "\n",
    "# one room per course, with enough seats\n",
    "for course in courses:\n",
    "    timetable += rule(f\"{course} has one room all week\",\n",
    "                      cp.sum([where[course, room] for room in ROOMS]) == 1)\n",
    "    too_small = [~where[course, room] for room in ROOMS if students[course] > ROOMS[room]]  # the rooms it doesn't fit in\n",
    "    if too_small:\n",
    "        timetable += rule(f\"{course} only gets a room with enough seats\",\n",
    "                          cp.all(too_small))\n",
    "\n",
    "# one lecture at a time in every room\n",
    "for room in ROOMS:\n",
    "    moments = []\n",
    "    for day in DAYS:\n",
    "        for time in TIMES:\n",
    "            in_this_room = [when[course, day, time] & where[course, room] for course in courses]\n",
    "            moments.append(cp.sum(in_this_room) <= 1)\n",
    "    timetable += rule(f\"{room} hosts at most one lecture at a time\",\n",
    "                      cp.all(moments))\n",
    "\n",
    "# a wish of a teacher\n",
    "timetable += rule(\"Prof. Maes doesn't teach on Wednesdays\",\n",
    "                  count_lectures(courses_of_teacher[\"Maes\"], [\"Wed\"], TIMES) == 0)\n",
    "\n",
    "solve(timetable)\n",
    "show_week(\"Engineering 1\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "4b5ffd92",
   "metadata": {},
   "source": [
    "A valid timetable: *Engineering 1* follows one lecture at a time, the lectures of a course are spread over the week, and every course has a room that is big enough.\n",
    "\n",
    "### 🚫 An impossible wish\n",
    "\n",
    "Prof. Peeters would like to teach on Tuesdays and Thursdays only. Try that wish on a copy of the model, `with_wish`, so that `timetable` itself stays as it is."
   ]
  },
  {
   "cell_type": "code",
   "id": "6aa18110",
   "metadata": {},
   "source": [
    "with_wish = timetable.copy()  # a copy of the rules so far ...\n",
    "with_wish += rule(\"Prof. Peeters only teaches on Tuesdays and Thursdays\",  # ... plus the wish\n",
    "                  count_lectures(courses_of_teacher[\"Peeters\"], [\"Mon\", \"Wed\", \"Fri\"], TIMES) == 0)\n",
    "\n",
    "solve(with_wish)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "ca83a916",
   "metadata": {},
   "source": [
    "### 🔍 Why not?\n",
    "\n",
    "With this many rules, you won't find the problem by reading them all. But the solver can tell you. `mus` (short for *minimal unsatisfiable subset*) looks for a set of rules that can't all hold at the same time, and that is as small as possible: drop any one rule from it, and the others can hold together again. That is one of the strengths of logic: the solver doesn't just say *no*, it can show you why. The function `explain` prints the sentences of those rules."
   ]
  },
  {
   "cell_type": "code",
   "id": "e6807371",
   "metadata": {},
   "source": [
    "def explain(model):\n",
    "    \"\"\"Print a set of rules that can't all hold together; drop any one of them and the rest can.\"\"\"\n",
    "    for conflict in mus(soft=model.constraints, solver=SOLVER):\n",
    "        print(\"❌\", conflict)  # print shows the sentence of the rule\n",
    "\n",
    "\n",
    "explain(with_wish)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "9f118a44",
   "metadata": {},
   "source": [
    "Calculus needs three lectures on three different days, and Prof. Peeters teaches it, but Tuesday and Thursday are only two days. None of the other rules has anything to do with it. The wish only went into the copy `with_wish`, so `timetable` still has a solution. Below, the wish comes back in a milder form."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "880833c5",
   "metadata": {},
   "source": [
    "### ⚖️ Preferences\n",
    "\n",
    "Many wishes aren't strict. Prof. Peeters *prefers* Tuesdays and Thursdays, and students *prefer* not to start at 08:30. Such a wish is a **preference** (or *soft constraint*): the solver may break it, but every time it does, the timetable gets **penalty points**. The solver then looks for the timetable with the lowest total penalty: an [optimization problem](https://ai.kuleuven.be/aivooriedereen/en/logic#constraint-optimization), just like the best party in the chapter.\n",
    "\n",
    "Every preference below counts how often it is broken:\n",
    "\n",
    "- 😴 **early lectures**: lectures at 08:30;\n",
    "- 🎄 **Friday afternoon**: lectures on Friday afternoon;\n",
    "- 🏝️ **lonely lectures**: lectures without another lecture of the same group right before or after them, so that students come to campus for a single lecture or wait around;\n",
    "- 🗓️ **Prof. Peeters prefers Tuesdays and Thursdays**: Peeters's lectures on other days. As a rule, this count had to be 0; as a preference, it simply adds to the penalty;\n",
    "- ☀️ **Prof. Janssens prefers mornings**: Janssens's lectures in the afternoon;\n",
    "- 🔗 **Prof. Claes likes to teach lectures back to back**: Claes's lectures without another Claes lecture right before or after them.\n",
    "\n",
    "The last three are the kind of personal wishes that teachers send to the timetable office every year."
   ]
  },
  {
   "cell_type": "code",
   "id": "d0ad3ae5",
   "metadata": {},
   "source": [
    "AFTERNOON = [\"13:30\", \"15:30\"]\n",
    "\n",
    "\n",
    "def busy(course_list, day, times):\n",
    "    \"\"\"True if one of these courses has a lecture on this day, at one of these times.\"\"\"\n",
    "    return count_lectures(course_list, [day], times) >= 1\n",
    "\n",
    "\n",
    "def lonely_lectures(course_list):\n",
    "    \"\"\"How many lectures of these courses have no other one right before or after them, on the same day?\"\"\"\n",
    "    lonely = []\n",
    "    for day in DAYS:\n",
    "        for i in range(len(TIMES)):\n",
    "            # the time slots right before and after this one (if they exist: 0 <= j < 4)\n",
    "            neighbors = [TIMES[j] for j in [i - 1, i + 1] if 0 <= j < len(TIMES)]\n",
    "            lonely.append(busy(course_list, day, [TIMES[i]]) & ~busy(course_list, day, neighbors))\n",
    "    return cp.sum(lonely)\n",
    "\n",
    "\n",
    "preferences = {\n",
    "    \"😴 lectures at 08:30\": count_lectures(courses, DAYS, [\"08:30\"]),\n",
    "    \"🎄 lectures on Friday afternoon\": count_lectures(courses, [\"Fri\"], AFTERNOON),\n",
    "    \"🏝️ lonely lectures\": cp.sum([lonely_lectures(courses_of_group[group]) for group in GROUPS]),\n",
    "    \"🗓️ Peeters's lectures not on Tue or Thu\": count_lectures(courses_of_teacher[\"Peeters\"], [\"Mon\", \"Wed\", \"Fri\"], TIMES),\n",
    "    \"☀️ Janssens's lectures in the afternoon\": count_lectures(courses_of_teacher[\"Janssens\"], DAYS, AFTERNOON),\n",
    "    \"🔗 Claes's lectures not back to back\": lonely_lectures(courses_of_teacher[\"Claes\"]),\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "1a066777",
   "metadata": {},
   "source": [
    "Not every preference is equally important. A **weight** says how many penalty points one broken preference costs: a lecture on Friday afternoon is worse than a lonely lecture. In Colab, you set the weights with the sliders next to the code. The penalty is the sum of all counts, each multiplied by its weight.\n",
    "\n",
    "The cell then looks for the best timetable, shows how the penalty adds up, and shows the week of the whole faculty."
   ]
  },
  {
   "cell_type": "code",
   "id": "092d127f",
   "metadata": {},
   "source": [
    "early_weight = 10  # @param {type:\"slider\", min:0, max:20}\n",
    "friday_weight = 10  # @param {type:\"slider\", min:0, max:20}\n",
    "lonely_weight = 5  # @param {type:\"slider\", min:0, max:20}\n",
    "peeters_weight = 5  # @param {type:\"slider\", min:0, max:20}\n",
    "janssens_weight = 3  # @param {type:\"slider\", min:0, max:20}\n",
    "claes_weight = 3  # @param {type:\"slider\", min:0, max:20}\n",
    "\n",
    "weights = [early_weight, friday_weight, lonely_weight, peeters_weight, janssens_weight, claes_weight]\n",
    "counts = list(preferences.values())\n",
    "penalty = cp.sum([weight * count for weight, count in zip(weights, counts)])  # zip: walk through both lists side by side\n",
    "\n",
    "solve(timetable, penalty)\n",
    "if counts[0].value() is not None:  # only if a timetable was found\n",
    "    for name, weight, count in zip(preferences, weights, counts):\n",
    "        print(f\"   {name}: {count.value()} × {weight} = {count.value() * weight} points\")\n",
    "show_faculty()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "8ff5d621",
   "metadata": {},
   "source": [
    "The penalty isn't 0, and that's not the solver's fault: some preferences can't all be met at the same time.\n",
    "\n",
    "- Seven big courses only fit in Aula A, the one room with more than 150 seats: 14 lectures in all. Outside 08:30 and Friday afternoon, the week has only 13 time slots, so one of those lectures has to go to 08:30 or to Friday afternoon. Both cost 10 points; change one of those two weights, and you decide which it is.\n",
    "- Calculus needs three different days, so Prof. Peeters can't stick to Tuesday and Thursday: the impossible wish from before now simply costs 5 points.\n",
    "- The two lectures of Electronics fall on different days, so Prof. Claes can never teach all three lectures back to back.\n",
    "\n",
    "To see the week of one group, pick it in the dropdown next to the cell below."
   ]
  },
  {
   "cell_type": "code",
   "id": "0c4f7b84",
   "metadata": {},
   "source": [
    "group = \"Engineering 1\"  # @param [\"Engineering 1\", \"Computer Science 1\", \"Chemistry 1\", \"Engineering 2\", \"Computer Science 2\", \"Chemistry 2\"]\n",
    "show_week(group)"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "35bd05bf",
   "metadata": {},
   "source": [
    "**Try it yourself** (move a slider or change a number in the cell with the weights, and run it again)\n",
    "\n",
    "- Set the weight of 😴 early lectures to 0. How many lectures move to 08:30, and which preferences benefit?\n",
    "- Make Aula A smaller (200 seats) in the cell of 📋 The faculty, and run the notebook again from there. Why is there no timetable any more? Ask `explain(timetable)`.\n",
    "- Add a preference of your own. Prof. Wouters wants Mondays off: `count_lectures(courses_of_teacher[\"Wouters\"], [\"Mon\"], TIMES)`. Or Ethics has to move to the afternoon. Add a line to `preferences` with a name and a count, give it a weight in the list `weights` (in the same order), and run both cells again.\n",
    "- Add a course of your own to `COURSES`, with a teacher and the groups that follow it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84047f7a",
   "metadata": {},
   "source": [
    "## 🧰 A solver for your own problem\n",
    "\n",
    "Secret Santa and the timetable follow the same recipe, and so does every other problem you give a solver:\n",
    "\n",
    "1. **Propositions** that describe a solution, such as `buys_for[giver, receiver]` or `when[course, day, time]`.\n",
    "2. **Rules** that every solution has to satisfy, added to a model with `+=`. With many rules, give each one a sentence, as `rule` does.\n",
    "3. Optionally, **preferences**: counts of what you'd rather avoid, each with a weight, combined into a penalty for the solver to minimize.\n",
    "4. `solve`, and `explain` when there is no solution at all.\n",
    "\n",
    "Think of a sudoku, the seating plan for a wedding, the schedule of a sports league, the shifts of a student job, or the exam period of your own study program. The CPMpy team's notebooks on [coloring a map](https://github.com/CPMpy/cpmpy/blob/master/examples/map_coloring_oz.ipynb) and [placing queens on a chessboard](https://github.com/CPMpy/cpmpy/blob/master/examples/nqueens_1000.ipynb) show two more problems, with variables that hold a number instead of true or false (`cp.intvar`).\n",
    "\n",
    "A tip from the [last part of the chapter](https://ai.kuleuven.be/aivooriedereen/en/logic#chatgpt-does-not-guarantee-correct-logic): a language model such as ChatGPT can help you translate rules from words into code like this. The solver then guarantees that its solution satisfies the rules as they are written. Whether those rules say what you meant is still up to you to check."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84ecc39f",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "*By [Thomas Winters](https://thomaswinters.be) for [AI voor Iedereen](https://ai.kuleuven.be/aivooriedereen/en), KU Leuven. The latest version of this notebook: [ai.kuleuven.be/aivooriedereen/en/notebook/constraint-solving](https://ai.kuleuven.be/aivooriedereen/en/notebook/constraint-solving).*"
   ]
  }
 ],
 "metadata": {
  "aivi": {
   "chapters": [
    "logica"
   ],
   "language": "en",
   "title": "Constraint solving in Python"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
