{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5fbb6606-ab9a-4481-bfb5-72a958b0d72c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# Lösungen SciPy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8455dadf-ad76-4c6e-b6c4-e72764d41e86",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "skip"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from scipy import stats\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78aed4e3-89b5-4baa-995a-2235e17ddd8b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Aufgabe\n",
    "\n",
    "*7 Punkte*\n",
    "\n",
    "Bestimme mittels Linearer Regression die *best fit* Funktion für die beiden gegebenen Datensets `x_data` & `y_data`, unter beachtung folgender Punkte:\n",
    "\n",
    "- Plotte das Ergebnis angemessen\n",
    "- Nutze SciPys `linregress` Funktion, speichere den Output vor dem entpacken in der Variablen `l`\n",
    "- Definiere die Funktion `reg_line` mit einem Eingabeparameter\n",
    "- Bestimme die Werte für `-0.3` & `3.4` speichere diese als liste in variablen `future`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a5dadce5-e415-4b39-80a5-0ad3cb5e6352",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "fragment"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "random = np.random.default_rng(420)\n",
    "\n",
    "# 2 scuffed up One-Liners :)\n",
    "x_data: np.array = np.sort(np.round(random.random(40)*np.pi, decimals=2))\n",
    "y_data: np.array = np.flip(np.sort(np.round(random.random(40)*np.sqrt(2), decimals=2)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "7b2b2652-1771-4434-ac6e-bf7d80ba15cf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "l = stats.linregress(x_data,y_data)\n",
    "slope, intercept, _, _, stderr = l\n",
    "\n",
    "def reg_line(x: float) -> float:\n",
    "    return float(np.round(slope*x+intercept,decimals=2))\n",
    "\n",
    "ext: tuple = (-0.3, 3.4)\n",
    "rl: np.array = np.vectorize(reg_line)(ext)\n",
    "\n",
    "future: list = [reg_line(ext[0]), reg_line(ext[1])]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "bf16eea1-0524-46e4-84d5-b5b87308941e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "skip"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Y')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 17364 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.title(\"Scattered Random Values\")\n",
    "plt.grid()\n",
    "plt.xlabel(\"X\")\n",
    "plt.ylabel(\"Y\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0a27e646-5b06-4f83-abf4-7925350a0ea7",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 36836 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.scatter(x_data,y_data, color='g', label=\"Original Data\")\n",
    "plt.plot(ext, rl, color='m', label=\"Fitted Line\")\n",
    "plt.scatter(ext, future, color='r', label=\"Predicted Data\")\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ca0bc7d-6fcb-475f-bdfc-c0b63579cc93",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Aufgabe \n",
    "\n",
    "*6 Punkte*\n",
    "\n",
    "Gegeben sind die nach Altersgruppe aufgeschlüsselten Durschnittskörpergrößen (in cm) von Frauen in Deutschland. (Zu finden beim [Statistischen Bundesamt](https://www.destatis.de/DE/Themen/Gesellschaft-Umwelt/Gesundheit/Gesundheitszustand-Relevantes-Verhalten/Tabellen/koerpermasse-frauen.html))\n",
    "\n",
    "Gehe wie folgt vor:\n",
    "\n",
    "- Berechne das arithmetische Mittel nutze dafür NumPy. und speichere das Ergebnis mit einer Genauigkeit von 1 Dezimalstelle nach dem Komma in der Variablen `avg_height`.\n",
    "- Gegeben ist auch die Standardabweichung von 15cm, stelle die Normalverteilung mittels `norm.pdf` auf. Speichere den Wert in `norm_height` und finde einen geeigneten linespace zum plotten.\n",
    "- Berechne folgend die Körpergröße unter die 80% aller Frauen (nach Datenset) fallen. Speichere den Wert in der Variablen `avg_percentile`.\n",
    "- Plotte das Ergebnis. Orientiere dich gerne an dem Bienenbeispiel. Finde eine geeignete Darstellung. *Tipp: Da die Y-Achse in diesem Beispiel keinen Sinn ergibt kannst du sie einfach austellen mit `plt.yticks([])`*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "2b3711d0-aed5-4be2-a6a5-18df1767a97f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Given\n",
    "avg_height_per_woman = {\n",
    "    \"18 - 20\": 167.6,\n",
    "    \"20 - 25\": 167.7,\n",
    "    \"25 - 30\": 167.3,\n",
    "    \"30 - 35\": 167.2,\n",
    "    \"35 - 40\": 167.3,\n",
    "    \"40 - 45\": 167.5,\n",
    "    \"45 - 50\": 167.1,\n",
    "    \"50 - 55\": 167.1,\n",
    "    \"55 - 60\": 166.9,\n",
    "    \"60 - 65\": 165.4,\n",
    "    \"65 - 70\": 164.5,\n",
    "    \"70 - 75\": 163.9,\n",
    "    \"75+\": 162.8\n",
    "}\n",
    "\n",
    "avg_height = None\n",
    "norm_height = None\n",
    "avg_percentile = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "9e931834-455b-4596-b1d6-4166a1e06852",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "avg_height = np.round(\n",
    "        np.mean(list(avg_height_per_woman.values()))\n",
    "        , decimals=1)\n",
    "std_sigma = 15\n",
    "\n",
    "norm_x = np.linspace(120, 220, 1000)\n",
    "norm_height = stats.norm(avg_height, std_sigma).pdf(norm_x)\n",
    "\n",
    "# Height of 80th percentile of woman heights\n",
    "avg_percentile = stats.norm(avg_height, std_sigma).ppf(0.8)\n",
    "\n",
    "x_percentile = np.arange(norm_x[0], avg_percentile, 0.01)\n",
    "y_percentile = stats.norm(avg_height, std_sigma).pdf(x_percentile)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "e36af98b-3fa7-4c3b-9418-cb2792da5235",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 34184 characters]",
      "text/plain": [
       "<Figure size 900x300 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, ax = plt.subplots(figsize=(9,3))\n",
    "ax.plot(norm_x, norm_height, color='r')\n",
    "ax.fill_between(x_percentile, y_percentile, 0, alpha=.5, color='#fa0000')\n",
    "ax.text(0.4,0.18,\n",
    "f\"80th percentile of Womens heigth\\n fall under {avg_percentile:.1f}cm\",\n",
    "ha='center', va='center', transform=ax.transAxes,\n",
    "bbox={'facecolor':'#fafafa','alpha':1,'edgecolor':'none','pad':1},\n",
    "color='#de2e0b'\n",
    ")\n",
    "plt.title(\"Woman Height Normal Distribution\")\n",
    "plt.xlabel(\"Height\")\n",
    "plt.yticks([]) # hide y\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7335367c-46e3-4396-bc41-d9d2e6621194",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Aufgabe\n",
    "\n",
    "*7 Punkte*\n",
    "\n",
    "Gegeben sind zwei Würfel aus dem Spiel **Super Mario Party**. Es wird im folgenden angenommen das die Charaktere ihre Würfel würfeln und deren Augenzahl addiert wird.\n",
    "\n",
    "- Stelle alle Kombinationen der Gegebenen Daten auf, speichere diese als Dictionary in der Variablen `dist_mp`.\n",
    "- Exthrahiere den am dritt häufigsten Aufkommenden Wert und speicher diesen in der Variablen `best3` als tuple in der Form `(<Augenzahl>, <Auftritte>)`.\n",
    "- Plotte eine geeignete binomiale Verteilung. *Tipp: schaue dir an wie du den Plot mittels matplotlib vergrößerst*"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27720a28-4a96-4567-b2f0-52961bdd387f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "Einige der Würfel gebem dem Charakter Münzen. Finde eine logische Schlussfolgerung diese mit anderen Werten zu ersetzen. Überlege dabei welche Auswirkungen es auf die Augenzahl hat das der Charakter Münzen bekomment.\n",
    "\n",
    "|Charakter|Dice|\n",
    "|-|-|\n",
    "|Mario|1, 3, 3, 3, 5, 6|\n",
    "|Peach|0, 2, 4, 4, 4, 6|\n",
    "|Boo|-2 Coins, -2 Coins, 5, 5, 7, 7|\n",
    "|Donkey Kong|+5 Coins, 0, 0, 0, 10, 10|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "e6b079fa-95b0-4a6c-90d2-fc39b8a045b7",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# define dices\n",
    "mario = [1, 3, 3, 3, 5, 6]\n",
    "peach = [0, 2, 4, 4, 4, 6]\n",
    "boo = [0, 0, 5, 5, 7, 7]\n",
    "dk = [0, 0, 0, 0, 10, 10]\n",
    "\n",
    "# Create Keys\n",
    "keys: set = {\n",
    "    m+p+b+d\n",
    "    for m in mario for p in peach\n",
    "    for b in boo for d in dk\n",
    "}\n",
    "\n",
    "# Creating a dict with all keys\n",
    "dist_mp: dict = {k: 0 for k in keys}\n",
    "\n",
    "# Summing all possible combinations and store them inside the dict\n",
    "for m in mario:\n",
    "    for p in peach:\n",
    "        for b in boo:\n",
    "            for d in dk:\n",
    "                dice_roll: int = m+p+b+d\n",
    "                dist_mp[dice_roll] += 1\n",
    "\n",
    "best3: tuple = (10, dist_mp[10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "ecbad816-1cf1-4cb8-ad95-e4da62fd6164",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 29752 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Plot\n",
    "plt.bar(dist_mp.keys(), dist_mp.values(), color='#F00a00')\n",
    "plt.xticks(list(dist_mp.keys()))\n",
    "plt.title(\"Mario Party Dice role Distribution\")\n",
    "plt.xlabel(\"Points rolled\")\n",
    "plt.ylabel(\"Number of occurrences\")\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.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
