{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Homework\n",
    "\n",
    "- Use this assignment to practice the chapter's concepts and coding skills in runnable Python code.\n",
    "- Sign in from the account menu before you start working on the assignment.\n",
    "- Write and run your code directly in the coding cells.\n",
    "- Multiple submissions are allowed. The highest score is kept.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**1. Labels**\n",
    "\n",
    "Like a classifier, k-means needs training examples whose group labels are already known.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 1 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q1\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q1\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# Clustering is unsupervised: it finds groups in unlabeled data. Classification learns from labeled examples.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**2. Scaling**\n",
    "\n",
    "Customers are described by annual spend (in dollars) and number of orders. Converting both features to standard units before k-means keeps spend from dominating the distances.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 2 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q2\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q2\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# True\n",
    "# Without scaling, a difference of a few dollars counts as much as a difference of a few orders, so spend decides the clusters.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**3. Smallest Inertia**\n",
    "\n",
    "Inertia always decreases as k increases, so the value of k with the smallest inertia is the best choice.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 3 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q3\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q3\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# Inertia keeps falling until every point is its own cluster. Look for the elbow where the improvement levels off, or compare silhouette scores.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**4. Silhouette Score**\n",
    "\n",
    "A silhouette score close to 1 means that points are much closer to their own cluster than to the nearest other cluster.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 4 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q4\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q4\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# True\n",
    "# Scores near 1 indicate tight, well-separated clusters; scores near 0 indicate overlapping clusters.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "::::{div} assignment-question-card\n",
    "\n",
    "**5. Cluster Numbers**\n",
    "\n",
    "In a k-means result, cluster 0 is always the most important segment, and cluster 0 in one run is the same group as cluster 0 in another run.\n",
    "\n",
    "<div class=\"tf-options\" role=\"radiogroup\" aria-label=\"Question 5 answer\">\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q5\" value=\"true\"> True</label>\n",
    "  <label><input type=\"radio\" name=\"ch15-hw-q5\" value=\"false\"> False</label>\n",
    "</div>\n",
    "\n",
    "::::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "# False\n",
    "# Cluster numbers are arbitrary names. Describe each cluster by its profile, such as average spend and orders, not by its number.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 6. Assigning Spend to Two Centers\n",
    "# One round of the assignment step on one feature.\n",
    "#   1. Assign each monthly spend value to the nearer center (0 or 1).\n",
    "#   2. Print the assignments and the size of each cluster.\n",
    "# Print exactly:\n",
    "# Assignments: [0, 0, 1, 0, 1, 1, 1]\n",
    "# Sizes: [3, 4]\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "spend = pd.Series([15, 22, 61, 30, 75, 58, 90])\n",
    "centers = [20, 70]\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Assignments: [0, 0, 1, 0, 1, 1, 1]\n",
      "Sizes: [3, 4]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "spend = pd.Series([15, 22, 61, 30, 75, 58, 90])\n",
    "centers = [20, 70]\n",
    "\n",
    "assignments = []\n",
    "for value in spend:\n",
    "    if abs(value - centers[0]) <= abs(value - centers[1]):\n",
    "        assignments.append(0)\n",
    "    else:\n",
    "        assignments.append(1)\n",
    "\n",
    "print(\"Assignments:\", assignments)\n",
    "print(\"Sizes:\", [assignments.count(0), assignments.count(1)])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 7. Inertia by Hand\n",
    "# Inertia is the sum of squared distances from each point to its own cluster's center.\n",
    "#   1. Compute the center of each cluster (the mean of its points).\n",
    "#   2. Compute the inertia.\n",
    "# Print exactly:\n",
    "# Centers: [[1.5, 1.5], [9.0, 8.0]]\n",
    "# Inertia: 5.0\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "points = pd.DataFrame({\n",
    "    \"x\": [1, 2, 8, 10, 9],\n",
    "    \"y\": [2, 1, 9, 7, 8],\n",
    "    \"cluster\": [0, 0, 1, 1, 1],\n",
    "})\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Centers: [[1.5, 1.5], [9.0, 8.0]]\n",
      "Inertia: 5.0\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "points = pd.DataFrame({\n",
    "    \"x\": [1, 2, 8, 10, 9],\n",
    "    \"y\": [2, 1, 9, 7, 8],\n",
    "    \"cluster\": [0, 0, 1, 1, 1],\n",
    "})\n",
    "\n",
    "centers = points.groupby('cluster')[['x', 'y']].mean()\n",
    "inertia = 0\n",
    "for x, y, cluster in zip(points['x'], points['y'], points['cluster']):\n",
    "    inertia = inertia + (x - centers.loc[cluster, 'x']) ** 2 + (y - centers.loc[cluster, 'y']) ** 2\n",
    "\n",
    "print(\"Centers:\", centers.values.tolist())\n",
    "print(\"Inertia:\", inertia)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 8. Clustering Stores\n",
    "# Twelve stores are described by foot traffic and basket size, in standard units.\n",
    "#   1. Fit KMeans(n_clusters=3, n_init=10, random_state=0).\n",
    "#   2. Print the cluster sizes, sorted from smallest to largest.\n",
    "# Print exactly:\n",
    "# Cluster sizes: [4, 4, 4]\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.cluster import KMeans\n",
    "\n",
    "stores = pd.DataFrame({\n",
    "    \"traffic_su\": [-1.2, -1.0, -1.3, -0.9, 0.1, 0.3, 0.0, 0.2, 1.3, 1.1, 1.4, 1.2],\n",
    "    \"basket_su\": [1.1, 0.9, 1.2, 1.0, -1.0, -1.2, -0.9, -1.1, 0.2, 0.0, 0.3, 0.1],\n",
    "})\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cluster sizes: [4, 4, 4]\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.cluster import KMeans\n",
    "\n",
    "stores = pd.DataFrame({\n",
    "    \"traffic_su\": [-1.2, -1.0, -1.3, -0.9, 0.1, 0.3, 0.0, 0.2, 1.3, 1.1, 1.4, 1.2],\n",
    "    \"basket_su\": [1.1, 0.9, 1.2, 1.0, -1.0, -1.2, -0.9, -1.1, 0.2, 0.0, 0.3, 0.1],\n",
    "})\n",
    "\n",
    "labels = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(stores)\n",
    "print(\"Cluster sizes:\", sorted(pd.Series(labels).value_counts().tolist()))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 9. How Many Store Groups?\n",
    "#   1. For k = 2, 3, and 4, fit KMeans(n_clusters=k, n_init=10, random_state=0) to\n",
    "#      stores and compute the silhouette score, rounded to 3 decimals.\n",
    "#   2. Print each score, then the k with the highest score.\n",
    "# Print exactly:\n",
    "# k=2: 0.682\n",
    "# k=3: 0.864\n",
    "# k=4: 0.773\n",
    "# Best k: 3\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.cluster import KMeans\n",
    "from sklearn.metrics import silhouette_score\n",
    "\n",
    "stores = pd.DataFrame({\n",
    "    \"traffic_su\": [-1.2, -1.0, -1.3, -0.9, 0.1, 0.3, 0.0, 0.2, 1.3, 1.1, 1.4, 1.2],\n",
    "    \"basket_su\": [1.1, 0.9, 1.2, 1.0, -1.0, -1.2, -0.9, -1.1, 0.2, 0.0, 0.3, 0.1],\n",
    "})\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "k=2: 0.682\n",
      "k=3: 0.864\n",
      "k=4: 0.773\n",
      "Best k: 3\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.cluster import KMeans\n",
    "from sklearn.metrics import silhouette_score\n",
    "\n",
    "stores = pd.DataFrame({\n",
    "    \"traffic_su\": [-1.2, -1.0, -1.3, -0.9, 0.1, 0.3, 0.0, 0.2, 1.3, 1.1, 1.4, 1.2],\n",
    "    \"basket_su\": [1.1, 0.9, 1.2, 1.0, -1.0, -1.2, -0.9, -1.1, 0.2, 0.0, 0.3, 0.1],\n",
    "})\n",
    "\n",
    "scores = {}\n",
    "for k in [2, 3, 4]:\n",
    "    labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(stores)\n",
    "    scores[k] = round(silhouette_score(stores, labels), 3)\n",
    "    print(\"k=\" + str(k) + \":\", scores[k])\n",
    "print(\"Best k:\", max(scores, key=scores.get))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### 10. Profiling Segments\n",
    "# K-means has assigned nine customers to clusters.\n",
    "#   1. Use groupby to compute each cluster's mean visits and mean spend.\n",
    "#   2. Find the cluster with the highest mean visits and print its mean spend\n",
    "#      and its number of customers.\n",
    "# Print exactly:\n",
    "# Most frequent visitors: cluster 1\n",
    "# Their mean spend: 45.0\n",
    "# Customers: 3\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "segments = pd.DataFrame({\n",
    "    \"visits\": [2, 3, 12, 14, 1, 13, 6, 5, 7],\n",
    "    \"spend\": [120, 140, 40, 50, 100, 45, 80, 70, 90],\n",
    "    \"cluster\": [0, 0, 1, 1, 0, 1, 2, 2, 2],\n",
    "})\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "tags": [
     "hide-input",
     "homework-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Most frequent visitors: cluster 1\n",
      "Their mean spend: 45.0\n",
      "Customers: 3\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "segments = pd.DataFrame({\n",
    "    \"visits\": [2, 3, 12, 14, 1, 13, 6, 5, 7],\n",
    "    \"spend\": [120, 140, 40, 50, 100, 45, 80, 70, 90],\n",
    "    \"cluster\": [0, 0, 1, 1, 0, 1, 2, 2, 2],\n",
    "})\n",
    "\n",
    "profile = segments.groupby('cluster')[['visits', 'spend']].mean()\n",
    "top = profile['visits'].idxmax()\n",
    "\n",
    "print(\"Most frequent visitors: cluster\", top)\n",
    "print(\"Their mean spend:\", profile.loc[top, 'spend'])\n",
    "print(\"Customers:\", (segments['cluster'] == top).sum())\n",
    "# Frequent visitors spend the least per month: possibly a segment to target with\n",
    "# bundles or add-ons.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch15-hw-grader { max-width: 900px; margin-top: 1rem; }\n",
    ".ch15-hw-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n",
    ".ch15-hw-feedback-list[hidden] { display: none; }\n",
    ".ch15-hw-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n",
    ".ch15-hw-feedback-row strong { margin-right: 0.35rem; }\n",
    ".ch15-hw-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n",
    ".ch15-hw-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n",
    ".ch15-hw-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n",
    ".ch15-hw-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n",
    ".ch15-hw-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch15-hw-actions.is-locked { opacity: 0.55; }\n",
    ".ch15-hw-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch15-hw-result { font-weight: 700; }\n",
    "</style>\n",
    "\n",
    "<div class='ch15-hw-grader' id='ch15-hw-grader'>\n",
    "  <div class='ch15-hw-feedback-list' aria-live='polite' hidden>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q6'><strong>Question 6</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q7'><strong>Question 7</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q8'><strong>Question 8</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q9'><strong>Question 9</strong><span></span></div>\n",
    "    <div class='ch15-hw-feedback-row' data-question='q10'><strong>Question 10</strong><span></span></div>\n",
    "  </div>\n",
    "  <div class='ch15-hw-actions'>\n",
    "    <button type='button' id='ch15-hw-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch15-hw-reset'>Clear Results</button>\n",
    "    <span class='ch15-hw-result' id='ch15-hw-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var homeworkId = 'ch15-homework';\n",
    "\n",
    "  function getParams() {\n",
    "    var params = new URLSearchParams(window.location.search);\n",
    "    return {\n",
    "      canvas_course_id: params.get('canvas_course_id') || params.get('course_id') || '',\n",
    "      canvas_assignment_id: params.get('canvas_assignment_id') || params.get('assignment_id') || '',\n",
    "      canvas_user_id: params.get('canvas_user_id') || params.get('user_id') || ''\n",
    "    };\n",
    "  }\n",
    "\n",
    "  function loadSessionIdentity(identity, actions, submit, result) {\n",
    "    submit.disabled = true;\n",
    "    actions.classList.add('is-locked');\n",
    "    result.textContent = 'Sign in from the account menu to submit this assignment.';\n",
    "\n",
    "    return fetch('/api/v1/session.php', { credentials: 'same-origin' })\n",
    "      .then(function (response) { return response.ok ? response.json() : null; })\n",
    "      .then(function (payload) {\n",
    "        if (!payload || !payload.authenticated || !payload.identity) return identity;\n",
    "        identity.canvas_user_id = payload.identity.canvas_user_id || identity.canvas_user_id || '';\n",
    "        identity.student_identifier = payload.identity.student_identifier || '';\n",
    "        submit.disabled = false;\n",
    "        actions.classList.remove('is-locked');\n",
    "        result.textContent = payload.identity.display_name ? 'Signed in as ' + payload.identity.display_name + '.' : 'Signed in.';\n",
    "        return identity;\n",
    "      })\n",
    "      .catch(function () { return identity; });\n",
    "  }\n",
    "\n",
    "  function codeFromCell(cell) {\n",
    "    var cm = cell.querySelector('.CodeMirror');\n",
    "    if (cm && cm.CodeMirror && typeof cm.CodeMirror.getValue === 'function') return cm.CodeMirror.getValue();\n",
    "    var cmContent = cell.querySelector('.cm-content');\n",
    "    if (cmContent && cmContent.cmView && cmContent.cmView.view) return cmContent.cmView.view.state.doc.toString();\n",
    "    var textarea = cell.querySelector('textarea');\n",
    "    if (textarea) return textarea.value;\n",
    "    var pre = cell.querySelector('.cell_input pre');\n",
    "    return pre ? pre.textContent : '';\n",
    "  }\n",
    "\n",
    "  function collectCodeCells() {\n",
    "    var cells = Array.prototype.slice.call(document.querySelectorAll('div.cell.tag_thebe-interactive')).slice(0, 5);\n",
    "    var code = {};\n",
    "    cells.forEach(function (cell, index) {\n",
    "      code['q' + (index + 6)] = codeFromCell(cell);\n",
    "    });\n",
    "    return code;\n",
    "  }\n",
    "\n",
    "  function collectAnswers() {\n",
    "    var answers = {};\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5'].forEach(function (question) {\n",
    "      var checked = document.querySelector('input[name=\"ch15-hw-' + question + '\"]:checked');\n",
    "      answers[question] = checked ? checked.value : '';\n",
    "    });\n",
    "    return answers;\n",
    "  }\n",
    "\n",
    "  function applyFeedback(grader, feedback) {\n",
    "    var list = grader.querySelector('.ch15-hw-feedback-list');\n",
    "    list.hidden = false;\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9', 'q10'].forEach(function (question) {\n",
    "      var row = grader.querySelector('[data-question=' + question + ']');\n",
    "      var message = row.querySelector('span');\n",
    "      var item = feedback[question];\n",
    "      row.className = 'ch15-hw-feedback-row';\n",
    "      if (!item) return;\n",
    "      message.textContent = item.message + ' (' + item.score + ' / ' + item.max_score + ')';\n",
    "      row.classList.add(item.correct ? 'correct' : 'incorrect');\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function clearFeedback(grader) {\n",
    "    var list = grader.querySelector('.ch15-hw-feedback-list');\n",
    "    list.hidden = true;\n",
    "    grader.querySelectorAll('.ch15-hw-feedback-row').forEach(function (row) {\n",
    "      row.className = 'ch15-hw-feedback-row';\n",
    "      var message = row.querySelector('span');\n",
    "      if (message) message.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function saveAttempt(payload) {\n",
    "    return fetch('/api/v1/homework-attempts.php', {\n",
    "      method: 'POST',\n",
    "      headers: { 'Content-Type': 'application/json' },\n",
    "      credentials: 'same-origin',\n",
    "      body: JSON.stringify(payload)\n",
    "    }).then(function (response) {\n",
    "      return response.text().then(function (text) {\n",
    "        var payload = text ? JSON.parse(text) : null;\n",
    "        if (!payload || !response.ok || !payload.ok) {\n",
    "          throw new Error((payload && (payload.message || payload.error)) || 'Submission API is unavailable.');\n",
    "        }\n",
    "        return payload;\n",
    "      });\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function initHomeworkGrader() {\n",
    "    var grader = document.getElementById('ch15-hw-grader');\n",
    "    if (!grader || grader.dataset.ready === 'true') return;\n",
    "    grader.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var actions = grader.querySelector('.ch15-hw-actions');\n",
    "    var result = document.getElementById('ch15-hw-result');\n",
    "    var submit = document.getElementById('ch15-hw-submit');\n",
    "    var reset = document.getElementById('ch15-hw-reset');\n",
    "\n",
    "    loadSessionIdentity(identity, actions, submit, result);\n",
    "\n",
    "    submit.addEventListener('click', function () {\n",
    "      clearFeedback(grader);\n",
    "      submit.disabled = true;\n",
    "      result.textContent = 'Submitting homework.';\n",
    "\n",
    "      saveAttempt({\n",
    "        homework_id: homeworkId,\n",
    "        answers: collectAnswers(),\n",
    "        code: collectCodeCells(),\n",
    "        canvas_course_id: identity.canvas_course_id,\n",
    "        canvas_assignment_id: identity.canvas_assignment_id,\n",
    "        canvas_user_id: identity.canvas_user_id\n",
    "      })\n",
    "        .then(function (payload) {\n",
    "          var best = (payload.best_score === null || typeof payload.best_score === 'undefined') ? payload.score : payload.best_score;\n",
    "          var attempt = (payload.attempt_count === null || typeof payload.attempt_count === 'undefined') ? '' : ' Attempt ' + payload.attempt_count + '.';\n",
    "          applyFeedback(grader, payload.feedback || {});\n",
    "          result.textContent = 'Submission saved.' + attempt + ' Score: ' + payload.score + ' / ' + payload.max_score + '. Best score: ' + best + ' / ' + payload.max_score + '. Canvas sync: ' + payload.canvas_sync_status + '.';\n",
    "        })\n",
    "        .catch(function (error) {\n",
    "          result.textContent = 'Could not save this attempt: ' + error.message;\n",
    "        })\n",
    "        .finally(function () {\n",
    "          submit.disabled = false;\n",
    "        });\n",
    "    });\n",
    "\n",
    "    reset.addEventListener('click', function () {\n",
    "      clearFeedback(grader);\n",
    "      result.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "  if (document.readyState === 'loading') {\n",
    "    document.addEventListener('DOMContentLoaded', initHomeworkGrader);\n",
    "  } else {\n",
    "    initHomeworkGrader();\n",
    "  }\n",
    "})();\n",
    "</script>\n"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
