blob: 76d0fbecc976e141eec18ade91903020b1fef4be [file] [log] [blame]
Philipp Le8aaf4232022-05-02 22:45:27 +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
10from pydantic import confloat
11from dcs.config import default_store, ConfigObject, ui_create, ConfigControlFrame
12import numpy as np
13from dcs.frames.base import BaseFrame, Window
14from dcs.frames.groups import Ch05Group
15from dcs.utils import swap_freq, abs_log_fft
16from typing import List
17from enum import Enum
18
19import matplotlib
20matplotlib.use('TkAgg')
21from matplotlib.figure import Figure
22from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
23
24
25SAMPLE_LEN = 512
26FFT_OVERSAMPLING = 64
27
28
29@ui_create
30class Function(ConfigObject):
31 freq: confloat(ge=0.0, lt=SAMPLE_LEN/4, multiple_of=(4.0/FFT_OVERSAMPLING)) = 1.0
32 amplitude: confloat(ge=0.0, lt=10.0, multiple_of=0.01) = 5.0
33 phase: confloat(ge=-180.0, le=180.0, multiple_of=0.1) = 0.0
34 offset: confloat(ge=-5.0, lt=5.0, multiple_of=0.01) = 0.0
35
36 def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame:
37 frm = ConfigControlFrame(parent)
38
39 ttk.Label(frm, text='Frequency:').grid(row=0, column=0)
40 w = self.ui_create_freq(frm)
41 frm.add_widget(w)
42 w.grid(row=0, column=1)
43
44 ttk.Label(frm, text='Amplitude:').grid(row=1, column=0)
45 w = self.ui_create_amplitude(frm)
46 frm.add_widget(w)
47 w.grid(row=1, column=1)
48
49 ttk.Label(frm, text='Phase:').grid(row=2, column=0)
50 w = self.ui_create_phase(frm)
51 frm.add_widget(w)
52 w.grid(row=2, column=1)
53 ttk.Label(frm, text='°').grid(row=2, column=2)
54
55 ttk.Label(frm, text='Offset:').grid(row=3, column=0)
56 w = self.ui_create_offset(frm)
57 frm.add_widget(w)
58 w.grid(row=3, column=1)
59
60 return frm
61
62 def calc_signal(self, t: np.ndarray, phi_mod_deg: int | np.ndarray = 0) -> np.ndarray:
63 phasor = self.amplitude * np.exp(1j * ((self.phase * np.pi / 180) + phi_mod_deg))
64 phi = np.exp(1j * 2 * np.pi * self.freq * t)
65 return np.real(self.offset + (phasor * phi))
66
67 def make_title(self):
68 return f'n={self.freq}, {self.amplitude}, {self.phase}°'
69
70
71class ModulationMethod(str, Enum):
72 AM_DSB_TC = 'Amplitude Modulation (DSB-TC)'
73 AM_DSB_SC = 'Amplitude Modulation (DSB-SC)'
74 PM = 'Phase Modulation'
75
76
77@ui_create
78class ConfigCh05Modulation(ConfigObject):
79 _KEY = 'ch05_modulation'
80
81 baseband_funcs: List[Function] = [
82 Function(freq=1.0, amplitude=1.0),
83 Function(freq=1.5, amplitude=1.0),
84 ]
85 carrier: Function = Function(freq=10.0, amplitude=5.0)
86 method: ModulationMethod = ModulationMethod.AM_DSB_TC
87 am_mod_index: confloat(ge=0.0, lt=10.0, multiple_of=0.01) = 0.5
88 pm_mod_index: confloat(ge=0.0, lt=10.0, multiple_of=0.00001) = 0.5
89
90 def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame:
91 frm = ConfigControlFrame(parent, borderwidth=1, relief='raised')
92
93 ttk.Label(frm, text='Functions:').pack()
94 w = self.ui_create_baseband_funcs_list(frm, lambda e: e.make_title())
95 frm.add_widget(w)
96 w.pack()
97
98 frm2 = ttk.Frame(frm, borderwidth=1, relief='raised')
99 frm2.pack()
100 ttk.Label(frm2, text='Carrier:').pack()
101 carrier_frm = self.carrier.make_config_widget(frm2)
102 for w in carrier_frm.ctrl_widgets:
103 frm.add_widget(w)
104 carrier_frm.pack()
105
106 frm1 = ttk.Frame(frm)
107 frm1.pack()
108
109 ttk.Label(frm1, text='Modulation Method:').grid(row=0, column=0)
110 w = self.ui_create_method_dropdown(frm1)
111 frm.add_widget(w)
112 w.grid(row=0, column=1)
113
114 ttk.Label(frm1, text='AM Modulation Index:').grid(row=1, column=0)
115 w = self.ui_create_am_mod_index(frm1)
116 frm.add_widget(w)
117 w.grid(row=1, column=1)
118
119 ttk.Label(frm1, text='PM Modulation Index:').grid(row=2, column=0)
120 w = self.ui_create_pm_mod_index(frm1)
121 frm.add_widget(w)
122 w.grid(row=2, column=1)
123
124 return frm
125
126 def calc_baseband_signal(self, t: np.ndarray) -> np.ndarray:
127 x = np.zeros((len(self.baseband_funcs), len(t)))
128 for index, func in enumerate(self.baseband_funcs):
129 x[index, :] = func.calc_signal(t)
130 return np.sum(x, axis=0)
131
132 def calc_carrier_signal(self, t: np.ndarray, phi_mod_deg: int | np.ndarray = 0) -> np.ndarray:
133 return self.carrier.calc_signal(t, phi_mod_deg)
134
135 def _calc_am_dsb_tc(self, t: np.ndarray) -> np.ndarray:
136 return self.calc_carrier_signal(t) * (1 + (self.am_mod_index * self.calc_baseband_signal(t)))
137
138 def _calc_am_dsb_sc(self, t: np.ndarray) -> np.ndarray:
139 return self.calc_carrier_signal(t) * self.am_mod_index * self.calc_baseband_signal(t)
140
141 def _calc_pm(self, t: np.ndarray) -> np.ndarray:
142 phi_mod_deg = 2 * np.pi * self.pm_mod_index * self.calc_baseband_signal(t)
143 return self.calc_carrier_signal(t, phi_mod_deg)
144
145 def calc_modulated(self, t: np.ndarray) -> np.ndarray:
146 if self.method == ModulationMethod.AM_DSB_TC:
147 return self._calc_am_dsb_tc(t)
148 elif self.method == ModulationMethod.AM_DSB_SC:
149 return self._calc_am_dsb_sc(t)
150 elif self.method == ModulationMethod.PM:
151 return self._calc_pm(t)
152 else:
153 raise Exception('Unknown modulation method')
154
155
156class Ch05ModulationFrame(BaseFrame):
157 def __init__(self, *args, **kwargs):
158 super().__init__(*args, **kwargs)
159
160 self._config: ConfigCh05Modulation = default_store().get_config(ConfigCh05Modulation)
161
162 ctrl_frm = self._create_control()
163 ctrl_frm.pack(side=LEFT)
164
165 signal_frm = self._create_signal_canvas()
166 signal_frm.pack(expand=True, fill=BOTH)
167
168 def _create_control(self) -> ConfigControlFrame:
169 frm = self._config.make_config_widget(self)
170 frm.widgets_on_change(self._on_change)
171 return frm
172
173 def _on_change(self, _, __, ___):
174 default_store().save()
175 self.draw_signal()
176
177 def _create_signal_canvas(self) -> ttk.Widget:
178 frm = ttk.Frame(self)
179
180 self._signal_fig = Figure(figsize=(12, 6), dpi=100)
181
182 self._signal_canvas = FigureCanvasTkAgg(self._signal_fig, frm)
183 self._signal_canvas.get_tk_widget().pack(expand=True, fill=BOTH)
184
185 self.draw_signal()
186
187 return frm
188
189 def draw_signal(self):
190 self._signal_fig.clear()
191
192 ax_inp = self._signal_fig.add_subplot(3, 1, 1)
193 ax_inp.set_xlim(0.0, 1.0)
194 ax_inp.set_xlabel('time')
195 ax_inp.set_ylabel('value')
196 ax_inp.set_title('Input Signals')
197 ax_mod = self._signal_fig.add_subplot(3, 1, 2)
198 ax_mod.set_xlim(0.0, 1.0)
199 ax_mod.set_xlabel('time')
200 ax_mod.set_ylabel('value')
201 ax_mod.set_title('Modulated Signal')
202 ax_fft = self._signal_fig.add_subplot(3, 1, 3)
203 ax_fft.set_xlim(0, int(SAMPLE_LEN/4))
204 ax_fft.set_xlabel('frequency')
205 ax_fft.set_ylabel('value (logarithmic)')
206 ax_fft.set_title('Frequency-Domain')
207
208 t = np.arange(0, SAMPLE_LEN, 1) / SAMPLE_LEN
209 t_ovs = np.arange(0, (SAMPLE_LEN * FFT_OVERSAMPLING), 1) / SAMPLE_LEN
210
211 f_ovs = swap_freq(np.fft.fftfreq(t_ovs.shape[-1], 1.0/SAMPLE_LEN))
212
213 ax_inp.plot(t, self._config.calc_baseband_signal(t), label='Baseband', linestyle='solid', color='blue', linewidth=1)
214 ax_inp.plot(t, self._config.calc_carrier_signal(t), label='Carrier', linestyle='solid', color='red', linewidth=1)
215 ax_inp.legend()
216
217 ax_mod.plot(t, self._config.calc_modulated(t), label='Modulated', linestyle='solid', color='green', linewidth=1)
218 ax_mod.legend()
219
220 ax_fft.plot(f_ovs, abs_log_fft(self._config.calc_baseband_signal(t_ovs)), label='Baseband', linestyle='solid', color='blue', linewidth=1)
221 ax_fft.plot(f_ovs, abs_log_fft(self._config.calc_carrier_signal(t_ovs)), label='Carrier', linestyle='solid', color='red', linewidth=1)
222 ax_fft.plot(f_ovs, abs_log_fft(self._config.calc_modulated(t_ovs)), label='Modulated', linestyle='solid', color='green', linewidth=1)
223 ax_fft.legend()
224
225 self._signal_fig.tight_layout()
226
227 self._signal_canvas.draw()
228
229
230class Ch05ModulationWindow(Window):
231 GROUP = Ch05Group
232 TITLE = 'Modulation'
233 FRAME = Ch05ModulationFrame
234
235
236if __name__ == '__main__':
237 Ch05ModulationWindow.main()
238