{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Calculations with Reference States\n",
    "\n",
    "## Experimental Reference States: Formation and Mixing Energy\n",
    "\n",
    "By default, energies calculated with pycalphad (e.g. `GM`, `HM`, etc.) are the absolute energies as defined in the database and are not calculated with respect to any reference state.\n",
    "\n",
    "pycalphad allows the reference for any property to be set to arbitrary phases and temperature/pressure conditions through the `ReferenceState` meta-property, which creates new properties for the specified property that are referenced to the specified reference state.\n",
    "\n",
    "### Enthalpy of mixing\n",
    "\n",
    "The enthalpy of mixing in the liquid, analogous to what would be measured experimentally, is calculated and plotted below with the reference states of the pure elements both set to the liquid phase. No temperature and pressure are specified as we would like the reference state to be calculated with respect to the calculation temperature."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-02-19T19:18:27.132381Z",
     "iopub.status.busy": "2022-02-19T19:18:27.132381Z",
     "iopub.status.idle": "2022-02-19T19:18:28.216231Z",
     "shell.execute_reply": "2022-02-19T19:18:28.215232Z"
    }
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-02-19T19:18:28.232251Z",
     "iopub.status.busy": "2022-02-19T19:18:28.230250Z",
     "iopub.status.idle": "2022-02-19T19:18:30.551328Z",
     "shell.execute_reply": "2022-02-19T19:18:30.551328Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 38832 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from pycalphad import Workspace, variables as v\n",
    "from pycalphad.property_framework import ReferenceState\n",
    "\n",
    "wks = Workspace(\"nbre_liu.tdb\", [\"NB\", \"RE\", \"VA\"], [\"LIQUID_RENB\"],\n",
    "                {v.P: 101325, v.T: 2800, v.X(\"RE\"): (0, 1, 0.005)})\n",
    "\n",
    "ref = ReferenceState([(\"LIQUID_RENB\", {v.X(\"RE\"): 0}),\n",
    "                      (\"LIQUID_RENB\", {v.X(\"RE\"): 1})\n",
    "                     ], wks)\n",
    "\n",
    "ref_enthalpy = ref('HM')\n",
    "ref_enthalpy.display_name = 'Enthalpy of Mixing'\n",
    "\n",
    "wks.plot(v.X('RE'), ref_enthalpy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Enthalpy of formation - convex hull\n",
    "\n",
    "Formation enthalpies are often reported in the literature with respect to the pure elements in their stable phase at 298.15 K. The enthalpy of formation of the phases in equilibrium, analogous to what would be measured experimentally, is calculated and plotted below for T=2800 K, with the reference states of the pure elements both set to the stable phases and fixed at 298.15 K and 1 atm."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-02-19T19:18:30.561221Z",
     "iopub.status.busy": "2022-02-19T19:18:30.561221Z",
     "iopub.status.idle": "2022-02-19T19:18:32.001422Z",
     "shell.execute_reply": "2022-02-19T19:18:32.001422Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 65204 characters]",
      "text/plain": [
       "<Figure size 900x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from pycalphad import Database, Workspace, as_property, variables as v\n",
    "from pycalphad.property_framework import ReferenceState\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "dbf_nbre = Database(\"nbre_liu.tdb\")\n",
    "\n",
    "wks2 = Workspace(dbf_nbre, [\"NB\", \"RE\", \"VA\"], sorted(dbf_nbre.phases.keys()),\n",
    "                 {v.P: 101325, v.T: 2800, v.X(\"RE\"): (0, 1, 0.005)})\n",
    "\n",
    "ref2 = ReferenceState([(\"BCC_RENB\", {v.X(\"RE\"): 0, v.T: 298.15}), # NB\n",
    "                       (\"HCP_RENB\", {v.X(\"RE\"): 1, v.T: 298.15})  # RE\n",
    "                     ], wks2)\n",
    "\n",
    "x_re, enthalpy_of_formation = wks2.get(v.X('RE'), ref2('HM'))\n",
    "\n",
    "# Find the groups of stable phases in equilibrium e.g. [CHI_RENB] and [CHI_RENB, HCP_RENB]\n",
    "unique_phase_sets = np.unique(wks2.eq.Phase.squeeze(), axis=0)\n",
    "\n",
    "# Plot\n",
    "fig = plt.figure(figsize=(9,6))\n",
    "ax = fig.gca()\n",
    "for phase_set in unique_phase_sets:\n",
    "    label = '+'.join([ph for ph in phase_set if ph != ''])\n",
    "    # composition indices with the same stable set of phases\n",
    "    unique_phase_idx = np.nonzero(np.all(wks2.eq.Phase.squeeze() == phase_set, axis=1))[0]\n",
    "    ax.plot(x_re[unique_phase_idx], enthalpy_of_formation[unique_phase_idx], marker='.', label=label)\n",
    "ax.set_xlim((0, 1))\n",
    "ax.set_xlabel(f'X(RE) [{v.X(\"RE\").implementation_units}]')\n",
    "ax.set_ylabel(f'Enthalpy of Formation [{as_property(\"HM\").implementation_units}]')\n",
    "ax.set_title('Nb-Re Formation Enthalpy (T=2800 K)')\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.10.6 64-bit",
   "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.6"
  },
  "vscode": {
   "interpreter": {
    "hash": "dffc026621927c134bf51c98cc1a2a1db0bb9758f5626f77d77eb66ad657b830"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
