| Philipp Le | 20439ab | 2022-05-18 00:57:58 +0200 | [diff] [blame] | 1 | # SPDX-License-Identifier: MPL-2.0 |
| 2 | # Copyright (c) 2022 Philipp Le <philipp@philipple.de>. |
| 3 | # This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | # License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | # file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | from tkinter import ttk, LEFT, BOTH, BOTTOM |
| 10 | from pydantic import confloat, conint |
| 11 | from dcs.config import default_store, ConfigObject, ui_create, ConfigControlFrame |
| 12 | import numpy as np |
| 13 | import scipy.signal |
| 14 | from scipy.interpolate import make_interp_spline |
| 15 | from dcs.frames.base import BaseFrame, Window |
| 16 | from dcs.frames.groups import Ch06Group |
| 17 | from dcs.utils import swap_freq, abs_log_fft |
| 18 | from typing import List, Tuple |
| 19 | |
| 20 | import matplotlib |
| 21 | matplotlib.use('TkAgg') |
| 22 | from matplotlib.figure import Figure |
| 23 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk |
| 24 | |
| 25 | |
| 26 | OVERSAMPLING_LEN = 512 |
| 27 | FFT_LEN = 2048 |
| 28 | |
| 29 | |
| 30 | @ui_create |
| 31 | class Function(ConfigObject): |
| 32 | freq: confloat(ge=0, lt=OVERSAMPLING_LEN/2, multiple_of=(4.0/OVERSAMPLING_LEN)) = 1.0 |
| 33 | amplitude: confloat(ge=0.0, lt=10.0, multiple_of=0.01) = 5.0 |
| 34 | phase: confloat(ge=-180.0, le=180.0, multiple_of=0.1) = 0.0 |
| 35 | offset: confloat(ge=-5.0, lt=5.0, multiple_of=0.01) = 0.0 |
| 36 | |
| 37 | def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame: |
| 38 | frm = ConfigControlFrame(parent) |
| 39 | |
| 40 | ttk.Label(frm, text='Frequency:').grid(row=0, column=0) |
| 41 | w = self.ui_create_freq(frm) |
| 42 | frm.add_widget(w) |
| 43 | w.grid(row=0, column=1) |
| 44 | |
| 45 | ttk.Label(frm, text='Amplitude:').grid(row=1, column=0) |
| 46 | w = self.ui_create_amplitude(frm) |
| 47 | frm.add_widget(w) |
| 48 | w.grid(row=1, column=1) |
| 49 | |
| 50 | ttk.Label(frm, text='Phase:').grid(row=2, column=0) |
| 51 | w = self.ui_create_phase(frm) |
| 52 | frm.add_widget(w) |
| 53 | w.grid(row=2, column=1) |
| 54 | ttk.Label(frm, text='°').grid(row=2, column=2) |
| 55 | |
| 56 | ttk.Label(frm, text='Offset:').grid(row=3, column=0) |
| 57 | w = self.ui_create_offset(frm) |
| 58 | frm.add_widget(w) |
| 59 | w.grid(row=3, column=1) |
| 60 | |
| 61 | return frm |
| 62 | |
| 63 | def calc_signal(self, t: np.ndarray) -> np.ndarray: |
| 64 | phasor = self.amplitude * np.exp(1j * self.phase * np.pi / 180) |
| 65 | phi = np.exp(1j * 2 * np.pi * self.freq * t) |
| 66 | return np.real(self.offset + (phasor * phi)) |
| 67 | |
| 68 | def make_title(self): |
| 69 | return f'f={self.freq}, {self.amplitude}, {self.phase}°' |
| 70 | |
| 71 | |
| 72 | @ui_create |
| 73 | class ConfigCh06DownSampling(ConfigObject): |
| 74 | _KEY = 'ch06_down_sampling' |
| 75 | |
| 76 | input_funcs: List[Function] = [ |
| 77 | Function(freq=1.0, amplitude_dB=0.0, phase=0.0), |
| 78 | Function(freq=1.5, amplitude_dB=0.0, phase=90.0), |
| 79 | ] |
| 80 | sample_rate: confloat(ge=0, lt=OVERSAMPLING_LEN/2, multiple_of=(4.0/OVERSAMPLING_LEN)) = 16.0 |
| 81 | decimation: conint(ge=0, lt=64) = 4 |
| 82 | lp_cutoff_freq: confloat(ge=0, lt=OVERSAMPLING_LEN/2, multiple_of=(4.0/OVERSAMPLING_LEN)) = 4.0 |
| 83 | |
| 84 | def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame: |
| 85 | frm = ConfigControlFrame(parent, borderwidth=1, relief='raised') |
| 86 | |
| 87 | ttk.Label(frm, text='Input Functions:').pack() |
| 88 | w = self.ui_create_input_funcs_list(frm, lambda e: e.make_title()) |
| 89 | frm.add_widget(w) |
| 90 | w.pack() |
| 91 | |
| 92 | frm1 = ttk.Frame(frm, borderwidth=1, relief='raised') |
| 93 | frm1.pack() |
| 94 | |
| 95 | ttk.Label(frm1, text='Sample Rate:').grid(row=0, column=0) |
| 96 | w = self.ui_create_sample_rate(frm1) |
| 97 | frm.add_widget(w) |
| 98 | w.grid(row=0, column=1) |
| 99 | |
| 100 | ttk.Label(frm1, text='Decimation Factor:').grid(row=1, column=0) |
| 101 | w = self.ui_create_decimation(frm1) |
| 102 | frm.add_widget(w) |
| 103 | w.grid(row=1, column=1) |
| 104 | |
| 105 | ttk.Label(frm1, text='Anti-Aliasing Low Pass Cut-off:').grid(row=2, column=0) |
| 106 | ttk.Label(frm1, text='(0 = disable):').grid(row=3, column=1) |
| 107 | w = self.ui_create_lp_cutoff_freq(frm1) |
| 108 | frm.add_widget(w) |
| 109 | w.grid(row=2, column=1) |
| 110 | |
| 111 | return frm |
| 112 | |
| 113 | def have_filter(self) -> bool: |
| 114 | return not (self.lp_cutoff_freq == 0) |
| 115 | |
| 116 | def _decimate_vec(self, vec: np.ndarray) -> np.ndarray: |
| 117 | return np.array([vec[idx] for idx in range(0, len(vec), self.decimation)]) |
| 118 | |
| 119 | def calc_input_signal(self, t: np.ndarray) -> np.ndarray: |
| 120 | x = np.zeros((len(self.input_funcs), len(t)), dtype=np.float64) |
| 121 | for index, func in enumerate(self.input_funcs): |
| 122 | x[index, :] = func.calc_signal(t) |
| 123 | return np.sum(x, axis=0) |
| 124 | |
| 125 | def calc_decimated_bypassed_signal(self, t: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: |
| 126 | sig = self.calc_input_signal(t) |
| 127 | return self._decimate_vec(t), self._decimate_vec(sig) |
| 128 | |
| 129 | def calc_filtered_signal(self, t: np.ndarray) -> np.ndarray: |
| 130 | inp = self.calc_input_signal(t) |
| 131 | |
| 132 | if self.have_filter(): |
| 133 | b, a = scipy.signal.cheby1(N=5, Wn=self.lp_cutoff_freq, rp=1, btype='low', fs=self.sample_rate) |
| 134 | zi = scipy.signal.lfilter_zi(b, a) |
| 135 | z, _ = scipy.signal.lfilter(b, a, inp, zi=zi*inp[0]) |
| 136 | return z |
| 137 | else: |
| 138 | return inp |
| 139 | |
| 140 | def calc_decimated_signal(self, t: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: |
| 141 | sig = self.calc_filtered_signal(t) |
| 142 | return self._decimate_vec(t), self._decimate_vec(sig) |
| 143 | |
| 144 | |
| 145 | class Ch06DownSamplingFrame(BaseFrame): |
| 146 | def __init__(self, *args, **kwargs): |
| 147 | super().__init__(*args, **kwargs) |
| 148 | |
| 149 | self._config: ConfigCh06DownSampling = default_store().get_config(ConfigCh06DownSampling) |
| 150 | |
| 151 | ctrl_frm = self._create_control() |
| 152 | ctrl_frm.pack(side=LEFT) |
| 153 | |
| 154 | signal_frm = self._create_signal_tabs() |
| 155 | signal_frm.pack(expand=True, fill=BOTH) |
| 156 | |
| 157 | def _create_control(self) -> ConfigControlFrame: |
| 158 | frm = self._config.make_config_widget(self) |
| 159 | frm.widgets_on_change(self._on_change) |
| 160 | return frm |
| 161 | |
| 162 | def _on_change(self, _, __, ___): |
| 163 | default_store().save() |
| 164 | self.draw_td() |
| 165 | self.draw_fd() |
| 166 | |
| 167 | def _create_signal_tabs(self) -> ttk.Widget: |
| 168 | tabs = ttk.Notebook(self) |
| 169 | |
| 170 | td_frm = ttk.Frame(tabs) |
| 171 | tabs.add(td_frm, text='Time Domain') |
| 172 | self._td_fig = Figure(figsize=(12, 6), dpi=100) |
| 173 | self._td_canvas = FigureCanvasTkAgg(self._td_fig, td_frm) |
| 174 | self._td_canvas.get_tk_widget().pack(expand=True, fill=BOTH) |
| 175 | td_tb = NavigationToolbar2Tk(self._td_canvas, td_frm, pack_toolbar=False) |
| 176 | td_tb.pack(side=BOTTOM) |
| 177 | |
| 178 | fd_frm = ttk.Frame(tabs) |
| 179 | tabs.add(fd_frm, text='Frequency Domain') |
| 180 | self._fd_fig = Figure(figsize=(12, 6), dpi=100) |
| 181 | self._fd_canvas = FigureCanvasTkAgg(self._fd_fig, fd_frm) |
| 182 | self._fd_canvas.get_tk_widget().pack(expand=True, fill=BOTH) |
| 183 | fd_tb = NavigationToolbar2Tk(self._fd_canvas, fd_frm, pack_toolbar=False) |
| 184 | fd_tb.pack(side=BOTTOM) |
| 185 | |
| 186 | self.draw_td() |
| 187 | self.draw_fd() |
| 188 | |
| 189 | return tabs |
| 190 | |
| 191 | def draw_td(self): |
| 192 | self._td_fig.clear() |
| 193 | |
| 194 | if self._config.have_filter(): |
| 195 | ax_inp = self._td_fig.add_subplot(3, 1, 1) |
| 196 | else: |
| 197 | ax_inp = self._td_fig.add_subplot(2, 1, 1) |
| 198 | ax_inp.set_xlim(0.0, 1.1) |
| 199 | ax_inp.set_xlabel('time') |
| 200 | ax_inp.set_ylabel('value') |
| 201 | ax_inp.set_title('Input Signal') |
| 202 | if self._config.have_filter(): |
| 203 | ax_flt = self._td_fig.add_subplot(3, 1, 2) |
| 204 | ax_flt.set_xlim(0.0, 1.1) |
| 205 | ax_flt.set_xlabel('time') |
| 206 | ax_flt.set_ylabel('value') |
| 207 | ax_flt.set_title('Signal After Anti-Aliasing Filter') |
| 208 | ax_dec = self._td_fig.add_subplot(3, 1, 3) |
| 209 | else: |
| 210 | ax_dec = self._td_fig.add_subplot(2, 1, 2) |
| 211 | ax_dec.set_xlim(0.0, 1.1) |
| 212 | ax_dec.set_xlabel('time') |
| 213 | ax_dec.set_ylabel('value') |
| 214 | ax_dec.set_title('Decimated Signal') |
| 215 | |
| 216 | t = np.arange(0, 1.1, 1.0/self._config.sample_rate) |
| 217 | if len(t) > 3: |
| 218 | t_interp = np.linspace(np.min(t), np.max(t), OVERSAMPLING_LEN) |
| 219 | else: |
| 220 | t_interp = np.zeros((0,)) |
| 221 | |
| 222 | x_inp = self._config.calc_input_signal(t) |
| 223 | t_inp_dec, x_inp_dec = self._config.calc_decimated_bypassed_signal(t) |
| 224 | if len(t) > 3: |
| 225 | fn_inp_interp = make_interp_spline(t, x_inp) |
| 226 | x_inp_interp = fn_inp_interp(t_interp) |
| 227 | else: |
| 228 | x_inp_interp = np.zeros((0,)) |
| 229 | |
| 230 | if self._config.have_filter(): |
| 231 | x_flt = self._config.calc_filtered_signal(t) |
| 232 | if len(t) > 3: |
| 233 | fn_flt_interp = make_interp_spline(t, x_flt) |
| 234 | x_flt_interp = fn_flt_interp(t_interp) |
| 235 | else: |
| 236 | x_flt_interp = np.zeros((0,)) |
| 237 | |
| 238 | t_dec, x_dec = self._config.calc_decimated_signal(t) |
| 239 | if len(t) > 3: |
| 240 | fn_dec_interp = make_interp_spline(t_dec, x_dec) |
| 241 | x_dec_interp = fn_dec_interp(t_interp) |
| 242 | else: |
| 243 | x_dec_interp = np.zeros((0,)) |
| 244 | |
| 245 | ax_inp.plot(t_inp_dec, x_inp_dec, label='Input Signal (Decimated)', marker='o', linestyle='none', color='red', linewidth=1) |
| 246 | ax_inp.plot(t, x_inp, label='Input Signal (Sampled)', marker='x', linestyle='none', color='blue', linewidth=1) |
| 247 | ax_inp.plot(t_interp, x_inp_interp, label='Input Signal (Interpolated)', linestyle='dashed', color='blue', linewidth=1) |
| 248 | ax_inp.legend() |
| 249 | |
| 250 | if self._config.have_filter(): |
| 251 | ax_flt.plot(t_dec, x_dec, label='Filtered Signal (Decimated)', marker='o', linestyle='none', color='red', linewidth=1) |
| 252 | ax_flt.plot(t, x_flt, label='Filtered Signal (Sampled)', marker='x', linestyle='none', color='green', linewidth=1) |
| 253 | ax_flt.plot(t_interp, x_flt_interp, label='Filtered Signal (Interpolated)', linestyle='dashed', color='green', linewidth=1) |
| 254 | ax_flt.legend() |
| 255 | |
| 256 | ax_dec.plot(t_dec, x_dec, label='Decimated Signal (Sampled)', marker='x', linestyle='none', color='red', linewidth=1) |
| 257 | ax_dec.plot(t_interp, x_dec_interp, label='Decimated Signal (Interpolated)', linestyle='dashed', color='red', linewidth=1) |
| 258 | ax_dec.legend() |
| 259 | |
| 260 | self._td_fig.tight_layout() |
| 261 | self._td_canvas.draw() |
| 262 | |
| 263 | def draw_fd(self): |
| 264 | self._fd_fig.clear() |
| 265 | |
| 266 | if self._config.have_filter(): |
| 267 | ax_inp = self._fd_fig.add_subplot(3, 1, 1) |
| 268 | else: |
| 269 | ax_inp = self._fd_fig.add_subplot(2, 1, 1) |
| 270 | ax_inp.set_xlim(-self._config.sample_rate/2, self._config.sample_rate/2) |
| 271 | ax_inp.set_xlabel('frequency') |
| 272 | ax_inp.set_ylabel('value (dB)') |
| 273 | ax_inp.set_title('Input Signal') |
| 274 | if self._config.have_filter(): |
| 275 | ax_flt = self._fd_fig.add_subplot(3, 1, 2) |
| 276 | ax_flt.set_xlim(-self._config.sample_rate/2, self._config.sample_rate/2) |
| 277 | ax_flt.set_xlabel('frequency') |
| 278 | ax_flt.set_ylabel('value (dB)') |
| 279 | ax_flt.set_title('Signal After Anti-Aliasing Filter') |
| 280 | ax_dec = self._fd_fig.add_subplot(3, 1, 3) |
| 281 | else: |
| 282 | ax_dec = self._fd_fig.add_subplot(2, 1, 2) |
| 283 | ax_dec.set_xlim(-self._config.sample_rate/(self._config.decimation * 2), self._config.sample_rate/(self._config.decimation * 2)) |
| 284 | ax_dec.set_xlabel('frequency') |
| 285 | ax_dec.set_ylabel('value (dB)') |
| 286 | ax_dec.set_title('Decimated Signal') |
| 287 | |
| 288 | t = np.arange(0, FFT_LEN, 1) / self._config.sample_rate |
| 289 | f = swap_freq(np.fft.fftfreq(t.shape[-1], 1.0/self._config.sample_rate)) |
| 290 | |
| 291 | x_inp = self._config.calc_input_signal(t) |
| 292 | |
| 293 | if self._config.have_filter(): |
| 294 | x_flt = self._config.calc_filtered_signal(t) |
| 295 | |
| 296 | t_dec, x_dec = self._config.calc_decimated_signal(t) |
| 297 | f_dec = swap_freq(np.fft.fftfreq(t_dec.shape[-1], 1.0 * self._config.decimation / self._config.sample_rate)) |
| 298 | |
| 299 | ax_inp.plot(f, abs_log_fft(x_inp), label='Input Signal', linestyle='solid', color='blue', linewidth=1) |
| 300 | ax_inp.legend() |
| 301 | |
| 302 | if self._config.have_filter(): |
| 303 | ax_flt.plot(f, abs_log_fft(x_flt), label='Filtered Signal', linestyle='solid', color='green', linewidth=1) |
| 304 | ax_flt.legend() |
| 305 | |
| 306 | ax_dec.plot(f_dec, abs_log_fft(x_dec), label='Decimated Signal', linestyle='solid', color='red', linewidth=1) |
| 307 | ax_dec.legend() |
| 308 | |
| 309 | self._fd_fig.tight_layout() |
| 310 | self._fd_canvas.draw() |
| 311 | |
| 312 | |
| 313 | class Ch06DownSamplingWindow(Window): |
| 314 | GROUP = Ch06Group |
| 315 | TITLE = 'Down Sampling' |
| 316 | FRAME = Ch06DownSamplingFrame |
| 317 | |
| 318 | |
| 319 | if __name__ == '__main__': |
| 320 | Ch06DownSamplingWindow.main() |
| 321 | |