{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b52dac62",
   "metadata": {},
   "outputs": [],
   "source": [
    "from src import coil_helpers\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "from src import coil_class as BC\n",
    "\n",
    "import magpylib as magpy\n",
    "import matplotlib.ticker as ticker\n",
    "\n",
    "import scipy.constants as const\n",
    "from scipy.optimize import curve_fit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "eb31f3b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def Self_Inductance_Abbot(alpha, beta, gamma, N):\n",
    "            \"\"\"\n",
    "            Formula for self inductance of circular coil by J.J.Abbott\n",
    "            \"\"\"\n",
    "            L = (7.9e-6 * alpha**2 * N**2) / (3*alpha + 9*beta + 10*gamma)\n",
    "            return L"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd0253e6",
   "metadata": {},
   "source": [
    "# Calculate analytically\n",
    "\n",
    "## low field"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "dcf06437",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R = 2.7028704961530403 Ohm\n",
      "L = 1.605617334411143 mH\n",
      "tau = 0.5940415335090589 ms\n"
     ]
    }
   ],
   "source": [
    "radius = radius=65*1e-3\n",
    "distance=65*1e-3\n",
    "layers=8\n",
    "windings=10\n",
    "I=1\n",
    "\n",
    "wire_height = .5 *1e-3\n",
    "wire_width = .5 *1e-3\n",
    "insulation_thickness = (0.552-0.5)/2 *1e-3\n",
    "\n",
    "HH_Coil = BC.BCoil(HH = 1, distance = distance*1e3, radius = radius*1e3, layers = layers, windings = windings,\n",
    "                    wire_height = wire_height*1e3, wire_width = wire_width*1e3, insulation_thickness = insulation_thickness*1e3,\n",
    "                    is_round = True, winding_scheme= 2)\n",
    "\n",
    "\n",
    "alpha = 2*HH_Coil.radius\n",
    "beta = HH_Coil.get_coil_width()\n",
    "gamma = HH_Coil.get_coil_height()\n",
    "N = HH_Coil.get_N()\n",
    "dist = distance*0\n",
    "\n",
    "L_single = Self_Inductance_Abbot(alpha, dist + beta, gamma, N)\n",
    "R_single = HH_Coil.get_wire_length() * 0.08708\n",
    "\n",
    "print(f\"R = {R_single} Ohm\")\n",
    "print(f\"L = {L_single*1e3} mH\")\n",
    "print(f\"tau = {L_single/R_single*1e3} ms\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11d82be9",
   "metadata": {},
   "source": [
    "## high field"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a7a3f420",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R = 7.194888061621959 Ohm\n",
      "L = 11.652411339780059 mH\n",
      "tau = 1.6195403236271104 ms\n"
     ]
    }
   ],
   "source": [
    "radius = radius=50*1e-3\n",
    "distance=50*1e-3\n",
    "layers=25\n",
    "windings=11\n",
    "I=1\n",
    "\n",
    "wire_height = .5 *1e-3\n",
    "wire_width = .5 *1e-3\n",
    "insulation_thickness = (0.552-0.5)/2 *1e-3\n",
    "\n",
    "HH_Coil = BC.BCoil(HH = 1, distance = distance*1e3, radius = radius*1e3, layers = layers, windings = windings,\n",
    "                    wire_height = wire_height*1e3, wire_width = wire_width*1e3, insulation_thickness = insulation_thickness*1e3,\n",
    "                    is_round = True, winding_scheme= 2)\n",
    "\n",
    "\n",
    "alpha = 2*HH_Coil.radius\n",
    "beta = HH_Coil.get_coil_width()\n",
    "gamma = HH_Coil.get_coil_height()\n",
    "N = HH_Coil.get_N()\n",
    "dist = distance*0\n",
    "\n",
    "L_single = Self_Inductance_Abbot(alpha, dist + beta, gamma, N)\n",
    "R_single = HH_Coil.get_wire_length() * 0.08708\n",
    "\n",
    "print(f\"R = {R_single} Ohm\")\n",
    "print(f\"L = {L_single*1e3} mH\")\n",
    "print(f\"tau = {L_single/R_single*1e3} ms\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cdf41ba",
   "metadata": {},
   "source": [
    "# Measurement\n",
    "\n",
    "## low field"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "39e3c9fd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tau = 0.5097366740354674 ms\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 47612 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# Load CSV and skip first row if it's a multi-line header\n",
    "df = pd.read_csv('time_responce_testcoils/NewFile2.csv', skiprows=1)\n",
    "increment = 5e-5\n",
    "\n",
    "# Clean up column names if necessary\n",
    "df.columns = df.columns.str.strip()\n",
    "\n",
    "# Extract the columns you care about into NumPy arrays\n",
    "x = df.iloc[:, 0].to_numpy()       # X (Sequence)\n",
    "ch1 = df.iloc[:, 1].to_numpy()     # CH1 Volt\n",
    "ch2 = df.iloc[:, 2].to_numpy()     # CH2 Volt\n",
    "\n",
    "time = x*increment\n",
    "\n",
    "start = 550\n",
    "stop = 770\n",
    "\n",
    "plt.plot(time[start:stop]*1e3,ch1[start:stop], label=\"signal\")\n",
    "plt.plot(time[start:stop]*1e3,ch2[start:stop], label=\"responce\")\n",
    "plt.xlabel(\"time [ms]\")\n",
    "plt.ylabel(\"Voltage\")\n",
    "\n",
    "def exp_fit(t, tau, t0, A,B):\n",
    "    res = A*(1-np.exp(-(t-t0)/tau))\n",
    "    return np.where(res<0,0,res)+ B\n",
    "\n",
    "p0=[0.003,0.03,0.64,-0.4,]\n",
    "popt, pcov = curve_fit(exp_fit,time[start:stop], ch2[start:stop],p0=p0)\n",
    "plt.plot(time[start:stop]*1e3, exp_fit(time[start:stop],*popt),label=f\"fit (tau = {popt[0]*1e3:.3f} ms)\")\n",
    "print(f\"tau = {popt[0]*1e3} ms\")\n",
    "\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d98d95a2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tau = 0.5452206023940863 ms\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 47264 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# Load CSV and skip first row if it's a multi-line header\n",
    "df = pd.read_csv('time_responce_testcoils/NewFile2.csv', skiprows=1)\n",
    "increment = 5e-5\n",
    "\n",
    "# Clean up column names if necessary\n",
    "df.columns = df.columns.str.strip()\n",
    "\n",
    "# Extract the columns you care about into NumPy arrays\n",
    "x = df.iloc[:, 0].to_numpy()       # X (Sequence)\n",
    "ch1 = df.iloc[:, 1].to_numpy()     # CH1 Volt\n",
    "ch2 = df.iloc[:, 2].to_numpy()     # CH2 Volt\n",
    "\n",
    "time = x*increment\n",
    "\n",
    "start = 0\n",
    "stop = 300\n",
    "\n",
    "plt.plot(time[start:stop]*1e3,ch1[start:stop], label=\"signal\")\n",
    "plt.plot(time[start:stop]*1e3,ch2[start:stop], label=\"responce\")\n",
    "plt.xlabel(\"time [ms]\")\n",
    "plt.ylabel(\"Voltage\")\n",
    "\n",
    "def exp_fit(t, tau, t0, A,B):\n",
    "    res = A*(1-np.exp(-(t-t0)/tau))\n",
    "    return np.where(res<0,0,-res)+ B\n",
    "\n",
    "p0=[0.003,0.004,0.64,0.4,]\n",
    "popt, pcov = curve_fit(exp_fit,time[start:stop], ch2[start:stop],p0=p0)\n",
    "plt.plot(time[start:stop]*1e3, exp_fit(time[start:stop],*popt),label=f\"fit (tau = {popt[0]*1e3:.3f} ms)\")\n",
    "print(f\"tau = {popt[0]*1e3} ms\")\n",
    "\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8c5ebbc",
   "metadata": {},
   "source": [
    "### with PI-control"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "7e0cea79",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tau = 0.007814569602245835 ms\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 42932 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load CSV and skip first row if it's a multi-line header\n",
    "df = pd.read_csv('time_responce_testcoils/NewFile5.csv', skiprows=1)\n",
    "increment = 1e-5\n",
    "\n",
    "# Clean up column names if necessary\n",
    "df.columns = df.columns.str.strip()\n",
    "\n",
    "# Extract the columns you care about into NumPy arrays\n",
    "x = df.iloc[:, 0].to_numpy()       # X (Sequence)\n",
    "ch1 = df.iloc[:, 1].to_numpy()     # CH1 Volt\n",
    "ch2 = df.iloc[:, 2].to_numpy()     # CH2 Volt\n",
    "\n",
    "time = x*increment\n",
    "\n",
    "start = 550\n",
    "stop = 750\n",
    "\n",
    "plt.plot(time[start:stop]*1e3,ch1[start:stop], label=\"signal\")\n",
    "plt.plot(time[start:stop]*1e3,ch2[start:stop], label=\"responce\")\n",
    "plt.xlabel(\"time [ms]\")\n",
    "plt.ylabel(\"Voltage\")\n",
    "\n",
    "def exp_fit(t, tau, t0, A,B):\n",
    "    res = A*(1-np.exp(-(t-t0)/tau))\n",
    "    return np.where(res<0,0,res)+ B\n",
    "\n",
    "p0=[0.003,0.006,0.64,-0.4,]\n",
    "popt, pcov = curve_fit(exp_fit,time[start:stop], ch2[start:stop],p0=p0)\n",
    "plt.plot(time[start:stop]*1e3, exp_fit(time[start:stop],*popt),label=f\"fit (tau = {popt[0]*1e3:.3f} ms)\")\n",
    "print(f\"tau = {popt[0]*1e3} ms\")\n",
    "\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3865025a",
   "metadata": {},
   "source": [
    "## high field"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "17461fb9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tau = 1.5308889002187382 ms\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 47748 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "# Load CSV and skip first row if it's a multi-line header\n",
    "df = pd.read_csv('time_responce_testcoils/NewFile3.csv', skiprows=1)\n",
    "increment = 1e-4\n",
    "\n",
    "# Clean up column names if necessary\n",
    "df.columns = df.columns.str.strip()\n",
    "\n",
    "# Extract the columns you care about into NumPy arrays\n",
    "x = df.iloc[:, 0].to_numpy()       # X (Sequence)\n",
    "ch1 = df.iloc[:, 1].to_numpy()     # CH1 Volt\n",
    "ch2 = df.iloc[:, 2].to_numpy()     # CH2 Volt\n",
    "\n",
    "time = x*increment\n",
    "\n",
    "start = 500\n",
    "stop = 750\n",
    "\n",
    "plt.plot(time[start:stop]*1e3,ch1[start:stop], label=\"signal\")\n",
    "plt.plot(time[start:stop]*1e3,ch2[start:stop], label=\"responce\")\n",
    "plt.xlabel(\"time [ms]\")\n",
    "plt.ylabel(\"Voltage\")\n",
    "\n",
    "\n",
    "\n",
    "def exp_fit(t, tau, t0, A,B):\n",
    "    res = A*(1-np.exp(-(t-t0)/tau))\n",
    "    return np.where(res<0,0,res)+ B\n",
    "\n",
    "p0=[0.008,0.06,0.3,-0.13]\n",
    "popt, pcov = curve_fit(exp_fit,time[start:stop], ch2[start:stop],p0=p0)\n",
    "plt.plot(time[start:stop]*1e3, exp_fit(time[start:stop],*popt),label=f\"fit (tau = {popt[0]*1e3:.3f} ms)\")\n",
    "print(f\"tau = {popt[0]*1e3} ms\")\n",
    "\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c59127d",
   "metadata": {},
   "source": [
    "### with PI-control"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d7d78680",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tau = 0.12373891080680194 ms\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 43656 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load CSV and skip first row if it's a multi-line header\n",
    "df = pd.read_csv('time_responce_testcoils/NewFile4.csv', skiprows=1)\n",
    "increment = 2e-5\n",
    "\n",
    "# Clean up column names if necessary\n",
    "df.columns = df.columns.str.strip()\n",
    "\n",
    "# Extract the columns you care about into NumPy arrays\n",
    "x = df.iloc[:, 0].to_numpy()       # X (Sequence)\n",
    "ch1 = df.iloc[:, 1].to_numpy()     # CH1 Volt\n",
    "ch2 = df.iloc[:, 2].to_numpy()     # CH2 Volt\n",
    "\n",
    "time = x*increment\n",
    "\n",
    "start = 550\n",
    "stop = 770\n",
    "\n",
    "plt.plot(time[start:stop]*1e3,ch1[start:stop], label=\"signal\")\n",
    "plt.plot(time[start:stop]*1e3,ch2[start:stop], label=\"responce\")\n",
    "plt.xlabel(\"time [ms]\")\n",
    "plt.ylabel(\"Voltage\")\n",
    "\n",
    "def exp_fit(t, tau, t0, A,B):\n",
    "    res = A*(1-np.exp(-(t-t0)/tau))\n",
    "    return np.where(res<0,0,res)+ B\n",
    "\n",
    "p0=[0.003,0.006,0.64,-0.4,]\n",
    "popt, pcov = curve_fit(exp_fit,time[start:stop], ch2[start:stop],p0=p0)\n",
    "plt.plot(time[start:stop]*1e3, exp_fit(time[start:stop],*popt),label=f\"fit (tau = {popt[0]*1e3:.3f} ms)\")\n",
    "print(f\"tau = {popt[0]*1e3} ms\")\n",
    "\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
