{
 "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": 1,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 1: Delivery Percentiles\n",
    "# An online store wants to promise a delivery time that most orders meet.\n",
    "#   1. Compute the 75th and 90th percentiles of days with\n",
    "#      np.percentile(..., method='nearest'), as in this chapter.\n",
    "# These describe this sample, not a guaranteed future delivery promise.\n",
    "# Print exactly:\n",
    "# 75th percentile: 6\n",
    "# 90th percentile: 8\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "days = pd.Series([2, 3, 3, 4, 4, 5, 5, 6, 8, 12])\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": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "75th percentile: 6\n90th percentile: 8\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "days = pd.Series([2, 3, 3, 4, 4, 5, 5, 6, 8, 12])\n",
    "\n",
    "print(\"75th percentile:\", np.percentile(days, 75, method='nearest'))\n",
    "print(\"90th percentile:\", np.percentile(days, 90, method='nearest'))\n",
    "# Nine of these ten observed orders arrived within 8 days.\n",
    "# A small historical sample does not guarantee future delivery performance.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 2: An Estimate and One Resample\n",
    "# HR has a random sample of 12 salaries (in $1,000s) and wants to estimate the\n",
    "# median salary of all employees.\n",
    "#   1. Compute the sample median: the estimate of the population median.\n",
    "#   2. Draw len(salaries) values WITH replacement using salaries.sample(\n",
    "#      len(salaries), replace=True, random_state=3). Compute its median.\n",
    "# Print exactly:\n",
    "# Sample median: 71.0\n",
    "# Resample median: 84.5\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "salaries = pd.Series([62, 58, 75, 81, 66, 93, 70, 59, 88, 64, 120, 72])\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": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Sample median: 71.0\nResample median: 84.5\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "salaries = pd.Series([62, 58, 75, 81, 66, 93, 70, 59, 88, 64, 120, 72])\n",
    "resample = salaries.sample(len(salaries), replace=True, random_state=3)\n",
    "\n",
    "print(\"Sample median:\", salaries.median())\n",
    "print(\"Resample median:\", resample.median())\n",
    "# Some salaries appear more than once in the resample and some\n",
    "# not at all, which is what drawing with replacement does.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 3: A 95% Bootstrap Confidence Interval\n",
    "# Generate a bootstrap distribution for the population median salary.\n",
    "#   1. Repeat 5,000 times: draw len(salaries) values with rng.choice(...,\n",
    "#      size=len(salaries), replace=True), and append np.median(resample)\n",
    "#      to bootstrap_medians. Initialize the list before your for loop.\n",
    "#   2. Use its 2.5th and 97.5th percentiles (method='nearest') as endpoints.\n",
    "# The seed is set once; do not reset it in the loop. The original sample\n",
    "# still contains only 12 employees, so interpret this interval cautiously.\n",
    "# Print exactly:\n",
    "# 95% CI: 63.0 to 84.5\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "salaries = pd.Series([62, 58, 75, 81, 66, 93, 70, 59, 88, 64, 120, 72])\n",
    "rng = np.random.default_rng(42)\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "95% CI: 63.0 to 84.5\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "salaries = pd.Series([62, 58, 75, 81, 66, 93, 70, 59, 88, 64, 120, 72])\n",
    "rng = np.random.default_rng(42)\n",
    "bootstrap_medians = []\n",
    "for i in range(5000):\n",
    "    resample = rng.choice(salaries, size=len(salaries), replace=True)\n",
    "    bootstrap_medians.append(np.median(resample))\n",
    "\n",
    "left = np.percentile(bootstrap_medians, 2.5, method='nearest')\n",
    "right = np.percentile(bootstrap_medians, 97.5, method='nearest')\n",
    "print(\"95% CI:\", left, \"to\", right)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 4: 95% vs. 80% Confidence\n",
    "# Using the same bootstrap medians:\n",
    "#   1. Compute the width of the 95% interval (2.5th to 97.5th percentile).\n",
    "#   2. Compute the width of the 80% interval (10th to 90th percentile).\n",
    "#   Use method='nearest' for all percentiles.\n",
    "# Print exactly:\n",
    "# 95% width: 21.5\n",
    "# 80% width: 13.0\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "salaries = pd.Series([62, 58, 75, 81, 66, 93, 70, 59, 88, 64, 120, 72])\n",
    "rng = np.random.default_rng(42)\n",
    "bootstrap_medians = []\n",
    "for i in range(5000):\n",
    "    resample = rng.choice(salaries, size=len(salaries), replace=True)\n",
    "    bootstrap_medians.append(np.median(resample))\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "95% width: 21.5\n80% width: 13.0\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "salaries = pd.Series([62, 58, 75, 81, 66, 93, 70, 59, 88, 64, 120, 72])\n",
    "rng = np.random.default_rng(42)\n",
    "bootstrap_medians = []\n",
    "for i in range(5000):\n",
    "    resample = rng.choice(salaries, size=len(salaries), replace=True)\n",
    "    bootstrap_medians.append(np.median(resample))\n",
    "\n",
    "def width(low, high):\n",
    "    return np.percentile(bootstrap_medians, high, method='nearest') - np.percentile(bootstrap_medians, low, method='nearest')\n",
    "\n",
    "print(\"95% width:\", width(2.5, 97.5))\n",
    "print(\"80% width:\", width(10, 90))\n",
    "# Here the 80% interval is narrower; ties can produce equal widths.\n",
    "# More resamples alone would not add employees to the original sample.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 5: Is It a Majority?\n",
    "# In a random sample of 200 customers, 116 (0.58) would recommend the store.\n",
    "# The 40 supplied bootstrap proportions are a short arithmetic exercise.\n",
    "# Use thousands of resamples and check the sampling design before acting.\n",
    "#   1. Compute the 95% confidence interval (method='nearest').\n",
    "#   2. Check whether the whole interval is above 0.5, which supports the claim\n",
    "#      that a majority of all customers would recommend the store.\n",
    "# Print exactly:\n",
    "# 95% CI: 0.52 to 0.625\n",
    "# Whole interval above 0.5: True\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "bootstrap_props = pd.Series([0.585, 0.56, 0.585, 0.57, 0.595, 0.62, 0.56, 0.555, 0.53, 0.545,\n",
    "                             0.56, 0.625, 0.525, 0.59, 0.54, 0.585, 0.575, 0.565, 0.61, 0.585,\n",
    "                             0.59, 0.52, 0.575, 0.56, 0.615, 0.585, 0.52, 0.54, 0.58, 0.59,\n",
    "                             0.645, 0.58, 0.585, 0.575, 0.61, 0.565, 0.6, 0.58, 0.515, 0.565])\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "95% CI: 0.52 to 0.625\nWhole interval above 0.5: True\n"
    }
   ],
   "source": [
    "### Solution\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "bootstrap_props = pd.Series([0.585, 0.56, 0.585, 0.57, 0.595, 0.62, 0.56, 0.555, 0.53, 0.545,\n",
    "                             0.56, 0.625, 0.525, 0.59, 0.54, 0.585, 0.575, 0.565, 0.61, 0.585,\n",
    "                             0.59, 0.52, 0.575, 0.56, 0.615, 0.585, 0.52, 0.54, 0.58, 0.59,\n",
    "                             0.645, 0.58, 0.585, 0.575, 0.61, 0.565, 0.6, 0.58, 0.515, 0.565])\n",
    "\n",
    "left = np.percentile(bootstrap_props, 2.5, method='nearest')\n",
    "right = np.percentile(bootstrap_props, 97.5, method='nearest')\n",
    "\n",
    "print(\"95% CI:\", left, \"to\", right)\n",
    "print(\"Whole interval above 0.5:\", left > 0.5)\n",
    "# This coarse practice interval supports, but does not prove, a majority.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch11-lab-grader { max-width: 900px; margin-top: 1rem; }\n",
    ".ch11-lab-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n",
    ".ch11-lab-feedback-list[hidden] { display: none; }\n",
    ".ch11-lab-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n",
    ".ch11-lab-feedback-row strong { margin-right: 0.35rem; }\n",
    ".ch11-lab-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n",
    ".ch11-lab-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n",
    ".ch11-lab-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n",
    ".ch11-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",
    ".ch11-lab-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch11-lab-actions.is-locked { opacity: 0.55; }\n",
    ".ch11-lab-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch11-lab-result { font-weight: 700; }\n",
    "</style>\n",
    "\n",
    "<div class='ch11-lab-grader' id='ch11-lab-grader'>\n",
    "  <div class='ch11-lab-feedback-list' aria-live='polite' hidden>\n",
    "    <div class='ch11-lab-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n",
    "    <div class='ch11-lab-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n",
    "    <div class='ch11-lab-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n",
    "    <div class='ch11-lab-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n",
    "    <div class='ch11-lab-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n",
    "  </div>\n",
    "  <div class='ch11-lab-actions'>\n",
    "    <button type='button' id='ch11-lab-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch11-lab-reset'>Clear Results</button>\n",
    "    <span class='ch11-lab-result' id='ch11-lab-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var labId = 'ch11-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('.ch11-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 = 'ch11-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('.ch11-lab-feedback-list');\n",
    "    list.hidden = true;\n",
    "    grader.querySelectorAll('.ch11-lab-feedback-row').forEach(function (row) {\n",
    "      row.className = 'ch11-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('ch11-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('.ch11-lab-actions');\n",
    "    var result = document.getElementById('ch11-lab-result');\n",
    "    var submit = document.getElementById('ch11-lab-submit');\n",
    "    var reset = document.getElementById('ch11-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
}
