{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "734149be-310f-4d27-a8f2-211c94451773",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os \n",
    "\n",
    "os.environ[\"SPICEROOT\"] = \"/Users/krodriguez/isisdata/\"\n",
    "os.environ[\"ISISDATA\"] = os.environ[\"SPICEROOT\"]\n",
    "os.environ[\"SPICEQL_CACHE_DIR\"] = \"/Users/krodriguez/spiceql-cache/\"\n",
    "\n",
    "# os.environ[\"SPICEQL_LOG_LEVEL\"] = \"TRACE\"\n",
    "\n",
    "import pprint\n",
    "from osgeo import gdal\n",
    "import pyspiceql as pql\n",
    "import urllib\n",
    "import plio \n",
    "import matplotlib\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np \n",
    "from dateutil import parser"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d3b11c4-fc51-4409-860f-7463a95d0cc9",
   "metadata": {},
   "source": [
    "# Get Start and Stop Times "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 198,
   "id": "f51d23f3-1f7e-4641-90ec-c762b8c6c763",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "num ets: 1000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(599572869.1839148, 599659269.1839437)"
      ]
     },
     "execution_count": 198,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "startet = pql.utcToEt(\"2019-01-01\")\n",
    "stopet = pql.utcToEt(\"2019-01-02\")\n",
    "# get an array of times in regular intervals throughout the exposure \n",
    "ets = np.linspace(start=startet, stop=stopet, num=1000)\n",
    "print(\"num ets:\", len(ets))\n",
    "dates = [parser.parse(pql.etToUtc(et, searchKernels=False)) for et in ets]\n",
    "startet, stopet"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b040736f-4c31-4ff8-948e-3fb77082d007",
   "metadata": {},
   "source": [
    "# Search for Appropriate Kernels\n",
    "\n",
    "Spiceql will load them for us if we use `searchKernels=True` later when getting the rotations, but here we will load them manually so we know exactly what kernels are being used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 199,
   "id": "1017851a-05d4-4454-9def-9ee3b58c6938",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Base kernels Used\n",
      "{'lsk': {'kernels': [['/Users/krodriguez/isisdata//base/kernels/lsk/naif0012.tls']]},\n",
      " 'pck': {'kernels': [['/Users/krodriguez/isisdata//base/kernels/pck/pck00009.tpc']]},\n",
      " 'spk': {'kernels': [['/Users/krodriguez/isisdata//base/kernels/spk/de430.bsp'],\n",
      "                     ['/Users/krodriguez/isisdata//base/kernels/spk/mar097.bsp'],\n",
      "                     ['/Users/krodriguez/isisdata//base/kernels/spk/nep090.bsp'],\n",
      "                     ['/Users/krodriguez/isisdata//base/kernels/spk/sat425.bsp'],\n",
      "                     ['/Users/krodriguez/isisdata//base/kernels/spk/ura115.bsp']]}}\n",
      "LROC kernels Used\n",
      "{'ck': {'reconstructed': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/ck/lrolc_2018334_2019001_v01.bc'],\n",
      "                                      ['/Users/krodriguez/isisdata//lro/kernels/ck/lrolc_2018365_2019032_v01.bc'],\n",
      "                                      ['/Users/krodriguez/isisdata//lro/kernels/ck/moc42r_2018334_2019001_v01.bc'],\n",
      "                                      ['/Users/krodriguez/isisdata//lro/kernels/ck/moc42r_2018365_2019032_v01.bc']]}},\n",
      " 'fk': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/fk/lro_frames_2014049_v01.tf']]},\n",
      " 'iak': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/iak/lro_instrumentAddendum_v05.ti']]},\n",
      " 'ik': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/ik/lro_lroc_v18.ti'],\n",
      "                    ['/Users/krodriguez/isisdata//lro/kernels/ik/lro_instruments_v12.ti']]},\n",
      " 'pck': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/pck/moon_080317.tf'],\n",
      "                     ['/Users/krodriguez/isisdata//lro/kernels/pck/moon_assoc_me.tf']]},\n",
      " 'sclk': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/sclk/lro_clkcor_2023103_v00.tsc']]},\n",
      " 'spk': {'reconstructed': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/spk/fdf29r_2018335_2019001_v01.bsp'],\n",
      "                                       ['/Users/krodriguez/isisdata//lro/kernels/spk/fdf29r_2019001_2019032_v01.bsp']]},\n",
      "         'smithed': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/spk/LRO_ES_77_201902_GRGM900C_L600.BSP']]}},\n",
      " 'tspk': {'kernels': [['/Users/krodriguez/isisdata//lro/kernels/tspk/de421.bsp'],\n",
      "                      ['/Users/krodriguez/isisdata//lro/kernels/tspk/moon_pa_de421_1900-2050.bpc']]}}\n"
     ]
    }
   ],
   "source": [
    "# Get all Base kernels, not really worried about being minimal \n",
    "cfg = pql.Config()\n",
    "base_kernels = pql.getLatestKernels(cfg[\"base\"].get())\n",
    "print(\"Base kernels Used\")\n",
    "pprint.pprint(base_kernels)\n",
    "\n",
    "# furnish the kernels found\n",
    "base_set = pql.KernelSet(base_kernels)\n",
    "\n",
    "# Get appropriate LROC kernels\n",
    "cfg = pql.Config()\n",
    "lroc_kernels = cfg[\"lroc\"].get()\n",
    "lroc_kernels = pql.getLatestKernels(pql.searchMissionKernels(lroc_kernels, ets, False))\n",
    "print(\"LROC kernels Used\")\n",
    "pprint.pprint(lroc_kernels)\n",
    "\n",
    "# furnish the kernels found\n",
    "lroc_set = pql.KernelSet(lroc_kernels)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c9b42bf-93c2-41b5-8069-ec121028bd4a",
   "metadata": {},
   "source": [
    "# Get orientations and convert to Euler Angles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 200,
   "id": "72d92472-ee36-4ef9-a197-fa4d1d3f99f2",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Instrument Frame:  -85600\n",
      "Target Frame:  10020\n"
     ]
    }
   ],
   "source": [
    "def quaternion_to_ypr(quats):\n",
    "    qw, qx, qy, qz = orientations[:,:4].transpose()\n",
    "    \n",
    "    yaw = np.degrees(np.arctan2(2.0*(qy*qz + qw*qx), qw*qw - qx*qx - qy*qy + qz*qz));\n",
    "    pitch = np.degrees(np.arcsin(-2.0*(qx*qz - qw*qy)));\n",
    "    roll = np.degrees(np.arctan2(2.0*(qx*qy + qw*qz), qw*qw + qx*qx - qy*qy - qz*qz));\n",
    "    return yaw, pitch, roll\n",
    "\n",
    "\n",
    "# get orientations relative to the moon \n",
    "inst_frame = pql.translateNameToCode(\"LRO_LROCNACL\", \"lro\")\n",
    "target_frame = pql.translateNameToCode(\"IAU_MOON\", \"base\")\n",
    "\n",
    "print(\"Instrument Frame: \", inst_frame)\n",
    "print(\"Target Frame: \", target_frame)\n",
    "\n",
    "orientations = pql.getTargetOrientations(ets, -85000, target_frame, \"lro\", \"reconstructed\", False)\n",
    "orientations = np.asarray(orientations)\n",
    "\n",
    "yaw, pitch, roll = quaternion_to_ypr(orientations)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "577b4b7f-3a78-4e15-8230-4d04d004e3fd",
   "metadata": {},
   "source": [
    "# Use Matplotlib to Make Some Basic Plots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 201,
   "id": "438582d4-88da-4e07-bcd4-99cc37410110",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 138540 characters]",
      "text/plain": [
       "<Figure size 1500x400 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)\n",
    "fig.suptitle(f'{image_id} Rotations')\n",
    "fig.set_figheight(4)\n",
    "fig.set_figwidth(15)\n",
    "ax1.plot(dates, yaw)\n",
    "ax1.set_title(\"YAW\")\n",
    "ax2.plot(dates, pitch)\n",
    "ax2.set_title(\"PITCH\")\n",
    "ax3.plot(dates, roll)\n",
    "ax3.set_title(\"ROLL\")\n",
    "fig.supxlabel(\"Ephemeris Time\")\n",
    "fig.supylabel(\"Angle in Degrees\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 202,
   "id": "e98568ef-fc7c-46da-9226-4f5119e70ad0",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 267840 characters]",
      "text/plain": [
       "<Figure size 2000x500 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig, (ax1, ax2, ax3) = plt.subplots(3, 1)\n",
    "fig.suptitle(f'{image_id} Angular Velocities')\n",
    "fig.set_figheight(5)\n",
    "fig.set_figwidth(20)\n",
    "ax1.plot(ets, orientations[:, 4])\n",
    "ax1.set_title(\"AV X\")\n",
    "ax2.plot(ets, orientations[:, 5])\n",
    "ax2.set_title(\"AV Y\")\n",
    "ax3.plot(ets, orientations[:, 6])\n",
    "ax3.set_title(\"AV Z\")\n",
    "plt.show()"
   ]
  }
 ],
 "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.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
