{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simultaneously fit multiple lightcurves with airmass detrending\n",
    "\n",
    "Here we will fit multiple lightcurves simultaneously using the global fitter in exotic. We will set up bounds for each lightcurve that specify what parameters to fit along with 'global' bounds that are shared between all lightcurves. \n",
    "\n",
    "![](https://s3.amazonaws.com/aasie/images/0004-6256/164/5/null/ajac8deef3_hr.jpg)\n",
    "\n",
    "This notebook will show you how to reproduce something similar to Figure 4 in a study on HD 80606 b, https://ui.adsabs.harvard.edu/abs/2022AJ....164..178P/abstract \n",
    "\n",
    "Please cite that paper if you use this code"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Find lightcurve data in the Exoplanet Watch Database\n",
    "\n",
    "The command `get` will fetch priors, light curves and an ephemeris (O-C) for each target."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded 358 targets\n",
      "['CoRoT-11 b', 'CoRoT-14 b', 'CoRoT-18 b', 'CoRoT-1 b', 'CoRoT-27 b', 'CoRoT-29 b', 'CoRoT-2 b', 'CoRoT-5 b', 'CoRoT-7 b', 'CoRoT-8 b', 'CoRoTID 223977153 b', 'EPIC 206042996 c', 'Gaia-1 b', 'Gaia-2 b', 'GJ 1214 b', 'GJ 3470 b', 'GJ 436 b', 'GPX-1 b', 'HAT-P-11 b', 'HAT-P-12 b', 'HAT-P-13 b', 'HAT-P-16 b', 'HAT-P-17 b', 'HAT-P-18 b', 'HAT-P-19 b', 'HAT-P-1 b', 'HAT-P-20 b', 'HAT-P-21 b', 'HAT-P-22 b', 'HAT-P-23 b', 'HAT-P-25 b', 'HAT-P-26 b', 'HAT-P-27 b', 'HAT-P-28 b', 'HAT-P-29 b', 'HAT-P-30 b', 'HAT-P-32 b', 'HAT-P-33 b', 'HAT-P-34 b', 'HAT-P-36 b', 'HAT-P-37 b', 'HAT-P-38 b', 'HAT-P-39 b', 'HAT-P-3 b', 'HAT-P-41 b', 'HAT-P-44 b', 'HAT-P-45 b', 'HAT-P-49 b', 'HAT-P-4 b', 'HAT-P-50 b', 'HAT-P-51 b', 'HAT-P-52 b', 'HAT-P-53 b', 'HAT-P-54 b', 'HAT-P-55 b', 'HAT-P-56 b', 'HAT-P-57 b', 'HAT-P-59 b', 'HAT-P-5 b', 'HAT-P-65 b', 'HAT-P-68 b', 'HAT-P-6 b', 'HAT-P-70 b', 'HAT-P-7 b', 'HAT-P-8 b', 'HAT-P-9 b', 'HATS-18 b', 'HATS-22 b', 'HATS-24 b', 'HATS-2 b', 'HATS-33 b', 'HATS-38 b', 'HATS-44 b', 'HATS-47 b', 'HATS-62 b', 'HATS-67 b', 'HATS-7 b', 'HD 149026 b', 'HD 189733 b', 'HD 209458 b', 'HD 80606 b', 'K2-105 b', 'K2-117 b', 'K2-121 b', 'K2-123 b', 'K2-127 b', 'K2-137 b', 'K2-140 b', 'K2-141 c', 'K2-146 b', 'K2-153 b', 'K2-183 b', 'K2-216 b', 'K2-229 b', 'K2-22 b', 'K2-237 b', 'K2-242 b', 'K2-246 b', 'K2-247 c', 'K2-250 b', 'K2-25 b', 'K2-260 b', 'K2-266 b', 'K2-270 c', 'K2-271 b', 'K2-284 b', 'K2-285 b', 'K2-295 b', 'K2-29 b', 'K2-308 b', 'K2-30 b', 'K2-31 b', 'K2-321 b', 'K2-343 b', 'K2-34 b', 'K2-371 b', 'K2-411 b', 'KELT-16 b', 'KELT-17 b', 'KELT-18 b', 'KELT-19 A b', 'KELT-1 b', 'KELT-20 b', 'KELT-21 b', 'KELT-23 A b', 'KELT-24 b', 'KELT-3 b', 'KELT-4 A b', 'KELT-7 b', 'KELT-8 b', 'Kepler-1086 b', 'Kepler-1087 b', 'Kepler-1124 b', 'Kepler-1320 b', 'Kepler-1321 c', 'Kepler-1350 b', 'Kepler-1350 c', 'Kepler-1351 b', 'Kepler-148 c', 'Kepler-1520 b', 'Kepler-1582 b', 'Kepler-15 b', 'Kepler-1650 b', 'Kepler-1651 b', 'Kepler-167 e', 'Kepler-17 b', 'Kepler-210 b', 'Kepler-231 b', 'Kepler-254 b', 'Kepler-257 b', 'Kepler-283 b', 'Kepler-296 c', 'Kepler-412 b', 'Kepler-41 b', 'Kepler-423 b', 'Kepler-424 b', 'Kepler-425 b', 'Kepler-426 b', 'Kepler-428 b', 'Kepler-42 b', 'Kepler-42 c', 'Kepler-43 b', 'Kepler-446 b', 'Kepler-446 c', 'Kepler-447 b', 'Kepler-44 b', 'Kepler-45 b', 'Kepler-471 b', 'Kepler-472 b', 'Kepler-488 b', 'Kepler-491 b', 'Kepler-493 b', 'Kepler-495 b', 'Kepler-49 c', 'Kepler-546 b', 'Kepler-548 b', 'Kepler-553 b', 'Kepler-554 b', 'Kepler-586 b', 'Kepler-673 b', 'Kepler-685 b', 'Kepler-686 b', 'Kepler-693 b', 'Kepler-695 b', 'Kepler-697 b', 'Kepler-6 b', 'Kepler-702 b', 'Kepler-718 b', 'Kepler-720 b', 'Kepler-723 b', 'Kepler-729 b', 'Kepler-74 b', 'Kepler-76 b', 'Kepler-77 b', 'Kepler-785 b', 'Kepler-81 c', 'Kepler-861 b', 'Kepler-8 b', 'Kepler-913 b', 'Kepler-94 b', 'Kepler-957 b', 'KOI-13 b', 'KOI-217 b', 'KPS-1 b', 'LHS 1140 c', 'MASCARA-1 b', 'NGTS-10 b', 'NGTS-13 b', 'NGTS-1 b', 'NGTS-5 b', 'NGTS-8 b', 'NGTS-9 b', 'Qatar-10 b', 'Qatar-1 b', 'Qatar-2 b', 'Qatar-4 b', 'Qatar-5 b', 'Qatar-6 b', 'Qatar-7 b', 'Qatar-8 b', 'Qatar-9 b', 'TOI-1130 b', 'TOI-1181 b', 'TOI-1246 b', 'TOI-1246 c', 'TOI-1259 A b', 'TOI-1333 b', 'TOI-1431 b', 'TOI-1442 b', 'TOI-150.01', 'TOI-1516 b', 'TOI-1518 b', 'TOI-157 b', 'TOI-1634 b', 'TOI-1728 b', 'TOI-1811 b', 'TOI-2046 b', 'TOI-2109 b', 'TOI-2154 b', 'TOI-2445 b', 'TOI-2796 b', 'TOI-3629 b', 'TOI-3693 b', 'TOI-3714 b', 'TOI-3757 b', 'TOI-3807 b', 'TOI-3884 b', 'TOI-4087 b', 'TOI-4137 b', 'TOI-4463 A b', 'TOI-4479 b', 'TOI-519 b', 'TOI-5205 b', 'TOI-532 b', 'TOI-564 b', 'TOI-620 b', 'TOI-969 b', 'TRAPPIST-1 b', 'TRAPPIST-1 c', 'TrES-1 b', 'TrES-2 b', 'TrES-3 b', 'TrES-4 b', 'TrES-5 b', 'WASP-103 b', 'WASP-104 b', 'WASP-107 b', 'WASP-10 b', 'WASP-113 b', 'WASP-114 b', 'WASP-118 b', 'WASP-11 b', 'WASP-127 b', 'WASP-129 b', 'WASP-12 b', 'WASP-135 b', 'WASP-138 b', 'WASP-13 b', 'WASP-140 b', 'WASP-148 b', 'WASP-14 b', 'WASP-150 b', 'WASP-153 b', 'WASP-156 b', 'WASP-157 b', 'WASP-160 B b', 'WASP-163 b', 'WASP-164 b', 'WASP-169 b', 'WASP-16 b', 'WASP-170 b', 'WASP-176 b', 'WASP-177 b', 'WASP-180 A b', 'WASP-181 b', 'WASP-183 b', 'WASP-192 b', 'WASP-19 b', 'WASP-1 b', 'WASP-21 b', 'WASP-23 b', 'WASP-24 b', 'WASP-25 b', 'WASP-26 b', 'WASP-28 b', 'WASP-29 b', 'WASP-2 b', 'WASP-31 b', 'WASP-32 b', 'WASP-33 b', 'WASP-34 b', 'WASP-35 b', 'WASP-36 b', 'WASP-39 b', 'WASP-3 b', 'WASP-41 b', 'WASP-43 b', 'WASP-47 b', 'WASP-48 b', 'WASP-49 b', 'WASP-4 b', 'WASP-50 b', 'WASP-52 b', 'WASP-53 b', 'WASP-54 b', 'WASP-55 b', 'WASP-56 b', 'WASP-57 b', 'WASP-58 b', 'WASP-59 b', 'WASP-5 b', 'WASP-60 b', 'WASP-64 b', 'WASP-65 b', 'WASP-67 b', 'WASP-69 b', 'WASP-6 b', 'WASP-74 b', 'WASP-75 b', 'WASP-77 A b', 'WASP-80 b', 'WASP-82 b', 'WASP-84 b', 'WASP-85 A b', 'WASP-89 b', 'WASP-92 b', 'WASP-93 b', 'WASP-96 b', 'WASP-98 b', 'Wendelstein-2 b', 'WTS-2 b', 'XO-1 b', 'XO-2 N b', 'XO-3 b', 'XO-4 b', 'XO-5 b', 'XO-6 b', 'XO-7 b']\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "dict_keys(['raw_result', 'host', 'name', 'priors', 'timestamp', 'identifier', 'reduction_count', 'observation_count', 'ephemeris', 'observations'])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "from copy import deepcopy\n",
    "from exotic.api.ew import ExoplanetWatch, translate_keys\n",
    "from IPython.display import display, Image\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "\n",
    "# This will load the results JSON from the link above\n",
    "EW = ExoplanetWatch()\n",
    "print(EW.target_list)\n",
    "\n",
    "# names are case and space sensitive\n",
    "target ='WASP-77 A b'\n",
    "result = EW.get(target)\n",
    "\n",
    "# directory to save outputs to\n",
    "output_dir = target.replace(\" \",\"_\").replace(\"-\",\"_\")\n",
    "\n",
    "# make the directory if it doesn't exist\n",
    "if not os.path.exists(output_dir):\n",
    "    os.mkdir(output_dir)\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": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'R*': {'units': 'Sol',\n",
       "  'value': '0.95',\n",
       "  'reference': 'Kokori%20et%20al.%202022',\n",
       "  'uncertainty': '0.01'},\n",
       " 'RA': {'units': 'decimal',\n",
       "  'value': '37.1555223',\n",
       "  'reference': None,\n",
       "  'uncertainty': None},\n",
       " 'Rp': {'units': 'R_Earth',\n",
       "  'value': '13.79',\n",
       "  'reference': 'Cort&eacute;s-Zuleta%20et%20al.%202020',\n",
       "  'uncertainty': '0.35'},\n",
       " 'T*': {'units': 'K',\n",
       "  'value': '5500.0',\n",
       "  'reference': 'Kokori%20et%20al.%202022',\n",
       "  'uncertainty': '80.0'},\n",
       " 'Tc': {'units': 'BJD-TDB',\n",
       "  'value': '2457658.8889',\n",
       "  'reference': 'Ivshina%20&amp;%20Winn%202022',\n",
       "  'uncertainty': '0.00014'},\n",
       " 'DEC': {'units': 'decimal',\n",
       "  'value': '-7.0606675',\n",
       "  'reference': None,\n",
       "  'uncertainty': None},\n",
       " 'Tcs': [{'units': 'BJD, BJD-TDB',\n",
       "   'value': '2455870.4500266667',\n",
       "   'reference': 'Bonomo%20et%20al.%202017,%20Turner%20et%20al.%202016,%20Maxted%20et%20al.%202013',\n",
       "   'uncertainty': '0.00014'},\n",
       "  {'units': 'BJD-TDB',\n",
       "   'value': '2456663.34757',\n",
       "   'reference': 'Kokori%20et%20al.%202022',\n",
       "   'uncertainty': '0.00012'},\n",
       "  {'units': 'BJD-TDB',\n",
       "   'value': '2457420.88439',\n",
       "   'reference': 'Cort&eacute;s-Zuleta%20et%20al.%202020',\n",
       "   'uncertainty': '0.0008'},\n",
       "  {'units': 'BJD-TDB',\n",
       "   'value': '2457658.8889',\n",
       "   'reference': 'Ivshina%20&amp;%20Winn%202022',\n",
       "   'uncertainty': '0.00014'},\n",
       "  {'units': 'BJD',\n",
       "   'value': '2459168.520849',\n",
       "   'reference': 'ExoFOP-TESS%20TOI',\n",
       "   'uncertainty': '5.6e-05'}],\n",
       " 'ecc': {'units': None,\n",
       "  'value': '0.0074',\n",
       "  'reference': 'Cort&eacute;s-Zuleta%20et%20al.%202020',\n",
       "  'uncertainty': '0.0069'},\n",
       " 'inc': {'units': 'deg',\n",
       "  'value': '88.91',\n",
       "  'reference': 'Cort&eacute;s-Zuleta%20et%20al.%202020',\n",
       "  'uncertainty': '0.74'},\n",
       " 'FE/H': {'units': None,\n",
       "  'value': '0.0',\n",
       "  'reference': 'Kokori%20et%20al.%202022',\n",
       "  'uncertainty': '0.11'},\n",
       " 'LOGG': {'units': 'Log10(cgs)',\n",
       "  'value': '4.33',\n",
       "  'reference': 'Kokori%20et%20al.%202022',\n",
       "  'uncertainty': '0.08'},\n",
       " 'a/R*': {'units': None,\n",
       "  'value': '5.332',\n",
       "  'reference': 'Cort&eacute;s-Zuleta%20et%20al.%202020',\n",
       "  'uncertainty': '0.057'},\n",
       " 'Rp/R*': {'units': None,\n",
       "  'value': '0.1335',\n",
       "  'reference': 'Cort&eacute;s-Zuleta%20et%20al.%202020',\n",
       "  'uncertainty': '0'},\n",
       " 'omega': {'units': 'deg',\n",
       "  'value': '-166.0',\n",
       "  'reference': 'Cort&eacute;s-Zuleta%20et%20al.%202020',\n",
       "  'uncertainty': '66.0'},\n",
       " 'Period': {'units': 'day',\n",
       "  'value': '1.36002869',\n",
       "  'reference': 'Ivshina%20&amp;%20Winn%202022',\n",
       "  'uncertainty': '1.6e-07'}}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.priors"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# translate json to exotic compatible format\n",
    "transit_priors = {\n",
    "    'ecc': float(result.priors['ecc']['value']),\n",
    "    'inc': float(result.priors['inc']['value']),\n",
    "    'omega': float(result.priors['omega']['value']),\n",
    "    'tmid': float(result.priors['Tc']['value']),\n",
    "    'a1': 1, 'a2': 0, # airmass: a1 * exp(a2 * sec(z))\n",
    "    'ars': float(result.priors['a/R*']['value']),\n",
    "    'rprs': float(result.priors['Rp/R*']['value']),\n",
    "    'per': float(result.priors['Period']['value']),\n",
    "    # u0,u1,u2,u3 - non-linear limb darkening added later\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Observations\n",
    "A list of observations for each target. These are used to fit the light curve model to the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "50"
      ]
     },
     "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": "markdown",
   "metadata": {},
   "source": [
    "# Download the light curve data + plot best fit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Downloading __databases__.pickle_new...\n",
      "    Done!\n",
      "Checking exotethys database...\n",
      "Checking ephemerides database...\n",
      "Checking photometry database...\n",
      "Checking catalogues database...\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Text(0, 0.5, 'Rel. Flux')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 33920 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# let's over plot the transit model too\n",
    "from exotic.api.elca import transit\n",
    "\n",
    "time, flux, fluxerr, airmass, airmasscorr = result.observations[0].get_data()\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": "markdown",
   "metadata": {},
   "source": [
    "## Fit a single lightcurve using EXOTIC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "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": "5142cb49ed4e4d96ac8daeed27cc90fc",
       "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   [-34.8862..-34.8858]*| it/evals=6240/14899 eff=43.0375% N=400   0 0  0  \n",
      "[ultranest] Likelihood function evaluations: 14978\n",
      "[ultranest]   logZ = -45.92 +- 0.0809\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1958.4, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.08, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.08 tail:0.01 total:0.08 required:<0.50\n",
      "[ultranest] done iterating.\n"
     ]
    }
   ],
   "source": [
    "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.ephemeris['Tc']-0.02,\n",
    "             result.ephemeris['Tc']+0.02],\n",
    "    'inc':[ result.observations[0].parameters['inc']-3, \n",
    "            min(90,result.observations[0].parameters['inc']+3)],\n",
    "    'a2':[-0.5,0.5] # airmass curvature\n",
    "}\n",
    "\n",
    "# add limb darkening priors or generate them from a model (e.g. exotethys)\n",
    "transit_priors['u0'] = result.observations[0].parameters['u0']\n",
    "transit_priors['u1'] = result.observations[0].parameters['u1']\n",
    "transit_priors['u2'] = result.observations[0].parameters['u2']\n",
    "transit_priors['u3'] = result.observations[0].parameters['u3']\n",
    "\n",
    "# fit the light curve\n",
    "myfit = lc_fitter(time, flux, fluxerr, airmass, deepcopy(transit_priors), mybounds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 66760 characters]",
      "text/plain": [
       "<Figure size 900x600 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "myfit.plot_bestfit()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 491296 characters]",
      "text/plain": [
       "<Figure size 970x970 with 16 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# show the posterior distributions\n",
    "myfit.plot_triangle()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Fit multiple light curves\n",
    "\n",
    "We're going to optimize the multi-lightcurve fit by first fitting the lightcurves individually to remove airmass variations and then we'll perform a joint simultaneous fit called \"global\" fit, which has shared parameters like Rp/Rs, Inclination, Tmid and Period across all the light curves."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from astropy.time import Time\n",
    "from copy import deepcopy\n",
    "from exotic.api.elca import glc_fitter\n",
    "\n",
    "# prep data for global fitter\n",
    "input_data = []\n",
    "\n",
    "# free parameters for each light curve\n",
    "local_bounds = []"
   ]
  },
  {
   "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": "0664d4a7103d4187ae599f07ebb6ef24",
       "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   [-34.8710..-34.8707]*| it/evals=6920/17480 eff=40.5152% N=400        0  \n",
      "[ultranest] Likelihood function evaluations: 17513\n",
      "[ultranest]   logZ = -47.56 +- 0.1522\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1936.7, 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.15, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.17 bs:0.15 tail:0.01 total:0.15 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "Skipping FMAA due to high scatter\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6ffbc5ad29ad4275a0211f8da684e972",
       "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=-4e+01   [-41.3758..-41.3756]*| it/evals=3640/16577 eff=22.5011% N=400 \n",
      "[ultranest] Likelihood function evaluations: 16814\n",
      "[ultranest]   logZ = -45.89 +- 0.05972\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1462.9, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.06, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.09 bs:0.06 tail:0.01 total:0.06 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "Skipping FMAA due to large residuals\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "dedc49721bf74a3b9dd09e3f3133a718",
       "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   [-31.8273..-31.8270]*| it/evals=5920/16611 eff=36.5184% N=400       \n",
      "[ultranest] Likelihood function evaluations: 16629\n",
      "[ultranest]   logZ = -41.97 +- 0.1077\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2057.1, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "Skipping FMAA due to high scatter\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5cf8a54b1b2b42aeb9a0a5ee1eee6a36",
       "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=-4e+01   [-37.7336..-37.7335]*| it/evals=5720/20357 eff=28.6616% N=400     \n",
      "[ultranest] Likelihood function evaluations: 20414\n",
      "[ultranest]   logZ = -47.39 +- 0.1135\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2247.3, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.47+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.14 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "FMAA 1 : 2020-10-24T04:15:46.520 (-0.0601) - 2020-10-24T08:24:37.407 (0.0670)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "af0ed598da474c7c941f053c09b779c7",
       "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=-4e+01   [-36.5799..-36.5789]*| it/evals=6400/19218 eff=34.0100% N=400     \n",
      "[ultranest] Likelihood function evaluations: 19347\n",
      "[ultranest]   logZ = -47.98 +- 0.1128\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2459.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "FMAA 2 : 2020-10-28T06:10:06.251 (-0.0587) - 2020-10-28T10:26:06.868 (0.0720)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f82395087c0d477d9314aba96b10964c",
       "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=-2e+01   [-19.2639..-19.2638]*| it/evals=5280/15971 eff=33.9092% N=400  \n",
      "[ultranest] Likelihood function evaluations: 15996\n",
      "[ultranest]   logZ = -27.82 +- 0.09947\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2245.1, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.07 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.10, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.13 bs:0.10 tail:0.01 total:0.10 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "BTSB 3 : 2021-09-18T07:29:03.908 (-0.0528) - 2021-09-18T11:53:05.427 (0.0820)\n",
      "Failed to fit KADB\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:301: RuntimeWarning: divide by zero encountered in divide\n",
      "  detrend = self.data / model  # used to estimate a1\n",
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:302: RuntimeWarning: invalid value encountered in multiply\n",
      "  model *= np.median(detrend)\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b3616c4ec0c04f82a489ee0a68198e6e",
       "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+02  .68 [-291.8408..-291.8407]*| it/evals=7880/21534 eff=37.2859% N=400   0  \n",
      "[ultranest] Likelihood function evaluations: 21619\n",
      "[ultranest]   logZ = -306.9 +- 0.09976\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2102.6, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.10, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.18 bs:0.10 tail:0.01 total:0.10 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "KADB 4 : 2021-11-06T06:36:32.314 (-0.0559) - 2021-11-06T10:32:41.654 (0.0646)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "bdcf8a66ec1040bca2bfe0bd74e18170",
       "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=-2e+02  .21 [-192.3495..-192.3495]*| it/evals=7720/20761 eff=37.9156% N=400   00  \n",
      "[ultranest] Likelihood function evaluations: 20762\n",
      "[ultranest]   logZ = -207 +- 0.1353\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2110.3, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.14, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.18 bs:0.14 tail:0.01 total:0.14 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "KADB 5 : 2021-11-28T01:21:27.994 (-0.0416) - 2021-11-28T04:44:29.789 (0.0620)\n",
      "Failed to fit KADB\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:301: RuntimeWarning: divide by zero encountered in divide\n",
      "  detrend = self.data / model  # used to estimate a1\n",
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:301: RuntimeWarning: overflow encountered in divide\n",
      "  detrend = self.data / model  # used to estimate a1\n",
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:300: RuntimeWarning: overflow encountered in exp\n",
      "  model *= np.exp(self.prior['a2'] * self.airmass)\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ab53c89a6b6b4d23a47ea1eac463a15a",
       "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=-8  01 [-8.0829..-8.0827]*| it/evals=4200/11725 eff=37.0861% N=400 0  \n",
      "[ultranest] Likelihood function evaluations: 11786\n",
      "[ultranest]   logZ = -14 +- 0.07175\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2235.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.08 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.07, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.10 bs:0.07 tail:0.01 total:0.07 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "Skipping GSAD due to null transit detection\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0c3728c3594f46e9be0dca1710ccf41b",
       "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=-1e+02  .84 [-126.9715..-126.9714]*| it/evals=6160/20901 eff=30.0473% N=400  \n",
      "[ultranest] Likelihood function evaluations: 21086\n",
      "[ultranest]   logZ = -137.8 +- 0.1124\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1920.4, 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.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "KADB 6 : 2021-12-17T01:39:51.322 (-0.0544) - 2021-12-17T05:41:45.398 (0.0692)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "30fd5233b87249878483ab9ed50df3d0",
       "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=-4e+02  .42 [-375.7441..-375.7440]*| it/evals=9560/30693 eff=31.5584% N=400 0 0  \n",
      "[ultranest] Likelihood function evaluations: 30775\n",
      "[ultranest]   logZ = -395 +- 0.1722\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2351.3, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.17, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.21 bs:0.17 tail:0.01 total:0.17 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "KADB 7 : 2022-01-05T02:33:41.386 (-0.0631) - 2022-01-05T06:45:40.781 (0.0655)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "4f0c60c114df4170b52216b1bc38707f",
       "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=-7e+01   [-71.8492..-71.8483]*| it/evals=6400/22487 eff=28.9763% N=400   0 0  \n",
      "[ultranest] Likelihood function evaluations: 22496\n",
      "[ultranest]   logZ = -83.11 +- 0.09062\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2344.8, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.09 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.09, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.09 tail:0.01 total:0.09 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "FMAA 8 : 2022-01-05T02:34:20.222 (-0.0538) - 2022-01-05T06:46:08.826 (0.0747)\n",
      "Failed to fit KADB\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:300: RuntimeWarning: overflow encountered in exp\n",
      "  model *= np.exp(self.prior['a2'] * self.airmass)\n",
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:302: RuntimeWarning: invalid value encountered in multiply\n",
      "  model *= np.median(detrend)\n",
      "/Users/kpearson/Programs/exoplanets/EXOTIC/exotic/api/elca.py:301: RuntimeWarning: divide by zero encountered in divide\n",
      "  detrend = self.data / model  # used to estimate a1\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ad8624a47d014fa5a857045b469e338f",
       "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   [-30.7768..-30.7767]*| it/evals=3120/10031 eff=32.3954% N=400 \n",
      "[ultranest] Likelihood function evaluations: 10111\n",
      "[ultranest]   logZ = -33.97 +- 0.04338\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1931.3, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.08 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.04, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.06 bs:0.04 tail:0.01 total:0.04 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "Skipping DJEI due to large residuals\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fad726d2590e4014a2da9af77174d7ce",
       "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   [-31.8539..-31.8534]*| it/evals=4360/13179 eff=34.1185% N=400  0 \n",
      "[ultranest] Likelihood function evaluations: 13312\n",
      "[ultranest]   logZ = -38.11 +- 0.08043\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1878.5, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.08, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.11 bs:0.08 tail:0.01 total:0.08 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "Skipping OAS due to large residuals\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6b108162d9064672a806ec2a092bbd6b",
       "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=-1e+02  .79 [-116.9384..-116.9383]*| it/evals=6040/21396 eff=28.7674% N=400 \n",
      "[ultranest] Likelihood function evaluations: 21455\n",
      "[ultranest]   logZ = -127.5 +- 0.1049\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2250.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.47+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.10 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "Skipping DLMA due to large residuals\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d33d95cafdc6444c90dd28c068c3c33a",
       "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=-2e+02  .61 [-164.7802..-164.7801]*| it/evals=6300/20051 eff=32.0594% N=400  \n",
      "[ultranest] Likelihood function evaluations: 20151\n",
      "[ultranest]   logZ = -175.9 +- 0.1088\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1929.9, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.07 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "PJAE 9 : 2022-11-26T03:31:56.152 (-0.0670) - 2022-11-26T07:58:33.875 (0.0691)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "99ea02d693df4b32aeca6f7cc53228c5",
       "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=-5e+02  .42 [-539.7560..-539.7559]*| it/evals=9200/35563 eff=26.1639% N=400    0  0 \n",
      "[ultranest] Likelihood function evaluations: 35720\n",
      "[ultranest]   logZ = -558.1 +- 0.1939\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2065.9, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.19, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.20 bs:0.19 tail:0.01 total:0.19 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "SAJB 10 : 2023-01-12T18:05:56.918 (-0.0615) - 2023-01-12T22:05:59.021 (0.0611)\n"
     ]
    }
   ],
   "source": [
    "# fit the individual light curves from Exoplanet Watch and detrend airmass extinction\n",
    "for n,obs in enumerate(result.observations):\n",
    "\n",
    "    try:\n",
    "        time, flux, fluxerr, airmass, airmasscorr = obs.get_data()\n",
    "    except:\n",
    "        data = obs.get_data()\n",
    "        time, flux, fluxerr, airmass = data[:,0], data[:,1], data[:,2], data[:,3]\n",
    "\n",
    "    # add limb darkening priors or generate them from a model (e.g. exotethys)\n",
    "    transit_priors['u0'] = result.observations[n].parameters['u0']\n",
    "    transit_priors['u1'] = result.observations[n].parameters['u1']\n",
    "    transit_priors['u2'] = result.observations[n].parameters['u2']\n",
    "    transit_priors['u3'] = result.observations[n].parameters['u3']\n",
    "    prior = deepcopy(transit_priors)\n",
    "\n",
    "    # compute tmid closest to observations\n",
    "    tmid = prior['tmid']\n",
    "    per = prior['per']\n",
    "    obs_time = 0.5*(time.min() + time.max())\n",
    "    obs_tmid = tmid + per*np.round((obs_time - tmid)/per)\n",
    "\n",
    "    # mask out nans and 0 errors\n",
    "    mask = np.isnan(flux) | (fluxerr <= 0) | np.isnan(fluxerr) | (airmass <= 1)\n",
    "    \n",
    "    if mask.sum() == len(flux):\n",
    "        continue\n",
    "\n",
    "    time = time[~mask]\n",
    "    flux = flux[~mask]\n",
    "    fluxerr = fluxerr[~mask]\n",
    "    airmass = airmass[~mask]\n",
    "\n",
    "    # only define bounds for the \"free\" parameters during fitting\n",
    "    mybounds = {\n",
    "        # [lower, upper]\n",
    "        'rprs':[0, prior['rprs']*2],\n",
    "        'tmid':[ obs_tmid-0.05,\n",
    "                 obs_tmid+0.05],\n",
    "        'inc':[ prior['inc']-3, min(90,prior['inc']+3)],\n",
    "        'a2':[-0.5,0.5] # airmass curvature\n",
    "    }\n",
    "\n",
    "    try:\n",
    "        # fit the light curve\n",
    "        myfit = lc_fitter(time, flux, fluxerr, airmass, prior, mybounds) \n",
    "    except:\n",
    "        print(f\"Failed to fit {obs.obscode['id']}\")\n",
    "        continue\n",
    "\n",
    "    rprs2 = myfit.parameters['rprs']**2\n",
    "    rprs2err = myfit.errors['rprs']*2*myfit.parameters['rprs']\n",
    "\n",
    "    # residuals must be smaller than transit depth\n",
    "    if myfit.res_stdev > prior['rprs']**2:\n",
    "        print(f\"Skipping {obs.obscode['id']} due to large residuals\")\n",
    "        continue\n",
    "    elif rprs2-3*rprs2err < 0: # 3 sigma clip\n",
    "        print(f\"Skipping {obs.obscode['id']} due to null transit detection\")\n",
    "    elif np.std(flux) > 0.03:  # ignore noisy data\n",
    "        print(f\"Skipping {obs.obscode['id']} due to high scatter\")\n",
    "        continue\n",
    "    else:\n",
    "        #prior = deepcopy(result.observations[n].parameters)\n",
    "\n",
    "        # add data to list\n",
    "        input_data.append({\n",
    "            'time':time,\n",
    "            'flux':myfit.detrended,\n",
    "            'ferr':myfit.detrendederr,\n",
    "            'airmass':np.zeros_like(time),\n",
    "            'priors':prior,\n",
    "            'name':f\"{obs.obscode['id']}\",\n",
    "\n",
    "            # save individual fit parameters\n",
    "            'parameters':myfit.parameters,\n",
    "            'errors':myfit.errors,\n",
    "            'res_std':myfit.res_stdev\n",
    "        })\n",
    "\n",
    "        # add parameter for individual airmass detrending\n",
    "        local_bounds.append({}) \n",
    "\n",
    "        # print some timing info\n",
    "        mint = Time(input_data[-1]['time'].min(),format='jd').isot\n",
    "        maxt = Time(input_data[-1]['time'].max(),format='jd').isot\n",
    "        maxphase = (input_data[-1]['time'].max() - prior['tmid'])/prior['per']\n",
    "        minphase = (input_data[-1]['time'].min() - prior['tmid'])/prior['per']\n",
    "        print(f\"{input_data[-1]['name']} {len(input_data)} : {mint} ({minphase:.4f}) - {maxt} ({maxphase:.4f})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run the next block of code only if you want to add TESS data to the global fit\n",
    "\n",
    "\n",
    "In order to make lightcurves from TESS please inspect the file `tess.py` in the `examples/` directory. You will need to set up a new environment and then run the script based on instructions at the top of the file. Once you have the lightcurves, you can run the next block of code to add them to the global fit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 19 TESS light curves\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "917ef6a1920d40b0925c6517d6317142",
       "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   [-31.5109..-31.5109]*| it/evals=6040/12097 eff=51.6372% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 12125\n",
      "[ultranest]   logZ = -42.03 +- 0.1262\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1723.1, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.13, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.13 tail:0.01 total:0.13 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 11 : 2018-10-20T16:25:32.462 (-0.1179) - 2018-10-21T00:07:32.695 (0.1180)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9fa348ad3e9f45bfa577bdb2ef72dacc",
       "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   [-25.3255..-25.3253]*| it/evals=6040/11613 eff=53.8660% N=400    0 0 \n",
      "[ultranest] Likelihood function evaluations: 11618\n",
      "[ultranest]   logZ = -35.78 +- 0.111\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1710.7, 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.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 12 : 2018-11-03T06:51:27.594 (-0.1172) - 2018-11-03T14:31:27.225 (0.1177)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ae977785d2494fdbbb69af5a35c82d59",
       "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=-7e+02  .50 [-652.6683..-652.6682]*| it/evals=7264/15683 eff=47.5299% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 15701\n",
      "[ultranest]   logZ = -666.2 +- 0.152\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1908.3, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.09 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.15, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.17 bs:0.15 tail:0.01 total:0.15 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 13 : 2020-10-25T11:02:14.184 (-0.1180) - 2020-10-25T18:44:14.121 (0.1179)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "70d07d1e5445419ebfa873a665bbd179",
       "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=-2e+01   [-22.6958..-22.6957]*| it/evals=6160/11217 eff=56.9474% N=400        \n",
      "[ultranest] Likelihood function evaluations: 11226\n",
      "[ultranest]   logZ = -33.5 +- 0.1361\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1866.6, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.14, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.14 tail:0.01 total:0.14 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 14 : 2018-11-06T00:07:23.679 (-0.1174) - 2018-11-06T07:47:23.118 (0.1175)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e687348cc7e046cf87c6a0a6fce9497b",
       "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=-2e+01   [-24.9287..-24.9287]*| it/evals=6080/11601 eff=54.2809% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 11623\n",
      "[ultranest]   logZ = -35.54 +- 0.1007\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1808.3, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.10, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.10 tail:0.01 total:0.10 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 15 : 2018-11-11T10:41:11.726 (-0.1176) - 2018-11-11T18:21:10.880 (0.1173)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a7d739de24d84d11ba7f70ae1791de6d",
       "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=-7e+02  .08 [-671.2991..-671.2988]*| it/evals=7320/17437 eff=42.9653% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 17474\n",
      "[ultranest]   logZ = -684.9 +- 0.1265\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1990.8, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.47+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.13, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.17 bs:0.13 tail:0.01 total:0.13 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 16 : 2020-10-26T19:40:33.776 (-0.1180) - 2020-10-27T03:22:33.629 (0.1179)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "7dedba0ccb10483296eaa870edffa69c",
       "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   [-25.5443..-25.5442]*| it/evals=6240/11709 eff=55.1773% N=400      0 \n",
      "[ultranest] Likelihood function evaluations: 11752\n",
      "[ultranest]   logZ = -36.62 +- 0.1123\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2004.6, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.07 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 17 : 2018-11-08T17:25:18.311 (-0.1169) - 2018-11-09T01:05:17.598 (0.1180)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fe84b162e2064e1cbff755506f18645c",
       "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=-7e+02  .76 [-659.8441..-659.8441]*| it/evals=7120/13509 eff=54.3138% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 13586\n",
      "[ultranest]   logZ = -673.1 +- 0.1359\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1915.6, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.14, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.17 bs:0.14 tail:0.01 total:0.14 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 18 : 2020-10-24T02:23:54.206 (-0.1179) - 2020-10-24T10:05:54.239 (0.1180)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c165e73beb1a4f0db281b85fea8cb08c",
       "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=-2e+01   [-24.6140..-24.6139]*| it/evals=6120/11711 eff=54.1066% N=400    0 0 \n",
      "[ultranest] Likelihood function evaluations: 11774\n",
      "[ultranest]   logZ = -35.38 +- 0.1069\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1890.9, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.09 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 19 : 2018-11-12T19:19:08.037 (-0.1179) - 2018-11-13T03:01:07.137 (0.1180)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "71f9de992de740849d82a7ced3aa6b31",
       "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   [-26.2099..-26.2098]*| it/evals=6080/11724 eff=53.6913% N=400       \n",
      "[ultranest] Likelihood function evaluations: 11780\n",
      "[ultranest]   logZ = -36.82 +- 0.141\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1750.4, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.14, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.14 tail:0.01 total:0.14 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 20 : 2018-11-04T15:29:25.843 (-0.1174) - 2018-11-04T23:09:25.369 (0.1175)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "32ea6088fa0b46ada080aaf83a2ca529",
       "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=-2e+01   [-20.7671..-20.7669]*| it/evals=6160/11443 eff=55.7819% N=400       \n",
      "[ultranest] Likelihood function evaluations: 11494\n",
      "[ultranest]   logZ = -31.59 +- 0.114\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1958.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.47+-0.08 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.11, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.11 tail:0.01 total:0.11 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 21 : 2018-10-22T01:05:33.268 (-0.1173) - 2018-10-22T08:45:33.394 (0.1176)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "60ec37fde1c04e62b1978d0533d29b21",
       "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   [-27.0351..-27.0351]*| it/evals=6210/11704 eff=54.9363% N=400       \n",
      "[ultranest] Likelihood function evaluations: 11761\n",
      "[ultranest]   logZ = -37.96 +- 0.1031\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1985.9, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.10, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.10 tail:0.01 total:0.10 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 22 : 2018-10-23T09:43:33.660 (-0.1173) - 2018-10-23T17:23:33.700 (0.1176)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "96071a31686c4e77aca63ac43f8432e9",
       "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   [-25.9712..-25.9708]*| it/evals=6040/11614 eff=53.8612% N=400       \n",
      "[ultranest] Likelihood function evaluations: 11671\n",
      "[ultranest]   logZ = -36.44 +- 0.1038\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1944.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.10, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.10 tail:0.01 total:0.10 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 23 : 2018-11-10T02:03:15.162 (-0.1175) - 2018-11-10T09:43:14.379 (0.1174)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "35f7570ab8074a1fb33f04eff8963714",
       "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=-7e+02  .10 [-680.1586..-680.1585]*| it/evals=7240/13135 eff=56.8512% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 13193\n",
      "[ultranest]   logZ = -693.7 +- 0.1316\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1920.5, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.06 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.13, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.17 bs:0.13 tail:0.01 total:0.13 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 24 : 2020-10-28T04:19:13.024 (-0.1177) - 2020-10-28T12:01:12.799 (0.1182)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "dd4e1d25071241849f0e12ff774989f3",
       "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=-7e+02  .08 [-675.2161..-675.2161]*| it/evals=7231/14131 eff=52.6619% N=400   0    \n",
      "[ultranest] Likelihood function evaluations: 14144\n",
      "[ultranest]   logZ = -688.7 +- 0.12\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1936.8, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.47+-0.08 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.12, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.17 bs:0.12 tail:0.01 total:0.12 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 25 : 2020-10-22T17:45:13.750 (-0.1179) - 2020-10-23T01:27:13.910 (0.1180)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6d35c1997cce4a279a22285d0ff7eaa8",
       "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=-2e+01   [-23.7460..-23.7459]*| it/evals=6120/11437 eff=55.4499% N=400    0  \n",
      "[ultranest] Likelihood function evaluations: 11476\n",
      "[ultranest]   logZ = -34.52 +- 0.1021\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1919.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.45+-0.05 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.10, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.10 tail:0.01 total:0.10 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 26 : 2018-10-26T02:59:33.409 (-0.1178) - 2018-10-26T10:39:33.296 (0.1171)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "961598dac3c3478ab9304906530ce4e0",
       "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=-7e+02  .46 [-747.7095..-747.7094]*| it/evals=6960/15404 eff=46.3876% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 15483\n",
      "[ultranest]   logZ = -760.4 +- 0.1172\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1922.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.08 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.12, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.17 bs:0.12 tail:0.01 total:0.12 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 27 : 2020-10-29T12:57:51.950 (-0.1179) - 2020-10-29T20:39:31.653 (0.1178)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "467f8c37e00a4a119b94342689071364",
       "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   [-27.0526..-27.0525]*| it/evals=6160/12482 eff=50.9849% N=400   0   \n",
      "[ultranest] Likelihood function evaluations: 12482\n",
      "[ultranest]   logZ = -37.8 +- 0.1033\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1910.7, 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.10, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.10 tail:0.01 total:0.10 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 28 : 2018-11-07T08:45:21.159 (-0.1178) - 2018-11-07T16:27:20.516 (0.1181)\n",
      "[ultranest] Sampling 400 live points from prior ...\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1cb3af07048b470387510b5f4882aa6d",
       "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=-2e+01   [-21.5162..-21.5160]*| it/evals=6240/11583 eff=55.7990% N=400       \n",
      "[ultranest] Likelihood function evaluations: 11590\n",
      "[ultranest]   logZ = -32.45 +- 0.1479\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 1897.2, need >400)\n",
      "[ultranest] Posterior uncertainty strategy is satisfied (KL: 0.47+-0.08 nat, need <0.50 nat)\n",
      "[ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.15, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.15 bs:0.15 tail:0.01 total:0.15 required:<0.50\n",
      "[ultranest] done iterating.\n",
      "TESS 29 : 2018-10-24T18:21:33.697 (-0.1176) - 2018-10-25T02:01:33.657 (0.1173)\n"
     ]
    }
   ],
   "source": [
    "import glob\n",
    "from pylightcurve import exotethys\n",
    "\n",
    "# generate limb darkening coefficients for TESS\n",
    "get_prior = lambda key: float(result.priors[key]['value'])\n",
    "u0,u1,u2,u3 = exotethys(get_prior('LOGG'), get_prior('T*'), get_prior('FE/H'), 'TESS', method='claret', stellar_model='phoenix')\n",
    "\n",
    "# get files from local directory\n",
    "tess_lightcurves = glob.glob(f\"output/{target.replace(' ','_').replace('-','_')}/*_AAVSO.txt\")\n",
    "print(f\"Found {len(tess_lightcurves)} TESS light curves\")\n",
    "\n",
    "# add TESS data\n",
    "for n,lc in enumerate(tess_lightcurves):\n",
    "\n",
    "    # read in data\n",
    "    time, flux, fluxerr, airmass, airmasscorr = np.loadtxt(lc, unpack=True, delimiter=',')\n",
    "    prior = deepcopy(transit_priors)\n",
    "    prior['u0'] = u0\n",
    "    prior['u1'] = u1\n",
    "    prior['u2'] = u2\n",
    "    prior['u3'] = u3\n",
    "    prior['tmid'] = result.ephemeris['Tc']\n",
    "    prior['per'] = result.ephemeris['Period']\n",
    "    prior['a2'] = 0.0 # no airmass correction for TESS\n",
    "\n",
    "    # compute tmid closest to observations\n",
    "    tmid = prior['tmid']\n",
    "    per = prior['per']\n",
    "    obs_time = 0.5*(time.min() + time.max())\n",
    "    obs_tmid = tmid + per*np.round((obs_time - tmid)/per)\n",
    "\n",
    "    # only define bounds for the \"free\" parameters during fitting\n",
    "    mybounds = {\n",
    "        # [lower, upper]\n",
    "        'rprs':[0, prior['rprs']*2],\n",
    "        'tmid':[ obs_tmid-0.05,\n",
    "                 obs_tmid+0.05],\n",
    "        'inc':[ prior['inc']-5, min(90,prior['inc']+5)]\n",
    "    }\n",
    "\n",
    "    try:\n",
    "        myfit = lc_fitter(time, flux, fluxerr, airmass, prior, mybounds) \n",
    "    except:\n",
    "        print(f\"Failed to fit {obs.obscode['id']}\")\n",
    "        continue\n",
    "    \n",
    "    # add data to list\n",
    "    input_data.append({\n",
    "        'time':time,\n",
    "        'flux':flux,\n",
    "        'ferr':fluxerr,\n",
    "        'airmass':np.zeros(time.shape),\n",
    "        'priors':prior,\n",
    "        'name':f\"TESS\",\n",
    "\n",
    "        # save individual fit parameters\n",
    "        'parameters':myfit.parameters,\n",
    "        'errors':myfit.errors,\n",
    "        'res_std':myfit.res_stdev\n",
    "    })\n",
    "\n",
    "    # no airmass detrending\n",
    "    local_bounds.append({})\n",
    "\n",
    "    # print some timing info\n",
    "    mint = Time(input_data[-1]['time'].min(),format='jd').isot\n",
    "    maxt = Time(input_data[-1]['time'].max(),format='jd').isot\n",
    "    maxphase = (input_data[-1]['time'].max() - prior['tmid'])/prior['per']\n",
    "    minphase = (input_data[-1]['time'].min() - prior['tmid'])/prior['per']\n",
    "    print(f\"{input_data[-1]['name']} {len(input_data)} : {mint} ({minphase:.4f}) - {maxt} ({maxphase:.4f})\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ecc': 0.0074,\n",
       " 'inc': 87.713010716479,\n",
       " 'omega': -166.0,\n",
       " 'tmid': 2458416.424893059,\n",
       " 'a1': 1,\n",
       " 'a2': 0.0,\n",
       " 'ars': 5.332,\n",
       " 'rprs': 0.11810311272220649,\n",
       " 'per': 1.3600290306112939,\n",
       " 'u0': 0.5007438874039994,\n",
       " 'u1': -0.08351946282301767,\n",
       " 'u2': 0.4675323137274613,\n",
       " 'u3': -0.2166556367766898}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prior"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ecc': 0.0074,\n",
       " 'inc': 86.07999373157074,\n",
       " 'omega': -166.0,\n",
       " 'tmid': 2459146.759302781,\n",
       " 'a1': 1,\n",
       " 'a2': -0.0027830397249283267,\n",
       " 'ars': 5.332,\n",
       " 'rprs': 0.1343620266815629,\n",
       " 'per': 1.36002869,\n",
       " 'u0': 1.9620417119554874,\n",
       " 'u1': -3.53068378927721,\n",
       " 'u2': 4.032966684059403,\n",
       " 'u3': -1.4643245466417936}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "input_data[0]['priors']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "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": "fa38512fed5c41d38f3af38a19501a46",
       "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=-7e+03  740.55 [-6740.6776..-6740.6775]*| it/evals=10798/27291 eff=40.1547% N=400    \n",
      "[ultranest] Likelihood function evaluations: 27293\n",
      "[ultranest]   logZ = -6763 +- 0.1661\n",
      "[ultranest] Effective samples strategy satisfied (ESS = 2108.8, 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.17, need <0.5)\n",
      "[ultranest]   logZ error budget: single: 0.23 bs:0.17 tail:0.01 total:0.17 required:<0.50\n",
      "[ultranest] done iterating.\n"
     ]
    }
   ],
   "source": [
    "# bounds shared by all light curves\n",
    "global_bounds = {\n",
    "    'rprs':(prior['rprs']*0.75, prior['rprs']*1.33),\n",
    "    'inc':(prior['inc']-5, min(90,prior['inc']+5)),\n",
    "    'per':( result.ephemeris['Period']-0.001,\n",
    "            result.ephemeris['Period']+0.001),\n",
    "    'tmid':( result.ephemeris['Tc']-0.01,\n",
    "             result.ephemeris['Tc']+0.01),\n",
    "}\n",
    "\n",
    "global_fit = glc_fitter(input_data, global_bounds, local_bounds, individual_fit=False, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 582068 characters]",
      "text/plain": [
       "<Figure size 970x970 with 16 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "global_fit.plot_triangle()\n",
    "plt.savefig(os.path.join(output_dir,\"posteriors.png\"),facecolor='white')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 1680952 characters]",
      "text/plain": [
       "<Figure size 1500x1200 with 2 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "global_fit.plot_bestfit(alpha=0.025, bin_dt = 15./60/24, title=f\"{target} Global Fit\",phase_limits='median', ylim_sigma=10)\n",
    "plt.savefig(os.path.join(output_dir,\"bestfit.png\"),facecolor='white')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ecc': 0.0074,\n",
       " 'inc': 87.713010716479,\n",
       " 'omega': -166.0,\n",
       " 'tmid': 2458416.424893059,\n",
       " 'a1': 1,\n",
       " 'a2': 0.0,\n",
       " 'ars': 5.332,\n",
       " 'rprs': 0.11810311272220649,\n",
       " 'per': 1.3600290306112939,\n",
       " 'u0': 0.5007438874039994,\n",
       " 'u1': -0.08351946282301767,\n",
       " 'u2': 0.4675323137274613,\n",
       " 'u3': -0.2166556367766898}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prior"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ecc': 0.0074,\n",
       " 'inc': 87.96694041934134,\n",
       " 'omega': -166.0,\n",
       " 'tmid': 2459957.337648647,\n",
       " 'a1': 1,\n",
       " 'a2': -0.0027830397249283267,\n",
       " 'ars': 5.332,\n",
       " 'rprs': 0.11805133900539692,\n",
       " 'per': 1.360029059910445,\n",
       " 'u0': 1.9620417119554874,\n",
       " 'u1': -3.53068378927721,\n",
       " 'u2': 4.032966684059403,\n",
       " 'u3': -1.4643245466417936}"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "global_fit.parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'ecc': 0.0074,\n",
       " 'inc': 86.056714996829,\n",
       " 'omega': -166.0,\n",
       " 'tmid': 2459146.7588232975,\n",
       " 'a1': 0.9417598570625737,\n",
       " 'a2': -0.005521919257919672,\n",
       " 'ars': 5.332,\n",
       " 'rprs': 0.13602179453975768,\n",
       " 'per': 1.36002869,\n",
       " 'u0': 1.9620417119554874,\n",
       " 'u1': -3.53068378927721,\n",
       " 'u2': 4.032966684059403,\n",
       " 'u3': -1.4643245466417936}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "global_fit.lc_data[0]['parameters']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 2517140 characters]",
      "text/plain": [
       "<Figure size 4500x4000 with 32 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "global_fit.plot_bestfits()\n",
    "plt.savefig(os.path.join(output_dir,\"bestfits.png\"),facecolor='white')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## LaTeX Output for Global Fit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rprs & 0.11805 $\\pm$ 0.0001471 \\\\\n",
      "inc & 87.96694 $\\pm$ 0.0723284 \\\\\n",
      "per & 1.36003 $\\pm$ 0.0000002 \\\\\n",
      "tmid & 2459957.33765 $\\pm$ 0.0001239 \\\\\n"
     ]
    }
   ],
   "source": [
    "# create latex formatted table for global fit parameters\n",
    "for key in global_fit.errors:\n",
    "    print(f\"{key} & {global_fit.parameters[key]:.5f} $\\pm$ {global_fit.errors[key]:.7f} \\\\\\\\\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Name & rprs & tmid & inc & $\\sigma_{res}$ \\\\\n",
      "FMAA & 0.136022 $\\pm$ 0.010948 & 2459146.758823 $\\pm$ 0.004392 & 86.056715 $\\pm$ 1.190071 & 0.011515 \\\\\n",
      "FMAA & 0.125723 $\\pm$ 0.007814 & 2459150.837679 $\\pm$ 0.002041 & 85.917627 $\\pm$ 1.021602 & 0.006658 \\\\\n",
      "BTSB & 0.167016 $\\pm$ 0.009833 & 2459475.883579 $\\pm$ 0.004874 & 89.584823 $\\pm$ 1.002267 & 0.010720 \\\\\n",
      "KADB & 0.109107 $\\pm$ 0.002481 & 2459524.851389 $\\pm$ 0.000602 & 89.985425 $\\pm$ 0.475624 & 0.008494 \\\\\n",
      "KADB & 0.109676 $\\pm$ 0.003097 & 2459546.613226 $\\pm$ 0.000790 & 89.941082 $\\pm$ 0.603683 & 0.007162 \\\\\n",
      "KADB & 0.132647 $\\pm$ 0.004659 & 2459565.643569 $\\pm$ 0.001527 & 87.243102 $\\pm$ 1.170833 & 0.009445 \\\\\n",
      "KADB & 0.140129 $\\pm$ 0.001670 & 2459584.692330 $\\pm$ 0.000474 & 85.910036 $\\pm$ 0.025738 & 0.007218 \\\\\n",
      "FMAA & 0.149629 $\\pm$ 0.009138 & 2459584.680663 $\\pm$ 0.002911 & 85.911414 $\\pm$ 1.139028 & 0.013322 \\\\\n",
      "PJAE & 0.139842 $\\pm$ 0.005205 & 2459909.738916 $\\pm$ 0.001110 & 87.102550 $\\pm$ 1.092492 & 0.009798 \\\\\n",
      "SAJB & 0.132836 $\\pm$ 0.000751 & 2459957.337786 $\\pm$ 0.000202 & 88.889789 $\\pm$ 0.493753 & 0.003245 \\\\\n",
      "TESS & 0.117291 $\\pm$ 0.001118 & 2458412.344649 $\\pm$ 0.000354 & 88.281017 $\\pm$ 0.684870 & 0.000907 \\\\\n",
      "TESS & 0.116970 $\\pm$ 0.001060 & 2458425.945080 $\\pm$ 0.000341 & 88.755501 $\\pm$ 0.616326 & 0.000774 \\\\\n",
      "TESS & 0.116934 $\\pm$ 0.000487 & 2459148.120324 $\\pm$ 0.000140 & 87.825243 $\\pm$ 0.209700 & 0.001633 \\\\\n",
      "TESS & 0.117466 $\\pm$ 0.001135 & 2458428.664753 $\\pm$ 0.000356 & 87.956655 $\\pm$ 0.673918 & 0.000741 \\\\\n",
      "TESS & 0.118283 $\\pm$ 0.001084 & 2458434.105217 $\\pm$ 0.000345 & 88.162619 $\\pm$ 0.675932 & 0.000770 \\\\\n",
      "TESS & 0.116010 $\\pm$ 0.000437 & 2459149.480302 $\\pm$ 0.000159 & 88.160304 $\\pm$ 0.305209 & 0.001661 \\\\\n",
      "TESS & 0.118433 $\\pm$ 0.001148 & 2458431.384904 $\\pm$ 0.000340 & 87.729581 $\\pm$ 0.582843 & 0.000784 \\\\\n",
      "TESS & 0.117097 $\\pm$ 0.000475 & 2459146.760232 $\\pm$ 0.000142 & 88.062580 $\\pm$ 0.261825 & 0.001661 \\\\\n",
      "TESS & 0.116746 $\\pm$ 0.001143 & 2458435.465270 $\\pm$ 0.000351 & 88.029105 $\\pm$ 0.690727 & 0.000765 \\\\\n",
      "TESS & 0.116909 $\\pm$ 0.001058 & 2458427.305076 $\\pm$ 0.000350 & 88.318395 $\\pm$ 0.669091 & 0.000798 \\\\\n",
      "TESS & 0.117849 $\\pm$ 0.001049 & 2458413.705124 $\\pm$ 0.000355 & 87.771350 $\\pm$ 0.626348 & 0.000710 \\\\\n",
      "TESS & 0.118820 $\\pm$ 0.001129 & 2458415.064811 $\\pm$ 0.000328 & 87.639812 $\\pm$ 0.561763 & 0.000812 \\\\\n",
      "TESS & 0.117607 $\\pm$ 0.001125 & 2458432.745353 $\\pm$ 0.000360 & 87.943320 $\\pm$ 0.696069 & 0.000782 \\\\\n",
      "TESS & 0.117524 $\\pm$ 0.000461 & 2459150.840090 $\\pm$ 0.000141 & 87.917785 $\\pm$ 0.225982 & 0.001703 \\\\\n",
      "TESS & 0.117945 $\\pm$ 0.000472 & 2459145.400116 $\\pm$ 0.000142 & 88.150624 $\\pm$ 0.267485 & 0.001665 \\\\\n",
      "TESS & 0.117286 $\\pm$ 0.001108 & 2458417.784875 $\\pm$ 0.000363 & 87.768359 $\\pm$ 0.645987 & 0.000763 \\\\\n",
      "TESS & 0.117208 $\\pm$ 0.000454 & 2459152.200526 $\\pm$ 0.000154 & 88.440362 $\\pm$ 0.408192 & 0.001749 \\\\\n",
      "TESS & 0.117863 $\\pm$ 0.001147 & 2458430.025050 $\\pm$ 0.000367 & 87.877703 $\\pm$ 0.665252 & 0.000796 \\\\\n",
      "TESS & 0.118041 $\\pm$ 0.001110 & 2458416.424900 $\\pm$ 0.000355 & 87.718769 $\\pm$ 0.609928 & 0.000716 \\\\\n"
     ]
    }
   ],
   "source": [
    "# create column headers\n",
    "header = \"Name\"\n",
    "for key in input_data[0]['errors']:\n",
    "    # skip airmass parameters\n",
    "    if 'a1' in key or 'a2' in key:\n",
    "        continue\n",
    "    header += f\" & {key}\"\n",
    "header += \" & $\\sigma_{res}$\"\n",
    "header += \" \\\\\\\\\"\n",
    "print(header)\n",
    "\n",
    "# create latex formatted string\n",
    "for lcdata in input_data:\n",
    "    fstring = lcdata['name']\n",
    "    for key in lcdata['errors']:\n",
    "\n",
    "        # skip airmass parameters\n",
    "        if 'a1' in key or 'a2' in key:\n",
    "            continue\n",
    "\n",
    "        # add to string\n",
    "        fstring += f\" & {lcdata['parameters'][key]:.6f} $\\pm$ {lcdata['errors'][key]:.6f}\"\n",
    "\n",
    "    # add res_std\n",
    "    fstring += f\" & {lcdata['res_std']:.6f}\"\n",
    "    fstring += f\" \\\\\\\\\"\n",
    "    print(fstring)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'dude' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[24], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m dude()\n",
      "\u001b[0;31mNameError\u001b[0m: name 'dude' is not defined"
     ]
    }
   ],
   "source": [
    "dude()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Mid-transit times and uncertainties from Nasa Exoplanet Archive"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nea_tmids = []\n",
    "nea_tmids_err = []\n",
    "\n",
    "for i in range(len(result.ephemeris['nea_tmids'])):\n",
    "    clean_ref = result.ephemeris['nea_references'][i].replace('%20', ' ').replace('&amp;', '&')\n",
    "\n",
    "    # remove ExoFOP-TESS values since we're using TESS data itself, no need to double count\n",
    "    if 'ExoFOP-TESS' in clean_ref:\n",
    "        continue\n",
    "\n",
    "    nea_tmids.append(result.ephemeris['nea_tmids'][i])\n",
    "    nea_tmids_err.append(result.ephemeris['nea_tmids_err'][i])\n",
    "\n",
    "    print(f\"{float(result.ephemeris['nea_tmids'][i]):.6f} +- {float(result.ephemeris['nea_tmids_err'][i]):.6f} : {clean_ref}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fit an ephemeris to the mid-transit times\n",
    "\n",
    "T_next = T_0 + n * Period"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from exotic.api.nested_linear_fitter import linear_fitter\n",
    "\n",
    "# min and max values to search between for fitting the ephemeris\n",
    "bounds = {\n",
    "    'm':[ # orbital period\n",
    "        global_fit.parameters['per']-10*global_fit.errors['per'], \n",
    "        global_fit.parameters['per']+10*global_fit.errors['per']\n",
    "    ], \n",
    "    'b':[ # mid-transit time\n",
    "        global_fit.parameters['tmid']-10*global_fit.errors['tmid'],\n",
    "        global_fit.parameters['tmid']+10*global_fit.errors['tmid']\n",
    "    ] \n",
    "}\n",
    "\n",
    "# used to plot red overlay in O-C figure\n",
    "prior = {\n",
    "    'm':[global_fit.parameters['per'], global_fit.errors['per']],   # value from global\n",
    "    'b':[global_fit.parameters['tmid'], global_fit.errors['tmid']]  # value from WLS\n",
    "}\n",
    "\n",
    "# extract data from individual light curves in global fit\n",
    "tmids = [lcfit['parameters']['tmid'] for lcfit in input_data]\n",
    "tmids_err = [lcfit['errors']['tmid'] for lcfit in input_data]\n",
    "rprs2 = [lcfit['parameters']['rprs']**2 for lcfit in input_data]\n",
    "rprs = [lcfit['parameters']['rprs'] for lcfit in input_data]\n",
    "rprs_err = [lcfit['errors']['rprs'] for lcfit in input_data]\n",
    "res_stdev = [lcfit['res_std'] for lcfit in input_data]\n",
    "name = [lcfit['name'] for lcfit in input_data]\n",
    "tmids_err = np.array(tmids_err)\n",
    "\n",
    "# filter bad data\n",
    "mask = (res_stdev < np.mean(rprs2)) & (np.mean(rprs) > 5 * np.mean(rprs_err)) & (tmids_err*24*60<5)\n",
    "# TODO 3sigma clip away from global ephemeris\n",
    "\n",
    "# apply mask\n",
    "tmids = np.array(tmids)[mask]\n",
    "tmids_err = np.array(tmids_err)[mask]\n",
    "\n",
    "# combine the good data from reprocessing of Exoplanet Watch and NASA Exoplanet Archive\n",
    "tmids = np.array(list(tmids) + nea_tmids, dtype=float)\n",
    "tmids_err = np.array(list(tmids_err) + nea_tmids_err, dtype=float)\n",
    "\n",
    "# fit the data and compare ephemeris to global light curve fit\n",
    "lf = linear_fitter( tmids, tmids_err, bounds, prior=prior )\n",
    "\n",
    "# plot the O-C diagram\n",
    "fig,ax = lf.plot_oc(prior_name='Global Fit')\n",
    "plt.tight_layout()\n",
    "plt.savefig(os.path.join(output_dir,\"oc_global.png\"),facecolor='white')\n",
    "plt.close()\n",
    "Image(os.path.join(output_dir,\"oc_global.png\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Search for periodic signals in the O-C data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax = lf.plot_periodogram()\n",
    "plt.tight_layout()\n",
    "plt.savefig(os.path.join(output_dir,\"periodogram.png\"),facecolor='white')\n",
    "plt.close()\n",
    "Image(os.path.join(output_dir,\"periodogram.png\"))"
   ]
  }
 ],
 "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.11.0"
  },
  "vscode": {
   "interpreter": {
    "hash": "9bea94c061466e98e3c4227ef91da81db5f711c134da0c4ba8a34c93e3b51d83"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
