blob: ae3c91287b19e91dfebace6fb51c4cdc95b2b3da [file] [log] [blame]
Philipp Le66248592022-05-09 20:25:18 +02001# 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
7from __future__ import annotations
8
9from tkinter import ttk, LEFT, BOTH, BOTTOM
10from pydantic import confloat
11from dcs.config import default_store, ConfigObject, ui_create, ConfigControlFrame
12import numpy as np
13import scipy.signal
14from dcs.frames.base import BaseFrame, Window
15from dcs.frames.groups import Ch05Group
16from dcs.utils import swap_freq
17from typing import List
18from enum import Enum
19
20import matplotlib
21matplotlib.use('TkAgg')
22from matplotlib.figure import Figure
23from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
24
25
26SAMPLE_LEN = 512
27FFT_OVERSAMPLING = 64
28
29
30@ui_create
31class Function(ConfigObject):
32 freq: confloat(ge=-SAMPLE_LEN/4, lt=SAMPLE_LEN/4, multiple_of=(4.0/FFT_OVERSAMPLING)) = 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 self.offset + (phasor * phi)
67
68 def make_title(self):
69 return f'n={self.freq}, {self.amplitude}, {self.phase}°'
70
71
72class Direction(str, Enum):
73 DOWN = 'Down Conversion'
74 UP = 'Up Conversion'
75
76
77class DisplayMode(str, Enum):
78 FULL = 'Full (I, Q, I+jQ)'
79 IQ = 'IQ Channels (I, Q)'
80 CMPLX = 'Complex (I+jQ)'
81 BASEBAND = 'Baseband only'
82 CARRIER = 'Carrier only'
83 HF = 'HF only'
84
85
86@ui_create
87class ConfigCh05Iq(ConfigObject):
88 _KEY = 'ch05_iq'
89
90 hf_funcs: List[Function] = [
91 Function(freq=-1.0, amplitude=1.0, phase=90.0),
92 Function(freq=2.0, amplitude=1.0, phase=0.0),
93 ]
94 baseband_funcs: List[Function] = [
95 Function(freq=18.0, amplitude=1.0, phase=0.0),
96 Function(freq=21.0, amplitude=1.0, phase=90.0),
97 ]
98 direction: Direction = Direction.DOWN
99 carrier: Function = Function(freq=20.0, amplitude=1.0)
100 lp_cutoff_freq: confloat(ge=0, lt=SAMPLE_LEN/4, multiple_of=(4.0/FFT_OVERSAMPLING)) = 0.0
101 display: DisplayMode = DisplayMode.FULL
102
103 def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame:
104 frm = ConfigControlFrame(parent, borderwidth=1, relief='raised')
105
106 ttk.Label(frm, text='HF Functions (for Down Conversion):').pack()
107 w = self.ui_create_hf_funcs_list(frm, lambda e: e.make_title())
108 frm.add_widget(w)
109 w.pack()
110
111 ttk.Label(frm, text='Baseband Functions (for Up Conversion):').pack()
112 w = self.ui_create_baseband_funcs_list(frm, lambda e: e.make_title())
113 frm.add_widget(w)
114 w.pack()
115
116 frm1 = ttk.Frame(frm)
117 frm1.pack()
118 ttk.Label(frm1, text='Conversion Direction:').grid(row=0, column=0)
119 w = self.ui_create_direction_dropdown(frm1)
120 frm.add_widget(w)
121 w.grid(row=0, column=1)
122
123 frm2 = ttk.Frame(frm, borderwidth=1, relief='raised')
124 frm2.pack()
125 ttk.Label(frm2, text='Carrier:').pack()
126 carrier_frm = self.carrier.make_config_widget(frm2)
127 for w in carrier_frm.ctrl_widgets:
128 frm.add_widget(w)
129 carrier_frm.pack()
130
131 frm3 = ttk.Frame(frm)
132 frm3.pack()
133 ttk.Label(frm3, text='Down Conv. Baseband Low Pass Cut-off:').grid(row=0, column=0)
134 ttk.Label(frm3, text='(0 = disable):').grid(row=1, column=1)
135 w = self.ui_create_lp_cutoff_freq(frm3)
136 frm.add_widget(w)
137 w.grid(row=0, column=1)
138 ttk.Label(frm3, text='Display Mode:').grid(row=2, column=0)
139 w = self.ui_create_display_dropdown(frm3)
140 frm.add_widget(w)
141 w.grid(row=2, column=1)
142
143 return frm
144
145 def calc_carrier_signal(self, t: np.ndarray) -> np.ndarray:
146 return self.carrier.calc_signal(t)
147
148 def calc_baseband_signal(self, t: np.ndarray) -> np.ndarray:
149 if self.direction == Direction.UP:
150 x = np.zeros((len(self.baseband_funcs), len(t)), dtype='complex128')
151 for index, func in enumerate(self.baseband_funcs):
152 x[index, :] = func.calc_signal(t)
153 return np.sum(x, axis=0)
154 elif self.direction == Direction.DOWN:
155 i_mixed = self.calc_hf_signal(t) * np.real(self.calc_carrier_signal(t))
156 q_mixed = self.calc_hf_signal(t) * np.imag(self.calc_carrier_signal(t))
157 base = i_mixed - (1j * q_mixed)
158
159 if self.lp_cutoff_freq == 0:
160 return base
161 else:
162 b, a = scipy.signal.butter(5, self.lp_cutoff_freq, btype='low', fs=SAMPLE_LEN)
163 zi = scipy.signal.lfilter_zi(b, a)
164 z, _ = scipy.signal.lfilter(b, a, base, zi=zi*base[0])
165 return z
166 else:
167 raise Exception('Invalid direction')
168
169 def calc_hf_signal(self, t: np.ndarray) -> np.ndarray:
170 if self.direction == Direction.DOWN:
171 x = np.zeros((len(self.hf_funcs), len(t)), dtype='float128')
172 for index, func in enumerate(self.hf_funcs):
173 x[index, :] = np.real(func.calc_signal(t))
174 return np.sum(x, axis=0)
175 elif self.direction == Direction.UP:
176 i_mixed = np.real(self.calc_baseband_signal(t)) * np.real(self.calc_carrier_signal(t))
177 q_mixed = np.imag(self.calc_baseband_signal(t)) * np.imag(self.calc_carrier_signal(t))
178 return i_mixed - q_mixed
179 else:
180 raise Exception('Invalid direction')
181
182
183class Ch05IqFrame(BaseFrame):
184 def __init__(self, *args, **kwargs):
185 super().__init__(*args, **kwargs)
186
187 self._config: ConfigCh05Iq = default_store().get_config(ConfigCh05Iq)
188
189 ctrl_frm = self._create_control()
190 ctrl_frm.pack(side=LEFT)
191
192 signal_frm = self._create_signal_tabs()
193 signal_frm.pack(expand=True, fill=BOTH)
194
195 def _create_control(self) -> ConfigControlFrame:
196 frm = self._config.make_config_widget(self)
197 frm.widgets_on_change(self._on_change)
198 return frm
199
200 def _on_change(self, _, __, ___):
201 default_store().save()
202 self.draw_input()
203 self.draw_fft()
204 self.draw_output()
205
206 def _create_signal_tabs(self) -> ttk.Widget:
207 tabs = ttk.Notebook(self)
208
209 in_frm = ttk.Frame(tabs)
210 tabs.add(in_frm, text='Input Signals')
211 self._in_fig = Figure(figsize=(12, 6), dpi=100)
212 self._in_canvas = FigureCanvasTkAgg(self._in_fig, in_frm)
213 self._in_canvas.get_tk_widget().pack(expand=True, fill=BOTH)
214
215 fft_frm = ttk.Frame(tabs)
216 tabs.add(fft_frm, text='Frequency Domain')
217 self._fft_fig = Figure(figsize=(12, 6), dpi=100)
218 self._fft_canvas = FigureCanvasTkAgg(self._fft_fig, fft_frm)
219 self._fft_canvas.get_tk_widget().pack(expand=True, fill=BOTH)
220 fft_tb = NavigationToolbar2Tk(self._fft_canvas, fft_frm, pack_toolbar=False)
221 fft_tb.pack(side=BOTTOM)
222
223 out_frm = ttk.Frame(tabs)
224 tabs.add(out_frm, text='Output Signals')
225 self._out_fig = Figure(figsize=(12, 6), dpi=100)
226 self._out_canvas = FigureCanvasTkAgg(self._out_fig, out_frm)
227 self._out_canvas.get_tk_widget().pack(expand=True, fill=BOTH)
228
229 self.draw_input()
230 self.draw_fft()
231 self.draw_output()
232
233 return tabs
234
235 def draw_input(self):
236 self._in_fig.clear()
237
238 ax_inp = self._in_fig.add_subplot(3, 1, 1)
239 ax_inp.set_xlim(0.0, 1.0)
240 ax_inp.set_xlabel('time')
241 ax_inp.set_ylabel('value')
242 ax_inp.set_title('Baseband Signal' if self._config.direction == Direction.UP else 'HF Signal')
243 ax_carr = self._in_fig.add_subplot(3, 1, 2)
244 ax_carr.set_xlim(0.0, 1.0)
245 ax_carr.set_xlabel('time')
246 ax_carr.set_ylabel('value')
247 ax_carr.set_title('Carrier Signal')
248 ax_3d = self._in_fig.add_subplot(3, 1, 3, projection='3d')
249 ax_3d.set_xlabel('real')
250 ax_3d.set_ylabel('imaginary')
251 ax_3d.set_zlabel('time')
252
253 t = np.arange(0, SAMPLE_LEN, 1) / SAMPLE_LEN
254
255 if self._config.direction == Direction.UP:
256 x_base = self._config.calc_baseband_signal(t)
257 ax_inp.plot(t, np.real(x_base), label='Baseband I', linestyle='solid', color='blue', linewidth=1)
258 ax_inp.plot(t, np.imag(x_base), label='Baseband Q', linestyle='solid', color='red', linewidth=1)
259 ax_3d.plot(np.real(x_base), np.imag(x_base), t, label='Baseband', linestyle='solid', color='purple', linewidth=1)
260 elif self._config.direction == Direction.DOWN:
261 x_hf = self._config.calc_hf_signal(t)
262 ax_inp.plot(t, x_hf, label='HF', linestyle='solid', color='brown', linewidth=1)
263 ax_3d.plot(x_hf, np.zeros(len(x_hf)), t, label='HF', linestyle='solid', color='brown', linewidth=1)
264 else:
265 raise Exception('Invalid direction')
266 ax_inp.legend()
267
268 x_carr = self._config.calc_carrier_signal(t)
269 ax_carr.plot(t, np.real(x_carr), label='Carrier I', linestyle='solid', color='green', linewidth=1)
270 ax_carr.plot(t, np.imag(x_carr), label='Carrier Q', linestyle='solid', color='orange', linewidth=1)
271 ax_carr.legend()
272
273 ax_3d.plot(np.real(x_carr), np.imag(x_carr), t, label='Carrier', linestyle='solid', color='yellow', linewidth=1)
274 ax_3d.legend()
275
276 self._in_fig.tight_layout()
277 self._in_canvas.draw()
278
279 @classmethod
280 def _log_real(cls, x: np.ndarray) -> np.ndarray:
281 return np.real(x)
282
283 @classmethod
284 def _log_imag(cls, x: np.ndarray) -> np.ndarray:
285 return np.imag(x)
286
287 @classmethod
288 def _log_abs(cls, x: np.ndarray) -> np.ndarray:
289 return np.abs(x)
290
291 def draw_fft(self):
292 self._fft_fig.clear()
293
294 # ax_3d = self._fft_fig.add_subplot(3, 1, 1, projection='3d')
295 # ax_3d.set_zlim(-int(SAMPLE_LEN/4), int(SAMPLE_LEN/4))
296 # ax_3d.set_xlabel('real')
297 # ax_3d.set_ylabel('imag')
298 # ax_3d.set_zlabel('frequency')
299 #ax_real = self._fft_fig.add_subplot(3, 1, 2)
300 ax_real = self._fft_fig.add_subplot(2, 1, 1)
301 ax_real.set_xlim(-int(SAMPLE_LEN/4), int(SAMPLE_LEN/4))
302 ax_real.set_xlabel('frequency')
303 ax_real.set_ylabel('value')
304 ax_real.set_title('Real(FFT)')
305 #ax_imag = self._fft_fig.add_subplot(3, 1, 3)
306 ax_imag = self._fft_fig.add_subplot(2, 1, 2)
307 ax_imag.set_xlim(-int(SAMPLE_LEN/4), int(SAMPLE_LEN/4))
308 ax_imag.set_xlabel('frequency')
309 ax_imag.set_ylabel('value')
310 ax_imag.set_title('Imag(FFT)')
311
312 t_ovs = np.arange(0, (SAMPLE_LEN * FFT_OVERSAMPLING), 1) / SAMPLE_LEN
313 f_ovs = swap_freq(np.fft.fftfreq(t_ovs.shape[-1], 1.0/SAMPLE_LEN))
314
315 x_base = self._config.calc_baseband_signal(t_ovs)
316 X_base_i = swap_freq(np.fft.fft(np.real(x_base))) / len(t_ovs)
317 X_base_q = swap_freq(np.fft.fft(np.imag(x_base))) / len(t_ovs)
318 X_base_cmplx = swap_freq(np.fft.fft(x_base)) / len(t_ovs)
319 if (self._config.display == DisplayMode.FULL) or (self._config.display == DisplayMode.IQ) or (self._config.display == DisplayMode.BASEBAND):
320 ax_real.plot(f_ovs, np.real(X_base_i), label='Baseband I', linestyle='solid', color='blue', marker='x', linewidth=1)
321 ax_imag.plot(f_ovs, np.imag(X_base_i), label='Baseband I', linestyle='solid', color='blue', marker='x', linewidth=1)
322 #ax_3d.plot(np.real(X_base_i), np.imag(X_base_i), f_ovs, label='Baseband I', linestyle='solid', color='blue', marker='x', linewidth=1)
323 ax_real.plot(f_ovs, np.real(X_base_q), label='Baseband Q', linestyle='solid', color='red', marker='o', linewidth=1)
324 ax_imag.plot(f_ovs, np.imag(X_base_q), label='Baseband Q', linestyle='solid', color='red', marker='o', linewidth=1)
325 #ax_3d.plot(np.real(X_base_q), np.imag(X_base_q), f_ovs, label='Baseband Q', linestyle='solid', color='red', marker='o', linewidth=1)
326 if (self._config.display == DisplayMode.FULL) or (self._config.display == DisplayMode.CMPLX) or (self._config.display == DisplayMode.BASEBAND):
327 ax_real.plot(f_ovs, np.real(X_base_cmplx), label='Baseband I + j*Q', linestyle='solid', color='purple', marker='^', linewidth=1)
328 ax_imag.plot(f_ovs, np.imag(X_base_cmplx), label='Baseband I + j*Q', linestyle='solid', color='purple', marker='^', linewidth=1)
329 #ax_3d.plot(np.real(X_base_cmplx), np.imag(X_base_cmplx), f_ovs, label='Baseband I + j*Q', linestyle='solid', color='purple', marker='^', linewidth=1)
330
331 x_carr = self._config.calc_carrier_signal(t_ovs)
332 X_carr_i = swap_freq(np.fft.fft(np.real(x_carr))) / len(t_ovs)
333 X_carr_q = swap_freq(np.fft.fft(np.imag(x_carr))) / len(t_ovs)
334 X_carr_cmplx = swap_freq(np.fft.fft(x_carr)) / len(t_ovs)
335 if (self._config.display == DisplayMode.FULL) or (self._config.display == DisplayMode.IQ) or (self._config.display == DisplayMode.CARRIER):
336 ax_real.plot(f_ovs, np.real(X_carr_i), label='Carrier I', linestyle='solid', color='green', marker='x', linewidth=1)
337 ax_imag.plot(f_ovs, np.imag(X_carr_i), label='Carrier I', linestyle='solid', color='green', marker='x', linewidth=1)
338 #ax_3d.plot(np.real(X_carr_i), np.imag(X_carr_i), f_ovs, label='Baseband I', linestyle='solid', color='green', marker='x', linewidth=1)
339 ax_real.plot(f_ovs, np.real(X_carr_q), label='Carrier Q', linestyle='solid', color='orange', marker='o', linewidth=1)
340 ax_imag.plot(f_ovs, np.imag(X_carr_q), label='Carrier Q', linestyle='solid', color='orange', marker='o', linewidth=1)
341 #ax_3d.plot(np.real(X_carr_q), np.imag(X_carr_q), f_ovs, label='Baseband Q', linestyle='solid', color='orange', marker='o', linewidth=1)
342 if (self._config.display == DisplayMode.FULL) or (self._config.display == DisplayMode.CMPLX) or (self._config.display == DisplayMode.CARRIER):
343 ax_real.plot(f_ovs, np.real(X_carr_cmplx), label='Carrier I + j*Q', linestyle='solid', color='yellow', marker='^', linewidth=1)
344 ax_imag.plot(f_ovs, np.imag(X_carr_cmplx), label='Carrier I + j*Q', linestyle='solid', color='yellow', marker='^', linewidth=1)
345 #ax_3d.plot(np.real(X_carr_cmplx), np.imag(X_carr_cmplx), f_ovs, label='Carrier I + j*Q', linestyle='solid', color='yellow', marker='^', linewidth=1)
346
347 x_hf = self._config.calc_hf_signal(t_ovs)
348 X_hf_cmplx = swap_freq(np.fft.fft(x_hf)) / len(t_ovs)
349 if (self._config.display != DisplayMode.BASEBAND) and (self._config.display != DisplayMode.CARRIER):
350 ax_real.plot(f_ovs, np.real(X_hf_cmplx), label='HF', linestyle='solid', color='brown', marker='^', linewidth=1)
351 ax_imag.plot(f_ovs, np.imag(X_hf_cmplx), label='HF', linestyle='solid', color='brown', marker='^', linewidth=1)
352 #ax_3d.plot(np.real(X_hf_cmplx), np.imag(X_hf_cmplx), f_ovs, label='HF', linestyle='solid', color='brown', linewidth=1)
353
354 #ax_3d.legend()
355 ax_real.legend()
356 ax_imag.legend()
357
358 self._fft_fig.tight_layout()
359 self._fft_canvas.draw()
360
361 def draw_output(self):
362 self._out_fig.clear()
363
364 ax_outp = self._out_fig.add_subplot(2, 1, 1)
365 ax_outp.set_xlim(0.0, 1.0)
366 ax_outp.set_xlabel('time')
367 ax_outp.set_ylabel('value')
368 ax_outp.set_title('HF Signal' if self._config.direction == Direction.UP else 'Baseband Signal')
369 ax_3d = self._out_fig.add_subplot(2, 1, 2, projection='3d')
370 ax_3d.set_xlabel('real')
371 ax_3d.set_ylabel('imaginary')
372 ax_3d.set_zlabel('time')
373
374 t = np.arange(0, SAMPLE_LEN, 1) / SAMPLE_LEN
375
376 if self._config.direction == Direction.UP:
377 x_hf = self._config.calc_hf_signal(t)
378 ax_outp.plot(t, x_hf, label='HF', linestyle='solid', color='brown', linewidth=1)
379 ax_3d.plot(x_hf, np.zeros(len(x_hf)), t, label='HF', linestyle='solid', color='brown', linewidth=1)
380 elif self._config.direction == Direction.DOWN:
381 x_base = self._config.calc_baseband_signal(t)
382 ax_outp.plot(t, np.real(x_base), label='Baseband I', linestyle='solid', color='blue', linewidth=1)
383 ax_outp.plot(t, np.imag(x_base), label='Baseband Q', linestyle='solid', color='red', linewidth=1)
384 ax_3d.plot(np.real(x_base), np.imag(x_base), t, label='Baseband', linestyle='solid', color='purple', linewidth=1)
385 else:
386 raise Exception('Invalid direction')
387 ax_outp.legend()
388 ax_3d.legend()
389
390 self._out_fig.tight_layout()
391 self._out_canvas.draw()
392
393
394class Ch05IqWindow(Window):
395 GROUP = Ch05Group
396 TITLE = 'IQ Mixer'
397 FRAME = Ch05IqFrame
398
399
400if __name__ == '__main__':
401 Ch05IqWindow.main()
402