{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Lab\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",
    "\n",
    "<div data-lab-answers-release-at=\"2099-12-31T23:59:00-06:00\"></div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 1: Fitting a Multiple Regression\n",
    "# A real estate agent has 16 recent sales (prices in $1,000s).\n",
    "#   1. Fit a LinearRegression model that predicts price from sqft, rooms, and age.\n",
    "#   2. Print the intercept and each coefficient, rounded to 2 decimals,\n",
    "#      in the order sqft, rooms, age.\n",
    "# Print exactly:\n",
    "# Intercept: 34.71\n",
    "# sqft: 0.1\n",
    "# rooms: 15.5\n",
    "# age: -1.87\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\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",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Intercept: 34.71\n",
      "sqft: 0.1\n",
      "rooms: 15.5\n",
      "age: -1.87\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\n",
    "})\n",
    "\n",
    "X = homes[['sqft', 'rooms', 'age']]\n",
    "y = homes['price']\n",
    "model = LinearRegression().fit(X, y)\n",
    "\n",
    "print(\"Intercept:\", round(model.intercept_, 2))\n",
    "for name, coefficient in zip(X.columns, model.coef_):\n",
    "    print(name + \":\", round(coefficient, 2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 2: Holding Other Features Fixed\n",
    "# Use the model from Question 1 (fit it again here).\n",
    "#   1. Predict the price of house_a and of house_b, which is the same house\n",
    "#      with one more room. Round each to 1 decimal.\n",
    "#   2. Compute the difference, B minus A, rounded to 2 decimals. Compare it\n",
    "#      with the rooms coefficient.\n",
    "# Print exactly:\n",
    "# House A: 276.7\n",
    "# House B: 292.2\n",
    "# Difference: 15.5\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\n",
    "})\n",
    "house_a = pd.DataFrame({\"sqft\": [1800], \"rooms\": [6], \"age\": [20]})\n",
    "house_b = pd.DataFrame({\"sqft\": [1800], \"rooms\": [7], \"age\": [20]})\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "House A: 276.7\n",
      "House B: 292.2\n",
      "Difference: 15.5\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\n",
    "})\n",
    "house_a = pd.DataFrame({\"sqft\": [1800], \"rooms\": [6], \"age\": [20]})\n",
    "house_b = pd.DataFrame({\"sqft\": [1800], \"rooms\": [7], \"age\": [20]})\n",
    "\n",
    "model = LinearRegression().fit(homes[['sqft', 'rooms', 'age']], homes['price'])\n",
    "price_a = model.predict(house_a)[0]\n",
    "price_b = model.predict(house_b)[0]\n",
    "\n",
    "print(\"House A:\", round(price_a, 1))\n",
    "print(\"House B:\", round(price_b, 1))\n",
    "print(\"Difference:\", round(price_b - price_a, 2))\n",
    "# The difference is the rooms coefficient: the change in predicted price for\n",
    "# one more room, with square feet and age held fixed.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 3: Spotting Multicollinearity\n",
    "#   1. Compute the correlation matrix of the three predictors with .corr().\n",
    "#   2. Find the pair of DIFFERENT predictors with the largest absolute correlation.\n",
    "#   3. Print the pair (in column order) and its correlation, rounded to 2 decimals.\n",
    "# Print exactly:\n",
    "# Most correlated pair: sqft and rooms\n",
    "# Correlation: 0.94\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\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",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Most correlated pair: sqft and rooms\n",
      "Correlation: 0.94\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\n",
    "})\n",
    "\n",
    "predictors = homes[['sqft', 'rooms', 'age']]\n",
    "corr = predictors.corr()\n",
    "columns = list(predictors.columns)\n",
    "\n",
    "best_pair = None\n",
    "best_value = 0\n",
    "for i in range(len(columns)):\n",
    "    for j in range(i + 1, len(columns)):\n",
    "        value = corr.iloc[i, j]\n",
    "        if abs(value) > abs(best_value):\n",
    "            best_value = value\n",
    "            best_pair = (columns[i], columns[j])\n",
    "\n",
    "print(\"Most correlated pair:\", best_pair[0], \"and\", best_pair[1])\n",
    "print(\"Correlation:\", round(best_value, 2))\n",
    "# Bigger houses have more rooms, so the two coefficients are hard to separate.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 4: Simple vs. Multiple on Test Data\n",
    "#   1. Split homes into training and test sets with\n",
    "#      train_test_split(X, y, test_size=0.25, random_state=1).\n",
    "#   2. On the training set, fit a simple model (sqft only) and a multiple model\n",
    "#      (sqft, rooms, age).\n",
    "#   3. Compute each model's test RMSE: np.sqrt(mean_squared_error(...)),\n",
    "#      rounded to 2 decimals.\n",
    "# Print exactly:\n",
    "# Simple RMSE: 32.8\n",
    "# Multiple RMSE: 7.38\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\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",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Simple RMSE: 32.8\n",
      "Multiple RMSE: 7.38\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\n",
    "})\n",
    "\n",
    "X = homes[['sqft', 'rooms', 'age']]\n",
    "y = homes['price']\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)\n",
    "\n",
    "simple = LinearRegression().fit(X_train[['sqft']], y_train)\n",
    "multiple = LinearRegression().fit(X_train, y_train)\n",
    "\n",
    "simple_rmse = np.sqrt(mean_squared_error(y_test, simple.predict(X_test[['sqft']])))\n",
    "multiple_rmse = np.sqrt(mean_squared_error(y_test, multiple.predict(X_test)))\n",
    "print(\"Simple RMSE:\", round(simple_rmse, 2))\n",
    "print(\"Multiple RMSE:\", round(multiple_rmse, 2))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 5: R-squared on the Test Set\n",
    "#   1. Use the same split and multiple model as Question 4.\n",
    "#   2. Compute R-squared on the test set with r2_score(y_test, predictions),\n",
    "#      rounded to 3 decimals.\n",
    "# Print exactly:\n",
    "# Test R-squared: 0.99\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\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",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Test R-squared: 0.99\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.linear_model import LinearRegression\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import mean_squared_error, r2_score\n",
    "\n",
    "homes = pd.DataFrame({\n",
    "    \"sqft\": [2800, 2700, 2600, 2700, 1300, 2600, 2800, 1600, 1500, 1300, 2600, 2900, 2200, 2300, 2600, 1200],\n",
    "    \"rooms\": [9, 9, 8, 9, 5, 8, 9, 6, 6, 3, 9, 9, 7, 9, 9, 4],\n",
    "    \"age\": [44, 26, 42, 7, 45, 41, 27, 25, 17, 13, 15, 39, 20, 49, 20, 27],\n",
    "    \"price\": [400, 417, 350, 450, 151, 363, 390, 247, 259, 198, 403, 387, 326, 325, 409, 168],   # $1,000s\n",
    "})\n",
    "\n",
    "X = homes[['sqft', 'rooms', 'age']]\n",
    "y = homes['price']\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1)\n",
    "\n",
    "multiple = LinearRegression().fit(X_train, y_train)\n",
    "print(\"Test R-squared:\", round(r2_score(y_test, multiple.predict(X_test)), 3))\n",
    "# The predictions account for about 99% of the variation in test prices.\n",
    "# With only 4 test houses, treat that as a rough figure.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch13-lab-grader { max-width: 900px; margin-top: 1rem; }\n",
    ".ch13-lab-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n",
    ".ch13-lab-feedback-list[hidden] { display: none; }\n",
    ".ch13-lab-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n",
    ".ch13-lab-feedback-row strong { margin-right: 0.35rem; }\n",
    ".ch13-lab-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n",
    ".ch13-lab-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n",
    ".ch13-lab-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n",
    ".ch13-lab-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n",
    ".ch13-lab-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch13-lab-actions.is-locked { opacity: 0.55; }\n",
    ".ch13-lab-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch13-lab-result { font-weight: 700; }\n",
    "</style>\n",
    "\n",
    "<div class='ch13-lab-grader' id='ch13-lab-grader'>\n",
    "  <div class='ch13-lab-feedback-list' aria-live='polite' hidden>\n",
    "    <div class='ch13-lab-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n",
    "    <div class='ch13-lab-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n",
    "    <div class='ch13-lab-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n",
    "    <div class='ch13-lab-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n",
    "    <div class='ch13-lab-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n",
    "  </div>\n",
    "  <div class='ch13-lab-actions'>\n",
    "    <button type='button' id='ch13-lab-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch13-lab-reset'>Clear Results</button>\n",
    "    <span class='ch13-lab-result' id='ch13-lab-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var labId = 'ch13-lab';\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 + 1)] = codeFromCell(cell);\n",
    "    });\n",
    "    return code;\n",
    "  }\n",
    "\n",
    "  function applyFeedback(grader, feedback) {\n",
    "    var list = grader.querySelector('.ch13-lab-feedback-list');\n",
    "    list.hidden = false;\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5'].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 = 'ch13-lab-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('.ch13-lab-feedback-list');\n",
    "    list.hidden = true;\n",
    "    grader.querySelectorAll('.ch13-lab-feedback-row').forEach(function (row) {\n",
    "      row.className = 'ch13-lab-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/lab-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 initLabGrader() {\n",
    "    var grader = document.getElementById('ch13-lab-grader');\n",
    "    if (!grader || grader.dataset.ready === 'true') return;\n",
    "    grader.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var actions = grader.querySelector('.ch13-lab-actions');\n",
    "    var result = document.getElementById('ch13-lab-result');\n",
    "    var submit = document.getElementById('ch13-lab-submit');\n",
    "    var reset = document.getElementById('ch13-lab-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 code.';\n",
    "\n",
    "      saveAttempt({\n",
    "        lab_id: labId,\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', initLabGrader);\n",
    "  } else {\n",
    "    initLabGrader();\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
}
