{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "abb0b5e6",
   "metadata": {},
   "source": [
    "# Tutorial for the HN module of HavNegpy package"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "419f647e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "import HavNegpy as dd\n",
    "%matplotlib qt\n",
    "os.chdir(r'M:\\Marshall_Data\\mohamed_data\\mohamed_data\\n44')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6b9e2def",
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_dataframe(f):\n",
    "        col_names = ['Freq', 'T', 'Eps1', 'Eps2']\n",
    "        #f = input(str(\"Enter the filename:\"))\n",
    "        df = pd.read_csv(f, sep=r\"\\s+\",index_col=False,usecols = [0,1,2,3],names=col_names,header=None,skiprows=4,encoding='unicode_escape',engine='python')\n",
    "        col1 = ['log f']    \n",
    "        for start in range(0, len(df), 63):\n",
    "           name = df['T'][start]\n",
    "           #print(name)\n",
    "           col1.append(name)\n",
    "        df2 = pd.DataFrame()   \n",
    "        f1 = df['Freq'][0:63].values\n",
    "        x1 = np.log10((f1))\n",
    "        e = pd.DataFrame(x1)\n",
    "        df2['log f'] = pd.concat([e],axis=1,ignore_index=True)\n",
    "        global Cooling,Heating\n",
    "        for start in range(0, len(df), 63):\n",
    "        \n",
    "            \n",
    "            f = df['Eps2'][start:start+63].values\n",
    "            ep = np.log10(f)\n",
    "            d = pd.DataFrame(ep)\n",
    "         \n",
    "           \n",
    "            \n",
    "            df2[start] = pd.concat([d],axis=1,ignore_index=True)\n",
    "            \n",
    "        df2.columns = col1\n",
    "        '''\n",
    "        a = int(len(col1)/3)\n",
    "        b = 2*a\n",
    "        c = int(len(col1)) - b\n",
    "    \n",
    "        Heating1 = df2.iloc[8:,0:a+1]\n",
    "        Cooling = df2.iloc[8:,a+1:b+1]\n",
    "        Heating2 = df2.iloc[8:,b+1:]\n",
    "        \n",
    "        heat1_col = col1[0:a+1]\n",
    "        cool_col = col1[a+1:b+1]\n",
    "        heat2_col = col1[b+1:]\n",
    "        Cooling.columns = cool_col\n",
    "        Heating1.columns = heat1_col\n",
    "        Heating2.columns = heat2_col\n",
    "        \n",
    "        f2 = df['Freq'][8:59].values\n",
    "        x2 = np.log10((f2))\n",
    "        \n",
    "        Cooling['Freq'] = x2\n",
    "        Heating1['Freq'] = x2\n",
    "        Heating2['Freq'] = x2\n",
    "        '''   \n",
    "        Cooling = df2.iloc[:,0:25]\n",
    "        Heating = df2.iloc[:,25:]\n",
    "        return df,df2,Cooling,Heating #Heating2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0da19910",
   "metadata": {},
   "outputs": [],
   "source": [
    "df,df2,cool,heat = create_dataframe('EPS.TXT')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3f6bf042",
   "metadata": {},
   "outputs": [],
   "source": [
    "x,y = df2['log f'][9:], heat[40][9:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "e9b8e689",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'Example for HN fitting')"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "plt.figure()\n",
    "plt.scatter(x,y,label='data for fitting')\n",
    "plt.xlabel('log f [Hz]')\n",
    "plt.ylabel('log $\\epsilon$\"')\n",
    "plt.legend()\n",
    "plt.title('Example for HN fitting')"
   ]
  },
  {
   "attachments": {
    "diel_loss_plot.png": {
     "image/png": "[encoded data, 26284 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "eba2e3b4",
   "metadata": {},
   "source": [
    "image of the plot we are using in this tutorial\n",
    "![diel_loss_plot.png](attachment:diel_loss_plot.png)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "29bd8d2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "''' instantiate the HN module from HavgNegpy'''\n",
    "hn = dd.HN()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "1c8c74e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.47 4.506\n",
      "[4.419354255377861, 4.290321818876993, 4.161290121759072, 4.032256025890453, 3.9032256828161698, 3.7741934966314363, 3.6451618110869344, 3.5161293137865632, 3.387096044251562, 3.2580647093021717, 3.1290321534708663, 3.0, 2.8709677707186825, 2.741935143884554, 2.6129035360243327, 2.483871028902048]\n",
      "[-0.2443240510276534, -0.22529257039572312, -0.21013736995361834, -0.1995214368622129, -0.19437070753700492, -0.1952031468647596, -0.2036491153542296, -0.2196898901497833, -0.24406952771835763, -0.2775281456056566, -0.3200155093339718, -0.3713229983490028, -0.4312258541304883, -0.4980757508187894, -0.5690498167129617, -0.642492038012267]\n",
      "[(2.500202181392442, -0.6355371196230044), (4.475515699010058, -0.2513736191421395)]\n",
      "x_lower_limit 2.500202181392442 x_upper_limit 4.475515699010058\n"
     ]
    }
   ],
   "source": [
    "''' select range to perform hn fitting'''\n",
    "''' the select range functions pops in a separate window and allows you two clicks to select the region of interest (ROI)'''\n",
    "''' In this tutorial, I'll plot the ROI and append as an image in the next cell'''\n",
    "\n",
    "x1,y1 = hn.select_range(x,y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "efde25dc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'ROI selected from HN module')"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "''' view the data from select range'''\n",
    "plt.scatter(x1,y1,label = 'Data for fitting')\n",
    "plt.xlabel('log f [Hz]')\n",
    "plt.ylabel('log $\\epsilon$\"')\n",
    "plt.legend()\n",
    "plt.title('ROI selected from HN module')"
   ]
  },
  {
   "attachments": {
    "ROI.png": {
     "image/png": "[encoded data, 24556 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "68a130ad",
   "metadata": {},
   "source": [
    "image of the ROI from HN module![ROI.png](attachment:ROI.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "ff16b35a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "enter the beta value:0.5\n",
      "enter the gamma value:1\n",
      "enter the fm:3.75\n",
      "enter the deps:0.5\n",
      "enter the cond:0\n",
      "enter the s:1\n",
      "dumped_parameters {'beta': 0.5, 'gamma': 1.0, 'freq': 5623.413251903491, 'deps': 0.5, 'cond': 0.0, 'n': 1.0}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "()"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "''' dump the initial guess parameters using dump parameters method (varies for each fn), which dumps the parameters in a json file'''\n",
    "''' this is required before performing the first fitting as it takes the initial guess from the json file created'''\n",
    "hn.dump_parameters_hn()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "1ddeac90",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loaded parameters \n",
      " {'beta': 0.5, 'gamma': 1.0, 'freq': 5623.413251903491, 'deps': 0.5, 'cond': 0.0, 'n': 1.0}\n"
     ]
    }
   ],
   "source": [
    "''' view the initial guess for the ROI using initial_view method'''\n",
    "''' I'll append the image in the next cell'''\n",
    "hn.initial_view_hn(x1,y1)"
   ]
  },
  {
   "attachments": {
    "initial_guess.png": {
     "image/png": "[encoded data, 30112 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "7f0721f3",
   "metadata": {},
   "source": [
    "image of the initial guess![initial_guess.png](attachment:initial_guess.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "54a8e042",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Choose the fit function\n",
      " 1 -- HN, 2 -- HN with cond, 3 -- Hn-flank, 4 -- double HN, 5 -- double HN with cond:1\n",
      "0.7273425866263455 0.35735677206483585 2006.9130813366762 3.225343019206658\n",
      "log fmax: 3.8537356017041864\n",
      "fit parameters dumped for next iteration {'beta': 0.7273425866263455, 'gamma': 0.35735677206483585, 'freq': 2006.9130813366762, 'deps': 3.225343019206658, 'cond': 0, 'n': 0}\n"
     ]
    }
   ],
   "source": [
    "''' pefrorm least squares fitting'''\n",
    "''' The image of the curve fit is added in the next cell '''\n",
    "hn.fit(x1,y1)"
   ]
  },
  {
   "attachments": {
    "fit_example.png": {
     "image/png": "[encoded data, 37988 characters]"
    }
   },
   "cell_type": "markdown",
   "id": "06a85428",
   "metadata": {},
   "source": [
    "Example of the fit performed using single HN function\n",
    "the procedure is similar for double HN and HN with conductivity\n",
    "![fit_example.png](attachment:fit_example.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "694dbafa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Do you want to use an existing file to save fit results? \n",
      " eg: existing file to save HN parameters, y or n:n\n",
      "Choose the fit function\n",
      " 1 -- HN, 2 -- HN with cond, 3 -- HN-flank, 4 -- double HN, 5 -- double HN with cond:1\n",
      "Enter the analysis_file_name:hn_fit.TXT\n",
      "file did not exist, created hn_fit.TXT\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "()"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'''create a file to save fit results using create_analysis file method'''\n",
    "''' before saving fit results an analysis file has to be created '''\n",
    "hn.create_analysis_file()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "26796b6c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "()"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "''' save the fit results using save_fit method of the corresponding fit function'''\n",
    "''' takes one argument, read more on the documentation'''\n",
    "hn.save_fit_hn(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e33ddec9",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
