m-thesis-introduction/simulations/05_grid_search_and_timing_error.ipynb

513 lines
217 KiB
Text
Raw Normal View History

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Perform a grid search to find the timing error"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"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",
"\n",
"import numpy as np\n",
"rng = np.random.default_rng(12345)\n",
"\n",
"import matplotlib.pyplot as plt\n",
2022-07-11 11:20:03 +02:00
"from scipy import signal\n",
"import copy\n",
"\n",
"from lib.signals import DigitisedSignal\n",
"import lib.util as util\n",
"\n",
"\n",
"km = 1e3\n",
"ns = 1e9\n",
"\n",
"# monkey patch correlation_lags into signal if it does not exist\n",
2022-07-11 11:20:03 +02:00
"if not hasattr(signal, 'correlation_lags'):\n",
" def correlation_lags(in1_len, in2_len, mode='full'):\n",
" r\"\"\"\n",
" Calculates the lag / displacement indices array for 1D cross-correlation.\n",
" Parameters\n",
" ----------\n",
" in1_size : int\n",
" First input size.\n",
" in2_size : int\n",
" Second input size.\n",
" mode : str {'full', 'valid', 'same'}, optional\n",
" A string indicating the size of the output.\n",
" See the documentation `correlate` for more information.\n",
" See Also\n",
" --------\n",
" correlate : Compute the N-dimensional cross-correlation.\n",
" Returns\n",
" -------\n",
" lags : array\n",
" Returns an array containing cross-correlation lag/displacement indices.\n",
" Indices can be indexed with the np.argmax of the correlation to return\n",
" the lag/displacement.\n",
" Notes\n",
" -----\n",
" Cross-correlation for continuous functions :math:`f` and :math:`g` is\n",
" defined as:\n",
" .. math::\n",
" \\left ( f\\star g \\right )\\left ( \\tau \\right )\n",
" \\triangleq \\int_{t_0}^{t_0 +T}\n",
" \\overline{f\\left ( t \\right )}g\\left ( t+\\tau \\right )dt\n",
" Where :math:`\\tau` is defined as the displacement, also known as the lag.\n",
" Cross correlation for discrete functions :math:`f` and :math:`g` is\n",
" defined as:\n",
" .. math::\n",
" \\left ( f\\star g \\right )\\left [ n \\right ]\n",
" \\triangleq \\sum_{-\\infty}^{\\infty}\n",
" \\overline{f\\left [ m \\right ]}g\\left [ m+n \\right ]\n",
" Where :math:`n` is the lag.\n",
" Examples\n",
" --------\n",
" Cross-correlation of a signal with its time-delayed self.\n",
" >>> from scipy import signal\n",
" >>> from numpy.random import default_rng\n",
" >>> rng = default_rng()\n",
" >>> x = rng.standard_normal(1000)\n",
" >>> y = np.concatenate([rng.standard_normal(100), x])\n",
" >>> correlation = signal.correlate(x, y, mode=\"full\")\n",
" >>> lags = signal.correlation_lags(x.size, y.size, mode=\"full\")\n",
" >>> lag = lags[np.argmax(correlation)]\n",
" \"\"\"\n",
"\n",
" # calculate lag ranges in different modes of operation\n",
" if mode == \"full\":\n",
" # the output is the full discrete linear convolution\n",
" # of the inputs. (Default)\n",
" lags = np.arange(-in2_len + 1, in1_len)\n",
" elif mode == \"same\":\n",
" # the output is the same size as `in1`, centered\n",
" # with respect to the 'full' output.\n",
" # calculate the full output\n",
" lags = np.arange(-in2_len + 1, in1_len)\n",
" # determine the midpoint in the full output\n",
" mid = lags.size // 2\n",
" # determine lag_bound to be used with respect\n",
" # to the midpoint\n",
" lag_bound = in1_len // 2\n",
" # calculate lag ranges for even and odd scenarios\n",
" if in1_len % 2 == 0:\n",
" lags = lags[(mid-lag_bound):(mid+lag_bound)]\n",
" else:\n",
" lags = lags[(mid-lag_bound):(mid+lag_bound)+1]\n",
" elif mode == \"valid\":\n",
" # the output consists only of those elements that do not\n",
" # rely on the zero-padding. In 'valid' mode, either `in1` or `in2`\n",
" # must be at least as large as the other in every dimension.\n",
"\n",
" # the lag_bound will be either negative or positive\n",
" # this let's us infer how to present the lag range\n",
" lag_bound = in1_len - in2_len\n",
" if lag_bound >= 0:\n",
" lags = np.arange(lag_bound + 1)\n",
" else:\n",
" lags = np.arange(lag_bound, 1)\n",
" return lags\n",
"\n",
2022-07-11 11:20:03 +02:00
" signal.correlation_lags = correlation_lags"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYoAAAEWCAYAAAB42tAoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAACVuklEQVR4nOyddZhc1d2A3zPu6xt3IQLxBHd3t1IopYWihQqFflSoQFugghWKFSheiru7xggRQhJim2yS1XGf8/1x7/id2dnI7rK57/PsMztXzpx7Z/f87s+FlBIdHR0dHZ1SGHp7Ajo6Ojo6fRtdUOjo6OjolEUXFDo6Ojo6ZdEFhY6Ojo5OWXRBoaOjo6NTFl1Q6Ojo6OiURRcUOjo6Ojpl0QWFTr9ECLFGCHFIL8/BKoS4VwixVgjhF0IsEEIcmbN/pBBCCiECOT+/LjPeSCHES0KIDiHEJiHEbUIIU89cjc7OjP5HpqOz4zAB64H9gXXAUcATQojdpJRrco6rllImKhjvn8AWYBBQDbwOXAzcsh3nrKNThK5R6OxUCCFqhBAvCCFa1CfzF4QQQ3P2jxJCvKdqAG8IIW4XQjy0NZ8lpQxKKa+VUq6RUqaklC8Aq4GZWzn9UcATUsqIlHIT8AowWetAIcS5QogPhBA3qde5ukCbOVcI8Y16nauFEGdt5Zx0dgJ0QaGzs2EA/g2MAIYDYeC2nP2PAJ8BdcC1wNm5JwshFgkhvrM1HyyEGACMB5YU7ForhGgSQvxbCFFfZoibgTOEEA4hxBDgSBRhUYrdgeVAPXADcK9QcKJoIUdKKd3AXsDCrbkmnZ0DXVDo7FRIKduklP+TUoaklH7gOhTTEEKI4cBs4DdSypiU8gPguYLzp0gpH+nu5wohzMDDwANSyq/Uza3q541A0TLc6jGleBdFg/ABTcBc4Jkyx6+VUt4tpUwCD6CYrAao+1LArkIIu5SyWUpZKLx0dDLogkJnp0J9Gv+X6mD2Ae8B1UIIIz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o0aNyvgKpJR88cUXAOyxxx7873//A+Cxxx7LnD9ixAiWLl1KNBrF6/Xy5pvFgSM+nw+n00lVVRWbN2/m5Zdf3iHXogsKne4TaAFnI7gHZN9vJaFYgsuP+glrTj+XuT+5loN/8E9iiVTXJ37bCHfCw6fB8le6f+7GhfDgCVmTH/DBilbOue8z2oPdF6yfXPJ/fHbwSchUP7zPfYzp06czdepUHnvsMR5++GHuvfdepk6dyuTJk3n2WSW0/B//+Ad/+9vfmDNnDs3NzVRVVQEwbNgwTjvtNKZMmcJZZ53F9OnTi8afOnUq06dPZ/LkyZx33nnsvffeO+Q69FpPOt0nuEXRKBx1yvvQ1ifKtfqVha7eZSGiCojOUIxGj22bp9mnWPgIrHgVWr+GXY7o3rnv3QjfvA2f3QNHXA/AnQ+9wwcRG09/tJIfHDqp4qFCHV72+OefAPj6pXcYf8xB3ZuLTpcEAvk+u+effz7z+yuvFD8oDBkyhE8++QQhBI899hizZs3K7Lvhhhu44YYbis555513Mr9rRUIBrFmzpnsTL4MuKHS6T7AF6saC1QMG0zYJitD7H7Dg5jNZM+lBAhY7dz31R/wnDKFxj2nbb759gXUfK6+dayEWBEuFtmMpoUlNrGr6DICIL8D9fzgdk0yx4M0D4NDKQ4qXfbWe1JBJzN6wlPY33gVdUPQ68+bN49JLL0VKSXV1Nffdd19vT6kI3fSk0z2kVE1PDSCEolVsg6AIr99ITcSPq76GmmSEw1Z8Qnjlmu03375C2mwkU9CyvPLzgi0QUB38W5aBlGxasBSTVLSvhjUrujWNBQkHp571F9rsHgxLtj0HRmfb2Xffffniiy9YtGgR7733HmPHju3tKRW
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Setup signal\n",
"########################\n",
"\n",
"signal_t_length = 200e-9\n",
"signal_sample_rate = 5e9 # Hz\n",
"signal_time = util.sampled_time(\n",
" sample_rate=signal_sample_rate,\n",
" start=0,\n",
" end=signal_t_length\n",
")\n",
"double_signal_time = np.concatenate((signal_time, signal_time[-1] + signal_time)) \\\n",
" - (signal_time[-1] - signal_time[0])/2\n",
"\n",
"fc = 50e6# MHz\n",
"\n",
"if True:\n",
"\n",
" shift = -25.8e-9\n",
" signal_pulse1_center = 125e-9 # 100 ns\n",
" \n",
" if not True:\n",
2022-07-11 11:20:03 +02:00
" signal_1 = DigitisedSignal(signal.gausspulse(signal_time - signal_pulse1_center, fc=fc),\n",
" signal_sample_rate)\n",
2022-07-11 11:20:03 +02:00
" signal_2 = DigitisedSignal(signal.gausspulse(signal_time - signal_pulse1_center, fc=fc), \n",
" signal_sample_rate)\n",
" signal_2.t_0 = shift\n",
" else:\n",
" signal_1 = DigitisedSignal(np.sin(2*np.pi*(signal_time)*fc/5.4) + np.sin(2*np.pi*(signal_time)*fc),\n",
" signal_sample_rate)\n",
"\n",
" signal_2 = copy.copy(signal_1)\n",
" signal_2.t_0 = shift\n",
" \n",
" signal_1.periodic = False\n",
" signal_2.periodic = False\n",
" del signal_pulse1_center\n",
"\n",
"\n",
"del fc, signal_t_length, signal_sample_rate\n",
"\n",
"\n",
"# Pre calculated values\n",
"sig_1 = signal_1(double_signal_time)\n",
"sig_2 = signal_2(double_signal_time)\n",
"\n",
"\n",
"if True:\n",
" fig, ax = plt.subplots()\n",
" ax.plot(double_signal_time * ns, sig_1, label='Regular')\n",
" ax.plot((double_signal_time) * ns, sig_2, label=\"Shifted\")\n",
" ax.plot((double_signal_time) * ns, signal_2(double_signal_time + shift), 'r--', label=\"Cheat\")\n",
" ax.set_xlabel(\"Time (ns)\")\n",
" ax.set_ylabel(\"Amplitude\")\n",
" ax.set_title(\"Lag: {:.4g} ns\".format(shift*ns))\n",
" plt.legend()\n",
" plt.show()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAYoAAAEWCAYAAAB42tAoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGli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fAihUrOOKII5g6dSozZ87kiy++yG3fe++92XPPPfnVr36Fx+MB4K233uKYY47JjXXJJZdw7733ll3jhz/8IdOmTWPs2LH8+te/zm0fPnw4v/3tb9lvv/14/PHHt+Fd6rPdnNlq4/i7gCVq+0wtnkPpG/woihO726jJ3wdoX6F8Nu4GHSu3eDjzl0uJWWy0e2oxrV61xeMZ7Fhc+/wiFq8vNTZsGXsM9PHrY8dWdWw6neb111/n+9//PgDnn38+t99+O2PGjOGjjz7ioosu4o033uDyyy/n8ssv58wzz+T222/vYdRy/vCHP1BXV0c6nebggw/m888/Z8KECYCS+/Dee+9t8phbi+2pUewLnA0cJISYr/4cJYS4UAhxoXrMbOArYDlKf+WLttNcDQrp+Er5HD4TYl0QD23RcM6vV7GxcRCtDQNxNeu1vjYw6F2i0SiTJk2ivr6ejo4ODj30UEKhEO+//z6nnnoqkyZN4oILLqC5WXl3/eCDDzj11FMBOOusszb5eo899hhTpkxh8uTJLFq0iMWL8wGgp59++ta5qc1ku2kUUsr30PZBFB4jgYt7Z0YGVRNYD8IMg/eEOf9WTFGNu272cK7ONiIN/QjWNDLkc8P0ZFBMtW/+W5usj6K7u5tjjjmGW2+9lXPOOQe/38/8+fOrHsdisZDJZHLftXIYVq5cyQ033MCcOXOora3lnHPOKTrO7XZv0b1sKdvdmW3wDSS8EdwN4FfdR91rKh/fA+02N4F
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"## Using scipy\n",
"\n",
"if True:\n",
2022-07-11 11:20:03 +02:00
" scipy_corr = signal.correlate(sig_1, sig_2, mode='same')\n",
" scipy_id = scipy_corr.argmax()\n",
" calc_shift = ((len(scipy_corr)-1)/2 -scipy_id)/signal_1.sample_rate\n",
"\n",
" if not True:\n",
" signal_2.periodic = True\n",
"\n",
" fig, ax = plt.subplots()\n",
" ax.plot(double_signal_time * ns, sig_1, label='Regular')\n",
" ax.plot((double_signal_time) * ns, sig_2, label=\"Shifted\")\n",
" ax.plot((double_signal_time) * ns, signal_2(double_signal_time + calc_shift), 'r--', label='Recovered')\n",
" ax.set_xlabel(\"Time (ns)\")\n",
" ax.set_ylabel(\"Correlation\")\n",
" ax.set_title(\"Calculated Lag: {:.4g} ns\".format(calc_shift*ns))\n",
" ax.legend()\n",
" plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## new code"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"def lag_gridsearch(grid, sample_rate, signal_data, reference):\n",
" \"\"\"\n",
" Return the best time shift found when doing a grid search.\n",
" \n",
" Parameters\n",
" ----------\n",
" lag_grid - ndarray\n",
" The array specifying the grid that is to be searched.\n",
" sample_rate - float\n",
" Sample rate of signal_data to transform index to time.\n",
" signal_data - ndarray\n",
" The real signal to find the time shift for.\n",
" reference - ndarray\n",
" Real signal to use as reference to obtain lag.\n",
" \n",
" Returns\n",
" -------\n",
" lag : ndarray\n",
" The best time shift obtained\n",
" err : tuple\n",
" Difference to the previous and next time shift from lag, resp.\n",
" \"\"\"\n",
"\n",
" assert signal_data.shape == reference.shape\n",
" \n",
" corrs = grid_correlate(grid, signal_data, reference)\n",
" \n",
" idx = np.argmax(corrs)\n",
" \n",
" lag = grid[idx]/sample_rate\n",
" \n",
" err_min = (grid[idx-1]-grid[idx])/(2*sample_rate)\n",
" err_plus = (grid[idx+1]-grid[idx])/(2*sample_rate)\n",
"\n",
" return lag, (err_min, err_plus)\n",
" \n",
"\n",
"def grid_correlate(grid, x, reference):\n",
" \"\"\"\n",
" Determine correlation between x and reference using grid as \n",
" the lags to be used for the correlation.\n",
" \n",
" Parameters\n",
" ----------\n",
" grid - ndarray\n",
" The array specifying the grid that is to be searched.\n",
" x - ndarray\n",
" The real signal to find the time shift for.\n",
" reference - ndarray\n",
" Real signal to use as reference to obtain lag.\n",
" \n",
" Returns\n",
" -------\n",
" corrs - ndarray\n",
" The correlations along grid.\n",
" \"\"\"\n",
" grid = np.asarray(grid)\n",
" x = np.asarray(x)\n",
" reference = np.asarray(reference)\n",
"\n",
" assert x.shape == reference.shape\n",
" \n",
" ref_conj = np.conjugate(reference)\n",
" \n",
" corrs = np.array([np.dot(np.roll(ref_conj, lag), x) for lag in grid], dtype=np.float64)\n",
" \n",
" return corrs\n",
"\n",
"def correlation_grid(grid_size=None, in1_len=None, in2_len = None, end = None, start=None, mode='full'):\n",
" \"\"\"\n",
" Abuse correlation_lags to determine the endpoints of the grid.\n",
" \"\"\"\n",
" \n",
" if in1_len is not None or in2_len is not None:\n",
" if in2_len is None:\n",
" in2_len = in1_len\n",
" elif in1_len is None:\n",
" in1_len = in2_len\n",
"\n",
2022-07-11 11:20:03 +02:00
" lags = signal.correlation_lags(in1_len, in2_len, mode=mode)\n",
"\n",
" max_lag = max(lags)\n",
" min_lag = min(lags)\n",
" else:\n",
" max_lag = np.inf\n",
" min_lag = -np.inf\n",
"\n",
" if end is None:\n",
" end = max_lag\n",
" elif end > max_lag:\n",
" raise ValueError(\"Grid end is too high\")\n",
"\n",
" if start is None:\n",
" start = min_lag\n",
" elif start < min_lag:\n",
" raise ValueError(\"Grid start is too low\")\n",
"\n",
" return np.linspace(start, end, grid_size, dtype=int, endpoint=False)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAX8AAAEWCAYAAACOv5f1AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAABw30lEQVR4nO29d5xcZ33v//6e6X22qndLcpdsycaUxKabEgw3BbhgauJLaMnNDQEC4TokpHBDgDT4ATEloSUQMBBMMcG02NiSu2XLlq22Ktun95nn98c5Z3fKmSLtrnZX+7xfL700+5zzzHx3duZznvN9vkWUUmg0Go1mZWEstgEajUajOfdo8ddoNJ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lL3sZu3btYtOmTezdu5dYLNZ13mc/+1ne9KY3EQwGeeELX+h4zvXXX8/999/P3r178Xq9vPjFL+Yv/uIv+PznP89b3vIWcrkcW7du5bOf/WzX1/N6vXzta1/jne98J8lkkkqlwu///u9zySWzd0vxeJzf+Z3f4bLLLmPz5s1cddVVM8fe8IY38Ja3vIVAINBw97BmzRr+8i//kmc/+9kopXjxi1/MDTfc0NWes0Yp1fM/YDPwcN3P/w94j/X4PcCHrceXAA8APmAL8BTgso7dA1yDeRdwG/DiXl57z549SqOZC//9mT9Q1Q/EVLlUVNkPDKk7/+l/LbZJS4oDBw4stgkqnU4rpZTKZrNqz549av/+/Yts0fLC6W8I7FMOmtrzyl9
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"ids 872 871\n",
"ts -2.58e-08 -2.58e-08 =: -2.58e-08\n",
"avail ts -2e-07 - 1.996e-07 : 1.9979999999999997e-10\n",
"grid size 2000 2000 2000\n"
]
}
],
"source": [
"#################\n",
"\n",
"grid_size = 2000\n",
"my_mode = 'same'\n",
"grid = correlation_grid(grid_size, in1_len=len(sig_1), in2_len=len(sig_2), mode=my_mode)\n",
"t_grid = grid/signal_1.sample_rate\n",
"\n",
"scipy_mode = my_mode\n",
2022-07-11 11:20:03 +02:00
"scipy_corr = signal.correlate(sig_2, sig_1, mode=scipy_mode)\n",
"scipy_lags = signal.correlation_lags(len(sig_2), len(sig_1), mode=scipy_mode)\n",
"corrs = grid_correlate(grid, sig_2, sig_1)\n",
" \n",
"\n",
"scipy_id = np.argmax(scipy_corr)\n",
"my_id = np.argmax(corrs)\n",
"\n",
"\n",
"fig, ax = plt.subplots()\n",
"ax.set_title(\"Correlations\")\n",
"\n",
"if not True:\n",
" x_grid = grid\n",
" scipy_grid = scipy_lags\n",
" ax.set_xlabel(\"Index Lag\")\n",
"else:\n",
" x_grid = t_grid * 1e9\n",
" scipy_grid = scipy_lags / signal_1.sample_rate * 1e9\n",
" ax.set_xlabel(\"Time [ns]\")\n",
" \n",
"ax.plot(x_grid, corrs, label='grid correlation')\n",
"ax.plot(scipy_grid, scipy_corr, label='scipy')\n",
"\n",
"ax.legend()\n",
"\n",
"plt.show();\n",
"\n",
"\n",
"if scipy_mode == 'same':\n",
" scipy_corr_grid = scipy_corr[grid]\n",
"else:\n",
" scipy_corr_grid = scipy_corr[grid]\n",
" \n",
"\n",
"if len(grid) <= 10:\n",
" print(\"G\", grid)\n",
" print(\"TG\", grid/signal_1.sample_rate)\n",
" print(\"C\", corrs)\n",
" print(\"SC\", scipy_corr_grid)\n",
" \n",
" \n",
"print(\"ids\", my_id, scipy_id)\n",
"print(\"ts\", t_grid[my_id], scipy_lags[np.argmax(scipy_corr)]/signal_1.sample_rate, '=:', signal_2.t_0)\n",
"print(\"avail ts\", t_grid[0], '-', t_grid[-1] ,':', (t_grid[-1] - t_grid[0])/len(t_grid))\n",
"print(\"grid size\", len(t_grid), len(sig_2), len(sig_1))"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-2.58e-08 = -2.58e-08 \\pm (-1e-10, 1e-10)\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA7gAAAEGCAYAAABPZjl3AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAC2s0lEQVR4nOz9d3hkV5XvD3935RwVW7Fzu7O726ExxgYbkwyMwWBgAswwYGC4mMt9mfBy78CP++PeeRlgGA9mMAwDA8OMSWOiAYPB2ODUDm23O6qDpFYuqXJO+/1j15FKUoWTSlKr1+d59Ki7ap9zdkl1Svu711rfxTjnIAiCIAiCIAiCIIhLHcNqT4AgCIIgCIIgCIIg9IAELkEQBEEQB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hU6s7NwCYegGwuoDgVvF//6C4h2fqz+2Lz92L7898CIPt4vV0uG3o9Nhwemr1W2qNhNNIZIvY2+sDAJhNJry857UYy5zEUPji6k6OIAiCWAYJXIJYJ5hNBrS7L0WBOwk4AqJGrx7urksmRfnxMeFOeGXnnrpjOj02FMs5jITnVmpaxHoiMiLSfdursgRcnYAj2FBErgilAhC5ALRtBwyVJQZjYq6RC0BheeZCuVzGC+HHsc17JdxW+/zj27vcmI5nEU3nV2r2NTkfSsJiMmAw6Jh/7M3bXwcA+N7JB1ZrWgRBEEQdSOASBLG6JKYAd3fjMa4uIB2uuTheaxydeREAw7V9e+uOcdjy+ObUH+E7Z763chMj1g/hcyL119u/8Bhjold
"text/plain": [
"<Figure size 1152x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"##########################\n",
"##########################\n",
"calc_shift, err = lag_gridsearch(grid, signal_1.sample_rate, sig_2, sig_1)\n",
"print(signal_2.t_0, \"=\", calc_shift, \"\\pm\", err)\n",
"\n",
"if True:\n",
" signal_2.periodic = False\n",
"\n",
" fig, ax = plt.subplots(figsize=(16,4))\n",
" ax.plot(double_signal_time * ns, sig_1, alpha=0.5, label='Regular')\n",
" ax.plot(double_signal_time * ns, sig_2, alpha=0.5, label='Shifted')\n",
" ax.plot((double_signal_time) * ns, signal_2(double_signal_time + calc_shift), ls=(0, (10,)), label='Recovered')\n",
"\n",
" \n",
" ax.axvline(calc_shift * ns)\n",
" for i, _ in enumerate(err):\n",
" ax.axvline((calc_shift + err[i]) * ns, ls=(5*i, (4, 4)))\n",
"\n",
" ax.set_xlabel(\"Time (ns)\")\n",
" ax.set_ylabel(\"Amplitude\")\n",
" ax.legend()\n",
"\n",
" plt.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.10.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
}