{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Find Sine delay in Beacon"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import signal\n",
    "\n",
    "\n",
    "import os\n",
    "import sys\n",
    "# Append parent directory to import path so lib can be found\n",
    "sys.path.append(os.path.dirname(os.path.abspath(os.getcwd())))\n",
    "from lib.util import *\n",
    "\n",
    "from lib.timing import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "us = 1e3 # ns\n",
    "ns = 1/us # us\n",
    "\n",
    "samplerate = 500 # MHz\n",
    "timelength = 0.2 # us\n",
    "\n",
    "\n",
    "beacon_time = np.arange(0, timelength, 1/samplerate)\n",
    "f_beacon = 70 # MHz\n",
    "\n",
    "\n",
    "beacon_init_phase = phase2time(42/ns, f_beacon)\n",
    "beacon_phase_offset = 1.2*np.pi\n",
    "\n",
    "beacons = np.array([\n",
    "    sin_delay(f_beacon, beacon_time, phase=-beacon_init_phase),\n",
    "    sin_delay(f_beacon, beacon_time, phase=-beacon_init_phase-beacon_phase_offset)\n",
    "])\n",
    "\n",
    "ref_time = np.arange(0, 1/f_beacon, 1/samplerate)\n",
    "ref_beacon = sin_delay(f_beacon, ref_time, t_delay=0, phase=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Reference Delay"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cheat Time Delay [ns]: 2.8311078050095477 \\pm [0. 0.]\n",
      "Calculated Time Delay [ns]: 2.857142857142857 \\pm [-1.  1.]\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 58432 characters]\n",
      "text/plain": [
       "<Figure size 1152x288 with 3 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "show_originals = True\n",
    "\n",
    "\n",
    "fig, axes = plt.subplots(3,1, sharex=True, figsize=(16,4))\n",
    "axes[0].set_title(\"Determine phase delay of a single beacon\")\n",
    "axes[-1].set_xlabel(\"Time [ns]\")\n",
    "\n",
    "## Originals\n",
    "i=0\n",
    "axes[i].set_ylabel(\"Originals\")\n",
    "axes[i].plot(beacon_time/ns, \n",
    "             np.pad(ref_beacon, (0,len(beacons[0])-len(ref_beacon)), 'constant', constant_values=0), \n",
    "             label=\"Reference\",\n",
    "             color='g')\n",
    "axes[i].plot(beacon_time/ns, \n",
    "             beacons[0], \n",
    "             label=\"Beacon 0\",\n",
    "             color='r'\n",
    "            )\n",
    "axes[i].legend(loc='center right')\n",
    "\n",
    "for i in range(1, 3):    \n",
    "    if i == 1:\n",
    "        label = \"Cheat\"\n",
    "        time_delay = phase2time(phase_modulo(beacon_init_phase,0), f_beacon)\n",
    "        time_delay_err = np.array([0,0])\n",
    "\n",
    "        \n",
    "    ## Calculated\n",
    "    else:\n",
    "        label = \"Calculated\"\n",
    "        phase_delay, phase_err = beacon_phase_delay(samplerate, f_beacon, ref_beacon, beacons[0])\n",
    "        time_delay = phase2time(phase_modulo(phase_delay, 0), f_beacon)\n",
    "        time_delay_err = phase2time(phase_err, f_beacon)\n",
    "    \n",
    "    axes[i].set_ylabel(label)\n",
    "    print(\"{} Time Delay [ns]: {} \\pm {}\".format(label, time_delay/ns, time_delay_err/ns))\n",
    "\n",
    "    ### Show original\n",
    "    if show_originals:\n",
    "        axes[i].plot(beacon_time/ns, \n",
    "                     beacons[0],\n",
    "                     color='r', alpha=0.4\n",
    "                    )\n",
    "\n",
    "    axes[i].axvline(time_delay/ns)\n",
    "    axes[i].plot(beacon_time/ns,\n",
    "                 sin_delay(f_beacon, beacon_time, t_delay=time_delay),\n",
    "                 ls = (4, (10, 4)),\n",
    "                 label='sin')\n",
    "    axes[i].plot((ref_time+time_delay)/ns,\n",
    "                 ref_beacon,\n",
    "                 ls = (6, (10, 4)),\n",
    "                 label='roll')\n",
    "    axes[i].legend(loc='center right')\n",
    "\n",
    "axes[0].set_xlim(0, 30)\n",
    "fig.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Determine delay between beacons"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 58916 characters]\n",
      "text/plain": [
       "<Figure size 1152x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "abs_time_delay, time_delay_err = beacon_time_delay(samplerate, beacons[0], beacons[1])\n",
    "time_delay = abs_time_delay % (1/f_beacon)\n",
    "\n",
    "\n",
    "fig, axes = plt.subplots(2, sharex=True, figsize=(16,4))\n",
    "axes[-1].set_xlabel(\"Time [ns]\")\n",
    "axes[0].set_title(\"Time Delay between two Beacons[ns]: {} \\pm {}\".format(time_delay/ns, time_delay_err/ns))\n",
    "\n",
    "\n",
    "## Originals\n",
    "i=0\n",
    "axes[i].set_ylabel(\"Originals\")\n",
    "axes[i].plot(beacon_time/ns, \n",
    "             beacons[0], \n",
    "             label=\"Beacon 0\",\n",
    "             color='g')\n",
    "axes[i].plot(beacon_time/ns, \n",
    "             beacons[1], \n",
    "             label=\"Beacon 1\",\n",
    "             color='r'\n",
    "            )\n",
    "axes[i].axvline(0, color='g', alpha=0.3)\n",
    "axes[i].axvline(time_delay/ns, color='r', alpha=0.3)\n",
    "\n",
    "## Correct Beacon 1\n",
    "i=1\n",
    "axes[i].set_ylabel(\"Corrected Beacon 1\")\n",
    "axes[i].plot(beacon_time/ns, \n",
    "             beacons[0], \n",
    "             #label=\"Beacon 0\",\n",
    "             color='g',\n",
    "            )\n",
    "axes[i].plot((beacon_time-time_delay)/ns,\n",
    "             beacons[1],\n",
    "             ls = (6, (10, 4)),\n",
    "             color='orange',\n",
    "             label='Corrected Beacon 1'\n",
    "            )\n",
    "\n",
    "axes[0].set_xlim(0, 30)\n",
    "# put legend between plots\n",
    "lines_labels = [ax.get_legend_handles_labels() for ax in fig.axes]\n",
    "lines, labels = [sum(lol, []) for lol in zip(*lines_labels)]\n",
    "\n",
    "fig.subplots_adjust(hspace=0.3)\n",
    "fig.legend(lines, labels ,loc='right', ncol=3, bbox_to_anchor=(0.55, 0.51))\n",
    "fig.show()"
   ]
  }
 ],
 "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.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
