| Philipp Le | f9cf766 | 2022-05-11 23:17:42 +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 |
| 11 | from dcs.config import default_store, ConfigObject, ui_create, ConfigControlFrame |
| 12 | import numpy as np |
| 13 | import scipy.signal |
| 14 | from dcs.frames.base import BaseFrame, Window |
| 15 | from dcs.frames.groups import Ch06Group |
| 16 | from dcs.utils import swap_freq, abs_log_fft |
| 17 | from typing import List |
| 18 | from enum import Enum |
| 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 | SAMPLE_LEN = 512 |
| 27 | FFT_OVERSAMPLING = 64 |
| 28 | |
| 29 | |
| 30 | @ui_create |
| 31 | class Function(ConfigObject): |
| 32 | freq: confloat(ge=-16*SAMPLE_LEN, lt=16*SAMPLE_LEN, multiple_of=(4.0/FFT_OVERSAMPLING)) = 1.0 |
| 33 | amplitude_dB: confloat(ge=-100.0, lt=10.0, multiple_of=1) = 0.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_dB(frm) |
| 47 | frm.add_widget(w) |
| 48 | w.grid(row=1, column=1) |
| 49 | ttk.Label(frm, text='dB').grid(row=1, column=2) |
| 50 | |
| 51 | ttk.Label(frm, text='Phase:').grid(row=2, column=0) |
| 52 | w = self.ui_create_phase(frm) |
| 53 | frm.add_widget(w) |
| 54 | w.grid(row=2, column=1) |
| 55 | ttk.Label(frm, text='°').grid(row=2, column=2) |
| 56 | |
| 57 | ttk.Label(frm, text='Offset:').grid(row=3, column=0) |
| 58 | w = self.ui_create_offset(frm) |
| 59 | frm.add_widget(w) |
| 60 | w.grid(row=3, column=1) |
| 61 | |
| 62 | return frm |
| 63 | |
| 64 | def calc_signal(self, t: np.ndarray) -> np.ndarray: |
| 65 | phasor = np.power(10, self.amplitude_dB / 20) * np.exp(1j * self.phase * np.pi / 180) |
| 66 | phi = np.exp(1j * 2 * np.pi * self.freq * t) |
| 67 | return self.offset + (phasor * phi) |
| 68 | |
| 69 | def make_title(self): |
| 70 | return f'f={self.freq}, {self.amplitude_dB} dB, {self.phase}°' |
| 71 | |
| 72 | |
| 73 | class Direction(str, Enum): |
| 74 | UP = 'Up Conversion' |
| 75 | DOWN = 'Down Conversion' |
| 76 | |
| 77 | |
| 78 | @ui_create |
| 79 | class ConfigCh06Mixer(ConfigObject): |
| 80 | _KEY = 'ch06_mixer' |
| 81 | |
| 82 | input_funcs: List[Function] = [ |
| 83 | Function(freq=-1.0, amplitude_dB=0.0, phase=0.0), |
| 84 | Function(freq=2.0, amplitude_dB=0.0, phase=90.0), |
| 85 | ] |
| 86 | direction: Direction = Direction.UP |
| 87 | nco: Function = Function(freq=20.0, amplitude_dB=0.0) |
| 88 | |
| 89 | def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame: |
| 90 | frm = ConfigControlFrame(parent, borderwidth=1, relief='raised') |
| 91 | |
| 92 | ttk.Label(frm, text='Input Functions:').pack() |
| 93 | w = self.ui_create_input_funcs_list(frm, lambda e: e.make_title()) |
| 94 | frm.add_widget(w) |
| 95 | w.pack() |
| 96 | |
| 97 | frm1 = ttk.Frame(frm) |
| 98 | frm1.pack() |
| 99 | ttk.Label(frm1, text='Conversion Direction:').grid(row=0, column=0) |
| 100 | w = self.ui_create_direction_dropdown(frm1) |
| 101 | frm.add_widget(w) |
| 102 | w.grid(row=0, column=1) |
| 103 | |
| 104 | frm2 = ttk.Frame(frm, borderwidth=1, relief='raised') |
| 105 | frm2.pack() |
| 106 | ttk.Label(frm2, text='Carrier:').pack() |
| 107 | carrier_frm = self.nco.make_config_widget(frm2) |
| 108 | for w in carrier_frm.ctrl_widgets: |
| 109 | frm.add_widget(w) |
| 110 | carrier_frm.pack() |
| 111 | |
| 112 | return frm |
| 113 | |
| 114 | def calc_oscillator_signal(self, t: np.ndarray) -> np.ndarray: |
| 115 | if self.direction == Direction.UP: |
| 116 | return self.nco.calc_signal(t) |
| 117 | elif self.direction == Direction.DOWN: |
| 118 | return np.conjugate(self.nco.calc_signal(t)) |
| 119 | else: |
| 120 | raise Exception('Invalid direction') |
| 121 | |
| 122 | def calc_input_signal(self, t: np.ndarray) -> np.ndarray: |
| 123 | x = np.zeros((len(self.input_funcs), len(t)), dtype='complex128') |
| 124 | for index, func in enumerate(self.input_funcs): |
| 125 | x[index, :] = func.calc_signal(t) |
| 126 | return np.sum(x, axis=0) |
| 127 | |
| 128 | def calc_output_signal(self, t: np.ndarray) -> np.ndarray: |
| 129 | inp = self.calc_input_signal(t) |
| 130 | carrier = self.calc_oscillator_signal(t) |
| 131 | re_mixed = (np.real(inp) * np.real(carrier)) - (np.imag(inp) * np.imag(carrier)) |
| 132 | im_mixed = (np.imag(inp) * np.real(carrier)) + (np.real(inp) * np.imag(carrier)) |
| 133 | return re_mixed + (1j * im_mixed) |
| 134 | |
| 135 | |
| 136 | class Ch06MixerFrame(BaseFrame): |
| 137 | def __init__(self, *args, **kwargs): |
| 138 | super().__init__(*args, **kwargs) |
| 139 | |
| 140 | self._config: ConfigCh06Mixer = default_store().get_config(ConfigCh06Mixer) |
| 141 | |
| 142 | ctrl_frm = self._create_control() |
| 143 | ctrl_frm.pack(side=LEFT) |
| 144 | |
| 145 | signal_frm = self._create_signal_tabs() |
| 146 | signal_frm.pack(expand=True, fill=BOTH) |
| 147 | |
| 148 | def _create_control(self) -> ConfigControlFrame: |
| 149 | frm = self._config.make_config_widget(self) |
| 150 | frm.widgets_on_change(self._on_change) |
| 151 | return frm |
| 152 | |
| 153 | def _on_change(self, _, __, ___): |
| 154 | default_store().save() |
| 155 | self.draw_td() |
| 156 | self.draw_fd() |
| 157 | |
| 158 | def _create_signal_tabs(self) -> ttk.Widget: |
| 159 | tabs = ttk.Notebook(self) |
| 160 | |
| 161 | td_frm = ttk.Frame(tabs) |
| 162 | tabs.add(td_frm, text='Time Domain') |
| 163 | self._td_fig = Figure(figsize=(12, 6), dpi=100) |
| 164 | self._td_canvas = FigureCanvasTkAgg(self._td_fig, td_frm) |
| 165 | self._td_canvas.get_tk_widget().pack(expand=True, fill=BOTH) |
| 166 | td_tb = NavigationToolbar2Tk(self._td_canvas, td_frm, pack_toolbar=False) |
| 167 | td_tb.pack(side=BOTTOM) |
| 168 | |
| 169 | fd_frm = ttk.Frame(tabs) |
| 170 | tabs.add(fd_frm, text='Frequency Domain') |
| 171 | self._fd_fig = Figure(figsize=(12, 6), dpi=100) |
| 172 | self._fd_canvas = FigureCanvasTkAgg(self._fd_fig, fd_frm) |
| 173 | self._fd_canvas.get_tk_widget().pack(expand=True, fill=BOTH) |
| 174 | fd_tb = NavigationToolbar2Tk(self._fd_canvas, fd_frm, pack_toolbar=False) |
| 175 | fd_tb.pack(side=BOTTOM) |
| 176 | |
| 177 | self.draw_td() |
| 178 | self.draw_fd() |
| 179 | |
| 180 | return tabs |
| 181 | |
| 182 | def draw_td(self): |
| 183 | self._td_fig.clear() |
| 184 | |
| 185 | ax_inp = self._td_fig.add_subplot(3, 1, 1) |
| 186 | ax_inp.set_xlim(0.0, 1.0) |
| 187 | ax_inp.set_xlabel('time') |
| 188 | ax_inp.set_ylabel('value') |
| 189 | ax_inp.set_title('Input Signal') |
| 190 | ax_nco = self._td_fig.add_subplot(3, 1, 2) |
| 191 | ax_nco.set_xlim(0.0, 1.0) |
| 192 | ax_nco.set_xlabel('time') |
| 193 | ax_nco.set_ylabel('value') |
| 194 | ax_nco.set_title('Numerically-Controlled Oscillator Signal') |
| 195 | ax_out = self._td_fig.add_subplot(3, 1, 3) |
| 196 | ax_out.set_xlim(0.0, 1.0) |
| 197 | ax_out.set_xlabel('time') |
| 198 | ax_out.set_ylabel('value') |
| 199 | ax_out.set_title('Output Signal') |
| 200 | |
| 201 | t = np.arange(0, SAMPLE_LEN, 1) / SAMPLE_LEN |
| 202 | |
| 203 | x_inp = self._config.calc_input_signal(t) |
| 204 | ax_inp.plot(t, np.real(x_inp), label='Input Re (I)', linestyle='solid', color='blue', linewidth=1) |
| 205 | ax_inp.plot(t, np.imag(x_inp), label='Input Im (Q)', linestyle='solid', color='red', linewidth=1) |
| 206 | ax_inp.legend() |
| 207 | |
| 208 | x_nco = self._config.calc_oscillator_signal(t) |
| 209 | ax_nco.plot(t, np.real(x_nco), label='NCO Re (I)', linestyle='solid', color='green', linewidth=1) |
| 210 | ax_nco.plot(t, np.imag(x_nco), label='NCO Im (Q)', linestyle='solid', color='orange', linewidth=1) |
| 211 | ax_nco.legend() |
| 212 | |
| 213 | x_out = self._config.calc_output_signal(t) |
| 214 | ax_out.plot(t, np.real(x_out), label='Output Re (I)', linestyle='solid', color='blue', linewidth=1) |
| 215 | ax_out.plot(t, np.imag(x_out), label='Output Im (Q)', linestyle='solid', color='red', linewidth=1) |
| 216 | ax_out.legend() |
| 217 | |
| 218 | self._td_fig.tight_layout() |
| 219 | self._td_canvas.draw() |
| 220 | |
| 221 | @classmethod |
| 222 | def _log_real(cls, x: np.ndarray) -> np.ndarray: |
| 223 | return np.real(x) |
| 224 | |
| 225 | @classmethod |
| 226 | def _log_imag(cls, x: np.ndarray) -> np.ndarray: |
| 227 | return np.imag(x) |
| 228 | |
| 229 | @classmethod |
| 230 | def _log_abs(cls, x: np.ndarray) -> np.ndarray: |
| 231 | return np.abs(x) |
| 232 | |
| 233 | def draw_fd(self): |
| 234 | self._fd_fig.clear() |
| 235 | |
| 236 | ax_inp = self._fd_fig.add_subplot(2, 1, 1) |
| 237 | ax_inp.set_xlim(-int(SAMPLE_LEN/2), int(SAMPLE_LEN/2)) |
| 238 | ax_inp.set_xlabel('frequency') |
| 239 | ax_inp.set_ylabel('value (dB)') |
| 240 | ax_inp.set_title('Input Signals') |
| 241 | ax_out = self._fd_fig.add_subplot(2, 1, 2) |
| 242 | ax_out.set_xlim(-int(SAMPLE_LEN/2), int(SAMPLE_LEN/2)) |
| 243 | ax_out.set_xlabel('frequency') |
| 244 | ax_out.set_ylabel('value (dB)') |
| 245 | ax_out.set_title('Output Signal') |
| 246 | |
| 247 | t_ovs = np.arange(0, (SAMPLE_LEN * FFT_OVERSAMPLING), 1) / SAMPLE_LEN |
| 248 | f_ovs = swap_freq(np.fft.fftfreq(t_ovs.shape[-1], 1.0/SAMPLE_LEN)) |
| 249 | |
| 250 | x_inp = self._config.calc_input_signal(t_ovs) |
| 251 | x_nco = self._config.calc_oscillator_signal(t_ovs) |
| 252 | ax_inp.plot(f_ovs, abs_log_fft(x_inp), label='Input', linestyle='solid', color='blue', linewidth=1) |
| 253 | ax_inp.plot(f_ovs, abs_log_fft(x_nco), label='NCO', linestyle='solid', color='green', linewidth=1) |
| 254 | ax_inp.legend() |
| 255 | |
| 256 | x_out = self._config.calc_output_signal(t_ovs) |
| 257 | ax_out.plot(f_ovs, abs_log_fft(x_out), label='Output', linestyle='solid', color='brown', linewidth=1) |
| 258 | ax_out.legend() |
| 259 | |
| 260 | self._fd_fig.tight_layout() |
| 261 | self._fd_canvas.draw() |
| 262 | |
| 263 | |
| 264 | class Ch06MixerWindow(Window): |
| 265 | GROUP = Ch06Group |
| 266 | TITLE = 'Digital Mixer' |
| 267 | FRAME = Ch06MixerFrame |
| 268 | |
| 269 | |
| 270 | if __name__ == '__main__': |
| 271 | Ch06MixerWindow.main() |
| 272 | |