{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Calculating Energy Surfaces [Legacy Method]\n",
    "\n",
    "**Note**: Since pycalphad 0.11, we recommend using the Computable Property API for calculating energy surfaces. This method remains supported, but is not recommended for new users.\n",
    "\n",
    "It is very common in CALPHAD modeling to directly examine the Gibbs energy surface of all the constituent phases in a system.\n",
    "\n",
    "Below we show how the Gibbs energy of all phases may be calculated as a function of composition at a given temperature (2800 K).\n",
    "\n",
    "Note that the chi phase has additional, internal degrees of freedom which allow it to take on multiple states for a given\n",
    "overall composition. Only the low-energy states are relevant to calculating the equilibrium phase diagram."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-02-19T19:16:49.958474Z",
     "iopub.status.busy": "2022-02-19T19:16:49.956474Z",
     "iopub.status.idle": "2022-02-19T19:16:50.747368Z",
     "shell.execute_reply": "2022-02-19T19:16:50.748370Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 107608 characters]",
      "text/plain": [
       "<Figure size 900x600 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "from pycalphad import Database, calculate, variables as v\n",
    "from pycalphad.plot.utils import phase_legend\n",
    "import numpy as np\n",
    "\n",
    "# Load database and choose the phases that will be plotted\n",
    "db_nbre = Database('nbre_liu.tdb')\n",
    "my_phases_nbre = ['CHI_RENB', 'SIGMARENB', 'FCC_RENB', 'LIQUID_RENB', 'BCC_RENB', 'HCP_RENB']\n",
    "\n",
    "# Get the colors that map phase names to colors in the legend\n",
    "legend_handles, color_dict = phase_legend(my_phases_nbre)\n",
    "\n",
    "fig = plt.figure(figsize=(9,6))\n",
    "ax = fig.gca()\n",
    "\n",
    "# Loop over phases, calculate the Gibbs energy, and scatter plot GM vs. X(RE)\n",
    "for phase_name in my_phases_nbre:\n",
    "    result = calculate(db_nbre, ['NB', 'RE'], phase_name, P=101325, T=2800, output='GM')\n",
    "    ax.scatter(result.X.sel(component='RE'), result.GM, marker='.', s=5, color=color_dict[phase_name])\n",
    "\n",
    "# Format the plot\n",
    "ax.set_xlabel('X(RE)')\n",
    "ax.set_ylabel('GM')\n",
    "ax.set_xlim((0, 1))\n",
    "ax.legend(handles=legend_handles, loc='center left', bbox_to_anchor=(1, 0.6))\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Triangular projection plots\n",
    "\n",
    "Importing the `pycalphad.plot.triangular` module automatically registers a `'triangular'` projection in matplotlib for you to use in custom plots, such as liquidus projections or contour plots of custom property models.\n",
    "\n",
    "Here we will use pycalphad to calculate the mixing enthalpy of the FCC phase in our Al-Cu-Y system. Then we will the triangular projection to plot the calculated points as a colored scatterplot on the triangular axes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-02-19T19:24:35.941781Z",
     "iopub.status.busy": "2022-02-19T19:24:35.941781Z",
     "iopub.status.idle": "2022-02-19T19:24:36.721283Z",
     "shell.execute_reply": "2022-02-19T19:24:36.721283Z"
    }
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 125632 characters]",
      "text/plain": [
       "<Figure size 640x480 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from pycalphad.plot import triangular\n",
    "from pycalphad import calculate\n",
    "\n",
    "db_al_cu_y = Database('Al-Cu-Y.tdb')\n",
    "comps = ['AL', 'CU', 'Y', 'VA']\n",
    "\n",
    "# some sample data, these could be from an equilibrium calculation or a property model.\n",
    "# here we are calculating the mixing enthlapy of the FCC_A1 phase at 830K. \n",
    "c = calculate(db_al_cu_y, comps, 'FCC_A1', output='HM_MIX', T=830, P=101325, pdens=5000)\n",
    "\n",
    "# Here we are getting the values from our plot. \n",
    "xs = c.X.values[0, 0, 0, :, 0]  # 1D array of Al compositions\n",
    "ys = c.X.values[0, 0, 0, :, 1]  # 1D array of Cu compositions\n",
    "zs = c.HM_MIX.values[0, 0, 0, :]  # 1D array of mixing enthalpies at these compositions\n",
    "\n",
    "# when we imported the pycalphad.plot.triangular module, it made the 'triangular' projection available for us to use.\n",
    "fig = plt.figure()\n",
    "ax = fig.add_subplot(projection='triangular')\n",
    "ax.scatter(xs, ys, c=zs, \n",
    "           cmap='coolwarm', \n",
    "           linewidth=0.0)\n",
    "\n",
    "# label the figure\n",
    "ax.set_xlabel('X (AL)')\n",
    "ax.set_ylabel('X (CU)')\n",
    "ax.yaxis.label.set_rotation(60)  # rotate ylabel\n",
    "ax.yaxis.set_label_coords(x=0.12, y=0.5)  # move the label to a pleasing position\n",
    "ax.set_title('AL-CU-Y HM_MIX at 830K')\n",
    "\n",
    "# set up the colorbar\n",
    "cm = plt.cm.ScalarMappable(cmap='coolwarm')\n",
    "cm.set_array(zs)\n",
    "fig.colorbar(cm, ax=ax);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "dffc026621927c134bf51c98cc1a2a1db0bb9758f5626f77d77eb66ad657b830"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
