{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import ale, json, os\n",
    "import knoten.csm as csm\n",
    "import ctypes\n",
    "import gdal\n",
    "import shapely.wkt\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from ale.drivers.cassini_drivers import CassiniIssPds3LabelNaifSpiceDriver\n",
    "from ale.drivers import JsonEncoder"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use the images to generate ISDs and create CSM cameras \n",
    "\n",
    "# Assume images are in current directory\n",
    "\n",
    "nac_stereo_1 = 'N1702360370_1.LBL'\n",
    "nac_stereo_2 = 'N1702360308_1.LBL'\n",
    "\n",
    "def generate_isd(filename): \n",
    "    driver = CassiniIssPds3LabelNaifSpiceDriver(filename)\n",
    "\n",
    "    # SPICE kernels are furnished inside this with\n",
    "    with driver as d:\n",
    "        # this is the information for the ISD in a python dict\n",
    "        aledict = d.to_dict()\n",
    "\n",
    "    # Export python dictionary ISD to external json file to be used by CSM\n",
    "    alelabel = os.path.splitext(filename)[0]+\".json\"\n",
    "    with open (alelabel, \"w\") as file:\n",
    "        json.dump(aledict, file, cls=JsonEncoder)\n",
    "    return aledict\n",
    "\n",
    "# Generate ISD and export to a json file\n",
    "nac1_dict = generate_isd(nac_stereo_1)\n",
    "nac2_dict = generate_isd(nac_stereo_2)\n",
    "\n",
    "# Construct a camera\n",
    "camera1 = csm.create_csm(nac_stereo_1)\n",
    "camera2 = csm.create_csm(nac_stereo_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'CSM footprints for N1702360370_1 and N1702360308_1')"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 32796 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# ALE + CSM footprints for the two nac images \n",
    "\n",
    "n1lines, n1samples = nac1_dict[\"image_lines\"], nac1_dict[\"image_samples\"]\n",
    "n2lines, n2samples = nac2_dict[\"image_lines\"], nac2_dict[\"image_samples\"]\n",
    "\n",
    "boundary1 = csm.generate_boundary((n1lines, n1samples))\n",
    "boundary2 = csm.generate_boundary((n2lines, n2samples))\n",
    "\n",
    "# A different way to plot this: \n",
    "lons1, lats1, alts1 = csm.generate_latlon_boundary(camera1, boundary1, nac1_dict['radii']['semimajor'], nac1_dict['radii']['semiminor'])\n",
    "lons2, lats2, alts2 = csm.generate_latlon_boundary(camera2, boundary2, nac1_dict['radii']['semimajor'], nac1_dict['radii']['semiminor'])\n",
    "\n",
    "plt.plot(lons1, lats1)\n",
    "plt.plot(lons2, lats2, 'r')\n",
    "plt.xlabel(\"longitude (degrees)\")\n",
    "plt.ylabel(\"latitude (degrees)\")\n",
    "plt.title(\"CSM footprints for N1702360370_1 and N1702360308_1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.legend.Legend at 0x7f4485459e48>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 31196 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# \"nac 1\" footprint geometry comparsion between ALE+CSM and ISIS\n",
    "\n",
    "# ALE + CSM footprint geometry\n",
    "csm_footprint = csm.generate_latlon_footprint(camera1, boundary1, nac1_dict['radii']['semimajor'], nac1_dict['radii']['semiminor'])\n",
    "csm_wkt = csm_footprint.ExportToWkt()\n",
    "csm_geom = shapely.wkt.loads(csm_wkt)\n",
    "csm_x, csm_y = csm_geom.geoms[0].exterior.coords.xy\n",
    "\n",
    "# ISIS footprint geometry\n",
    "\n",
    "# These are the steps to produce the WKT needed for this comparison, as it is outside of the notebook.\n",
    "#\n",
    "# In a working ISIS environment:\n",
    "#\n",
    "# ciss2isis fr=N1702360370_1.LBL to=N1702360370_1.cub\n",
    "# spiceinit fr=N1702360370_1.cub\n",
    "# footprintinit fr=N1702360370_1.cub\n",
    "# blobdump fr=N1702360370_1.cub name=Footprint type=Polygon to=N1702360370_wkt.txt\n",
    "#\n",
    "# Then, copy the contents of N1702360370_wkt.txt into the variable on the next line: \n",
    "\n",
    "isis_wkt = \"MULTIPOLYGON (((308.7766226791562758 -38.9793595270631172, 302.5898034059880501 -37.0172821519269988, 297.2322388264788060 -35.0861844460185566, 292.4554746270104033 -33.1839327771886232, 288.1104793753453919 -31.3093153012993888, 284.0970150353607551 -29.4605644938592128, 280.3435700723426862 -27.6357129030783106, 276.7967539502020031 -25.8327538405502501, 273.4151882926276471 -24.0497145867306479, 270.1657459955625882 -22.2846874073778594, 267.0211058213601518 -20.5358392049750513, 266.3013671020171387 -20.1152992042466607, 267.9941343285823905 -17.0959570696160590, 269.6416147037393216 -14.1270761413354418, 271.2629128269002763 -11.1946857855798729, 272.8733144744931565 -8.2892960662480064, 274.4870914529420816 -5.4021019422143111, 276.1181900043626456 -2.5247380975164306, 277.7808631026515513 0.3509356909223578, 279.4903166895359163 3.2330347666562691, 281.2634409550755663 6.1298496517986987, 283.1197135584058628 9.0500604383148584, 283.5818484454278519 9.7343343292771216, 286.5745512910930302 8.0879763858221612, 289.6176921178364978 6.4580762888259091, 292.7347457026794473 4.8416907992888749, 295.9488657721883555 3.2379674111861734, 299.2877948876923710 1.6462670575419474, 302.7861152346808353 0.0662090149774433, 306.4888559808638888 -1.5022468441659151, 310.4576979018125940 -3.0586488095795783, 314.7826060744896495 -4.6017606461944096, 319.6062769331790605 -6.1289386978209537, 320.8268343771581499 -6.4962397912255998, 318.6061398418910926 -9.4231491089585280, 316.6703428951187220 -12.3664232741211428, 314.9731311317106019 -15.3398593660871345, 313.4866145328350058 -18.3543803958300806, 312.1944279414427683 -21.4218678117189825, 311.0899207244888203 -24.5556837338397891, 310.1760037253627615 -27.7713181775189106, 309.4666161914537383 -31.0872606437287509, 308.9903784732705958 -34.5262473964737424, 308.7979582861563586 -38.1171421790197797, 308.7766226791562758 -38.9793595270631172)))\"\n",
    "isis_geom = shapely.wkt.loads(isis_wkt)\n",
    "isis_lon, isis_lat = isis_geom.geoms[0].exterior.coords.xy\n",
    "\n",
    "# Convert ISIS longitude to -180/180\n",
    "isis_lon_360 = np.asarray(isis_lon)\n",
    "isis_lon_180 = np.mod(isis_lon_360 - 180.0, 360.0) - 180.0\n",
    "\n",
    "# Plot comparison\n",
    "plt.title(\"N1702360370_1 Footprint Comparison between ISIS and CSM\")\n",
    "plt.xlabel(\"longitude (degrees)\")\n",
    "plt.ylabel(\"latitude (degrees)\")\n",
    "isis_plot, = plt.plot(isis_lon_180, isis_lat, 'r')\n",
    "csm_plot, = plt.plot(csm_x, csm_y, 'b')\n",
    "isis_plot.set_label(\"ISIS Footprint\")\n",
    "csm_plot.set_label(\"CSM Footprint\")\n",
    "plt.legend()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'N1702360308_1')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 490392 characters]\n",
      "text/plain": [
       "<Figure size 1440x1080 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# View the unprojected images\n",
    "\n",
    "# Open with gdal\n",
    "nac_stereo_1_data = gdal.Open(nac_stereo_1)\n",
    "nac_stereo_2_data = gdal.Open(nac_stereo_1)\n",
    "\n",
    "# Plot\n",
    "plt.figure(figsize=(20, 15))\n",
    "ax = plt.subplot(1, 2, 1)\n",
    "plt.imshow(nac_stereo_1_data.ReadAsArray())\n",
    "plt.title(\"N1702360370_1\")\n",
    "ax = plt.subplot(1, 2, 2)\n",
    "plt.imshow(nac_stereo_2_data.ReadAsArray())\n",
    "plt.title(\"N1702360308_1\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Text(0.5, 1.0, 'N1702360308_1')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 628124 characters]\n",
      "text/plain": [
       "<Figure size 1440x1080 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Project images and view\n",
    "\n",
    "nac_1_gcps = csm.generate_gcps(camera1, boundary1)\n",
    "nac_2_gcps = csm.generate_gcps(camera2, boundary2)\n",
    "\n",
    "proj_str = '+proj=longlat +a={} +b={} +no_defs'.format(nac1_dict['radii']['semimajor'], nac1_dict['radii']['semiminor'])\n",
    "nac_1_vrt = csm.generate_vrt([n1lines, n1samples], nac_1_gcps, nac_stereo_1, proj_str)\n",
    "nac_2_vrt = csm.generate_vrt([n2lines, n2samples], nac_2_gcps, nac_stereo_2, proj_str)\n",
    "\n",
    "warp_options = gdal.WarpOptions(format='VRT', dstNodata=0)\n",
    "nac_1_lvl2 = 'nac1_lvl2.tif'\n",
    "nac_2_lvl2 = 'nac2_lvl2.tif'\n",
    "\n",
    "nac_1_lvl2_data = gdal.Warp(nac_1_lvl2, nac_1_vrt, options=warp_options)\n",
    "nac_2_lvl2_data = gdal.Warp(nac_2_lvl2, nac_2_vrt, options=warp_options)\n",
    "\n",
    "plt.figure(figsize=(20, 15))\n",
    "ax = plt.subplot(1, 2, 1)\n",
    "plt.imshow(nac_1_lvl2_data.ReadAsArray())\n",
    "plt.title(\"N1702360370_1\")\n",
    "ax = plt.subplot(1, 2, 2)\n",
    "plt.imshow(nac_2_lvl2_data.ReadAsArray())\n",
    "plt.title(\"N1702360308_1\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
