{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Emitter/Receiver Simulation with Signals"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import matplotlib.pyplot as plt\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())))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Signal"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 39460 characters]\n",
      "text/plain": [
       "<Figure size 1152x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from lib import TravelSignal\n",
    "\n",
    "####\n",
    "from scipy.stats import norm\n",
    "\n",
    "sample_rate = 3e2 # Hz\n",
    "interp_sample_rate = sample_rate * 1/10 # Hz\n",
    "\n",
    "t_offset = 8\n",
    "periodic = False\n",
    "\n",
    "time   = t_offset + np.arange(0, 1, 1/sample_rate) #s\n",
    "time2  = t_offset + np.arange(-1.5, 1, 1/sample_rate) #s\n",
    "\n",
    "signal = norm.pdf(time, time[len(time)//2], (time[-1] - time[0])/10)\n",
    "\n",
    "if True:\n",
    "    mysignal = TravelSignal(signal, sample_rate, t_0 = t_offset, periodic=True)\n",
    "    mysignal2 = TravelSignal(signal, sample_rate, t_0 = t_offset, periodic=False)\n",
    "\n",
    "    fig, ax = plt.subplots(1, 1, figsize=(16,4))\n",
    "    ax.set_title(\"Raw and TravelSignal\")\n",
    "    ax.set_ylabel(\"Amplitude\")\n",
    "    ax.set_xlabel(\"Time\")\n",
    "\n",
    "    ax.plot(time,   signal,                    label='Raw signal')\n",
    "    ax.plot(time2,  mysignal(time2)+0.5,     '.-',     label='TravelSignal(periodic)+0.5')\n",
    "    ax.plot(time2,  mysignal2(time2)-0.5,     '.-',     label='TravelSignal-0.5')\n",
    "\n",
    "    ax.legend()\n",
    "\n",
    "    plt.show();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## New code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from lib.location import Receiver, Emitter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Testing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "if True:\n",
    "    sample_rate = 3e2 # Hz\n",
    "    periodic = False\n",
    "    \n",
    "    t_offset = -0.5\n",
    "    t_start = 0\n",
    "    t_end = 1\n",
    "    time   = t_offset + np.arange(t_start, t_end, 1/sample_rate) #s\n",
    "\n",
    "if False:\n",
    "    if True:\n",
    "        periodic = True\n",
    "        freq = sample_rate/8\n",
    "        signal = np.cos(2*np.pi*freq*time)\n",
    "    else: \n",
    "        from scipy.stats import norm\n",
    "        signal = norm.pdf(time, time[len(time)//2], (time[-1] - time[0])/10)\n",
    "\n",
    "\n",
    "#####\n",
    "# Setup Signal, Emitter and Antennae\n",
    "\n",
    "rot = lambda phi=0.12345: np.cos(np.array([phi, phi-np.pi/2]))\n",
    "\n",
    "km=1e7\n",
    "\n",
    "mysignal = TravelSignal(signal, sample_rate, t_0 = t_offset, periodic=periodic)\n",
    "\n",
    "source = Emitter([0,0,9])*km\n",
    "emitted = source.emit(mysignal)\n",
    "\n",
    "antennae = [\n",
    "    Receiver((*2*km*rot(0),8)),\n",
    "    Receiver((*3*km*rot(2), 4)),\n",
    "    Receiver((*10*km*rot(1), 7)),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 7228 characters]\n",
      "text/plain": [
       "<Figure size 144x144 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "########\n",
    "### Geometry Plot\n",
    "########\n",
    "ylabel_kw = {\"rotation\": \"horizontal\", \"va\":\"center\", \"ha\":\"center\", \"labelpad\": 30}\n",
    "\n",
    "fig, axs = plt.subplots(1,1, figsize=(2,2))\n",
    "axs = [ axs ]\n",
    "i = 0\n",
    "axs[i].grid()\n",
    "axs[i].set_title(\"Geometry of Emitter(s) and Antennae\")\n",
    "axs[i].set_ylabel(\"y (m)\", **ylabel_kw)\n",
    "axs[i].set_xlabel(\"x (m)\")\n",
    "axs[i].plot(*source.x, '*', label=\"Emitter\")\n",
    "\n",
    "for j, ant in enumerate(antennae):\n",
    "    axs[i].plot(*ant.x, '+', label=\"Antenna {}\".format(j))\n",
    "\n",
    "# make it a square plot\n",
    "axs[i].set_aspect('equal', 'datalim')\n",
    "axs[i].margins(0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 49764 characters]\n",
      "text/plain": [
       "<Figure size 864x432 with 4 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "t_longoffset = t_offset\n",
    "t_longstart = t_start\n",
    "t_longend = 2*t_end\n",
    "longtime = t_longoffset + np.arange(t_longstart, t_longend, 1/sample_rate) #s\n",
    "\n",
    "########\n",
    "### Plot Traces\n",
    "########\n",
    "\n",
    "fig, axs = plt.subplots(1+len(antennae),1, sharex=True, figsize=(12,6), gridspec_kw={\"hspace\":0})\n",
    "axs[0].set_title(\"Traces of Emitter and Antennae\")\n",
    "\n",
    "# Emitter\n",
    "i = 0\n",
    "axs[i].set_ylabel(\"Emitter\\n at ({})\".format(source.x), **ylabel_kw)\n",
    "axs[i].set_xlabel(\"Time (s)\")\n",
    "axs[i].plot(time, emitted(time))\n",
    "axs[i].plot(longtime, emitted(longtime))\n",
    "\n",
    "# Antenna\n",
    "for j, ant in enumerate(antennae):\n",
    "    i +=1\n",
    "    axs[i].set_ylabel(\"Antenna {}\\n at ({})\".format(j, ant.x), **ylabel_kw)\n",
    "    axs[i].plot(longtime, ant.recv(emitted)(longtime), label=\"Antenna {}\".format(j))\n",
    "    axs[i].set_xlabel(\"Time (s)\")\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 29020 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from lib.sampling import Digitizer\n",
    "\n",
    "digit = Digitizer(sampling_frequency=1e1, resolution=0.5)\n",
    "\n",
    "analog_samples = int(1e3)\n",
    "analog_time = np.linspace(0, 10, analog_samples)\n",
    "analog_signal = lambda t: np.cos(-t**2/6)\n",
    "\n",
    "sample_time = digit.sample(analog_time, analog_samples)\n",
    "quantised_signal = digit.digitise(analog_signal(sample_time))\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.set_xlabel(\"Time\")\n",
    "ax.set_ylabel(\"Amplitude\")\n",
    "ax.set_title(\"Digitised signals\")\n",
    "\n",
    "ax.plot(analog_time, analog_signal(analog_time), 'y', label='Analog')\n",
    "ax.plot(sample_time, quantised_signal)\n",
    "ax.scatter(sample_time, quantised_signal)\n",
    "\n",
    "plt.show();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Combination Antennae and Digitizers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 43516 characters]\n",
      "text/plain": [
       "<Figure size 864x432 with 4 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "digit = Digitizer(sampling_frequency=1e1, resolution=0.5)\n",
    "\n",
    "########\n",
    "### Plot Traces\n",
    "########\n",
    "\n",
    "fig, axs = plt.subplots(1+len(antennae),1, sharex=True, figsize=(12,6), gridspec_kw={\"hspace\":0})\n",
    "axs[0].set_title(\"Traces of Emitter and Antennae (digitised)\")\n",
    "\n",
    "# Emitter\n",
    "i = 0\n",
    "axs[i].set_ylabel(\"Emitter\\n at ({})\".format(source.x), **ylabel_kw)\n",
    "axs[i].set_xlabel(\"Time (s)\")\n",
    "axs[i].plot(time, digit.digitise(emitted(time)))\n",
    "axs[i].plot(longtime, emitted(longtime))\n",
    "\n",
    "# Antenna\n",
    "for j, ant in enumerate(antennae):\n",
    "    i +=1\n",
    "    axs[i].set_ylabel(\"Antenna {}\\n at ({})\".format(j, ant.x), **ylabel_kw)\n",
    "    axs[i].plot(longtime, digit.digitise(ant.recv(emitted)(longtime)), label=\"Digitised Antenna {}\".format(j))\n",
    "    axs[i].set_xlabel(\"Time (s)\")\n",
    "    "
   ]
  }
 ],
 "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
}
