| Philipp Le | 741d309 | 2022-05-18 23:00:53 +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 ConfigCh06UpSampling(ConfigObject): |
| 74 | _KEY = 'ch06_up_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 | interpolation: 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='Interpolation Factor:').grid(row=1, column=0) |
| 101 | w = self.ui_create_interpolation(frm1) |
| 102 | frm.add_widget(w) |
| 103 | w.grid(row=1, column=1) |
| 104 | |
| 105 | ttk.Label(frm1, text='Interpolation 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 calc_input_signal(self, t: np.ndarray) -> np.ndarray: |
| 117 | x = np.zeros((len(self.input_funcs), len(t)), dtype=np.float64) |
| 118 | for index, func in enumerate(self.input_funcs): |
| 119 | x[index, :] = func.calc_signal(t) |
| 120 | return np.sum(x, axis=0) |
| 121 | |
| 122 | def calc_zerofilled_signal(self, t: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: |
| 123 | slope = (np.max(t) - np.min(t)) / (len(t) - 1) |
| 124 | n_start = np.min(t) / slope |
| 125 | n_up = len(t) * self.interpolation |
| 126 | t_up = np.arange(n_start, n_start + n_up, 1) * slope / self.interpolation |
| 127 | sig = np.zeros((n_up,)) |
| 128 | for idx, val in enumerate(self.calc_input_signal(t)): |
| 129 | sig[idx * self.interpolation] = val |
| 130 | return t_up, sig |
| 131 | |
| 132 | def calc_filtered_signal(self, t: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: |
| 133 | t_up, zero_filled = self.calc_zerofilled_signal(t) |
| 134 | |
| 135 | if self.have_filter(): |
| 136 | b, a = scipy.signal.cheby1(N=5, Wn=self.lp_cutoff_freq, rp=1, btype='low', fs=self.sample_rate * self.interpolation) |
| 137 | zi = scipy.signal.lfilter_zi(b, a) |
| 138 | z, _ = scipy.signal.lfilter(b, a, zero_filled, zi=zi*zero_filled[0]) |
| 139 | return t_up, z |
| 140 | else: |
| 141 | return t_up, zero_filled |
| 142 | |
| 143 | |
| 144 | class Ch06UpSamplingFrame(BaseFrame): |
| 145 | def __init__(self, *args, **kwargs): |
| 146 | super().__init__(*args, **kwargs) |
| 147 | |
| 148 | self._config: ConfigCh06UpSampling = default_store().get_config(ConfigCh06UpSampling) |
| 149 | |
| 150 | ctrl_frm = self._create_control() |
| 151 | ctrl_frm.pack(side=LEFT) |
| 152 | |
| 153 | signal_frm = self._create_signal_tabs() |
| 154 | signal_frm.pack(expand=True, fill=BOTH) |
| 155 | |
| 156 | def _create_control(self) -> ConfigControlFrame: |
| 157 | frm = self._config.make_config_widget(self) |
| 158 | frm.widgets_on_change(self._on_change) |
| 159 | return frm |
| 160 | |
| 161 | def _on_change(self, _, __, ___): |
| 162 | default_store().save() |
| 163 | self.draw_td() |
| 164 | self.draw_fd() |
| 165 | |
| 166 | def _create_signal_tabs(self) -> ttk.Widget: |
| 167 | tabs = ttk.Notebook(self) |
| 168 | |
| 169 | td_frm = ttk.Frame(tabs) |
| 170 | tabs.add(td_frm, text='Time Domain') |
| 171 | self._td_fig = Figure(figsize=(12, 6), dpi=100) |
| 172 | self._td_canvas = FigureCanvasTkAgg(self._td_fig, td_frm) |
| 173 | self._td_canvas.get_tk_widget().pack(expand=True, fill=BOTH) |
| 174 | td_tb = NavigationToolbar2Tk(self._td_canvas, td_frm, pack_toolbar=False) |
| 175 | td_tb.pack(side=BOTTOM) |
| 176 | |
| 177 | fd_frm = ttk.Frame(tabs) |
| 178 | tabs.add(fd_frm, text='Frequency Domain') |
| 179 | self._fd_fig = Figure(figsize=(12, 6), dpi=100) |
| 180 | self._fd_canvas = FigureCanvasTkAgg(self._fd_fig, fd_frm) |
| 181 | self._fd_canvas.get_tk_widget().pack(expand=True, fill=BOTH) |
| 182 | fd_tb = NavigationToolbar2Tk(self._fd_canvas, fd_frm, pack_toolbar=False) |
| 183 | fd_tb.pack(side=BOTTOM) |
| 184 | |
| 185 | self.draw_td() |
| 186 | self.draw_fd() |
| 187 | |
| 188 | return tabs |
| 189 | |
| 190 | def draw_td(self): |
| 191 | self._td_fig.clear() |
| 192 | |
| 193 | if self._config.have_filter(): |
| 194 | ax_inp = self._td_fig.add_subplot(3, 1, 1) |
| 195 | ax_zer = self._td_fig.add_subplot(3, 1, 2) |
| 196 | ax_int = self._td_fig.add_subplot(3, 1, 3) |
| 197 | else: |
| 198 | ax_inp = self._td_fig.add_subplot(2, 1, 1) |
| 199 | ax_zer = self._td_fig.add_subplot(2, 1, 2) |
| 200 | ax_inp.set_xlim(0.0, 1.1) |
| 201 | ax_inp.set_xlabel('time') |
| 202 | ax_inp.set_ylabel('value') |
| 203 | ax_inp.set_title('Input Signal') |
| 204 | ax_zer.set_xlim(0.0, 1.1) |
| 205 | ax_zer.set_xlabel('time') |
| 206 | ax_zer.set_ylabel('value') |
| 207 | ax_zer.set_title('Zero-Filled Filter') |
| 208 | if self._config.have_filter(): |
| 209 | ax_int.set_xlim(0.0, 1.1) |
| 210 | ax_int.set_xlabel('time') |
| 211 | ax_int.set_ylabel('value') |
| 212 | ax_int.set_title('Interpolated Signal') |
| 213 | |
| 214 | t = np.arange(0, 1.1, 1.0/self._config.sample_rate) |
| 215 | if len(t) > 3: |
| 216 | t_interp = np.linspace(np.min(t), np.max(t), OVERSAMPLING_LEN) |
| 217 | else: |
| 218 | t_interp = np.zeros((0,)) |
| 219 | |
| 220 | x_inp = self._config.calc_input_signal(t) |
| 221 | if len(t) > 3: |
| 222 | fn_inp_interp = make_interp_spline(t, x_inp) |
| 223 | x_inp_interp = fn_inp_interp(t_interp) |
| 224 | else: |
| 225 | x_inp_interp = np.zeros((0,)) |
| 226 | |
| 227 | t_zer, x_zer = self._config.calc_zerofilled_signal(t) |
| 228 | if len(t) > 3: |
| 229 | fn_zer_interp = make_interp_spline(t_zer, x_zer) |
| 230 | x_zer_interp = fn_zer_interp(t_interp) |
| 231 | else: |
| 232 | x_zer_interp = np.zeros((0,)) |
| 233 | |
| 234 | if self._config.have_filter(): |
| 235 | t_int, x_int = self._config.calc_filtered_signal(t) |
| 236 | if len(t) > 3: |
| 237 | fn_int_interp = make_interp_spline(t_int, x_int) |
| 238 | x_int_interp = fn_int_interp(t_interp) |
| 239 | else: |
| 240 | x_int_interp = np.zeros((0,)) |
| 241 | |
| 242 | ax_inp.plot(t, x_inp, label='Input Signal (Sampled)', marker='x', linestyle='none', color='blue', linewidth=1) |
| 243 | ax_inp.plot(t_interp, x_inp_interp, label='Input Signal (Interpolated)', linestyle='dashed', color='blue', linewidth=1) |
| 244 | ax_inp.legend() |
| 245 | |
| 246 | ax_zer.plot(t, x_inp, label='Input Signal (Sampled)', marker='o', linestyle='none', color='blue', linewidth=1) |
| 247 | ax_zer.plot(t_zer, x_zer, label='Zero-Filled Signal (Sampled)', marker='x', linestyle='none', color='green', linewidth=1) |
| 248 | ax_zer.plot(t_interp, x_zer_interp, label='Zero-Filled Signal (Interpolated)', linestyle='dashed', color='green', linewidth=1) |
| 249 | ax_zer.legend() |
| 250 | |
| 251 | if self._config.have_filter(): |
| 252 | ax_int.plot(t_int, x_int, label='Interpolated Signal (Sampled)', marker='x', linestyle='none', color='red', linewidth=1) |
| 253 | ax_int.plot(t_interp, x_int_interp, label='Interpolated Signal (Interpolated)', linestyle='dashed', color='red', linewidth=1) |
| 254 | ax_int.legend() |
| 255 | |
| 256 | self._td_fig.tight_layout() |
| 257 | self._td_canvas.draw() |
| 258 | |
| 259 | def draw_fd(self): |
| 260 | self._fd_fig.clear() |
| 261 | |
| 262 | if self._config.have_filter(): |
| 263 | ax_inp = self._fd_fig.add_subplot(3, 1, 1) |
| 264 | ax_zer = self._fd_fig.add_subplot(3, 1, 2) |
| 265 | ax_int = self._fd_fig.add_subplot(3, 1, 3) |
| 266 | else: |
| 267 | ax_inp = self._fd_fig.add_subplot(2, 1, 1) |
| 268 | ax_zer = self._fd_fig.add_subplot(2, 1, 2) |
| 269 | ax_inp.set_xlim(-self._config.sample_rate/2, self._config.sample_rate/2) |
| 270 | ax_inp.set_xlabel('frequency') |
| 271 | ax_inp.set_ylabel('value (dB)') |
| 272 | ax_inp.set_title('Input Signal') |
| 273 | ax_zer.set_xlim(-self._config.interpolation * self._config.sample_rate/2, self._config.interpolation * self._config.sample_rate/2) |
| 274 | ax_zer.set_xlabel('frequency') |
| 275 | ax_zer.set_ylabel('value (dB)') |
| 276 | ax_zer.set_title('Zero-Filled Filter') |
| 277 | if self._config.have_filter(): |
| 278 | ax_int.set_xlim(-self._config.interpolation * self._config.sample_rate/2, self._config.interpolation * self._config.sample_rate/2) |
| 279 | ax_int.set_xlabel('frequency') |
| 280 | ax_int.set_ylabel('value (dB)') |
| 281 | ax_int.set_title('Interpolated Signal') |
| 282 | |
| 283 | t = np.arange(0, FFT_LEN, 1) / self._config.sample_rate |
| 284 | f = swap_freq(np.fft.fftfreq(t.shape[-1], 1.0/self._config.sample_rate)) |
| 285 | |
| 286 | x_inp = self._config.calc_input_signal(t) |
| 287 | t_zer, x_zer = self._config.calc_zerofilled_signal(t) |
| 288 | f_zer = swap_freq(np.fft.fftfreq(t_zer.shape[-1], 1.0 / (self._config.sample_rate * self._config.interpolation))) |
| 289 | |
| 290 | if self._config.have_filter(): |
| 291 | t_int, x_int = self._config.calc_filtered_signal(t) |
| 292 | f_int = swap_freq(np.fft.fftfreq(t_int.shape[-1], 1.0 / (self._config.sample_rate * self._config.interpolation))) |
| 293 | |
| 294 | ax_inp.plot(f, abs_log_fft(x_inp), label='Input Signal', linestyle='solid', color='blue', linewidth=1) |
| 295 | ax_inp.legend() |
| 296 | |
| 297 | ax_zer.plot(f_zer, abs_log_fft(x_zer), label='Zero-Filled Signal', linestyle='solid', color='green', linewidth=1) |
| 298 | ax_zer.legend() |
| 299 | |
| 300 | if self._config.have_filter(): |
| 301 | ax_int.plot(f_int, abs_log_fft(x_int), label='Interpolated Signal', linestyle='solid', color='red', linewidth=1) |
| 302 | ax_int.legend() |
| 303 | |
| 304 | self._fd_fig.tight_layout() |
| 305 | self._fd_canvas.draw() |
| 306 | |
| 307 | |
| 308 | class Ch06UpSamplingWindow(Window): |
| 309 | GROUP = Ch06Group |
| 310 | TITLE = 'Up Sampling' |
| 311 | FRAME = Ch06UpSamplingFrame |
| 312 | |
| 313 | |
| 314 | if __name__ == '__main__': |
| 315 | Ch06UpSamplingWindow.main() |
| 316 | |