{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "hw2-intro-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "# Homework 2\n",
    "## Covariance, MLE and MAP\n",
    "\n",
    "**Signal Processing · Lectures 4–7**\n",
    "\n",
    "- **A:** how uncertainty changes when we combine measurements.\n",
    "- **B:** how we divide the weight between data and prior information.\n",
    "- **C:** when the prior improves the estimate and when it increases the error.\n",
    "- **D:** personal exploration.\n",
    "\n",
    "**Sources:** slides and notes for Lectures 4–7, Practice Exercises for Lectures 4 (1.1, 2.1) and 6 (1.2, 4.1), and worked exercises covered in the tutorials.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-instructions-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### Before you start\n",
    "\n",
    "We use NumPy and Matplotlib. If they are missing, run `%pip install numpy matplotlib` in a separate cell and restart the kernel.\n",
    "\n",
    "Keep the variable and function names and the existing cells. Complete the code between `### TODO: ADD YOUR CODE HERE` and `### END of TODO`.\n",
    "\n",
    "These regions contain placeholders that **you must replace with your answers**:\n",
    "- `None`: enter the requested value, such as a number or `True`/`False`.\n",
    "- `np.nan`: enter the calculation or numerical result. For arrays, replace `np.full(..., np.nan)` with `np.array([...])` containing your values.\n",
    "\n",
    "For example, `answer = None` becomes `answer = 7` if the answer is 7. For an array of two values, `np.full(2, np.nan)` could become `np.array([3., 5.])`, depending on your answer.\n",
    "\n",
    "The initial notebook can run without errors even before you fill in your answers.\n",
    "\n",
    "**Numerical precision:** If you round an answer, keep **at least 4 decimal places**. You may use exact expressions, such as `7/3`, instead of decimal approximations. Integers and exact decimals, such as `2` and `2.5`, do not need trailing zeros. Keep full precision inside functions. Use option numbers and `True`/`False` as requested.\n",
    "\n",
    "In the next cell, enter your full name in `student_name` and your student ID in `student_id`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-identity",
   "metadata": {
    "hw2": {
     "fields": {
      "student_id": "str",
      "student_name": "str"
     },
     "part": "identity",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "student_name = \"Name Surname\"  # Replace with your full name.\n",
    "student_id = \"12345678\"  # Replace with your student ID.\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-imports",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-plot-helpers-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "**Provided plotting code**\n",
    "Run the next cell once, then continue to Part A. You can keep the code collapsed.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-plot-helpers",
   "metadata": {
    "hw2": {
     "role": "provided"
    },
    "jupyter": {
     "source_hidden": true
    }
   },
   "outputs": [],
   "source": [
    "# Provided plotting code for A, B and C.\n",
    "\n",
    "def normal_pdf(theta: np.ndarray, mean: float, variance: float) -> np.ndarray:\n",
    "    return np.exp(-(theta - mean)**2 / (2 * variance)) / np.sqrt(2 * np.pi * variance)\n",
    "\n",
    "\n",
    "def plot_measurement_uncertainty(sigma: np.ndarray, weights: np.ndarray) -> None:\n",
    "    # Provided plot. Numerical answers are entered in A2.\n",
    "    a_plot_sigma = np.asarray(sigma, dtype=float)\n",
    "    a_plot_weights = np.asarray(weights, dtype=float)\n",
    "    a_plot_variances = [a_plot_sigma[0, 0], a_plot_sigma[1, 1],\n",
    "                        a_plot_weights @ a_plot_sigma @ a_plot_weights]\n",
    "    limit = 4 * np.sqrt(max(a_plot_variances))\n",
    "    a_plot_errors = np.linspace(-limit, limit, 600)\n",
    "    combined_label = \"Average of the two\" if np.allclose(a_plot_weights, [0.5, 0.5]) else \"Weighted combination\"\n",
    "\n",
    "    fig, ax = plt.subplots(figsize=(8, 3.6))\n",
    "    for variance, label, color, style in zip(\n",
    "        a_plot_variances,\n",
    "        [\"Sensor 1\", \"Sensor 2\", combined_label],\n",
    "        [\"#235bba\", \"#b95008\", \"#087f69\"], [\"--\", \":\", \"-\"],\n",
    "    ):\n",
    "        density = np.exp(-a_plot_errors**2 / (2 * variance)) / np.sqrt(2 * np.pi * variance)\n",
    "        ax.plot(a_plot_errors, density, label=label, color=color, linestyle=style, linewidth=2.4)\n",
    "    ax.axvline(0, color=\"#555555\", linewidth=0.8, alpha=0.5)\n",
    "    ax.set(xlabel=\"Measurement error (°C)\", ylabel=\"Density (1/°C)\",\n",
    "           title=\"How closely do the errors cluster around zero?\")\n",
    "    ax.spines[[\"top\", \"right\"]].set_visible(False)\n",
    "    ax.grid(alpha=0.15)\n",
    "    ax.legend(frameon=False)\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def plot_prior_and_posterior(\n",
    "    data: np.ndarray, sigma_sq: float, mu0: float, sigma0_sq: float\n",
    ") -> None:\n",
    "    # Provided plot using the data from B.\n",
    "    b_plot_data = np.asarray(data, dtype=float)\n",
    "    b_plot_mu0, b_plot_prior_var = mu0, sigma0_sq\n",
    "    b_plot_mean_var = sigma_sq / len(b_plot_data)\n",
    "    b_plot_post_var = 1. / (1. / b_plot_mean_var + 1. / b_plot_prior_var)\n",
    "    b_plot_post_mean = b_plot_post_var * (\n",
    "        b_plot_data.mean() / b_plot_mean_var + b_plot_mu0 / b_plot_prior_var\n",
    "    )\n",
    "    lower = min(mu0 - 4 * np.sqrt(sigma0_sq), b_plot_data.mean() - 4 * np.sqrt(b_plot_mean_var))\n",
    "    upper = max(mu0 + 4 * np.sqrt(sigma0_sq), b_plot_data.mean() + 4 * np.sqrt(b_plot_mean_var))\n",
    "    b_plot_grid = np.linspace(lower, upper, 600)\n",
    "\n",
    "    fig, ax = plt.subplots(figsize=(8, 3.6))\n",
    "    for mean, variance, label, color, style in [\n",
    "        (b_plot_mu0, b_plot_prior_var, \"Prior\", \"#235bba\", \"--\"),\n",
    "        (b_plot_data.mean(), b_plot_mean_var, \"Likelihood (normalised)\", \"#b95008\", \":\"),\n",
    "        (b_plot_post_mean, b_plot_post_var, \"Posterior\", \"#087f69\", \"-\"),\n",
    "    ]:\n",
    "        ax.plot(b_plot_grid, normal_pdf(b_plot_grid, mean, variance),\n",
    "                label=label, color=color, linestyle=style, linewidth=2.4)\n",
    "    ci_lower = b_plot_post_mean - 1.96 * np.sqrt(b_plot_post_var)\n",
    "    ci_upper = b_plot_post_mean + 1.96 * np.sqrt(b_plot_post_var)\n",
    "    ci_grid = np.linspace(ci_lower, ci_upper, 300)\n",
    "    ax.fill_between(ci_grid, normal_pdf(ci_grid, b_plot_post_mean, b_plot_post_var),\n",
    "                    color=\"#087f69\", alpha=0.18,\n",
    "                    label=f\"95% credible interval [{ci_lower:.2f}, {ci_upper:.2f}]\")\n",
    "    ax.vlines([ci_lower, ci_upper], 0,\n",
    "              normal_pdf(np.array([ci_lower, ci_upper]), b_plot_post_mean, b_plot_post_var),\n",
    "              color=\"#087f69\", linestyle=\":\", linewidth=1.5)\n",
    "    ax.set(xlabel=\"θ (mK)\", ylabel=\"Density (1/mK)\",\n",
    "           title=\"Measurements and prior information give the posterior\")\n",
    "    ax.spines[[\"top\", \"right\"]].set_visible(False)\n",
    "    ax.grid(alpha=0.15)\n",
    "    ax.legend(frameon=False)\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def plot_ml_map_comparison(\n",
    "    differences: np.ndarray, tau_sq: float, mu0: float, sigma0_sq: float,\n",
    "    n_repeats: int = 20000, seed: int = 42,\n",
    ") -> None:\n",
    "    # Provided simulation with a fixed true value in each case.\n",
    "    g_plot_noise = np.random.default_rng(seed).normal(0., np.sqrt(tau_sq), size=n_repeats)\n",
    "    g_plot_mu0 = mu0\n",
    "    differences = np.asarray(differences, dtype=float)\n",
    "    gamma = sigma0_sq / (sigma0_sq + tau_sq)\n",
    "    all_ml = np.concatenate([g_plot_mu0 + difference + g_plot_noise for difference in differences])\n",
    "    hist_bins = np.linspace(all_ml.min() - 1., all_ml.max() + 1., 85)\n",
    "\n",
    "    fig, axes = plt.subplots(1, len(differences), figsize=(5.5 * len(differences), 4.2),\n",
    "                             sharex=True, sharey=True, squeeze=False)\n",
    "    axes = axes[0]\n",
    "    for ax, difference in zip(axes, differences):\n",
    "        true_value = g_plot_mu0 + difference\n",
    "        ml_estimates = true_value + g_plot_noise\n",
    "        map_estimates = g_plot_mu0 + gamma * (ml_estimates - g_plot_mu0)\n",
    "\n",
    "        ax.hist(ml_estimates, bins=hist_bins, density=True, color=\"#168c9c\",\n",
    "                alpha=0.45, label=\"ML estimates\")\n",
    "        ax.hist(map_estimates, bins=hist_bins, density=True, color=\"#dc8135\",\n",
    "                alpha=0.65, label=\"MAP estimates\")\n",
    "        ax.axvline(true_value, color=\"#242936\", linestyle=\"--\", linewidth=2,\n",
    "                   label=\"True value θ\")\n",
    "        ax.set_title(f\"d = {difference:g} mK   |   θ = {true_value:g} mK\", fontsize=12)\n",
    "        ax.set_xlabel(\"Estimated temperature deviation (mK)\")\n",
    "        ax.set_axisbelow(True)\n",
    "        ax.grid(axis=\"y\", alpha=0.18)\n",
    "        ax.spines[[\"top\", \"right\"]].set_visible(False)\n",
    "        ax.legend(fontsize=9, frameon=False, loc=\"upper right\")\n",
    "\n",
    "    axes[0].set_ylabel(\"Density of estimates (1/mK)\")\n",
    "    fig.suptitle(\"ML and MAP over repeated measurements\", fontsize=14)\n",
    "    fig.tight_layout()\n",
    "    plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-a-source-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "## Part A · How does uncertainty change when we combine measurements?\n",
    "\n",
    "Two sensors measure temperature, and their errors are correlated. We will examine how much the noise variance decreases when we average their readings.\n",
    "\n",
    "**Adapted from exercise 2.1, Practice Exercises, Lecture 4.**\n",
    "*Notes: Section 2.1, the “sum and difference” example.*\n",
    "\n",
    "The readings $\\boldsymbol{x}=[x_1\\ \\ x_2]^{\\top}$ of two sensors have mean $\\boldsymbol{\\mu}$ and covariance $\\operatorname{Cov}(\\boldsymbol{x})=\\boldsymbol{\\Sigma} =\\left[\\begin{matrix}6&2\\\\2&10\\end{matrix}\\right]$ (units: °C²). We define a new two-channel output:\n",
    "$$\n",
    "\\boldsymbol{v}= \\begin{bmatrix}1&1\\\\1&-1\\end{bmatrix}\\boldsymbol{x} +\\begin{bmatrix}10\\\\-20\\end{bmatrix}.\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-a-symbols-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "The readings are $x_1,x_2$. The vector $\\boldsymbol\\mu$ contains their means. The matrix $\\Sigma$ contains the variances on its diagonal and the covariances off the diagonal. We call the given matrix $A$ and the offset $\\boldsymbol b$. The symbol $\\top$ denotes transpose.\n",
    "\n",
    "$$\\mathbb E[\\boldsymbol v]=A\\boldsymbol\\mu+\\boldsymbol b,\\qquad\n",
    "\\operatorname{Cov}(\\boldsymbol v)=A\\Sigma A^\\top.$$\n",
    "\n",
    "### A1. How does the covariance change?\n",
    "Calculate $A\\Sigma A^\\top$ on paper and enter the final matrix in `sigma_v_hand`. Use `True` or `False` to state whether the constant offset changes the mean (`shift_changes_mean`) and the covariance (`shift_changes_cov`).\n",
    "\n",
    "From the off-diagonal entry of your result, are the sum and difference uncorrelated? Set `sum_diff_uncorrelated` to `True` or `False`. Uncorrelated means that their covariance is zero.\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-a1",
   "metadata": {
    "hw2": {
     "fields": {
      "shift_changes_cov": "bool",
      "shift_changes_mean": "bool",
      "sigma_v_hand": "float[2,2]",
      "sum_diff_uncorrelated": "bool"
     },
     "part": "A",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "sigma_v_hand = np.full((2, 2), np.nan)\n",
    "shift_changes_mean = None  # True or False.\n",
    "shift_changes_cov = None  # True or False.\n",
    "sum_diff_uncorrelated = None  # True or False.\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-a-preview-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "**Before calculating the average**\n",
    "Run the cell. Compare how widely the errors of the two sensors and their average spread around zero. The horizontal position shows the error in °C.\n",
    "\n",
    "For this illustration, we use zero-mean Gaussian errors with the given covariance $\\Sigma$. A narrower distribution means a smaller variance. In A2, we will calculate the reduction.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-a-preview",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "plot_measurement_uncertainty(sigma=np.array([[6., 2.], [2., 10.]]), weights=np.array([0.5, 0.5]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-a3-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### A2. Do two measurements always provide more information?\n",
    "If we copy the same measurement ten times, the average of the copies has exactly the same uncertainty as the original measurement. If we take ten independent measurements of the same quantity, each with the same noise variance, the variance of their average is ten times smaller.\n",
    "\n",
    "The average is $t=(x_1+x_2)/2=\\boldsymbol a^\\top\\boldsymbol x$, with weights $\\boldsymbol a=(1/2,1/2)^\\top$.\n",
    "\n",
    "1. Calculate $\\operatorname{Var}(t)=\\boldsymbol a^\\top\\Sigma\\boldsymbol a$ for the given matrix and enter it in `variance_average_hand`.\n",
    "2. Keep the sensor variances at 6 and 10, and set their covariance to zero. Enter the variance of the same average in `variance_average_uncorrelated_hand`.\n",
    "\n",
    "Compare the two values to see the effect of positive covariance. Variances are measured in °C².\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-a3",
   "metadata": {
    "hw2": {
     "fields": {
      "variance_average_hand": "float",
      "variance_average_uncorrelated_hand": "float"
     },
     "part": "A",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "variance_average_hand = None\n",
    "variance_average_uncorrelated_hand = None\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-a4-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### A3. How do we estimate covariance from measurements?\n",
    "**Adapted from exercise 1.1, Practice Exercises, Lecture 4.** The matrix $X$ is stored in `samples`. Each row is one repetition and each column is one sensor. These samples have their own estimated covariance $\\widehat\\Sigma$.\n",
    "\n",
    "In `sample_cov`, fill in the mean `mu_hat`, the centred measurements `centered`, and the covariance `sigma_hat`, using:\n",
    "$$\\widehat{\\boldsymbol\\mu}=\\frac1N\\sum_{r=1}^N\\boldsymbol x_r,\\qquad\n",
    "D=X-\\widehat{\\boldsymbol\\mu}^{\\top},\\qquad\n",
    "\\widehat\\Sigma=\\frac{D^\\top D}{N-1}.$$\n",
    "Here $N$ is the number of samples and $D$ contains the centred measurements. Implement the three steps using NumPy operations. Use `np.cov` only for the verification below.\n",
    "\n",
    "*Keep full precision inside the function, without rounding.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-a4-data",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "samples = np.array([[17., 19.], [20., 25.], [20., 19.], [23., 25.]])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-a4-function",
   "metadata": {
    "hw2": {
     "function": "sample_cov",
     "part": "A",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "def sample_cov(samples: np.ndarray) -> np.ndarray:\n",
    "    samples = np.asarray(samples, dtype=float)\n",
    "    n_samples, n_features = samples.shape\n",
    "    ### TODO: ADD YOUR CODE HERE\n",
    "    mu_hat = np.full(n_features, np.nan)\n",
    "    centered = np.full_like(samples, np.nan)\n",
    "    sigma_hat = np.full((n_features, n_features), np.nan)\n",
    "    ### END of TODO\n",
    "    return sigma_hat\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-a5-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "**Checking A3**\n",
    "Run the next cell and check that `sample_cov` agrees with `np.cov` and that:\n",
    "\n",
    "1. $\\widehat\\Sigma(X+\\boldsymbol b)=\\widehat\\Sigma(X)$.\n",
    "2. $\\widehat\\Sigma(V)=A\\widehat\\Sigma(X)A^\\top$, where $V=XA^\\top+\\boldsymbol b$.\n",
    "\n",
    "The code stores samples as rows, which is why we use `samples @ transform.T`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-a-check",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "transform = np.array([[1., 1.], [1., -1.]])\n",
    "offset = np.array([10., -20.])\n",
    "sigma_given = np.array([[6., 2.], [2., 10.]])\n",
    "sigma_hat = sample_cov(samples)\n",
    "transformed_samples = samples @ transform.T + offset\n",
    "print(\"Covariance from our function:\\n\", sigma_hat)\n",
    "print(\"NumPy:\\n\", np.cov(samples, rowvar=False, ddof=1))\n",
    "print(\"Agreement with NumPy:\", np.allclose(sigma_hat, np.cov(samples, rowvar=False, ddof=1)))\n",
    "print(\"Unchanged after the offset:\", np.allclose(sample_cov(samples+offset), sigma_hat))\n",
    "print(\"Transformation agreement:\", np.allclose(sample_cov(transformed_samples), transform @ sigma_hat @ transform.T))\n",
    "print(\"A1, given matrix:\\n\", transform @ sigma_given @ transform.T)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-b-source-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "## Part B · How do we combine measurements and prior knowledge?\n",
    "\n",
    "We have a few noisy measurements of a constant temperature deviation and some prior information about its value. We will calculate how they combine and how much each contributes to the final estimate.\n",
    "\n",
    "**Adapted from exercise 1.2, “Completing the square and MAP estimation”, Practice Exercises, Lecture 6.**\n",
    "\n",
    "Three independent measurements in mK satisfy $y_k=\\theta+n_k$, with $n_k\\sim\\mathcal N(0,36)$ and $\\boldsymbol y=(3,6,9)^\\top$. The prior distribution is $\\theta\\sim\\mathcal N(3,6)$.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-b1-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### B1. What do we estimate from the measurements?\n",
    "The unknown constant temperature deviation is $\\theta$, each noise term has variance $\\sigma^2=36$, and $N=3$ is the number of measurements. Write the likelihood as a product of Gaussian densities and take its logarithm.\n",
    "\n",
    "Fill in the coefficients in these expressions:\n",
    "$$J(\\theta)=\\sum_k(y_k-\\theta)^2=a\\theta^2+b\\theta+c,$$\n",
    "$$\\ell(\\theta)=K-qJ(\\theta).$$\n",
    "The term $K$ is constant with respect to $\\theta$ and does not affect the MLE.\n",
    "\n",
    "Enter $[a,b,c]$ in `j_coeffs` and $q$ in `loglike_j_weight`. Find $\\widehat\\theta_{\\rm ML}$ by setting the derivative $J'(\\theta)$ to zero and enter it in `theta_ml_hand`.\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-b1",
   "metadata": {
    "hw2": {
     "fields": {
      "j_coeffs": "float[3]",
      "loglike_j_weight": "float",
      "theta_ml_hand": "float"
     },
     "part": "B",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "j_coeffs = np.full(3, np.nan)  # [a, b, c].\n",
    "loglike_j_weight = None  # q.\n",
    "theta_ml_hand = None\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-b-preview-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "**Before combining measurements and prior information**\n",
    "Run the cell. The horizontal position is a possible value of the unknown deviation $\\theta$. Notice where the posterior peaks and how narrow it is compared with the other two curves. In B2, we will calculate its mean and variance.\n",
    "\n",
    "The likelihood has been normalised with respect to $\\theta$ so that we can compare the shapes of the curves.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-b-preview",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "plot_prior_and_posterior(data=np.array([3., 6., 9.]), sigma_sq=36., mu0=3., sigma0_sq=6.)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g1-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "**What does the shaded interval mean?**\n",
    "The plot provides the central 95% credible interval $[0.08,\\ 7.92]$ mK. Select its interpretation in `credible_interpretation` (1, 2 or 3):\n",
    "\n",
    "1. It contains 95% of the sensor's new measurements.\n",
    "2. It contains 95% of the posterior probability for $\\theta$, given the measurements and the prior.\n",
    "3. Its length equals 95% of the MAP value.\n",
    "\n",
    "*Source: Lecture 7, “How Sure? A Credible Interval” and “A Gaussian: Both Rules Agree”.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-g1",
   "metadata": {
    "hw2": {
     "fields": {
      "credible_interpretation": "choice:1,2,3"
     },
     "part": "B",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "credible_interpretation = None  # 1, 2 or 3.\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-b2-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### B2. How does the prior affect the estimate?\n",
    "The prior mean is $\\mu_0=3$ and its variance is $\\sigma_0^2=6$. Bayes' rule gives:\n",
    "$$\\log p(\\theta\\mid\\boldsymbol y)=C-\\frac1{72}\\left[J(\\theta)+6(\\theta-3)^2\\right].$$\n",
    "The term $C$ collects terms that are independent of $\\theta$.\n",
    "\n",
    "Expand the expression in brackets and complete the square:\n",
    "$$J(\\theta)+6(\\theta-3)^2=a_p\\theta^2+b_p\\theta+c_p\n",
    "=a_p(\\theta-m)^2+r.$$\n",
    "Enter $[a_p,b_p,c_p]$ in `posterior_poly`. The term $r$ is constant. Use $\\theta^2-2m\\theta=(\\theta-m)^2-m^2$. Identify the posterior in the form\n",
    "$$p(\\theta\\mid\\boldsymbol y)=k\\exp\\!\\left[-\\frac{(\\theta-m)^2}{2s^2}\\right].$$\n",
    "Here $m$ is the posterior mean, $s^2$ is its variance, and $k$ is the normalising constant. Enter the MAP estimate in `theta_map_hand` and the posterior variance in `posterior_variance_hand`.\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-b2",
   "metadata": {
    "hw2": {
     "fields": {
      "posterior_poly": "float[3]",
      "posterior_variance_hand": "float",
      "theta_map_hand": "float"
     },
     "part": "B",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "posterior_poly = np.full(3, np.nan)  # [a_p, b_p, c_p].\n",
    "theta_map_hand = None\n",
    "posterior_variance_hand = None  # s².\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-b3-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### B3. How much weight does each source receive?\n",
    "Find the variance $\\tau^2$ of the average $\\bar y$ of the three measurements and enter it in `mean_measurement_variance`. Enter the weights $w_{\\rm data}$ in `data_weight_hand` and $w_{\\rm prior}$ in `prior_weight_hand`, using\n",
    "$$\\widehat\\theta_{\\rm MAP}=w_{\\rm data}\\bar y+w_{\\rm prior}\\mu_0.$$\n",
    "\n",
    "Precision is the reciprocal of variance. Divide each source's precision by the sum of the two precisions to find its weight. For the data, use the variance $\\tau^2$ of the average. For the prior, use $\\sigma_0^2$.\n",
    "\n",
    "Keeping the measurements fixed, what value does the MAP estimate approach as the prior variance grows without bound? Enter the result in `map_vague_limit`.\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-b3",
   "metadata": {
    "hw2": {
     "fields": {
      "data_weight_hand": "float",
      "map_vague_limit": "float",
      "mean_measurement_variance": "float",
      "prior_weight_hand": "float"
     },
     "part": "B",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "mean_measurement_variance = None  # τ².\n",
    "data_weight_hand = None\n",
    "prior_weight_hand = None\n",
    "map_vague_limit = None\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-b5-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### B4. Computational verification\n",
    "In `gaussian_update`, fill in the posterior mean in `posterior_mean` and the posterior variance in `posterior_var`. The argument `tau_sq` is the variance of the **ML estimate**, and `sigma0_sq` is the prior variance. The argument `data_estimate` is the ML value, and `mu0` is the prior mean.\n",
    "\n",
    "The function returns two values in the order `(posterior_mean, posterior_var)`. The call `m, s2 = gaussian_update(...)` stores them in two variables.\n",
    "\n",
    "Use the precision relationship from B3. The plotting code is provided.\n",
    "\n",
    "*Keep full precision inside the function, without rounding.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-b5-function",
   "metadata": {
    "hw2": {
     "function": "gaussian_update",
     "part": "B",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "def gaussian_update(\n",
    "    data_estimate: float, tau_sq: float, mu0: float, sigma0_sq: float\n",
    ") -> tuple[float, float]:\n",
    "    ### TODO: ADD YOUR CODE HERE\n",
    "    posterior_mean = np.nan\n",
    "    posterior_var = np.nan\n",
    "    ### END of TODO\n",
    "    return posterior_mean, posterior_var\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-b-check",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "y_b = np.array([3., 6., 9.])\n",
    "mu0_b, sigma0_sq_b, sigma_sq_b = 3., 6., 36.\n",
    "tau_sq_b = sigma_sq_b / len(y_b)\n",
    "m_b, s2_b = gaussian_update(y_b.mean(), tau_sq_b, mu0_b, sigma0_sq_b)\n",
    "print(\"MAP from function / by hand:\", m_b, theta_map_hand)\n",
    "print(\"Posterior variance from function / by hand:\", s2_b, posterior_variance_hand)\n"
   ]
  },
  {
   "id": "hw2-g-intro-prompt",
   "cell_type": "markdown",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "## Part C · When does the prior help, and when does it increase the error?\n",
    "\n",
    "We will examine the uncertainty of our estimate and what happens when the prior mean is far from the true value. We want to find out whether MAP still has a smaller mean squared error than ML.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g-source-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### Bias and MSE of MAP\n",
    "**Adapted from exercise 4.1(a–c), “Posterior variance, estimator variance and MSE”, Practice Exercises, Lecture 6.**\n",
    "\n",
    "An ML estimate satisfies $z\\mid\\theta\\sim\\mathcal N(\\theta,16)$ in mK, and the prior distribution is $\\theta\\sim\\mathcal N(\\mu_0,16)$. Across repeated experiments, the true value $\\theta$ and the prior information stay fixed. Only $z$ changes. We define $\\gamma$ through $\\hat\\theta_{\\rm MAP}=\\mu_0+\\gamma(z-\\mu_0)$. The bias is $\\mathbb E[\\hat\\theta]-\\theta$ and the MSE is $\\mathbb E[(\\hat\\theta-\\theta)^2]$, with expectations taken over repeated measurements at this fixed $\\theta$.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g-plot-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "**Before calculating bias and MSE**\n",
    "Run the cell. Each plot shows estimates from 20,000 repetitions, with a fixed true value $\\theta$ and prior mean $\\mu_0=0$. The measurement noise changes each time. The quantity $d=\\theta-\\mu_0$ is the signed difference between the true value and the prior mean.\n",
    "\n",
    "Notice how widely the estimates spread and where they concentrate relative to the dashed line marking the true value. Both plots use the same scale. In C1–C3, we will calculate these properties and the overall error.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-g-plot",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "plot_ml_map_comparison(\n",
    "    differences=np.array([4., 8.]), tau_sq=16., mu0=0., sigma0_sq=16.,\n",
    "    n_repeats=20000, seed=42,\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g2-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### C1. Two variances\n",
    "The preceding plot shows how MAP estimates vary across repetitions with a fixed true value. In the plot in Part B, the posterior described uncertainty about the parameter, given the specific measurements and the prior. The two variances below correspond to these two different descriptions.\n",
    "\n",
    "The ML estimate is $z$, with variance $\\tau^2=16$. The prior variance is $\\sigma_0^2=16$. Calculate $\\gamma$ in `gamma_hand` and the posterior variance in `posterior_var_g`:\n",
    "$$\\gamma=\\frac{\\sigma_0^2}{\\sigma_0^2+\\tau^2},\\qquad\n",
    "\\sigma_{\\rm post}^2=\\left(\\frac1{\\tau^2}+\\frac1{\\sigma_0^2}\\right)^{-1}.$$\n",
    "For the estimator variance (`estimator_var_g`), use $\\operatorname{Var}(aZ+b)=a^2\\operatorname{Var}(Z)$ for constants $a,b$.\n",
    "\n",
    "Which variance describes MAP estimates across repetitions with a fixed true value? In `repetitions_variance_choice`, enter **1:** posterior variance, or **2:** estimator variance.\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-g2",
   "metadata": {
    "hw2": {
     "fields": {
      "estimator_var_g": "float",
      "gamma_hand": "float",
      "posterior_var_g": "float",
      "repetitions_variance_choice": "choice:1,2"
     },
     "part": "G",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "gamma_hand = None\n",
    "posterior_var_g = None\n",
    "estimator_var_g = None\n",
    "repetitions_variance_choice = None  # 1 or 2.\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g3-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### C2. How does an incorrect prior affect the error?\n",
    "Write $z=\\theta+\\varepsilon$, where $\\mathbb E[\\varepsilon]=0$ and $\\operatorname{Var}(\\varepsilon)=16$. The quantity $d=\\theta-\\mu_0$ is the **signed difference** between the true value and the prior mean. Substitution into the MAP estimate gives the error:\n",
    "$$\\hat\\theta-\\theta=-\\frac12d+\\frac12\\varepsilon.$$\n",
    "\n",
    "1. Take the expectation to find the bias in the form $b_d d$. Enter $b_d$ in `bias_d_coefficient`.\n",
    "2. Square the error and take the expectation to find the MSE in the form $q_d d^2+r$. Enter $[q_d,r]$ in `mse_coeffs`.\n",
    "\n",
    "Reminder: $\\mathbb E[\\varepsilon^2]=16$, since the mean is zero.\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-g3",
   "metadata": {
    "hw2": {
     "fields": {
      "bias_d_coefficient": "float",
      "mse_coeffs": "float[2]"
     },
     "part": "G",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "bias_d_coefficient = None  # b_d.\n",
    "mse_coeffs = np.full(2, np.nan)  # [q_d, r].\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g4-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### C3. When does MAP have a smaller MSE?\n",
    "Calculate the bias and MSE for $d=4$ and $d=8$ mK. In `comparison_hand`, enter two rows, first for $d=4$ and then for $d=8$, with columns `[bias_map, mse_map, mse_ml]`.\n",
    "\n",
    "Compare the MSE values in the table and select a conclusion in `mse_conclusion` (1 or 2):\n",
    "1. A smaller posterior variance guarantees a smaller MSE for every true value.\n",
    "2. The MSE also depends on the difference between the true value and the prior mean.\n",
    "\n",
    "*Precision: at least 4 decimal places if you round your answer.*\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-g4",
   "metadata": {
    "hw2": {
     "fields": {
      "comparison_hand": "float[2,3]",
      "mse_conclusion": "choice:1,2"
     },
     "part": "G",
     "role": "answer"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "comparison_hand = np.full((2, 3), np.nan)  # Rows d=4, d=8.\n",
    "mse_conclusion = None  # 1 or 2.\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g5-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "### C4. What do we observe over many repetitions?\n",
    "Run the following cells. The code generates 20,000 independent repetitions for each case in C3, with fixed $\\mu_0=0$ and $\\theta=d$. The provided `error_statistics` function calculates bias, estimator variance and MSE.\n",
    "\n",
    "Compare the numerical results with your table in C3. Relate the values to the plots before C1. No separate written answer is required.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-g5-function",
   "metadata": {
    "hw2": {
     "part": "G",
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "def error_statistics(estimates: np.ndarray, truth: float) -> tuple[float, float, float]:\n",
    "    estimates = np.asarray(estimates, dtype=float)\n",
    "    errors = estimates - truth\n",
    "    bias = errors.mean()\n",
    "    variance = np.var(estimates, ddof=0)\n",
    "    mse = np.mean(errors**2)\n",
    "    return bias, variance, mse\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-g-simulation",
   "metadata": {
    "hw2": {
     "role": "provided"
    }
   },
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(42)\n",
    "noise = rng.normal(0., 4., size=20000)  # Standard deviation sqrt(16)=4.\n",
    "mu0_g = 0.\n",
    "for d in [4., 8.]:\n",
    "    truth = mu0_g + d\n",
    "    z = truth + noise\n",
    "    estimates_map = mu0_g + 0.5*(z-mu0_g)\n",
    "    bias, variance, mse = error_statistics(estimates_map, truth)\n",
    "    print(f\"d={d:g}: bias={bias:.4f}, variance={variance:.4f}, MSE={mse:.4f}\")\n",
    "    print(\"MSE and bias² + variance agree:\", np.allclose(mse, bias**2+variance))\n",
    "    print(\"Empirical ML MSE:\", np.mean((z-truth)**2))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-g6-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "Small differences between the simulation and the analytical values are expected because we use a finite number of random measurements. With more repetitions, the estimates usually approach the theoretical values.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-00-prompt",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "instruction"
    }
   },
   "source": [
    "## Part D\n",
    "\n",
    "Choose **one question about the material in Lectures 4–7**. Design a small experiment to help you understand it better.\n",
    "\n",
    "### Choosing a topic\n",
    "\n",
    "Choose something that interests you or that you found difficult and would like to spend more time on. You can start from an exercise covered in class, the practice sheets, or a question of your own.\n",
    "\n",
    "Some possible directions are:\n",
    "\n",
    "- Visualisation: create a visual representation that helps explain a mathematical concept or method.\n",
    "\n",
    "- Experimentation: modify a familiar exercise or change a problem's parameters and examine how the result changes.\n",
    "\n",
    "- Implementation: investigate alternative implementations of a method or the behaviour of an algorithm.\n",
    "\n",
    "- Verification: check a solution, an assumption or a computational result.\n",
    "\n",
    "These are suggestions. You may follow any other approach you find interesting, as long as it relates to the course material.\n",
    "\n",
    "### Designing the experiment\n",
    "\n",
    "The aim is to investigate a specific question and explain what you observe. Reproducing a known solution or producing a plot alone is not enough.\n",
    "\n",
    "Design a **small test, comparison or visualisation** that helps answer your question. Decide what to vary, what to keep fixed and what you expect to observe.\n",
    "\n",
    "Your experiment can be simple. Even a result that contradicts your initial prediction can be a useful observation.\n",
    "\n",
    "### Tools\n",
    "\n",
    "Your exploration must include **Python code that runs in the notebook**. You may use any libraries you wish, as well as AI tools such as ChatGPT, Claude or Gemini. AI use is allowed and encouraged to help understand a concept, design an experiment, generate code or interpret results.\n",
    "\n",
    "Choose what you want to investigate first, based on your own questions and interests. Then use the tools to explore it.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-01-prompt",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "instruction"
    }
   },
   "source": [
    "### Deliverables\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-02-prompt",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "instruction"
    }
   },
   "source": [
    "#### D1. Question and initial prediction\n",
    "\n",
    "What question did you choose, why does it interest you, and what did you expect to happen?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-03",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "open_response"
    }
   },
   "source": [
    "*Write here.*\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-04-prompt",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "instruction"
    }
   },
   "source": [
    "#### D2. Method and tools\n",
    "\n",
    "Describe what you varied, what you kept fixed and how you investigated your question. If you used AI, report the model and prompts.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-05",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "open_response"
    }
   },
   "source": [
    "*Write here.*\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-06-prompt",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "instruction"
    }
   },
   "source": [
    "#### D3. Experiment code\n",
    "\n",
    "Include your Python code in the next code cell.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-d-07",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "open_response"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "# Write the Python code for your experiment here,\n",
    "# whether you wrote it yourself or obtained it from the AI tool you used.\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-08-prompt",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "instruction"
    }
   },
   "source": [
    "#### D4. Result and interpretation\n",
    "\n",
    "Present your result as code output, a table, a plot or another suitable format. You may refer to the output of D3. Make clear what you are comparing or checking. Explain your conclusion, whether the result agrees with your prediction and whether it answers your initial question. Add anything you would like to investigate further, if applicable.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-d-09",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "part": "D",
     "role": "open_response"
    }
   },
   "source": [
    "*Write here.*\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-submission-prompt",
   "metadata": {
    "hw2": {
     "role": "instruction"
    }
   },
   "source": [
    "## Before submitting\n",
    "\n",
    "- Check your full name, student ID and answers in A–D.\n",
    "- Select **Restart Kernel and Run All**. Save with visible outputs and plots. Running the code and saving the outputs are part of the assessment.\n",
    "- The code for each question must run without errors and produce correct results. Code that fails to run receives no credit for that question.\n",
    "- Submit the completed `homework_2_en.ipynb`. Feedback is optional.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-feedback-0",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "role": "feedback"
    }
   },
   "source": [
    "### Optional: give us feedback!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-feedback-1",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "role": "feedback"
    }
   },
   "source": [
    "How much did each of the following help you understand the material through this assignment? Rate from 0 (not at all) to 10 (very much).\n",
    "\n",
    "- Analytical exercises → `feedback_a`\n",
    "- Connecting analytical calculations with Python implementation → `feedback_b`\n",
    "- Personal exploration in Part D → `feedback_c`\n",
    "\n",
    "Optionally, enter in `time_spent_hours` approximately how many hours you spent on the whole assignment, including Part D and excluding breaks. A rough estimate is enough, such as `1.5` for an hour and a half.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hw2-feedback-2",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "role": "feedback"
    }
   },
   "outputs": [],
   "source": [
    "### TODO: ADD YOUR CODE HERE\n",
    "# Rate from 0 (Not at all) to 10 (Very much).\n",
    "\n",
    "feedback_a = None  # analytical exercises\n",
    "feedback_b = None  # connecting analytical exercises with Python implementation\n",
    "feedback_c = None  # personal exploration in Part D\n",
    "\n",
    "time_spent_hours = None  # Total time spent, in hours (e.g. 1.5).\n",
    "### END of TODO\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hw2-feedback-3",
   "metadata": {
    "hw2": {
     "execute_in_grading": false,
     "role": "feedback"
    }
   },
   "source": [
    "_You can write any other comments here._\n"
   ]
  }
 ],
 "metadata": {
  "hw2": {
   "lectures": [
    4,
    5,
    6,
    7
   ],
   "version": "2026-11-16"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
