{
 "cells": [
  {
   "cell_type": "raw",
   "id": "eaf29ef7",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    ".. _cookbook-iso:\n",
    "\n",
    "Isochrone Color-Magnitude Diagram\n",
    "=================================\n",
    "\n",
    "This :ref:`cookbook` recipe demonstrates how to create a color-magnitude diagram (CMD) for an isochrone, using the\n",
    "MSG Python interface.\n",
    "\n",
    "Preparation\n",
    "-----------\n",
    "\n",
    "Download :download:`isochrone-cmd.tar.bz2` and unpack it in your working directory. This archive contains the following items:\n",
    "\n",
    "* :file:`MIST.iso` |---| isochrone data [#isochrone]_\n",
    "* :file:`pg-*.h5` |---| :f-schema:`photgrid` files for each passband [#photgrids]_\n",
    "* :file:`read_mist_models.py` --- Python module for reading :file:`MIST.iso`\n",
    "\n",
    "Initialization\n",
    "--------------\n",
    "\n",
    "To start, import modules and set other parameters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2eb4244c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import modules\n",
    "\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "import astropy.constants as con\n",
    "\n",
    "import pymsg\n",
    "import read_mist_models\n",
    "\n",
    "# Set plot parameters\n",
    "\n",
    "%matplotlib inline\n",
    "plt.rcParams.update({'font.size': 16})"
   ]
  },
  {
   "cell_type": "raw",
   "id": "07a01f15",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    "Create PhotGrids\n",
    "----------------\n",
    "\n",
    "Next, create a pair of :py:class:`pymsg.PhotGrid` objects for interpolating fluxes in the Johnson B and V bands:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9c7a8544",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create PhotGrid objects\n",
    "\n",
    "photgrid_B = pymsg.PhotGrid('pg-Johnson-B.h5')\n",
    "photgrid_V = pymsg.PhotGrid('pg-Johnson-V.h5')"
   ]
  },
  {
   "cell_type": "raw",
   "id": "5b4d9d5f",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    "Read Isochrone Data\n",
    "-------------------\n",
    "\n",
    "Now read in the isochrone data file and extract the stellar parameters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2d008331-53c4-468b-983a-8682d3ab0882",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Reading in: MIST.iso\n"
     ]
    }
   ],
   "source": [
    "# Read isochrone data file\n",
    "\n",
    "iso = read_mist_models.ISO('MIST.iso')\n",
    "\n",
    "# Extract stellar parameters\n",
    "\n",
    "Teff = 10**iso.isos[0]['log_Teff']\n",
    "logg = iso.isos[0]['log_g']\n",
    "\n",
    "R = 10**iso.isos[0]['log_R']*con.R_sun.value"
   ]
  },
  {
   "cell_type": "raw",
   "id": "7e98770e-7c62-43a0-9ea8-27b1d3e50736",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    "Evaluate Fluxes\n",
    "---------------\n",
    "\n",
    "Using these parameters, evaluate the observed flux at 10 parsecs in each band:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "163c7134-4bf4-433c-9e89-af740f708f45",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Evaluate fluxes\n",
    "\n",
    "n = len(Teff)\n",
    "\n",
    "F_B = np.empty(n)\n",
    "F_V = np.empty(n)\n",
    "\n",
    "for i in range(n):\n",
    "\n",
    "    # Set up photospheric parameters dict\n",
    "\n",
    "    x = {'Teff': Teff[i],\n",
    "         'log(g)': logg[i]}\n",
    "    \n",
    "    # Evaluate fluxes. Use try/execpt clause to deal with \n",
    "    # points that fall outside the grid\n",
    "\n",
    "    try:\n",
    "        F_B[i] = (R[i]/(10*con.pc.value))**2 * photgrid_B.flux(x)\n",
    "        F_V[i] = (R[i]/(10*con.pc.value))**2 * photgrid_V.flux(x)\n",
    "    except (ValueError, LookupError):\n",
    "        F_B[i] = np.NAN\n",
    "        F_V[i] = np.NAN"
   ]
  },
  {
   "cell_type": "raw",
   "id": "fc36f462-c4f3-4c76-ab16-ae76a67b6b87",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    "Plot the CMD\n",
    "------------\n",
    "\n",
    "As a final step, convert fluxes to (absolute) magnitudes and plot the CMD:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d30546b7-42d4-4d3d-a1c6-4a1ec93676df",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, '$M_V$')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 28640 characters]\n",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.figure()\n",
    "\n",
    "M_B = -2.5*np.log10(F_B)\n",
    "M_V = -2.5*np.log10(F_V)\n",
    "\n",
    "plt.plot(M_B-M_V, M_V)\n",
    "\n",
    "plt.xlim(0, 2)\n",
    "plt.ylim(12.5,-2.5)\n",
    "\n",
    "plt.xlabel('$B-V$')\n",
    "plt.ylabel('$M_V$')"
   ]
  },
  {
   "cell_type": "raw",
   "id": "fb835442",
   "metadata": {
    "raw_mimetype": "text/restructuredtext"
   },
   "source": [
    ".. rubric:: Footnotes\n",
    "\n",
    ".. [#isochrone] Generated using the `MIST <mist_>`__ web interpolator for an age :math:`\\log(t/\\yr) = 9.6` (non-rotating, solar-metallicity).\n",
    ".. [#photgrids] Generated by applying the :command:`specgrid_to_photgrid` tool to the demo grid."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Raw Cell Format",
  "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.8.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
