{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fixed point device calibration of the CMN thermometer\n",
    "08.12.2023 Jakub - copied from the DilSc calibration run in 2021, code mainly written by Lise Hanson\n",
    "\n",
    "This script is for calibrating the CMN (cerium magnesium nitrate) thermometer by using the fix-point device called SRD (superconductive reference device). The temperature in the Dilution fridge was stabilised around at each transition temperature of superconductors, T_c, in the fix-point device for around one hour. The voltages of the CMN at T=T_c is then read out as an average over the stable time windows. All the individual time windows has to be specified manually (in the \"TransitionTimes\" array). Two sets of data is made: \n",
    "\n",
    "- H, When the fridge is heating up and \n",
    "- C, when the fridge is cooling down. \n",
    "\n",
    "This is done in order to ensure that the timesteps were sufficiently long to equilibriate the temperature between the bottom plate and the thermometers. \n",
    "\n",
    "The CMN can be used for calibration of thermometers between 8 mK and 2 K.\n",
    "\n",
    "\n",
    "#TO DO:\n",
    "add more poits around 15.12.2023 - there should be two more fixed points\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import datetime as dt\n",
    "from scipy.optimize import curve_fit\n",
    "from lmfit import Model\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib widget\n",
    "\n",
    "# Function for reading the SEA files\n",
    "def readseai(path):\n",
    "    with open(path) as fil:\n",
    "        line = fil.readline()\n",
    "        if bool(line.startswith(\"# SEA\")) :\n",
    "            content = fil.read()\n",
    "            headerlist = []\n",
    "            for linenr, line in enumerate(content.split('\\n')):\n",
    "                try:\n",
    "                    name,value = line.split(': ')\n",
    "                    value = value.replace(\"\\t\", \"\")\n",
    "                    headerlist.append(value.split()[0])\n",
    "                except:\n",
    "                    #print(linenr, '/'+line+'/')\n",
    "                    table = pd.read_csv(path, header=linenr, names=headerlist, delim_whitespace = True,)\n",
    "                    \n",
    "                    #Get the time of the data points:\n",
    "                    COL1=content.split('\\n')[0].split('.')\n",
    "                    Date = int(COL1[1])\n",
    "                    Year = int(COL1[3].split(' ')[0])+2000 #+2000 since the information is just 21 in year 2021 eg.\n",
    "                    MonthDict = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12} #Continue!\n",
    "                    Month = MonthDict.get(COL1[2])\n",
    "                    Hour = 0 #This should be default in the SEA data file\n",
    "                    Minutes = 0 #This should be default in the SEA data file\n",
    "                    Start_date=dt.datetime(Year,Month,Date,Hour,Minutes)\n",
    "                    \n",
    "                    rec_date=Start_date + pd.to_timedelta(table.iloc[:,0],unit='sec')\n",
    "                    table.insert(1,'REC_Date',rec_date)\n",
    "                    \n",
    "                    return table            \n",
    "        elif bool(line.startswith(\"# col\")) :\n",
    "            content = line + fil.read()         \n",
    "            headerlist = []\n",
    "            for linenr, line in enumerate(content.split('\\n')):\n",
    "                try:\n",
    "                    name,value = line.split(': ')\n",
    "                    value = value.replace(\"\\t\", \"\")\n",
    "                    headerlist.append(value.split()[0])\n",
    "                    \n",
    "                except:\n",
    "                    #print(linenr, '/'+line+'/')\n",
    "                    table = pd.read_csv(path, header=linenr-1, names=headerlist, delim_whitespace = True,)\n",
    "                    return table              \n",
    "        else:\n",
    "            return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['Time/1', 'REC_Date', 't_mix', 't_pt2head', 't_pt2plate', 't_still',\n",
      "       'htr_still', 't_coldpl', 't_mixcx', 't_pt1head', 't_pt1plate',\n",
      "       't_pucksensor', 't_pucksensor.target', 'htr_pucksensor', 't_magnet',\n",
      "       'action', 'p_dump', 'p_cond', 'p_still', 'p_fore', 'p_back', 'p_ovc',\n",
      "       'v1', 'v2', 'v4', 'v5', 'v9', 'mfx', 'mfx.target', 'mfy', 'mfy.target',\n",
      "       'mfz', 'mfz.target', 'mf', 'mf.target', 'res1.rx1', 'res1.set.power',\n",
      "       'res1.set.reg', 'res2.rx8', 'res2.set.power', 'res2.set.reg', 'cmn.u1',\n",
      "       'cmn.u2', 'cmn.temp', 'softloop.reg', 'softloop.target', 'res1.rx1.raw',\n",
      "       'res1.rx2.raw', 'res1.rx3.raw', 'res1.rx4.raw', 'res1.rx5.raw',\n",
      "       'res1.rx6.raw', 'res2.rx7.raw', 'res2.rx8.raw', 'res2.rx9.raw',\n",
      "       'res2.rx10.raw', 'res2.rx11.raw', 'res2.rx12.raw', 'res2.rx13.raw'],\n",
      "      dtype='object')\n"
     ]
    }
   ],
   "source": [
    "#Read the data\n",
    "d=readseai('2023_12_08.dat')\n",
    "print(d.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['Time/1', 'REC_Date', 't_mix', 'htr_still', 'htr_pucksensor', 'action',\n",
      "       'p_dump', 'p_cond', 'p_still', 'p_fore', 'p_back', 'p_ovc', 'v1', 'v2',\n",
      "       'v4', 'v5', 'v9', 'mfx', 'mfx.target', 'mfy', 'mfy.target', 'mfz',\n",
      "       'mfz.target', 'mf', 'mf.target', 'res1.set.power', 'res2.set.power',\n",
      "       'cmn.u1', 'cmn.u2', 'res1.rx1.raw', 'res1.rx2.raw', 'res1.rx3.raw',\n",
      "       'res1.rx4.raw', 'res1.rx5.raw', 'res1.rx6.raw', 'res2.rx7.raw',\n",
      "       'res2.rx8.raw', 'res2.rx9.raw', 'res2.rx10.raw', 'res2.rx11.raw',\n",
      "       'res2.rx12.raw', 'res2.rx13.raw'],\n",
      "      dtype='object')\n"
     ]
    }
   ],
   "source": [
    "#Read the data\n",
    "d2=readseai('2023_12_16-CMN_cooldown_v2.dat')\n",
    "print(d2.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Index(['Time/1', 'REC_Date', 't_mix', 't_pt2head', 't_pt2plate', 't_still',\n",
      "       'htr_still', 't_coldpl', 't_mixcx', 't_pt1head', 't_pt1plate',\n",
      "       't_pucksensor', 't_pucksensor.target', 'htr_pucksensor', 't_magnet',\n",
      "       'action', 'p_dump', 'p_cond', 'p_still', 'p_fore', 'p_back', 'p_ovc',\n",
      "       'v1', 'v2', 'v4', 'v5', 'v9', 'mfx', 'mfx.target', 'mfy', 'mfy.target',\n",
      "       'mfz', 'mfz.target', 'mf', 'mf.target', 'res1.rx1', 'res1.set.power',\n",
      "       'res1.set.reg', 'res2.rx8', 'res2.set.power', 'res2.set.reg', 'cmn.u1',\n",
      "       'cmn.u2', 'cmn.temp', 'softloop.reg', 'softloop.target', 'res1.rx1.raw',\n",
      "       'res1.rx2.raw', 'res1.rx3.raw', 'res1.rx4.raw', 'res1.rx5.raw',\n",
      "       'res1.rx6.raw', 'res2.rx7.raw', 'res2.rx8.raw', 'res2.rx9.raw',\n",
      "       'res2.rx10.raw', 'res2.rx11.raw', 'res2.rx12.raw', 'res2.rx13.raw'],\n",
      "      dtype='object')\n"
     ]
    }
   ],
   "source": [
    "#Read the data\n",
    "d3=readseai('2024_01_10-CMN_cooldown_v3.dat')\n",
    "print(d3.columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/l_samenv/py3_kernel/lib/python3.6/site-packages/ipykernel_launcher.py:1: FutureWarning: Sorting because non-concatenation axis is not aligned. A future version\n",
      "of pandas will change to not sort by default.\n",
      "\n",
      "To accept the future behavior, pass 'sort=False'.\n",
      "\n",
      "To retain the current behavior and silence the warning, pass 'sort=True'.\n",
      "\n",
      "  \"\"\"Entry point for launching an IPython kernel.\n"
     ]
    }
   ],
   "source": [
    "d = pd.concat([d,d2,d3],ignore_index=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "71e1bc07dcde491e9209b323777247ec",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Plot raw data between the indecies \"Start\" and \"End\"\n",
    "%matplotlib widget\n",
    "Start = 0 #Crop the data set to be plotted\n",
    "End = len(d['REC_Date'])-0\n",
    "\n",
    "fig, axs = plt.subplots(3, 1, sharex=True)\n",
    "axs[0].plot(d['REC_Date'][Start:End],d['cmn.u1'][Start:End]*1000,color='blue',label='CMN voltage')\n",
    "axs[0].set_ylabel('mV')\n",
    "axs[1].plot(d['REC_Date'][Start:End],d['cmn.u2'][Start:End]*1000,color='red',label='Fix point')\n",
    "axs[1].set_ylabel('mV')\n",
    "axs[2].plot(d['REC_Date'][Start:End],d['softloop.target'][Start:End],color='k',label='target')\n",
    "axs[2].plot(d['REC_Date'][Start:End],d['cmn.temp'][Start:End],color='coral',label='CMN temp',linewidth=1)\n",
    "axs[2].set_ylabel('Temp')\n",
    "axs[2].set_xlabel('Time')\n",
    "fig.autofmt_xdate()\n",
    "for i in range(len(axs)):\n",
    "    axs[i].minorticks_on()\n",
    "    axs[i].grid(b=True, which='major', color='silver', linestyle='-')\n",
    "    axs[i].grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "    axs[i].legend()\n",
    "fig.subplots_adjust(hspace=0)\n",
    "plt.tight_layout(pad=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5c941d1e807c4b26b4307ed51ce2df3c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No handles with labels found to put in legend.\n"
     ]
    }
   ],
   "source": [
    "# Plot raw data between the indecies \"Start\" and \"End\"\n",
    "\n",
    "Start = 0 #Crop the data set to be plotted\n",
    "End = len(d2['REC_Date'])-0\n",
    "\n",
    "fig, axs = plt.subplots(3, 1, sharex=True)\n",
    "axs[0].plot(d2['REC_Date'][Start:End],d2['cmn.u1'][Start:End]*1000,color='blue',label='CMN voltage')\n",
    "axs[0].set_ylabel('mV')\n",
    "axs[1].plot(d2['REC_Date'][Start:End],d2['cmn.u2'][Start:End]*1000,color='red',label='Fix point')\n",
    "axs[1].set_ylabel('mV')\n",
    "#axs[2].plot(d2['REC_Date'][Start:End],d2['softloop.target'][Start:End],color='k',label='target')\n",
    "#axs[2].plot(d2['REC_Date'][Start:End],d2['cmn.temp'][Start:End],color='coral',label='CMN temp',linewidth=1)\n",
    "axs[2].set_ylabel('Temp')\n",
    "axs[2].set_xlabel('Time')\n",
    "fig.autofmt_xdate()\n",
    "for i in range(len(axs)):\n",
    "    axs[i].minorticks_on()\n",
    "    axs[i].grid(b=True, which='major', color='silver', linestyle='-')\n",
    "    axs[i].grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "    axs[i].legend()\n",
    "fig.subplots_adjust(hspace=0)\n",
    "plt.tight_layout(pad=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'd4' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-16-d925ba3f579c>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0mStart\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;31m#Crop the data set to be plotted\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mEnd\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md4\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'REC_Date'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      6\u001b[0m \u001b[0mfig\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0maxs\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msubplots\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msharex\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'd4' is not defined"
     ]
    }
   ],
   "source": [
    "# Plot raw data between the indecies \"Start\" and \"End\"\n",
    "\n",
    "Start = 0 #Crop the data set to be plotted\n",
    "End = len(d4['REC_Date'])-0\n",
    "\n",
    "fig, axs = plt.subplots(3, 1, sharex=True)\n",
    "axs[0].plot(d4['REC_Date'][Start:End],d4['cmn.u1'][Start:End]*1000,color='blue',label='CMN voltage')\n",
    "axs[0].set_ylabel('mV')\n",
    "axs[1].plot(d4['REC_Date'][Start:End],d4['cmn.u2'][Start:End]*1000,color='red',label='Fix point')\n",
    "axs[1].set_ylabel('mV')\n",
    "#axs[2].plot(d2['REC_Date'][Start:End],d2['softloop.target'][Start:End],color='k',label='target')\n",
    "#axs[2].plot(d2['REC_Date'][Start:End],d2['cmn.temp'][Start:End],color='coral',label='CMN temp',linewidth=1)\n",
    "axs[2].set_ylabel('Temp')\n",
    "axs[2].set_xlabel('Time')\n",
    "fig.autofmt_xdate()\n",
    "for i in range(len(axs)):\n",
    "    axs[i].minorticks_on()\n",
    "    axs[i].grid(b=True, which='major', color='silver', linestyle='-')\n",
    "    axs[i].grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "    axs[i].legend()\n",
    "fig.subplots_adjust(hspace=0)\n",
    "plt.tight_layout(pad=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fe37590b86af4b048261cc0ecbda7472",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#Time arrays for when a stabilization around a superconducting transition starts and ends \n",
    "#Heating up = H\n",
    "TransitionTimeRampedHeating08Dec_Start = np.array([\n",
    "    dt.datetime(2023,12,8,12,23,0),\n",
    "    dt.datetime(2023,12,8,13,30,0),\n",
    "    dt.datetime(2023,12,8,14,12,0),\n",
    "    dt.datetime(2023,12,8,14,53,0),\n",
    "    dt.datetime(2023,12,8,16,26,0),\n",
    "    dt.datetime(2023,12,8,17,11,0),\n",
    "    dt.datetime(2023,12,8,18,0,0),\n",
    "    dt.datetime(2023,12,15,0,40,0),\n",
    "    dt.datetime(2023,12,15,1,55,0),\n",
    "    dt.datetime(2023,12,14,23,25,0),\n",
    "])\n",
    "TransitionTimeRampedHeating08Dec_End = np.array([\n",
    "    dt.datetime(2023,12,8,12,53,0),\n",
    "    dt.datetime(2023,12,8,13,58,0),\n",
    "    dt.datetime(2023,12,8,14,34,0),\n",
    "    dt.datetime(2023,12,8,15,20,0),\n",
    "    dt.datetime(2023,12,8,16,55,0),\n",
    "    dt.datetime(2023,12,8,17,37,0),\n",
    "    dt.datetime(2023,12,8,18,35,0),\n",
    "    dt.datetime(2023,12,15,1,15,0),\n",
    "    dt.datetime(2023,12,15,2,30,0),\n",
    "    dt.datetime(2023,12,15,0,3,0),\n",
    "])\n",
    "TransitionTimeH = np.array([TransitionTimeRampedHeating08Dec_Start,TransitionTimeRampedHeating08Dec_End])\n",
    "\n",
    "\n",
    "#Cooling down = C\n",
    "TransitionTimeRampedCooling07Dec_Start = np.array([\n",
    "    dt.datetime(2023,12,7,22,15,0),\n",
    "    dt.datetime(2023,12,7,23,5,0),\n",
    "    dt.datetime(2023,12,7,23,59,0),\n",
    "    dt.datetime(2023,12,8,8,52,0),\n",
    "    dt.datetime(2023,12,8,9,38,0),\n",
    "    dt.datetime(2023,12,8,10,38,0),\n",
    "    dt.datetime(2023,12,8,11,31,0),\n",
    "    dt.datetime(2023,12,15,6,50,0),\n",
    "    dt.datetime(2023,12,15,5,32,0),\n",
    "    dt.datetime(2023,12,15,4,15,0),\n",
    "])\n",
    "TransitionTimeRampedCooling07Dec_End = np.array([\n",
    "    dt.datetime(2023,12,7,22,46,0),\n",
    "    dt.datetime(2023,12,7,23,32,0),\n",
    "    dt.datetime(2023,12,8,0,21,0),\n",
    "    dt.datetime(2023,12,8,9,26,0),\n",
    "    dt.datetime(2023,12,8,10,9,0),\n",
    "    dt.datetime(2023,12,8,11,6,0),\n",
    "    dt.datetime(2023,12,8,12,3,0),\n",
    "    dt.datetime(2023,12,15,7,40,0),\n",
    "    dt.datetime(2023,12,15,6,16,0),\n",
    "    dt.datetime(2023,12,15,4,55,0),\n",
    "])\n",
    "TransitionTimeC = np.array([TransitionTimeRampedCooling07Dec_Start,TransitionTimeRampedCooling07Dec_End])\n",
    "\n",
    "#Tc values of all the 10 Superconductors --------------------------------------------------------------------\n",
    "Tc_W        = 0.01429\n",
    "Tc_Be       = 0.02059\n",
    "Tc_Ir80Rh20 = 0.03530\n",
    "Tc_Ir92Rh08 = 0.06536\n",
    "Tc_Ir       = 0.09308\n",
    "Tc_AuAl2    = 0.15539\n",
    "Tc_AuIn2    = 0.20773\n",
    "Tc_Cd       = 0.51558\n",
    "Tc_Zn       = 0.84880\n",
    "Tc_Al       = 1.182\n",
    "\n",
    "#Temperature arrays with the superconducting transitions that were observed in the data. Both for Heating up and cooling down.\n",
    "TcValuesH = np.array([ Tc_Ir92Rh08,Tc_Ir,Tc_AuAl2,Tc_AuIn2,Tc_Cd,Tc_Zn,Tc_Al,Tc_Ir80Rh20,Tc_Ir92Rh08,Tc_Be])\n",
    "TcValuesC = np.array([ Tc_Al,Tc_Zn,Tc_Cd,Tc_AuIn2,Tc_AuAl2,Tc_Ir,Tc_Ir92Rh08,Tc_Be,Tc_Ir80Rh20,Tc_Ir92Rh08])\n",
    "\n",
    "\n",
    "#Caluclating average voltages at each stabilization around a transition temperatuere-------------------------- \n",
    "def VcValuesFunc(TransitionTime):\n",
    "    VcValues=np.zeros(TransitionTime.shape[1])\n",
    "    for i in range(TransitionTime.shape[1]):\n",
    "        StepData=d[(d['REC_Date'] >= TransitionTime[0,i]) & (d['REC_Date'] <= TransitionTime[1,i])]['cmn.u1'].to_numpy()\n",
    "        VcValues[i] = np.mean(StepData)\n",
    "    return VcValues\n",
    "\n",
    "VcValuesH = VcValuesFunc(TransitionTimeH)\n",
    "VcValuesC = VcValuesFunc(TransitionTimeC)\n",
    "\n",
    "# Manually adding the last fixed point from \n",
    "\n",
    "#Plot of the mean voltages at each stabilized transition as a function of the superconducting transition temperatures.\n",
    "plt.figure()\n",
    "plt.plot(TcValuesH*10**(3),VcValuesH*10**(3),'o',color='red',markersize=4)\n",
    "plt.plot(TcValuesC*10**(3),VcValuesC*10**(3),'o',color='blue',markersize=3)\n",
    "plt.xlabel('T [mK]')\n",
    "plt.ylabel('V [mV]')\n",
    "plt.xscale('log')\n",
    "plt.minorticks_on()\n",
    "plt.grid(b=True, which='major', color='silver', linestyle='-')\n",
    "plt.grid(b=True, which='minor', color='gainsboro', linestyle='--')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6d5270bde11043a0bbed601e1d7eb5e2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#Plot to visually inspect wether the correct time windows were selected when calculating the average voltages.\n",
    "#Black lines = start of averaging time\n",
    "#Grey lines = end of averaging time\n",
    "#Dots = readings of the voltage at the end and beginning of the time window.\n",
    "Start_index = 20\n",
    "End_index = len(d['REC_Date'])\n",
    "col = np.array(['k','grey'])\n",
    "\n",
    "plt.figure()\n",
    "plt.plot(d['REC_Date'][Start_index:End_index],d['cmn.u1'][Start_index:End_index]*1000,color='blue',label='CMN')\n",
    "plt.plot(d['REC_Date'][Start_index:End_index],d['cmn.u2'][Start_index:End_index]*1000,color='red',label='Fix point')\n",
    "for i in range(2):\n",
    "    plt.plot(TransitionTimeH[i],VcValuesH*1000,'o',color=col[i],markersize = 3)\n",
    "    plt.plot(TransitionTimeC[i],VcValuesC*1000,'o',color=col[i],markersize = 3)\n",
    "    plt.vlines(TransitionTimeH[i],min(d['cmn.u1'])*1000,max(d['cmn.u1'])*1000,color=col[i],linewidth=1)\n",
    "    plt.vlines(TransitionTimeC[i],min(d['cmn.u1'])*1000,max(d['cmn.u1'])*1000,color=col[i],linewidth=1)\n",
    "plt.xlabel('Time')\n",
    "plt.ylabel('Voltage [mV]')\n",
    "plt.xticks(rotation=45)\n",
    "plt.minorticks_on()\n",
    "plt.grid(b=True, which='major', color='silver', linestyle='-')\n",
    "plt.grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "plt.legend()\n",
    "plt.tight_layout()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4eec649d01a2431ebdc5450a22790ebf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7f395ac60a20>"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def Function(V,intercept,B,A):\n",
    "    \"\"\"Hyperbolic function used to fit the Temperature as a function of the voltage on the CMN. \n",
    "    This fit is used as the calibration of the CMN. This function is adviced in the manual from hdleiden.\"\"\"\n",
    "    return intercept + B/(V-A)\n",
    "\n",
    "#Fitting the hyperbolic function\n",
    "mod= Model(Function)\n",
    "pars = mod.make_params(intercept=0.00085,B=16,A=0.06)\n",
    " \n",
    "#Heating\n",
    "resultH = mod.fit(TcValuesH, pars, V=VcValuesH)\n",
    "compsH = resultH.eval_components()\n",
    "#Cooling\n",
    "resultC = mod.fit(TcValuesC, pars, V=VcValuesC)\n",
    "compsC = resultC.eval_components()\n",
    "\n",
    "\n",
    "V = np.linspace(np.min(VcValuesC),np.max(VcValuesC),1000)#Voltage array for plotting the fit smoothly\n",
    "\n",
    "plt.figure()\n",
    "plt.plot(1/mod.eval(resultH.params,V=V)*1000,V*1000,color='red', label='H fit',linewidth=2)\n",
    "plt.plot(1/mod.eval(resultC.params,V=V)*1000,V*1000,color='blue', label='C fit',linewidth=1)\n",
    "plt.plot(1/TcValuesH*1000,VcValuesH*1000,'o',color='lightcoral',markersize=6,label = 'H data')\n",
    "plt.plot(1/TcValuesC*1000,VcValuesC*1000,'o',mfc='none', color='skyblue',markersize=9,label = 'C data')\n",
    "plt.xlabel('1/T [mK]')\n",
    "plt.ylabel('V [mV]')\n",
    "plt.minorticks_on()\n",
    "plt.grid(b=True, which='major', color='silver', linestyle='-')\n",
    "plt.grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "plt.legend()\n",
    "#plt.xscale('log')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5a414f6478a749c4bd83415abf9528cb",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#Plot of the relative deviation in voltages between the cooling and the heating data.\n",
    "plt.figure(figsize=(7,3))\n",
    "plt.plot(TcValuesC,(VcValuesH[::-1]-VcValuesC)/VcValuesC*100,'-o',label=r'$(V_{c,H}-V_{c,C})/V_{c,C}$')\n",
    "plt.xlabel('Tc')\n",
    "plt.ylabel('%')\n",
    "plt.minorticks_on()\n",
    "plt.grid(b=True, which='major', color='silver', linestyle='-')\n",
    "plt.grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "plt.legend()\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4235d0702bd4466db6dcbb4d2042e072",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#Linear plots of 1/(T-intercept). OBS! This plot is only used to see that the fit to \n",
    "#\"Function()\"=intercept+B/(V-A) went well and no systematical deviations appears. \n",
    "\n",
    "def line(x,a,b):\n",
    "    return a+b*x\n",
    "modLine = Model(line)\n",
    "parsLine = modLine.make_params(a=1.,b=1.)\n",
    "\n",
    "InterceptH = resultH.params['intercept'].value\n",
    "resultLineH = modLine.fit(VcValuesH, parsLine, x=1/(TcValuesH-InterceptH))\n",
    "compsLineH = resultLineH.eval_components()\n",
    "\n",
    "InterceptC = resultC.params['intercept'].value\n",
    "resultLineC = modLine.fit(VcValuesC, parsLine, x=1/(TcValuesC-InterceptC))\n",
    "compsLineC = resultLineC.eval_components()\n",
    "\n",
    "aH = np.round(resultLineH.params['a'].value,4)\n",
    "bH = np.round(resultLineH.params['b'].value,4)\n",
    "\n",
    "aC = np.round(resultLineC.params['a'].value,4)\n",
    "bC = np.round(resultLineC.params['b'].value,4)\n",
    "\n",
    "#plot\n",
    "plt.figure()\n",
    "plt.plot(1/(TcValuesH-InterceptH),VcValuesH*1000,'o',color='lightcoral',label = 'H data')\n",
    "plt.plot(1/(TcValuesC-InterceptC),VcValuesC*1000,'o',color='skyblue', label = 'C data')\n",
    "plt.plot(1/(TcValuesH-InterceptH),compsLineH['line']*1000,'r--',label=f'H fit: {aH}+{bH}/(T-{np.round(InterceptH,4)})')\n",
    "plt.plot(1/(TcValuesC-InterceptC),compsLineC['line']*1000,'b',label=f'C fit: {aC}+{bC}/(T-{np.round(InterceptC,4)})')\n",
    "# plt.plot(1/(TcValues-Intercept),A+B*1/(TcValues-Intercept),color=red )\n",
    "plt.xlabel('1/(T-intersept) [1/K]')\n",
    "plt.ylabel('V [mV]')\n",
    "plt.minorticks_on()\n",
    "plt.grid(b=True, which='major', color='silver', linestyle='-')\n",
    "plt.grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "plt.legend()\n",
    "plt.tight_layout()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "def T_calib(Volt,fit_result):\n",
    "    \"\"\"Function that takes a voltage from the CMN and returns the calibrated temperature at this voltage.\n",
    "    The calibration is based on the hyperbolic fit wich has shown to be better than the linear 1/T fit \"\"\"\n",
    "    A=fit_result.params['A'].value\n",
    "    B=fit_result.params['B'].value\n",
    "    inter=fit_result.params['intercept'].value\n",
    "    return inter + B/(Volt-A)\n",
    "\n",
    "def T_calib_Line(Volt,fit_result,intercept):\n",
    "    \"\"\"This function is not used in the following code. It takes a voltage from the CMN and returns\n",
    "    the calibrated temperature at this voltage. The calibration is based on the linear fit wich has\n",
    "    shown to be worse that the hyperbolic fit \"\"\"\n",
    "    a=fit_result.params['a'].value\n",
    "    b=fit_result.params['b'].value\n",
    "    inter=intercept\n",
    "    return inter + b/(Volt-a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ea245fd431b74189b02fdd1940b3abf0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#Plot of the calibrated CMN temperature as a function of time. The CMN temperature is calculated from \n",
    "#the CMN voltage that was recorded when stabilizing and ramping the temperatures around the transitions.\n",
    "\n",
    "Start = 500\n",
    "End = len(d['REC_Date'])-10\n",
    "\n",
    "plt.figure('Calibrated CMN')\n",
    "plt.plot(d['REC_Date'][Start:End],T_calib(d['cmn.u1'][Start:End],resultH)*1000,color='red',label='CMN Temp New H',linewidth=2)\n",
    "plt.plot(d['REC_Date'][Start:End],T_calib(d['cmn.u1'][Start:End],resultC)*1000,color='blue',label='CMN Temp New C',linewidth=1)\n",
    "#plt.plot(d['REC_Date'][Start:End],d['tcoldpl'][Start:End]*1000,color='red',label='tcoldpl')\n",
    "#plt.plot(d['REC_Date'][Start:End],d['tmix'][Start:End]*1000,color='darkred',label='tmix')\n",
    "for i,Tc in enumerate(TcValuesH):\n",
    "    EndTime = d['REC_Date'][End]\n",
    "    StartTime = d['REC_Date'][Start]\n",
    "    if i==0:\n",
    "        plt.hlines(Tc*1000, StartTime, EndTime, label='Tc values',color='green',linewidth=1)\n",
    "    else:\n",
    "        plt.hlines(Tc*1000, StartTime, EndTime,color='green',linewidth=1)\n",
    "\n",
    "plt.plot(d['REC_Date'][Start:End],d['cmn.temp'][Start:End]*1000,color='coral',label='CMN temp old calibration',linewidth=1)\n",
    "plt.ylabel('T [mK]')\n",
    "plt.xlabel('Time')\n",
    "plt.xticks(rotation=30)\n",
    "plt.minorticks_on()\n",
    "plt.grid(b=True, which='major', color='silver', linestyle='-')\n",
    "plt.grid(b=True, which='minor', color='gainsboro', linestyle='--')\n",
    "plt.legend()\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Save the calibration data in a txt file. The txt also includes the chi value of the fit \n",
    "#and errors on the variables\n",
    "with open('CMN_Calibration_result.txt', 'w+') as fh:\n",
    "    fh.write(resultH.fit_report())\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.6",
   "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.6.6"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
