{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dfe0f828",
   "metadata": {},
   "source": [
    "### Exercise 32"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f663470",
   "metadata": {},
   "source": [
    "#### Import"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "933c4e44",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from numpy.linalg import inv\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42b30c1e",
   "metadata": {},
   "source": [
    "#### Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f3dad044",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('sinusoidal.csv')\n",
    "\n",
    "x = df[['x']].to_numpy()\n",
    "y = df[['y']].to_numpy()\n",
    "n = len(x)\n",
    "\n",
    "x = x.reshape((n,))\n",
    "y = y.reshape((n,))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "734f8bbb",
   "metadata": {},
   "source": [
    "#### Plot parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "652a38b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "mplot = 200\n",
    "space = np.linspace(0, 1, mplot)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "161d69ec",
   "metadata": {},
   "source": [
    "#### Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "0491c1a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_Phi_poly(x, p, n):\n",
    "    X = np.zeros((n, p))\n",
    "    \n",
    "    for i in range(n):\n",
    "        for j in range(p):\n",
    "            X[i][j] = x[i]**j\n",
    "    return X\n",
    "\n",
    "\n",
    "def create_Phi_gauss(x, p, n):\n",
    "    X = np.zeros((n, p))\n",
    "    centres = np.linspace(0, 1, p)\n",
    "    \n",
    "    for i in range(n):\n",
    "        for j in range(p):\n",
    "            X[i][j] = np.exp(-50*(x[i] - centres[j])**2)\n",
    "    return X\n",
    "\n",
    "\n",
    "def fitted_curve_poly(space, w, mplot, p):\n",
    "    result = np.zeros(mplot)\n",
    "    for j in range(p):\n",
    "        result += w[j] * space**j\n",
    "    return result\n",
    "\n",
    "\n",
    "def fitted_curve_gauss(space, w, mplot, p):\n",
    "    result = np.zeros(mplot)\n",
    "    centres = np.linspace(0, 1, p)\n",
    "    for j in range(p):\n",
    "        result += w[j] * np.exp(-50*(space - centres[j])**2)\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "532d7098",
   "metadata": {},
   "source": [
    "### (a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20ca04e7",
   "metadata": {},
   "source": [
    "#### Parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c70f08fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "p = 4\n",
    "alpha = 0.0001\n",
    "beta = 10"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b043a483",
   "metadata": {},
   "source": [
    "#### Predictive mean and variance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "4cfcdf46",
   "metadata": {},
   "outputs": [],
   "source": [
    "Phi = create_Phi_poly(x, p, n)\n",
    "S_n = inv(alpha*np.eye(p) + beta*Phi.T @ Phi)\n",
    "m_n = beta* S_n @ Phi.T @ y\n",
    "\n",
    "fitted_curve = fitted_curve_poly(space, m_n, mplot, p)\n",
    "\n",
    "predictive_std = np.zeros(mplot)\n",
    "for j in range(mplot):\n",
    "    phi = space[j]**np.arange(p)\n",
    "    predictive_std[j] = np.sqrt(beta**(-1) + phi.T @ S_n @ phi)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54f9a282",
   "metadata": {},
   "source": [
    "#### Plot"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "867160f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(x, y, color='black')\n",
    "plt.plot(space, fitted_curve, color='black')\n",
    "plt.fill_between(space, fitted_curve - predictive_std, fitted_curve + predictive_std, color='black', alpha=.1)\n",
    "plt.ylim(np.min(y)-.2, np.max(y)+.2)\n",
    "plt.xlim(0,1) # looks better\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "0f6e9f8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "y2 = y[x > .4]\n",
    "x2 = x[x > .4]\n",
    "n2 = len(x2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "4fd16630",
   "metadata": {},
   "outputs": [],
   "source": [
    "Phi = create_Phi_poly(x2, p, n2)\n",
    "S_n = inv(alpha*np.eye(p) + beta*Phi.T @ Phi)\n",
    "m_n = beta* S_n @ Phi.T @ y2\n",
    "\n",
    "fitted_curve = fitted_curve_poly(space, m_n, mplot, p)\n",
    "\n",
    "predictive_std = np.zeros(mplot)\n",
    "for j in range(mplot):\n",
    "    phi = space[j]**np.arange(p)\n",
    "    predictive_std[j] = np.sqrt(beta**(-1) + phi.T @ S_n @ phi)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "7696b016",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.scatter(x2, y2, color='black')\n",
    "plt.plot(space, fitted_curve, color='black')\n",
    "plt.fill_between(space, fitted_curve - predictive_std, fitted_curve + predictive_std, color='black', alpha=.1)\n",
    "plt.ylim(np.min(y)-.2, np.max(y)+.2)\n",
    "plt.xlim(0,1) # looks better\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('y')\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "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.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
