{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a39d7464-a111-4ac6-80b0-bcaa20aa81fa",
   "metadata": {},
   "source": [
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0dbb86a3-8915-43d6-b821-379ab76b2849",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import scipy.optimize\n",
    "from scipy.signal import medfilt\n",
    "from scipy.optimize import curve_fit\n",
    "\n",
    "import warnings"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79273c57-b22e-4b9b-ad97-8b788969a4a6",
   "metadata": {},
   "source": [
    "## Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "9a43783f-d1bb-4c79-ae93-843086a00a26",
   "metadata": {},
   "outputs": [],
   "source": [
    "# --- Data Loading ---\n",
    "\n",
    "def lpr_cor_import(filename):\n",
    "    \"\"\" Import cor file as pandas dataframe.\"\"\"\n",
    "\n",
    "    try: \n",
    "        df = pd.read_csv(\n",
    "            filename,\n",
    "            skiprows=26,\n",
    "            sep='\\s+',\n",
    "            header=None,\n",
    "            names=[\"E\", \"i\", \"T\"],\n",
    "        ) \n",
    "        df.drop(columns=[\"T\"], inplace=True)\n",
    "        df.drop(df.head(150).index, inplace=True)\n",
    "        df[\"E\"] = df[\"E\"]*1e3 # Convert it to mV\n",
    "        \n",
    "    except FileNotFoundError as e:\n",
    "        print(f\"Error: File was not found.\")\n",
    "        print(e.message)\n",
    "        print(e.args)\n",
    "        return None\n",
    "    except Exception as e:\n",
    "        print(f\"Error reading the CSV file: {e}\")\n",
    "        return None   \n",
    "    else:\n",
    "        return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "6a2888b4-e151-4fae-97d5-7de521fb7b48",
   "metadata": {},
   "outputs": [],
   "source": [
    "HS1_1 = lpr_cor_import(\"HIPed_Stellite1_LPR/LPR_1.cor\")\n",
    "HS1_2 = lpr_cor_import(\"HIPed_Stellite1_LPR/LPR_2.cor\")\n",
    "HS1_3 = lpr_cor_import(\"HIPed_Stellite1_LPR/LPR_3.cor\")\n",
    "HS1_4 = lpr_cor_import(\"HIPed_Stellite1_LPR/LPR_4.cor\")\n",
    "HS1_5 = lpr_cor_import(\"HIPed_Stellite1_LPR/LPR_5.cor\")\n",
    "HS1_6 = lpr_cor_import(\"HIPed_Stellite1_LPR/LPR_6.cor\")\n",
    "\n",
    "# Keep it in the same cell to keep df reproducible, even if Vi clicks it multiple times\n",
    "area = 2 #cm^2\n",
    "\n",
    "for df in [HS1_1, HS1_2, HS1_3, HS1_4, HS1_5, HS1_6]:\n",
    "    df[\"i\"] = np.abs(df[\"i\"]/area) # Current density\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "0ad5c189-9bd6-4291-bdee-8b75fdd5a3cd",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>E</th>\n",
       "      <th>i</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>150</th>\n",
       "      <td>-205.474</td>\n",
       "      <td>3.492260e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>151</th>\n",
       "      <td>-205.464</td>\n",
       "      <td>3.335005e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>152</th>\n",
       "      <td>-205.454</td>\n",
       "      <td>2.995255e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>153</th>\n",
       "      <td>-205.444</td>\n",
       "      <td>2.772125e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>154</th>\n",
       "      <td>-205.434</td>\n",
       "      <td>2.682435e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3999</th>\n",
       "      <td>-167.010</td>\n",
       "      <td>6.514500e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4000</th>\n",
       "      <td>-167.003</td>\n",
       "      <td>6.453200e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4001</th>\n",
       "      <td>-167.005</td>\n",
       "      <td>6.450600e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4002</th>\n",
       "      <td>-166.991</td>\n",
       "      <td>6.511600e-11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4003</th>\n",
       "      <td>-166.998</td>\n",
       "      <td>6.448450e-11</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>3854 rows × 2 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "            E             i\n",
       "150  -205.474  3.492260e-11\n",
       "151  -205.464  3.335005e-11\n",
       "152  -205.454  2.995255e-11\n",
       "153  -205.444  2.772125e-11\n",
       "154  -205.434  2.682435e-11\n",
       "...       ...           ...\n",
       "3999 -167.010  6.514500e-11\n",
       "4000 -167.003  6.453200e-11\n",
       "4001 -167.005  6.450600e-11\n",
       "4002 -166.991  6.511600e-11\n",
       "4003 -166.998  6.448450e-11\n",
       "\n",
       "[3854 rows x 2 columns]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "HS1_3"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee328bd6-4817-41a9-8831-12cda31cb8f1",
   "metadata": {},
   "source": [
    "# Coding part!\n",
    "\n",
    "Separate code into analyze and plotting, with all answers in a dict.\n",
    "Can't believe it took me this long to really do it this way :|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bec9f9bc-b531-470e-9c27-a89b512e97ba",
   "metadata": {},
   "source": [
    "## Analyze Tafel Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 261,
   "id": "110a6031-ea23-46cf-8f1a-7c39ec6d88b9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from scipy.signal import medfilt\n",
    "import warnings\n",
    "\n",
    "def analyze_tafel(data: pd.DataFrame) -> dict:\n",
    "    \"\"\"\n",
    "    Analyzes Tafel data to determine electrochemical parameters.\n",
    "\n",
    "    Args:\n",
    "        data: DataFrame with 'E' (potential) and 'i' (current) columns.\n",
    "\n",
    "    Returns:\n",
    "        A dictionary containing the analysis results.\n",
    "    \"\"\"\n",
    "    INITIAL_KERNEL = 29\n",
    "    FIT_KERNEL = 99\n",
    "\n",
    "    # 1. Estimate Corrosion Potential (Ecorr) using a median filter\n",
    "    ecorr_guess = data['E'].iloc[np.argmin(medfilt(data['i'], kernel_size=INITIAL_KERNEL))]\n",
    "\n",
    "    # 2. Split data into anodic and cathodic regions based on Ecorr\n",
    "    anodic_data = data[data['E'] > ecorr_guess + 12].copy()\n",
    "    cathodic_data = data[data['E'] < ecorr_guess - 12].copy()\n",
    "\n",
    "    if anodic_data.empty or cathodic_data.empty:\n",
    "        warnings.warn(\"No data in anodic or cathodic regions. Ecorr guess may be incorrect.\")\n",
    "        return {}\n",
    "\n",
    "    anodic_data[\"i\"] = medfilt(anodic_data['i'], kernel_size=FIT_KERNEL)\n",
    "    cathodic_data[\"i\"] = medfilt(cathodic_data['i'], kernel_size=FIT_KERNEL)\n",
    "\n",
    "    # 3. Perform linear fit on E vs. log(i) for each branch\n",
    "    p_anodic = np.poly1d(np.polyfit(    \n",
    "        np.log10(anodic_data[\"i\"]), \n",
    "        anodic_data['E'], 1))\n",
    "    p_cathodic = np.poly1d(np.polyfit(\n",
    "        np.log10(cathodic_data[\"i\"]), \n",
    "        cathodic_data['E'], 1))\n",
    "    beta_a = p_anodic[1]\n",
    "    beta_c = -p_cathodic[1]\n",
    "\n",
    "    # 3.5 Find the i_corr according to each branch\n",
    "    # Find the roots of the polynomial p(log(i)) - E_corr = 0\n",
    "    icorr_anodic = np.power(10, ((p_anodic - ecorr_guess).roots)[0])\n",
    "    icorr_cathodic = np.power(10,((p_cathodic - ecorr_guess).roots)[0])\n",
    "    \n",
    "    # --- 4. Calculations ---\n",
    "    temp_kelvin = 25.0 + 273.15\n",
    "    R = 8.314  # Ideal Gas Constant (J/(mol·K))\n",
    "    F = 96485  # Faraday Constant (C/mol)\n",
    "    n = 3      # Number of electrons transferred\n",
    "\n",
    "    alpha_a, alpha_c = None, None\n",
    "    try:\n",
    "        # Calculate charge transfer coefficients\n",
    "        alpha_a = (2.303 * R * temp_kelvin) / (1e-3 * beta_a * n * F)\n",
    "        alpha_c = (2.303 * R * temp_kelvin) / (1e-3 * beta_c * n * F)\n",
    "    except ZeroDivisionError as e:\n",
    "        print(f\"Error during calculation: {e}. A slope was zero.\")\n",
    "\n",
    "    return {\n",
    "        \"ecorr_guess\": ecorr_guess,\n",
    "        \"p_anodic\": p_anodic,\n",
    "        \"p_cathodic\": p_cathodic,\n",
    "        \"anodic_data\": anodic_data,\n",
    "        \"cathodic_data\": cathodic_data,\n",
    "        \"beta_a\": beta_a,\n",
    "        \"beta_c\": beta_c,\n",
    "        \"alpha_a\": alpha_a,\n",
    "        \"alpha_c\": alpha_c,\n",
    "        \"icorr_anodic\": icorr_anodic,\n",
    "        \"icorr_cathodic\": icorr_cathodic,\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34f9a01d-0a09-4054-9eec-b12c512fe29a",
   "metadata": {},
   "source": [
    "## Plot Tafel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 264,
   "id": "56eba50b-b152-4033-af25-5ec5f2bbb80c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib import rcParams\n",
    "from matplotlib.ticker import MultipleLocator, AutoMinorLocator\n",
    "import warnings\n",
    "\n",
    "def plot_tafel(\n",
    "    data: pd.DataFrame,\n",
    "    results: dict = None,\n",
    "    save_path: str = None,\n",
    "    fig_format: str = 'png',\n",
    "    column: str = 'single'\n",
    "):\n",
    "    \"\"\"\n",
    "    Generates a publication-quality Tafel plot from experimental data and analysis results.\n",
    "\n",
    "    This function formats the plot for single or double-column layouts typical\n",
    "    in academic journals, including specific font sizes, line styles, and\n",
    "    LaTeX-formatted labels.\n",
    "\n",
    "    Args:\n",
    "        data (pd.DataFrame): The original DataFrame containing experimental data.\n",
    "                             Must include 'E' (Potential in mV) and 'i' (Current in A).\n",
    "        results (dict, optional): A dictionary from an analysis function containing keys\n",
    "                                  like 'ecorr_guess', 'beta_a', 'beta_c', 'p_anodic',\n",
    "                                  'p_cathodic', 'anodic_data', and 'cathodic_data'.\n",
    "        save_path (str, optional): The file path to save the figure (without extension).\n",
    "                                   If None, the plot is displayed instead. Defaults to None.\n",
    "        fig_format (str, optional): The format to save the figure in (e.g., 'png',\n",
    "                                    'tiff', 'svg'). Defaults to 'png'.\n",
    "        column (str, optional): The journal column type for the plot.\n",
    "                                Can be 'single' or 'double'. Defaults to 'single'.\n",
    "    \"\"\"\n",
    "\n",
    "    # --- 1. Validate Input ---\n",
    "    if results is None or not isinstance(results, dict):\n",
    "        warnings.warn(\n",
    "            \"Analysis 'results' dictionary not provided. Plotting experimental data only.\",\n",
    "            UserWarning\n",
    "        )\n",
    "        results = {} # Use an empty dict to avoid errors later\n",
    "\n",
    "    # --- 2. Configure Matplotlib for Publication Quality based on column type ---\n",
    "    if column == 'single':\n",
    "        # Parameters for a single-column figure (~3.5 inches wide)\n",
    "        figsize = (3.5, 3.0)\n",
    "        plot_params = {\n",
    "            'font.size': 8,\n",
    "            'axes.labelsize': 9,\n",
    "            'legend.fontsize': 7,\n",
    "            'xtick.labelsize': 7,\n",
    "            'ytick.labelsize': 7,\n",
    "            'axes.linewidth': 0.8\n",
    "        }\n",
    "        data_line_width = 1.0\n",
    "        fit_line_width = 1.2\n",
    "        ecorr_line_width = 0.7\n",
    "    elif column == 'double':\n",
    "        # Parameters for a double-column figure (~7 inches wide)\n",
    "        figsize = (7, 5)\n",
    "        plot_params = {\n",
    "            'font.size': 10,\n",
    "            'axes.labelsize': 11,\n",
    "            'legend.fontsize': 9,\n",
    "            'xtick.labelsize': 9,\n",
    "            'ytick.labelsize': 9,\n",
    "            'axes.linewidth': 1.0\n",
    "        }\n",
    "        data_line_width = 1.2\n",
    "        fit_line_width = 1.5\n",
    "        ecorr_line_width = 0.8\n",
    "    else:\n",
    "        raise ValueError(\"Invalid column type specified. Choose 'single' or 'double'.\")\n",
    "\n",
    "    # --- 3. Generate Plot within a temporary style context ---\n",
    "    with plt.rc_context(rc=plot_params):\n",
    "        fig, ax = plt.subplots(figsize=figsize, dpi=300)\n",
    "\n",
    "        # --- 3a. Plot Experimental Data as a Line Plot ---        \n",
    "        ax.semilogx(\n",
    "            np.abs(data[\"i\"]),         # x data\n",
    "            data[\"E\"],                 # y data\n",
    "            marker='none', \n",
    "            linestyle='-',\n",
    "            color='black',\n",
    "            linewidth=data_line_width,\n",
    "            label='Experimental Data'\n",
    "        )\n",
    "\n",
    "        # --- 3b. Plot E_corr line and Overpotential Axis ---\n",
    "        if 'ecorr_guess' in results:\n",
    "            ecorr = results[\"ecorr_guess\"]\n",
    "            ax.axhline(\n",
    "                y=ecorr,\n",
    "                color='k',\n",
    "                linestyle='--',\n",
    "                linewidth=ecorr_line_width,\n",
    "                alpha=0.8,\n",
    "                label=f'$E_{{corr}}$ = {ecorr:.1f} mV'\n",
    "            )\n",
    "\n",
    "            #ax.set_ylim(top=-160, bottom=-210) \n",
    "            #ax.set_xlim(left=10**-16) \n",
    "            \n",
    "            # Create a twin axis for overpotential\n",
    "            bx = ax.twinx()\n",
    "            ymin, ymax = ax.get_ylim()\n",
    "            bx.set_ylim(ymin - ecorr, ymax - ecorr)\n",
    "            bx.set_ylabel(\"Overpotential (mV)\")\n",
    "\n",
    "            # Set major ticks to be multiples of 50 mV and add minor ticks\n",
    "            bx.yaxis.set_major_locator(MultipleLocator(5))\n",
    "            bx.yaxis.set_minor_locator(AutoMinorLocator(1))\n",
    "\n",
    "            bx.tick_params(direction='in', which='both')\n",
    "            bx.spines['right'].set_position(('outward', 0))\n",
    "        else:\n",
    "            warnings.warn(\"Cannot plot E_corr line: 'ecorr_guess' not in results.\", UserWarning)\n",
    "\n",
    "        # --- 3c. Plot Tafel Fit Lines ---\n",
    "        required_fit_keys = [\"anodic_data\", \"cathodic_data\", \n",
    "                             'p_anodic', 'p_cathodic', \n",
    "                             'icorr_anodic', 'icorr_cathodic',                              \n",
    "                             'beta_a', 'beta_c']\n",
    "        if all(key in results for key in required_fit_keys):\n",
    "            # ANODIC LINE DOTTED\n",
    "            ax.plot(\n",
    "                np.logspace(\n",
    "                    np.log10(results[\"icorr_anodic\"]),\n",
    "                    np.log10(results[\"anodic_data\"][\"i\"].max()),\n",
    "                    100,\n",
    "                ), \n",
    "                results[\"p_anodic\"](\n",
    "                    np.log10(\n",
    "                        np.logspace(\n",
    "                            np.log10(results[\"icorr_anodic\"]),\n",
    "                            np.log10(results[\"anodic_data\"][\"i\"].max()),\n",
    "                            100,  \n",
    "                        ),\n",
    "                    )\n",
    "                ),\n",
    "                '--', color='#d62728', linewidth=fit_line_width,\n",
    "                label=f'$\\\\beta_a$ = {results[\"beta_a\"]:.1f} mV dec$^{{-1}}$ \\n $\\\\alpha_a$ = {results[\"alpha_a\"]:.2f}'\n",
    "            )\n",
    "            # ANODIC LINE             \n",
    "            ax.plot(\n",
    "                np.logspace(\n",
    "                    np.log10(results[\"anodic_data\"][\"i\"].min()),\n",
    "                    np.log10(results[\"anodic_data\"][\"i\"].max()),\n",
    "                    100,\n",
    "                ), \n",
    "                results[\"p_anodic\"](\n",
    "                    np.log10(               \n",
    "                        np.logspace(\n",
    "                            np.log10(results[\"anodic_data\"][\"i\"].min()),\n",
    "                            np.log10(results[\"anodic_data\"][\"i\"].max()),\n",
    "                            100,\n",
    "                        ), \n",
    "                    )\n",
    "                ),\n",
    "                color='#d62728', linewidth=fit_line_width,\n",
    "            )\n",
    "            \n",
    "            # CATHODIC LINE DOTTED\n",
    "            ax.plot(\n",
    "                np.logspace(\n",
    "                    np.log10(results[\"icorr_cathodic\"]),\n",
    "                    np.log10(results[\"cathodic_data\"][\"i\"].max()),\n",
    "                    100,\n",
    "                ), \n",
    "                results[\"p_cathodic\"](\n",
    "                    np.log10(               \n",
    "                        np.logspace(\n",
    "                            np.log10(results[\"icorr_cathodic\"]),\n",
    "                            np.log10(results[\"cathodic_data\"][\"i\"].max()),\n",
    "                            100,\n",
    "                        ), \n",
    "                    )\n",
    "                ),\n",
    "                '--', color='#1f77b4', linewidth=fit_line_width,\n",
    "                label=f'$\\\\beta_c$ = {results[\"beta_c\"]:.1f} mV dec$^{{-1}}$ \\n $\\\\alpha_c$ = {results[\"alpha_c\"]:.2f}'\n",
    "            )\n",
    "            # CATHODIC LINE \n",
    "            ax.plot(\n",
    "                np.logspace(\n",
    "                    np.log10(results[\"cathodic_data\"][\"i\"].min()),\n",
    "                    np.log10(results[\"cathodic_data\"][\"i\"].max()),\n",
    "                    100,\n",
    "                ), \n",
    "                results[\"p_cathodic\"](\n",
    "                    np.log10(               \n",
    "                        np.logspace(\n",
    "                            np.log10(results[\"cathodic_data\"][\"i\"].min()),\n",
    "                            np.log10(results[\"cathodic_data\"][\"i\"].max()),\n",
    "                            100,\n",
    "                        ), \n",
    "                    )\n",
    "                ),\n",
    "                color='#1f77b4', linewidth=fit_line_width,\n",
    "            )\n",
    "\n",
    "        else:\n",
    "            warnings.warn(\"Cannot plot Tafel fit lines: one or more required keys are missing from results.\", UserWarning)\n",
    "\n",
    "        # --- 3d. Configure Plot Aesthetics ---\n",
    "        ax.set_xlabel('Current Density, |$j$| (A/cm$^2$)')\n",
    "        ax.set_ylabel('Potential, $E$ vs. Ref. (mV)')\n",
    "        ax.tick_params(direction='in', which='both', top=True, right=False)\n",
    "        ax.grid(True, which=\"both\", ls=\"--\", linewidth=0.4, color='gray', alpha=0.6)\n",
    "\n",
    "        # Combine legends and make the frame less prominent\n",
    "        lines, labels = ax.get_legend_handles_labels()\n",
    "        ax.legend(\n",
    "            lines, labels, loc='best',\n",
    "            frameon=True,\n",
    "            framealpha=0.9,\n",
    "            edgecolor='0.7',\n",
    "            borderpad=0.3,\n",
    "            labelspacing=0.4\n",
    "        )\n",
    "\n",
    "        fig.tight_layout()\n",
    "\n",
    "    # --- 4. Finalize and Show/Save Plot ---\n",
    "    if save_path:\n",
    "        plt.savefig(f\"{save_path}.{fig_format}\", format=fig_format, bbox_inches='tight')\n",
    "        print(f\"✅ Plot saved to {save_path}.{fig_format}\")\n",
    "    else:\n",
    "        plt.show()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 265,
   "id": "0651c767-a244-4649-8a82-fcda97ade5b0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "alpha_a: 0.53\n",
      "alpha_c: 0.46\n",
      "Sum of alphas: 0.99\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 161080 characters]",
      "text/plain": [
       "<Figure size 1050x900 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Assuming 'HS1_6' is your DataFrame loaded with the experimental data\n",
    "# For example:\n",
    "# data = {'E': np.linspace(0, 1, 100), 'i': np.logspace(-6, -2, 100)}\n",
    "# HS1_6 = pd.DataFrame(data)\n",
    "\n",
    "# 1. Analyze the data\n",
    "analysis_results = analyze_tafel(HS1_5)\n",
    "\n",
    "# Print the calculated alpha values\n",
    "if analysis_results:\n",
    "    print(f\"alpha_a: {analysis_results['alpha_a']:.2f}\")\n",
    "    print(f\"alpha_c: {analysis_results['alpha_c']:.2f}\")\n",
    "    if analysis_results['alpha_a'] is not None and analysis_results['alpha_c'] is not None:\n",
    "        print(f\"Sum of alphas: {analysis_results['alpha_a'] + analysis_results['alpha_c']:.2f}\")\n",
    "\n",
    "\n",
    "# 2. Plot the data and the analysis\n",
    "plot_tafel(HS1_5, analysis_results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 255,
   "id": "2f13865b-557a-4fdf-b3d4-a8ffa5c2c8e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "p = analysis_results[\"p_anodic\"] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 256,
   "id": "5f19c6e5-d6db-4530-b1e1-59b9fbe8a17a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "poly1d([ 31.77354549, 155.49089313])"
      ]
     },
     "execution_count": 256,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "p\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 216,
   "id": "9c700d08-e08f-4dd8-9737-3b11e1a7af14",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.float64(1.6913954688266906e-11)"
      ]
     },
     "execution_count": 216,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(2.73)**((p.roots)[0])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a9c66d0-3f55-4f4a-a79c-9da787abdfae",
   "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.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
