{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exoplanet Watch API\n",
    "\n",
    "Learn how to explore the light curves, model fits and planetary ephemerides from EW using python programming. \n",
    "\n",
    "- Download light curve parameters, errors, posteriors or the raw data and fit it yourself\n",
    "- O-C plots with data curated from the NASA Exoplanet Archive and Exoplanet Watch\n",
    "- Over 100 targets with light curve data\n",
    "\n",
    "The results are hosted here: https://exoplanets.nasa.gov/exoplanet-watch/results/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded 120 targets\n",
      "['CoRoT-2 b', 'CoRoT-8 b', 'HAT-P-11 b', 'HAT-P-12 b', 'HAT-P-16 b', 'HAT-P-18 b', 'HAT-P-19 b', 'HAT-P-1 b', 'HAT-P-20 b', 'HAT-P-23 b', 'HAT-P-25 b', 'HAT-P-27 b', 'HAT-P-28 b', 'HAT-P-32 b', 'HAT-P-36 b', 'HAT-P-37 b', 'HAT-P-3 b', 'HAT-P-41 b', 'HAT-P-44 b', 'HAT-P-49 b', 'HAT-P-52 b', 'HAT-P-53 b', 'HAT-P-55 b', 'HAT-P-56 b', 'HAT-P-5 b', 'HAT-P-6 b', 'HAT-P-7 b', 'HAT-P-8 b', 'HATS-18 b', 'HATS-24 b', 'HATS-33 b', 'HD 149026 b', 'HD 189733 b', 'K2-137 b', 'K2-216 b', 'K2-30 b', 'KELT-16 b', 'KELT-1 b', 'KELT-21 b', 'KELT-23 A b', 'KELT-3 b', 'KELT-4 A b', 'KELT-7 b', 'KELT-8 b', 'Kepler-1086 b', 'Kepler-1650 b', 'Kepler-412 b', 'Kepler-426 b', 'Kepler-43 b', 'Kepler-446 b', 'Kepler-446 c', 'Kepler-447 b', 'Kepler-495 b', 'Kepler-673 b', 'Kepler-685 b', 'Kepler-693 b', 'Kepler-695 b', 'Kepler-702 b', 'Kepler-718 b', 'Kepler-74 b', 'Kepler-76 b', 'Kepler-77 b', 'Kepler-854 b', 'KPS-1 b', 'Qatar-10 b', 'Qatar-1 b', 'Qatar-2 b', 'Qatar-4 b', 'Qatar-5 b', 'Qatar-7 b', 'TrES-1 b', 'TrES-2 b', 'TrES-3 b', 'TrES-5 b', 'WASP-103 b', 'WASP-104 b', 'WASP-10 b', 'WASP-114 b', 'WASP-118 b', 'WASP-11 b', 'WASP-12 b', 'WASP-135 b', 'WASP-140 b', 'WASP-14 b', 'WASP-157 b', 'WASP-163 b', 'WASP-177 b', 'WASP-183 b', 'WASP-1 b', 'WASP-21 b', 'WASP-24 b', 'WASP-25 b', 'WASP-28 b', 'WASP-2 b', 'WASP-33 b', 'WASP-34 b', 'WASP-35 b', 'WASP-36 b', 'WASP-39 b', 'WASP-3 b', 'WASP-43 b', 'WASP-48 b', 'WASP-49 b', 'WASP-50 b', 'WASP-52 b', 'WASP-57 b', 'WASP-58 b', 'WASP-5 b', 'WASP-67 b', 'WASP-77 A b', 'WASP-80 b', 'WASP-92 b', 'WASP-93 b', 'WASP-98 b', 'WTS-2 b', 'XO-1 b', 'XO-2 N b', 'XO-5 b', 'XO-6 b', 'XO-7 b']\n"
     ]
    }
   ],
   "source": [
    "from exotic.api.ew import ExoplanetWatch\n",
    "from IPython.display import display, Image\n",
    "\n",
    "# This will load the results JSON from the link above\n",
    "EW = ExoplanetWatch()\n",
    "print(EW.target_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Query for a given target\n",
    "\n",
    "The command `get` will fetch priors, light curves and an ephemeris (O-C) for each target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['raw_result', 'host', 'name', 'priors', 'timestamp', 'identifier', 'reduction_count', 'observation_count', 'ephemeris', 'observations'])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# names are case and space sensitive\n",
    "result = EW.get('WASP-33 b')\n",
    "\n",
    "# list the result properties\n",
    "result.__dict__.keys()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Priors\n",
    "A list of stellar and planetary parameters with references. These are used to calculate a light curve model with non-linear limb darkening."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'R*': {'units': 'Sol',\n",
       "  'value': '1.44',\n",
       "  'reference': 'Chakrabarty &amp; Sengupta 2019',\n",
       "  'uncertainty': '0.03'},\n",
       " 'RA': {'units': 'decimal',\n",
       "  'value': '36.7127375',\n",
       "  'reference': None,\n",
       "  'uncertainty': None},\n",
       " 'T*': {'units': 'K',\n",
       "  'value': '7430.0',\n",
       "  'reference': 'Chakrabarty &amp; Sengupta 2019',\n",
       "  'uncertainty': '100.0'},\n",
       " 'Tc': {'units': 'BJD-UTC',\n",
       "  'value': '2454163.22367',\n",
       "  'reference': 'Zhang et al. 2018',\n",
       "  'uncertainty': '0.00022'},\n",
       " 'DEC': {'units': 'decimal',\n",
       "  'value': '37.5504441',\n",
       "  'reference': None,\n",
       "  'uncertainty': None},\n",
       " 'ecc': {'units': None,\n",
       "  'value': '0.0',\n",
       "  'reference': 'Stassun et al. 2017',\n",
       "  'uncertainty': None},\n",
       " 'inc': {'units': 'deg',\n",
       "  'value': '86.63',\n",
       "  'reference': 'Chakrabarty &amp; Sengupta 2019',\n",
       "  'uncertainty': '0.03'},\n",
       " 'FE/H': {'units': None,\n",
       "  'value': '0.1',\n",
       "  'reference': 'Zhang et al. 2018',\n",
       "  'uncertainty': '0.1'},\n",
       " 'LOGG': {'units': 'Log10(cgs)',\n",
       "  'value': '4.3',\n",
       "  'reference': 'Zhang et al. 2018',\n",
       "  'uncertainty': '0.1'},\n",
       " 'a/R*': {'units': None,\n",
       "  'value': '3.571',\n",
       "  'reference': 'Chakrabarty &amp; Sengupta 2019',\n",
       "  'uncertainty': '0.01'},\n",
       " 'Rp/R*': {'units': None,\n",
       "  'value': '0.1049',\n",
       "  'reference': 'Stassun et al. 2017',\n",
       "  'uncertainty': '0'},\n",
       " 'omega': {'units': 'deg',\n",
       "  'value': '0.0',\n",
       "  'reference': 'Chakrabarty &amp; Sengupta 2019',\n",
       "  'uncertainty': None},\n",
       " 'Period': {'units': 'day',\n",
       "  'value': '1.21987',\n",
       "  'reference': 'Chakrabarty &amp; Sengupta 2019',\n",
       "  'uncertainty': '1e-06'}}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.priors"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Observations\n",
    "\n",
    "Each observation is fit with a light curve model. For more information on how the light curve is fit please see: https://github.com/rzellem/EXOTIC/blob/main/exotic/api/elca.py#L602"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(result.observations)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['raw_observation', 'name', 'files', 'filter', 'obscode', 'identifier', 'secondary_obscodes', 'errors', 'parameters', 'lightcurve_url', 'posterior_url'])\n"
     ]
    }
   ],
   "source": [
    "# list the properties\n",
    "print(result.observations[0].__dict__.keys())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'u0': 2.073012980972075,\n",
       " 'u1': -3.6066268399883867,\n",
       " 'u2': 4.0864060212794415,\n",
       " 'u3': -1.5527921622631298,\n",
       " 'ecc': 0.0,\n",
       " 'inc': 86.63,\n",
       " 'omega': 0.0,\n",
       " 'duration': 0.1217,\n",
       " 'tmid': 2458154.6416,\n",
       " 'a1': 3.65,\n",
       " 'a2': -0.0052,\n",
       " 'ars': 3.584,\n",
       " 'rprs': 0.1237,\n",
       " 'per': 1.21987}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# print the best-fit parameters\n",
    "result.observations[0].parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<img src=\"https://exoplanets.nasa.gov/watch_results/formats/wasp-33_b/lc_0000344_wasp-33_b.png\"/>"
      ],
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# show the light curve\n",
    "display(Image(url=result.observations[0].lightcurve_url))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Download the light curve data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "time, flux, fluxerr, airmass, airmasscorr = result.observations[0].get_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Rel. Flux')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 12108 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "plt.plot(time, flux/airmasscorr, 'ko')\n",
    "plt.xlabel(\"Time [BJD]\")\n",
    "plt.ylabel(\"Rel. Flux\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Rel. Flux')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 15468 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# let's over plot the transit model too\n",
    "from exotic.api.elca import transit\n",
    "\n",
    "plt.plot(time, flux/airmasscorr, 'ko')\n",
    "plt.plot(time, transit(time, result.observations[0].parameters), 'r-')\n",
    "plt.xlabel(\"Time [BJD]\")\n",
    "plt.ylabel(\"Rel. Flux\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ea8d3be8832d44178f524e1cb6ff0cc3",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "VBox(children=(HTML(value=''), GridspecLayout(children=(HTML(value=\"<div style='background-color:#6E6BF4;'>&nb…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ultranest] Explored until L=-3e+01   [-32.5625..-32.5624]*| it/evals=4640/9169 eff=52.9137% N=400   \n",
      "[ultranest] Likelihood function evaluations: 9240\n",
      "[ultranest]   logZ = -39.59 +- 0.1049\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1851.0, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.07 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.20, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.12 bs:0.10 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n"
     ]
    }
   ],
   "source": [
    "# For more information on how to fit a light curve using exotic see: \n",
    "# https://github.com/rzellem/EXOTIC/blob/main/exotic/api/elca.py#L602\n",
    "from exotic.api.elca import lc_fitter\n",
    "\n",
    "# only define bounds for the \"free\" parameters during fitting\n",
    "mybounds = {\n",
    "    # [lower, upper]\n",
    "    'rprs':[0,0.2],\n",
    "    'tmid':[ result.observations[0].parameters['tmid']-0.02,\n",
    "             result.observations[0].parameters['tmid']+0.02],\n",
    "    'a2':[-0.1,0.1] # airmass curvature\n",
    "}\n",
    "\n",
    "myfit = lc_fitter(time, flux, fluxerr, airmass,\n",
    "                  result.observations[0].parameters, # priors\n",
    "                  mybounds, mode='ns' )  # ns = nested sampling, slow but robust + posteriors\n",
    "                                         # lm = levenberg mardquart, fast but no uncertainties"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 24248 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "myfit.plot_bestfit()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 180488 characters]\n",
      "text/plain": [
       "<Figure size 547.2x547.2 with 9 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "myfit.plot_triangle()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exoplanet Ephemeris\n",
    "\n",
    "After each light curve is fit, the mid-transit times are used along with values from the NASA Exoplanet Archive to derive a new ephemeris"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Tc': 2458154.641735694,\n",
       " 'Tcs': ['2458154.6416'],\n",
       " 'files': {'file_oc_pdf': './formats/wasp-33_b/oc_wasp-33_b.pdf',\n",
       "  'file_oc_png': './formats/wasp-33_b/oc_wasp-33_b.png'},\n",
       " 'notes': None,\n",
       " 'Period': 1.2198708522311985,\n",
       " 'Tc_err': 0.0005085746477986352,\n",
       " 'epochs': ['-0.0'],\n",
       " 'Tcs_err': ['0.0021'],\n",
       " 'datasets': ['0000344'],\n",
       " 'residuals': ['-0.00013569369912147522'],\n",
       " 'timesaved': 0.061,\n",
       " 'Period_err': 1.577331328497329e-07,\n",
       " 'nea_epochs': ['-4238.0', '-3272.0', '-2170.0', '-1000.0'],\n",
       " 'nea_references': ['Turner et al. 2016',\n",
       "  'Zhang et al. 2018\\n Collier Cameron et al. 2010 ',\n",
       "  ' von Essen et al. 2014 ',\n",
       "  'Johnson et al. 2015'],\n",
       " 'ephemeris_url': 'https://exoplanets.nasa.gov/watch_results/formats/wasp-33_b/oc_wasp-33_b.png'}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.ephemeris"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<img src=\"https://exoplanets.nasa.gov/watch_results/formats/wasp-33_b/oc_wasp-33_b.png\"/>"
      ],
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display(Image(url=result.ephemeris['ephemeris_url']))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO list nea_tmids in results file\n",
    "# result.ephemeris['nea_tmids']"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
