{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# We don't technically need this but it avoids a warning when importing pysis\n",
    "import os\n",
    "os.environ['ISISROOT'] = '/usgs/cpkgs/anaconda3_linux/envs/isis3.9.0'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='toc'></a>\n",
    "# AutoCNet Intro\n",
    "As mentioned earlier AutoCNet is a method for storing control networks and has outlier detection functionality. AutoCNet also contains a suite of functions that parallelize network generation that leverages and compliments ISIS processing. The advantage of AutoCNet network generation is it takes advantage of elementwise cluster processing (these elements can be images, points, measures, etc.) and postgresql for data storage and quick relational querying. \n",
    "\n",
    "In this notebook we are going to step through the network generation process in AutoCNet!\n",
    "\n",
    "For Quick Access:\n",
    "- [Load and apply configuration file](#configuration)\n",
    "- [Ingest images and calculate overlaps](#ingest)\n",
    "- [Distribute points in overlaps](#distribute)\n",
    "- [Subpixel register points](#registration)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Grab the Image Data\n",
    "We are going to process Kaguya Terrain Camera (TC) images surrounding the Reiner Gamma Lunar Swirl (4.9° - 9.9° N Planetocentric Latitude and 61.3° - 56.3° W Longitude). The data is located in '/scratch/ladoramkershner/moon/kaguya/workshop/original/', please use the cell below to copy the data into a directory of your choosing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import getpass\n",
    "uid = getpass.getuser()\n",
    "\n",
    "output_directory = f'/scratch/ladoramkershner/FY21_autocnet_workshop/workshop_scratch/{uid}' # put output directory path as string here\n",
    "print(output_directory)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# copy over the data to the 'lvl1' subdirectory\n",
    "!mkdir -p $output_directory/lvl1/ \n",
    "!cp -p /scratch/ladoramkershner/moon/kaguya/workshop/original/*cub $output_directory/lvl1/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We need to create a list of the cubes, to feed into AutoCNet. It is important that the cube list handed to AutoCNet contain **absolute** paths, as they will serve as an accessor for loading information from the cubes later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!ls $output_directory/lvl1/*cub > $output_directory/cubes.lis\n",
    "!head $output_directory/cubes.lis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id='configuration'></a>\n",
    "# Parse the Configuration File\n",
    "[Return To Top](#toc)\n",
    "\n",
    "\n",
    "The configuration parameters are typically held in a configuration yaml file. A configuration file has been compiled for use internal to the USGS ASC facilities leveraging a shared cluster and database. Use AutoCNet's function 'parse_config' to read in the yaml file and output a dictionary variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from autocnet.config_parser import parse_config\n",
    "\n",
    "config_path = '/scratch/ladoramkershner/FY21_autocnet_workshop/config_moon.yml'\n",
    "config = parse_config(config_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The config is a nested dictionary, meaning it has a larger dictionary structure defining sections for the services above and then each service section is a dictionary defining the particular configuration parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import numpy as np \n",
    "\n",
    "print('configuration dictionary keys: ')\n",
    "print(np.vstack(list(config.keys())), '\\n')\n",
    "\n",
    "print('cluster configuration dictionary keys: ')\n",
    "print(np.vstack(list(config['cluster'].keys())))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Although the configuration file is set up for internal use, some fields need to be altered to point to user specific areas or unique strings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "config['cluster']['cluster_log_dir'] = f'/scratch/ladoramkershner/FY21_autocnet_workshop/workshop_scratch/{uid}/logs'\n",
    "config['database']['name'] = f'workshop_{uid}_kaguyatc_reinergamma'\n",
    "config['redis']['basename'] = f'{uid}_queue'\n",
    "config['redis']['completed_queue'] = f'{uid}_queue:comp'\n",
    "config['redis']['processing_queue'] = f'{uid}_queue:proc'\n",
    "config['redis']['working_queue'] = f'{uid}_queue:work'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "default_log = config['cluster']['cluster_log_dir']\n",
    "\n",
    "print(f'your log directory: {default_log}')\n",
    "print('your database name:', config['database']['name'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create the NetworkCandidateGraph\n",
    "The NetworkCandidateGraph (NCG) class can be instantiated to an object without any arguments. However, this NCG object requires configuration before it can be used for any meaningful work, so we have to run 'config_from_dict'."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from autocnet.graph.network import NetworkCandidateGraph\n",
    "\n",
    "ncg = NetworkCandidateGraph()\n",
    "ncg.config_from_dict(config)\n",
    "ncg.from_database()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"ingest\"></a>\n",
    "# Ingest Image Data and Calculate Overlaps\n",
    "[Return To Top](#toc)\n",
    "\n",
    "At this point our ncg variable is empty, so if we try to plot the contents we will get an empty plot. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ncg.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We need to load the images into the ncg using 'add_from_filelist', which loads the images from a passed in list and then calculates the overlaps. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "filelist = f'{output_directory}/cubes.lis' # this should contain absolute paths\n",
    "ncg.add_from_filelist(filelist) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now when we plot the ncg, we see the undirected graph, where the circles are the nodes/images and the lines are the edges/overlaps. The Kaguya TC data has a very regular overlap pattern in this area, seen by the large number of edges shared between nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ncg.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We have access to the image data through the ncg, but the ncg does not persist after the notebook is shut down. To persist the network, AutoCNet leverages a database for the storage of the networks images, points, and measures. The ncg has access to this database through the ncg's 'session_scope'. Through the ncg.session_scope() you can interact and execute queries on your database in pure SQL."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with ncg.session_scope() as session:\n",
    "    img_count = session.execute(\"SELECT COUNT(*) FROM images\").fetchall()\n",
    "    overlap_count = session.execute(\"SELECT COUNT(*) FROM overlay\").fetchall()\n",
    "    print('  Number of images in database: ', img_count[0][0])\n",
    "    print('Number of overlaps in database: ', overlap_count)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "session.execute() is equivalent to running the input string in the database directly. It is a convenient if you are already familiar with pure sql commands, however, the return values are messy. The session.query() leverages a python module called sqlalchemy which allow pythonic calls to your database with clean output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from autocnet.io.db.model import Images, Overlay\n",
    "\n",
    "with ncg.session_scope() as session:\n",
    "    img_count = session.query(Images).count()\n",
    "    overlap_count = session.query(Overlay).count()\n",
    "    print('  Number of images in database: ', img_count)\n",
    "    print('Number of overlaps in database: ', overlap_count)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, session.execute() can be inconvenient if working with the actual data contained within the tables. For example, to access certain information you need to know the index where that information exists."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with ncg.session_scope() as session:\n",
    "    img = session.execute(\"SELECT * FROM images LIMIT 1\").fetchall()\n",
    "    print('image index: ', img[0][0])\n",
    "    print('product id: ', img[0][1])\n",
    "    print('image path: ', img[0][2])\n",
    "    print('image serial number: ', img[0][3])\n",
    "    print('image ignore flag: ', img[0][4])\n",
    "#     print('image geom: ', img[0][5]) # only uncomment after looking at other output\n",
    "    print('image camera type: ', img[0][7])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, if the structure of the database changes (order of the columns or a column is added/removed) or you cannot remember the order of the columns, working with the database data in this way is be very inconvenient. So AutoCNet built models for each table of the database tables to help interface with them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from autocnet.io.db.model import Measures, Points\n",
    "\n",
    "with ncg.session_scope() as session:\n",
    "    img = session.query(Images).first()\n",
    "    print('image index: ', img.id) \n",
    "    print('product id: ', img.name) \n",
    "    print('image path: ', img.path)\n",
    "    print('image serial number: ', img.serial)\n",
    "    print('image ignore flag: ', img.ignore)\n",
    "#     print('image geometry: ', img.geom) # only uncomment after looking at other output\n",
    "    print('image camera type: ', img.cam_type)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Accessing the information off of the img object is more intuitive as it is property based instead of index based.\n",
    "\n",
    "img[0][0] --> img.id <br>\n",
    "img[0][1] --> img.name <br>\n",
    "img[0][2] --> img.path <br>\n",
    "and so on.. \n",
    "\n",
    "Additionally, if you cannot remember the exact names of the properties you want to access, you can dir() the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "print(dir(Images))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, if you uncomment the prints of the geometry in the two previous cells you see that the raw database geometry (given by session.execute()) is stored as a hexadecimal string while the Images.geom property is a shapely Multipolygon with more intuitive longitude and latitude values. The MultiPolygon also has helpful functions which allows direct access to the latitude, longitude information. To plot the geometry all we have to do is..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "n = 25\n",
    "with ncg.session_scope() as session:\n",
    "    imgs = session.query(Images).limit(n)\n",
    "    \n",
    "    fig, axs = plt.subplots(1, 1, figsize=(5,10))\n",
    "    axs.set_title(f'Footprints of First {n} Images in Database')\n",
    "    for img in imgs:\n",
    "        x,y = img.geom.envelope.boundary.xy # this call!\n",
    "        axs.plot(x,y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"distribute\"></a>\n",
    "# Place Points in Overlap\n",
    "[Return To Top](#toc)\n",
    "\n",
    "The next step in the network generation process is to lay down points in the image overlaps. Before dispatching the function to the cluster, we need to make the log directory from our configuration file. If a SLURM job is submitted with a log directory argument that does not exist, the job will fail."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ppio_log_dir = default_log.replace('logs', 'ppio_logs')\n",
    "\n",
    "print('creating directory: ', ppio_log_dir)\n",
    "if not os.path.exists(ppio_log_dir):\n",
    "    os.mkdir(ppio_log_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are going to use the 'place_points_in_overlap' function to lay the points down. For now, we will use the default size and distribution arguments, which is easily accomplished by not handing in values for these arguments. However, we need to change our camera type from the default 'csm' to 'isis'. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from autocnet.spatial.overlap import place_points_in_overlap\n",
    "\n",
    "njobs = ncg.apply('spatial.overlap.place_points_in_overlap', \n",
    "                  on='overlaps', # start of function kwargs\n",
    "                  cam_type='isis',\n",
    "                  walltime='00:30:00', # start of apply kwargs\n",
    "                  log_dir=ppio_log_dir,\n",
    "                  arraychunk=50)\n",
    "\n",
    "print(njobs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!squeue -u $uid | head # helpful to grab job array id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The 'place_points_in_overlaps' function first evenly distributes points spatially into a given overlap, then it back-projects the points into the 'top' image. Once in image space, the function searches the area surrounding the measures to find interesting features to shift the measures to (this increases the chance of subpixel registration passing). The shifted measures are projected back to the ground and these updated longitudes and latitudes are used to propagate the points into all images associated with the overlap. So, this function requires:\n",
    "- An overlap (to evenly distribute points into)\n",
    "- Distribution kwargs (to decide how points are distributed into the overlap)\n",
    "- Size of the area around the measure (to search for the interesting feature)\n",
    "- Camera type (so it knows what to expect as inputs/output for the camera model)\n",
    "\n",
    "Since this function operates independently on each overlap, it is ideal for parallelization with the cluster. Notice that we are not passing in a single overlap to the apply call, instead we pass \"on = 'overlaps'\". The 'on' argument indicates which element (image, overlap, point, measure) to apply the function. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with ncg.session_scope() as session:\n",
    "    noverlay = session.query(Overlay).count()\n",
    "    print(noverlay)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multiple Ways to Check Job Array Process"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Log Files\n",
    "As jobs are put on the cluster, their corresponding log files are created. You can check how many jobs have been/ are being processed on the cluster by looking in the log directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!ls $ppio_log_dir | head -5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As more logs are placed in the log directory, you will have to specify which array job's logs you are checking on. The naming convention of the log files generated by AutoCNet are 'path.to.function.function_name-jobid.arrayid_taskid.out'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "jobid = '' # put jobid int here\n",
    "!ls $ppio_log_dir/*${jobid}_*.out | wc -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Slurm Account\n",
    "Using 'sacct' allows you to check the exit status of the tasks from your job array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!sacct -j $jobid -s 'completed' | wc -l\n",
    "!sacct -j $jobid -s 'failed'    | wc -l\n",
    "!sacct -j $jobid -s 'timeout'   | wc -l\n",
    "!sacct -j $jobid -s 'cancelled' | wc -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The return of '2' from the word count on the 'failed', 'timeout', and 'cancelled' job accounts are the header lines."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!sacct -j $jobid -s 'failed' | head"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### NCG Queue Length\n",
    "The queue holds the job packages in json files called 'queue messages' until the cluster is ready for the job. You can view how many messages are left on the queue with the 'queue_length' NCG property."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "print(\"jobs left on the queue: \", ncg.queue_length)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Reapply to the Cluster?\n",
    "Sometimes jobs fail to submit to the cluster, it is prudent to check the ncg.queue_length AFTER your squeue is empty."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!squeue -u $uid"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "print(\"jobs left on the queue: \", ncg.queue_length)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When reapplying a function to the cluster, you do not need to resubmit the function arguments, because those were already serialized into the queue message. However, the cluster submission arguments can be reformatted and the 'reapply' argument should be set to 'True'."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# njobs = ncg.apply('spatial.overlap.place_points_in_overlap', \n",
    "#                         chunksize=redis_orphans,\n",
    "#                         arraychunk=None,\n",
    "#                         walltime='00:20:00',\n",
    "#                         log_dir=ppio_log_dir,\n",
    "#                         reapply=True)\n",
    "# print(njobs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One advantage of using of a postgresql database for data storage is that it allows for storage of geometries. You can then use relational queries to view how different elements' geometries relate with one another."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from geoalchemy2 import functions\n",
    "from geoalchemy2.shape import to_shape\n",
    "\n",
    "with ncg.session_scope() as session:\n",
    "    results = (\n",
    "        session.query(\n",
    "        Overlay.id, \n",
    "        Overlay.geom.label('ogeom'), \n",
    "        Points.geom.label('pgeom')\n",
    "        )\n",
    "        .join(Points, functions.ST_Contains(Overlay.geom, Points.geom)=='True')\n",
    "        .filter(Overlay.id < 10) # Just view first 10 overlaps\n",
    "        .all()\n",
    "    )\n",
    "    print('number of points: ', len(results))\n",
    "    \n",
    "    fig, axs = plt.subplots(1, 1, figsize=(10,10))\n",
    "    axs.grid()\n",
    "    \n",
    "    oid = []\n",
    "    for res in results:\n",
    "        if res.id not in oid:\n",
    "            oid.append(res.id)\n",
    "            ogeom = to_shape(res.ogeom)\n",
    "            ox, oy = ogeom.envelope.boundary.xy\n",
    "            axs.plot(ox, oy, c='k')      \n",
    "        pgeom = to_shape(res.pgeom)\n",
    "        px, py = pgeom.xy\n",
    "        axs.scatter(px, py, c='grey')\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that the points are not in straight lines, this is because of the shifting place_points_in_overlap does to find interesting measure locations. \n",
    "\n",
    "However, the default distribution of points in the overlaps looks sparse, so let’s rerun place_points_in_overlap with new distribution kwargs. Before rerunning place_points_in_overlap, the points and measures tables need to be cleared using ncg's 'clear_db' method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with ncg.session_scope() as session:\n",
    "    npoints = session.query(Points).count()\n",
    "    print('number of points: ', npoints)\n",
    "    \n",
    "    nmeas = session.query(Measures).count()\n",
    "    print('number of measures: ', nmeas)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ncg.clear_db(tables=['points', 'measures']) # clear the 'points' and 'measures' database tables"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with ncg.session_scope() as session:\n",
    "    npoints = session.query(Points).count()\n",
    "    print('number of points: ', npoints)\n",
    "    \n",
    "    nmeas = session.query(Measures).count()\n",
    "    print('number of measures: ', nmeas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The distribution argument for place_points_in_overlap requires two **function** inputs. Since overlaps are variable shapes and sizes, one integer is not sufficient to determine effective gridding along every overlaps sides. Instead, the distribution of points along the N to S edge of the overlap and the E to W edge of the overlap are determined based on a function.  \n",
    "\n",
    "The default distribution functions are: <br />\n",
    "nspts_func=lambda x: ceil(round(x,1)\\*10) <br />\n",
    "ewpts_func=lambda x: ceil(round(x,1)\\*5) <br />\n",
    "\n",
    "Where x in nspts_func is the length of the overlap's longer edge (in km) and x in ewpts_func is the length of the overlap's shorter edge (in km). This way a shorter edge will receive less points and a longer side will receive more points. Change the multipliers in the 'ns' and 'ew' functions below to find a satisfying distribution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from autocnet.cg.cg import distribute_points_in_geom\n",
    "\n",
    "def ns(x):\n",
    "    from math import ceil\n",
    "    return ceil(round(x,1)*15)\n",
    "\n",
    "def ew(x):\n",
    "    from math import ceil\n",
    "    return ceil(round(x,1)*10)\n",
    "\n",
    "total=0\n",
    "with ncg.session_scope() as session:\n",
    "    srid = config['spatial']['latitudinal_srid']\n",
    "    overlaps = session.query(Overlay).filter(Overlay.geom.intersects(functions.ST_GeomFromText('LINESTRING(301.2 7.4, 303.7 7.4, 303.7 9.9, 301.2 9.9, 301.2 7.4)', srid))).all()\n",
    "    \n",
    "    print('overlaps in selected area: ', len(overlaps))\n",
    "    for overlap in overlaps:\n",
    "        ox, oy = overlap.geom.exterior.xy\n",
    "        plt.plot(ox,oy)\n",
    "        \n",
    "        valid = distribute_points_in_geom(overlap.geom, method='classic', nspts_func=ns, ewpts_func=ew, Session=session)\n",
    "        if valid:\n",
    "            total += len(valid)\n",
    "            px, py = list(zip(*valid))\n",
    "            plt.scatter(px, py, s=1)\n",
    "\n",
    "    print('  points in selected area: ', total)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then rerun the apply function, setting the 'distribute_points_kwargs' arguments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "distribute_points_kwargs = {'nspts_func':ns, 'ewpts_func':ew, 'method':'classic'}\n",
    "\n",
    "njobs = ncg.apply('spatial.overlap.place_points_in_overlap', \n",
    "                  on='overlaps', # start of function kwargs\n",
    "                  distribute_points_kwargs=distribute_points_kwargs, # NEW LINE\n",
    "                  cam_type='isis',\n",
    "                  walltime='00:30:00', # start of apply kwargs\n",
    "                  log_dir=ppio_log_dir,\n",
    "                  arraychunk=100)\n",
    "print(njobs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check the progress of your jobs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!squeue -u $uid | wc -l\n",
    "!squeue -u $uid | head"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Count the number of jobs started by looking for generated logs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "jobid = '' # put jobid int here\n",
    "! ls  $ppio_log_dir/*$jobid* | wc -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Monitor how many jobs have completed or failed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!sacct -j $jobid -s 'completed' | wc -l\n",
    "!sacct -j $jobid -s 'failed'    | wc -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check to see if the ncg redis queue is clear."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "redis_orphans = ncg.queue_length\n",
    "print(\"jobs left on the queue: \", redis_orphans)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reapply cluster job if there are still jobs left on the queue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# njobs = ncg.apply('spatial.overlap.place_points_in_overlap', \n",
    "#                         chunksize=redis_orphans,\n",
    "#                         arraychunk=None,\n",
    "#                         walltime='00:20:00',\n",
    "#                         log_dir=log_dir,\n",
    "#                         reapply=True)\n",
    "# print(njobs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Visualize the new distribution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "with ncg.session_scope() as session:\n",
    "    results = (\n",
    "        session.query(\n",
    "        Overlay.id, \n",
    "        Overlay.geom.label('ogeom'), \n",
    "        Points.geom.label('pgeom')\n",
    "        )\n",
    "        .join(Points, functions.ST_Contains(Overlay.geom, Points.geom)=='True')\n",
    "        .filter(Overlay.id < 10)\n",
    "        .all()\n",
    "    )\n",
    "    print('number of points: ', len(results))\n",
    "    \n",
    "    fig, axs = plt.subplots(1, 1, figsize=(10,10))\n",
    "    axs.grid()\n",
    "    \n",
    "    oid = []\n",
    "    for res in results:\n",
    "        if res.id not in oid:\n",
    "            oid.append(res.id)\n",
    "            ogeom = to_shape(res.ogeom)\n",
    "            ox, oy = ogeom.envelope.boundary.xy\n",
    "            axs.plot(ox, oy, c='k')      \n",
    "        pgeom = to_shape(res.pgeom)\n",
    "        px, py = pgeom.xy\n",
    "        axs.scatter(px, py, c='grey')\n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id=\"registration\"></a>\n",
    "# Subpixel Registration\n",
    "[Return To Top](#toc)\n",
    "\n",
    "The next step is to subpixel register the measures on the newly laid points, to do this we are going to use the 'subpixel_register_point' function. As the name suggests, 'subpixel_register_point' registers the measures on a single point, which makes it parallelizable on a network's points. Before we fire off the cluster jobs, let's create a new subpixel registration log directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "subpix_log_dir = default_log.replace('logs', 'subpix_logs')\n",
    "\n",
    "print('creating directory: ', subpix_log_dir)\n",
    "if not os.path.exists(subpix_log_dir):\n",
    "    os.mkdir(subpix_log_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## First Run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from autocnet.matcher.subpixel import subpixel_register_point\n",
    "\n",
    "?subpixel_register_point\n",
    "# ncg.apply?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "subpixel_template_kwargs = {'image_size':(81,81), 'template_size':(51,51)} \n",
    "\n",
    "njobs = ncg.apply('matcher.subpixel.subpixel_register_point', \n",
    "                  on='points', # start of function kwargs\n",
    "                  match_kwargs=subpixel_template_kwargs,\n",
    "                  geom_func='simple',\n",
    "                  match_func='classic',\n",
    "                  cost_func=lambda x,y:y,\n",
    "                  threshold=0.6, \n",
    "                  verbose=False,\n",
    "                  walltime=\"00:30:00\", # start of apply kwargs\n",
    "                  log_dir=subpix_log_dir,\n",
    "                  arraychunk=200,\n",
    "                  chunksize=20000) # maximum chunksize = 20,000\n",
    "\n",
    "print(njobs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check the progress of your jobs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!squeue -u $uid | head"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This function chooses a reference measure, affinely transforms the other images to the reference image, and clips an 'image' chip out of the reference image and a 'template' chip out of the transformed images. The template chips are marched across the image chip and the maximum correlation value and location is saved. \n",
    "\n",
    "The solution is then evaluated to see if the maximum correlation solution is acceptable. The evaluation is done using the 'cost_func' and 'threshold' arguments. The cost_func is dependent two independent variables, the first is the distance that a point has shifted from the starting location and the second is the correlation coefficient coming out of the template matcher. The __order__ that these variables are passed in __matters__. We are not going to consider the distance the measures were moved and just look at the maximum correlation value returned by the matcher. So, our function is simply: $y$.\n",
    "\n",
    "If the cost_func solution is greater than the threshold value, the registration is successful and the point is updated. If not, the registration is considered unsuccessful, the point is not updated, and is set to ignore.\n",
    "\n",
    "So, 'subpixel_register_point' requires the following arguments:\n",
    "- pointid\n",
    "- match_kwargs (image size, template size)\n",
    "- cost_func \n",
    "- threshold"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Count the number of jobs started by looking for generated logs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "jobid = '' # put jobid int here\n",
    "! ls $subpix_log_dir/*$jobid* | wc -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Monitor how many jobs have completed or failed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "!sacct -j $jobid -s 'completed' | wc -l\n",
    "!sacct -j $jobid -s 'failed'    | wc -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check to see if the ncg redis queue is clear once squeue is empty."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "redis_orphans = ncg.queue_length\n",
    "print(\"jobs left on the queue: \", redis_orphans)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reapply cluster job if there are still jobs left on the queue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# job_array = ncg.apply('matcher.subpixel.subpixel_register_point', \n",
    "#                       reapply=True,\n",
    "#                       chunksize=redis_orphans, \n",
    "#                       arraychunk=None,\n",
    "#                       walltime=\"00:30:00\",\n",
    "#                       log_dir=subpix1_log_dir)\n",
    "# print(job_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualize Point Registration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "from plio.io.io_gdal import GeoDataset\n",
    "from autocnet.transformation import roi\n",
    "from autocnet.utils.utils import bytescale\n",
    "\n",
    "roi_size = 25 \n",
    "\n",
    "with ncg.session_scope() as session:\n",
    "    measures = session.query(Measures).filter(Measures.template_metric < 0.8, Measures.template_metric!=1).limit(15)\n",
    "    for meas in measures:\n",
    "        pid = meas.pointid\n",
    "        source = session.query(Measures, Images).join(Images, Measures.imageid==Images.id).filter(Measures.pointid==pid, Measures.template_metric==1).all()\n",
    "        sx = source[0][0].sample\n",
    "        sy = source[0][0].line\n",
    "        s_roi = roi.Roi(GeoDataset(source[0][1].path), sx, sy, size_x=roi_size, size_y=roi_size)\n",
    "        s_image = bytescale(s_roi.clip())\n",
    "    \n",
    "        destination = session.query(Measures, Images).join(Images, Measures.imageid==Images.id).filter(Measures.pointid==pid, Measures.template_metric!=1).limit(1).all()\n",
    "        dx = destination[0][0].sample\n",
    "        dy = destination[0][0].line\n",
    "        d_roi = roi.Roi(GeoDataset(destination[0][1].path), dx, dy, size_x=roi_size, size_y=roi_size)\n",
    "        d_template = bytescale(d_roi.clip())\n",
    "\n",
    "        fig, axs = plt.subplots(1, 2, figsize=(10,10));\n",
    "        axs[0].imshow(s_image, cmap='Greys');\n",
    "        axs[0].scatter(image_size[0], image_size[1], c='r')\n",
    "        axs[0].set_title('Reference');\n",
    "        axs[1].imshow(d_template, cmap='Greys');\n",
    "        axs[1].scatter(image_size[0], image_size[1], c='r')\n",
    "        axs[1].set_title('Template');\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Second run\n",
    "We are going to rerun the subpixel registration with larger chips to attempt to register the measures that failed first run. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "subpixel_template_kwargs = {'image_size':(221,221), 'template_size':(81,81)} "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, 'subpixel_register_point' can be run on a subset of points, using either the 'filters' or the 'query_string' arguments. \n",
    "\n",
    "The 'filters' argument does a equals comparison on point properties and **filters out** points with a certain property value (e.g.: points where ignore=true). While the 'query_string' argument can perform inequalities and **applies on** the selected values. Some examples of possible filters and query_string values are"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "filters = {'ignore': 'true'} # filters out points where ignore=true\n",
    "query_string = \"\"\"\n",
    "        SELECT DISTINCT pointid FROM measures\n",
    "        WHERE \"templateMetric\" < 0.65\n",
    "        \"\"\" # only grabs points with template metrics less than 0.65"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "filters and query_string cannot be applied at the same time. So choose one, comment out the other argument's line and rerun the subpixel registration apply."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "njobs = ncg.apply('matcher.subpixel.subpixel_register_point', \n",
    "                  on='points', # start of function kwargs\n",
    "#                   filters=filters,  ##### NEW LINE\n",
    "                  query_string=query_string,\n",
    "                  match_kwargs=subpixel_template_kwargs,\n",
    "                  geom_func='simple',\n",
    "                  match_func='classic',\n",
    "                  cost_func=lambda x,y:y,\n",
    "                  threshold=0.6, \n",
    "                  verbose=False,\n",
    "                  walltime=\"00:30:00\", # start of apply kwargs\n",
    "                  log_dir=subpix_log_dir,\n",
    "                  arraychunk=50,\n",
    "                  chunksize=20000) # maximum chunksize = 20,000\n",
    "\n",
    "print(njobs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Subsequent runs of 'subpixel_register_point' can be run on all points, if this is done AutoCNet checks for a previous subpixel registration result in the database and only updates the geometry if the new result is better. Additionally, the apriori geometry (original camera pointing) is stored in the database and subpixel registration is always done on the apriori geometry to avoid 'measure walking'. 'Measure walking' refers to a measure's geometry moving further and further away from its original location due to multiple runs of subpixel registration. In traditional software the apriori geometry may be stored, but subpixel registration is typically run off of the current geometry."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Count the number of jobs started by looking for generated logs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "! squeue -u $uid | wc -l\n",
    "! squeue -u $uid | head"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Count the number of jobs started by looking for generated logs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "jobid = '' # put jobid int here\n",
    "\n",
    "! ls $log_dir/*$jobid* | wc -l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check to see if the ncg redis queue is clear once squeue is empty."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "redis_orphans = ncg.queue_length\n",
    "print(\"jobs left on the queue: \", redis_orphans)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reapply cluster job if there are still jobs left on the queue."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# njobs = ncg.apply('matcher.subpixel.subpixel_register_point', \n",
    "#                   reapply = True,\n",
    "#                   walltime=\"00:30:00\",\n",
    "#                   log_dir='/scratch/ladoramkershner/mars_quads/oxia_palus/subpix2_logs/',\n",
    "#                   arraychunk=50,\n",
    "#                   chunksize=20000) # maximum chunksize = 20,000\n",
    "\n",
    "# print(njobs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### subpix2: Write out Network\n",
    "Once you are finished leverage AutoCNet tools and want to move onto ISIS based analysis (qnet, jigsaw, etc.), you can use the ncg.to_isis() function to write the information in your database to an ISIS control network file. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "cnet = 'reiner_gamma_morning_ns7_ew5_t121x61_t221x81.net'\n",
    "ncg.to_isis(os.path.join(output_directory,cnet))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "AutoCNet PLIO (workshop)",
   "language": "python",
   "name": "autocnet_workshop"
  },
  "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.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
