{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import tikzplotlib\n",
    "\n",
    "\n",
    "def read_oscilloscope_file(file_name, time_div=200):\n",
    "    with open(file_name, 'r') as file:\n",
    "        lines = []\n",
    "        for line in file:\n",
    "            lines.append(line.strip())\n",
    "        # print(file.name)\n",
    "\n",
    "    data = pd.DataFrame()\n",
    "    \n",
    "    data[\"time\"] = np.linspace(0, 12*time_div, 1200)\n",
    "    data[\"CH1\"] = np.float_(lines[5:1205])\n",
    "    data[\"CH2\"] = np.float_(lines[1212:2412])\n",
    "\n",
    "    return data\n",
    "\n",
    "\n",
    "def plot_kurven(data: pd.DataFrame, title=\"\", xStart=0, xStop=0, xStep=200, xStepMinor=100, vlines=[]):\n",
    "    fig, ax = plt.subplots(figsize=(10, 4))\n",
    "\n",
    "    # time offset\n",
    "    if xStop > xStart:\n",
    "        data[\"time\"] -= xStart\n",
    "\n",
    "    ax.plot(\"time\", \"CH1\", data=data, label=\"Anfang\", ls=\"-\", marker='.')\n",
    "    ax.plot(\"time\", \"CH2\", data=data, label=\"Ende\", ls=\"-\", marker='.')\n",
    "\n",
    "\n",
    "    # Beschriftungen setzen\n",
    "    ax.set_xlabel(\"Zeit t [ns]\")\n",
    "    ax.set_ylabel(\"Spannung U [V]\")\n",
    "    if title != \"\": ax.set_title(title, fontsize=16, pad=10)\n",
    "\n",
    "    \n",
    "    # ax.set_xticks(np.arange(data[\"time\"].iloc[0], data[\"time\"].iloc[-1], xStepMinor), minor=True)\n",
    "    ax.set_xticks(np.arange(data[\"time\"].iloc[0], data[\"time\"].iloc[-1], xStep))\n",
    "\n",
    "    if xStop > xStart:\n",
    "        ax.set_xlim(left=0, right=xStop-xStart)\n",
    "    else:\n",
    "        ax.set_xlim(left=data[\"time\"].iloc[0], right=data[\"time\"].iloc[-1])\n",
    "\n",
    "    if xStepMinor != 0:\n",
    "        ax.grid(which=\"major\", ls=\"-\", linewidth=0.5)\n",
    "        # ax.grid(which=\"minor\", ls=\"-\", linewidth=0.1)\n",
    "    else: \n",
    "        ax.grid(which=\"major\")\n",
    "\n",
    "    ax.legend()\n",
    "    # ax.axvline(x=73, ls=\"--\", color=\"green\")\n",
    "    # ax.text(60, 1.0, \"$t_1$\", fontsize=24, color=\"green\", usetex=True)\n",
    "\n",
    "    # ax.axvline(x=123, ls=\"--\", color=\"green\")\n",
    "    # ax.text(110, 1.5, \"$t_2$\", fontsize=24, color=\"green\", usetex=True)\n",
    "    # plt.show()\n",
    "\n",
    "    return fig, ax\n",
    "\n",
    "def set_u_offset(data: pd.DataFrame, t1=600, t2=1000):\n",
    "    # Zeitraum zum Kalibrieren extrahieren\n",
    "    data_dt = data[(data[\"time\"] > t1) & (data[\"time\"] < 1000)]\n",
    "    \n",
    "    # Offset aus dem Druchschnittberechnen\n",
    "    ch1_offset = data_dt[\"CH1\"].mean()\n",
    "    ch2_offset = data_dt[\"CH2\"].mean()\n",
    "\n",
    "    # Offset aufs ursprüngliche Dataset anwenden\n",
    "    data[\"CH1\"] -= ch1_offset\n",
    "    data[\"CH2\"] -= ch2_offset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib widget"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lel = read_oscilloscope_file(\"Messungen/Rohdaten/Messung 2.1/Reflexion bei Kurzschluss.txt\", time_div=200)\n",
    "# plot_kurven(lel)\n",
    "plot_kurven(lel, 1000, 1400)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Alles plotten und als Bilder abspeichern\n",
    "current_directory = os.getcwd()\n",
    "\n",
    "# iterate over all files in the directory \"Messungen/Rohdaten/\"\n",
    "for root, dirs, files in os.walk(os.path.join(current_directory, \"Messungen/Rohdaten/\")):\n",
    "    if root == \"c:\\\\Users\\\\matth\\\\OneDrive\\\\Dokumente\\\\Studium\\\\WS23\\\\Grundlagen Elektrotechnik 3\\\\Praktikum\\\\V5\\\\get3-v5\\\\Messungen/Rohdaten/Messung 2.2\":\n",
    "        for file in files:\n",
    "            if file.endswith(\".txt\"):\n",
    "                file_path = os.path.join(root, file)\n",
    "                messung = read_oscilloscope_file(file_path, 200)\n",
    "                plot_kurven(messung, title=file[0:-4])\n",
    "                # plot_kurven(messung, title=file[0:-4], xStart=1000, xStop=1500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Diagramme für 3.2 Kurzschluss\n",
    "kurzschluss = read_oscilloscope_file(\"Messungen/Rohdaten/Messung 2.1/Reflexion bei Kurzschluss.txt\")\n",
    "# kurzschluss.set_index(\"time\", inplace=True)\n",
    "\n",
    "kurzschluss_fig = plot_kurven(kurzschluss, xStart=1060, xStop=1232, title=\"Reflexion bei Kurzschluss\", xStep=10, xStepMinor=5)\n",
    "kurzschluss_fig.savefig(\"Reflexion_bei_Kurzschluss\", dpi=250)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Leerlauf\n",
    "leerlauf = read_oscilloscope_file(\"Messungen/Rohdaten/Messung 2.1/Reflexion im Leerlauf.txt\")\n",
    "\n",
    "set_u_offset(leerlauf)\n",
    "\n",
    "leerlauf_fig, leerlauf_ax = plot_kurven(leerlauf, title=\"Relfexion bei Leerlauf\", xStart=1120, xStop=1370, xStep=20)\n",
    "\n",
    "# Markierungen von t1 und t2 zur Berechnung der Ausbreitungsgeschwindigkeit\n",
    "leerlauf_ax.text(60, 3.5, \"$t_1$\", fontsize=24, color=\"green\", usetex=True)\n",
    "leerlauf_ax.axvline(x=73, ls=\"--\", color=\"green\")\n",
    "leerlauf_ax.axvline(x=123, ls=\"--\", color=\"green\")\n",
    "leerlauf_ax.text(110, 4.0, \"$t_2$\", fontsize=24, color=\"green\", usetex=True)\n",
    "leerlauf_fig.savefig(\"Reflexion_bei_Leerlauf\", dpi=250)\n",
    "\n",
    "# Ausbreitungsgeschwindigkeit\n",
    "t1 = leerlauf[\"time\"].iloc[596] # ns\n",
    "t2 = leerlauf[\"time\"].iloc[621] # ns\n",
    "\n",
    "dt = t2 - t1 # ns\n",
    "v = 10 / (dt/1e9) # m/s\n",
    "\n",
    "# Permittivität des Dielektrikums\n",
    "permeabilität_r_cu = 0.9999904\n",
    "permeabilität_0 = 1.257e-6 # V*s / (A*m)\n",
    "c0 = 299792458 # m/s\n",
    "permittivität_0 = 8.854e-12 # F/m\n",
    "\n",
    "permittivität = 1 / (v**2 * permeabilität_0 * permeabilität_r_cu) # A*s / (V*m)\n",
    "permittivität_r = permittivität / permittivität_0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Endwiderstand\n",
    "endwiderstand = read_oscilloscope_file(\"Messungen/Rohdaten/Messung 2.1/Reflexion mit Endwiderstand.txt\")\n",
    "\n",
    "set_u_offset(endwiderstand)\n",
    "\n",
    "endwiderstand_fig, endwiderstand_fig_ax = plot_kurven(endwiderstand, title=\"Relfexion mit Endwiderstand\", xStart=1120, xStop=1340, xStep=20)\n",
    "endwiderstand_fig.savefig(\"Reflexion_mit_Endwiderstand\", dpi=250)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\\\begin{tabular}{lrrrrr}\\n\\\\toprule\\n & R [Ohm] & u_1max & u_2max & u_1max, reflektiert & r(R) \\\\\\\\\\n\\\\midrule\\n0 & inf & 2.317703 & 3.622311 & 1.690303 & 0.717294 \\\\\\\\\\n1 & 100.000000 & 2.317144 & 2.491171 & 0.528944 & 0.181034 \\\\\\\\\\n2 & 50.000000 & 2.243774 & 2.109313 & 0.361374 & 0.000000 \\\\\\\\\\n3 & 10.000000 & 2.238133 & 1.685512 & -1.024667 & -0.200919 \\\\\\\\\\n4 & 0.000000 & 2.348975 & 0.215327 & -1.478425 & -0.897916 \\\\\\\\\\n\\\\bottomrule\\n\\\\end{tabular}\\n'"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Berechnungen für ABschnitt 2.2\n",
    "\n",
    "#Berechnung der Theoriewerte\n",
    "    #Variablen\n",
    "r_leerlauf = np.inf\n",
    "r_100 = 100 #ohm\n",
    "r_50 = 50   #ohm\n",
    "r_10 = 10   #ohm\n",
    "r_kurzschluss = 0   #ohm\n",
    "Z_0 = 50    #ohm\n",
    "    #Berechnung\n",
    "r_ref_leerlauf = (r_leerlauf - Z_0)/(Z_0 + r_leerlauf)\n",
    "r_ref_100 = (r_100 - Z_0)/(Z_0 + r_100)\n",
    "r_ref_50 = (r_50 - Z_0)/(Z_0 + r_50)\n",
    "r_ref_10 = (r_10 - Z_0)/(Z_0 + r_10)\n",
    "r_ref_kurzschluss = (r_kurzschluss - Z_0)/(Z_0 + r_kurzschluss)\n",
    "\n",
    "#Brechnung der experimentell ermittelten Werte\n",
    "#Variablen\n",
    "messwerte_2_2 = pd.DataFrame({\n",
    "    \"R [Ohm]\": [np.inf, 100, 50, 10, 0],\n",
    "    \"u_1max\": [2.317703006, 2.317144, 2.243774, 2.238133, 2.3489755],\n",
    "    \"u_2max\": [3.6223106212, 2.491171, 2.109313, 1.685512, 0.2153265],\n",
    "    \"u_1max, reflektiert\": [1.690303006, 0.528944, 0.361374, -1.024667, -1.4784245]\n",
    "})\n",
    "\n",
    "# Berechnung des Reflexionsfaktors\n",
    "u_2max_50ohm = messwerte_2_2[\"u_2max\"].iloc[2]\n",
    "\n",
    "messwerte_2_2[\"r(R)\"] = messwerte_2_2[\"u_2max\"] / u_2max_50ohm - 1\n",
    "\n",
    "messwerte_2_2.to_latex()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# paths to the data files\n",
    "path_unendlich = \"Messungen/Rohdaten/Messung 2.2/Messung 2.2 mit unednlichem Widerstand.txt\"\n",
    "path_100ohm = \"Messungen/Rohdaten/Messung 2.2/Messung 2.2 mit 100 Ohm Widerstand.txt\"\n",
    "path_50ohm = \"Messungen/Rohdaten/Messung 2.2/Messung 2.2 mit 50 Ohm Widerstand.txt\"\n",
    "path_10ohm = \"Messungen/Rohdaten/Messung 2.2/Messung 2.2 mit 10 Ohm Widerstand.txt\"\n",
    "path_0ohm = \"Messungen/Rohdaten/Messung 2.2/Messung 2.2 mit Kurzschluss.txt\"\n",
    "\n",
    "# Messungen einlesen\n",
    "data_unendlich = read_oscilloscope_file(path_unendlich)\n",
    "data_100ohm = read_oscilloscope_file(path_100ohm)\n",
    "data_50ohm = read_oscilloscope_file(path_50ohm)\n",
    "data_10ohm = read_oscilloscope_file(path_10ohm)\n",
    "data_0ohm = read_oscilloscope_file(path_0ohm)\n",
    "\n",
    "# Offsets setzen\n",
    "set_u_offset(data_unendlich, t1=0, t2=400)\n",
    "set_u_offset(data_100ohm)\n",
    "set_u_offset(data_50ohm)\n",
    "set_u_offset(data_10ohm)\n",
    "set_u_offset(data_0ohm)\n",
    "\n",
    "# Plotten\n",
    "plot_kurven(data_unendlich, title=\"Unendlich\")\n",
    "plot_kurven(data_100ohm, title=\"100 Ohm\")\n",
    "plot_kurven(data_50ohm, title=\"50 Ohm\")\n",
    "plot_kurven(data_10ohm, title=\"10 Ohm\")\n",
    "plot_kurven(data_0ohm, title=\"Kurzschluss\")"
   ]
  }
 ],
 "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.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
