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

532 lines
220 KiB
Text
Raw Permalink 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+X6mD2Ae8B1U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7HY7o0aNyvgKpJR88cUXAOyxxx7873//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": "iVBORw0KGgoAAAANSUhEUgAAAYoAAAEWCAYAAAB42tAoAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG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NatWwfAihUrOOKII5g6dSozZ87kiy++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)"
]
},
2022-07-11 15:08:03 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Debug and test functions"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
2022-07-11 15:08:03 +02:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAX8AAAEWCAYAAACOv5f1AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAABylklEQVR4nO29d5xcV3n//37mTu/bd9WLLRdZtmzLxrTYBmzTgiHVhNAS4q8JhDT4UsPXISGFQEiHH04IJQRMIKHbgBO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fnBwkFQqVRcBFAqFSCaTTc/7rGc9ix/84AfMzs5SLpf5/Oc/35U9z5RTXflPiciYteofA6at8XFgc815m4AT1vgmm3GNZsVJz0/QB2zd/SyYhrmJI+zstVGaRS677DJe8YpXcNFFF7F161b27dtHJBLpOO9f//Vf+Y3f+A38fj/XXXed7TkvfvGLOXDgAPv27cPtdvPSl76UP/uzP+PTn/40N910E5lMhh07dvCv//qvHV/P7XbzpS99ibe97W3E43FKpRK/93u/x+7dS3dL0WiU3/qt32LPnj1s27aNyy67bPHYG97wBm666SZ8Pl/d3cPY2Bh//ud/ztVXX41Sipe+9KVcf/31He15xiiluv4HbAMeqvn5r4B3WY/fBXzIerwbuB/wANuBpwDDOnYvcAXmXcBtwEu7ee1LL71UaTSnwsFb363K74+oB4/OqtT7h9TdH/s/vTZpVfHII4/02gSVTCaVUkql02l16aWXqvvuu6/HFq0t7P6GwH5lo6l
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-07-11 15:08:03 +02:00
"ids 87 871\n",
"ts -2.62e-08 -2.58e-08 =: -2.58e-08\n",
"avail ts -2e-07 - 1.978e-07 : 1.989e-09\n",
"grid size 200 2000 2000\n"
]
}
],
"source": [
"#################\n",
2022-07-11 15:08:03 +02:00
"grid_size = 200\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))"
]
},
2022-07-11 15:08:03 +02:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Showcase functions"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-07-11 15:08:03 +02:00
"Known time offset: -2.58e-08\n",
"Calculated offset: -2.62e-08\n",
"Uncertainty on offset: (-1e-09, 1e-09)\n"
]
},
{
"data": {
2022-07-11 15:08:03 +02:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA7gAAAEGCAYAAABPZjl3AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRw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KhcIQhw8fZt++fVx11VV8+tOf5s///M/Xe0mWoQSuQnERc/s9j3D7PY+s9zLMkawmfwUHa9+v356aWpv1WMCZ6Bzx0iR7evfUvH8g5GFKCVyFGc4/KVv4txwEbxcM7YXJZ6F4AbTNzh2XxnGjrwS7Q37PJ2HmhboPmUzkmEnmuW60G5fDxsEdPeSLFY6cj6/hwmtTqWg8Ox5na4+PkW4flw4GuanvVmzCwd+/8PfrvTyFQqEwxE033cTTTz/NM888w/e//3127ty53kuyDCVwFYoNxK37h7l1//B6L6M99MpsoI7Adfllm2Py4ojAzhRKnErKEPU9PbUFbn/QTTRTvGCqU4qLjHJRisWBPeBwyduG9kKlDDMvru/aACafAXcAenbJn7tG5Xt4uv7anj+f4Fj2IQIBKWj7gx4GQh6OTq5/pNaZ+QzJXImrhiMA2GyCa7eMMuzez7+f+Q7linofKxQKxYWEErgKxQbitgMjF19EUHICfN1yRq8ewcGLpkV5KpFntnACgMt7Lq+5zUDIw+nsI7z5n99APL/+FSrFRUb0jGz37btk8bbAAPh6GorINaFchOgp6L0EbNVTDCHkWqOnoLi6c0HTNJ6bHOcH0Xt46MyiE+clg0GmEjlimcJarb4mJ2dSuBw2Rnt8C7ft6g+wzfsK5nNzPDH9xDq
"text/plain": [
"<Figure size 1152x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
2022-07-11 15:08:03 +02:00
"grid_size = 200\n",
"\n",
"grid = correlation_grid(grid_size, in1_len=len(sig_1), in2_len=len(sig_2), mode='same')\n",
"calc_shift, err = lag_gridsearch(grid, signal_1.sample_rate, sig_2, sig_1)\n",
2022-07-11 15:08:03 +02:00
"\n",
"print(\"Known time offset:\", signal_2.t_0)\n",
"print(\"Calculated offset:\", calc_shift)\n",
"print(\"Uncertainty on offset:\", err)\n",
"\n",
"if True:\n",
" signal_2.periodic = False\n",
"\n",
2022-07-11 15:08:03 +02:00
"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",
2022-07-11 15:08:03 +02:00
"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",
2022-07-11 15:08:03 +02:00
"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
}