blob: 2c365df1915e4324c3bf17baa3e75871d78e1625 [file] [log] [blame]
Philipp Le83e96b62022-05-01 17:36:30 +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, Listbox, LEFT, BOTH
10from pydantic import confloat, conint
11from dcs.config import default_store, ConfigObject, ui_create, ConfigControlFrame
12import numpy as np
13from scipy.interpolate import make_interp_spline
14from dcs.frames.base import BaseFrame, Window
15from dcs.frames.groups import Ch04Group
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
25@ui_create
26class Function(ConfigObject):
27 freq: confloat(ge=0.0, lt=128.0, multiple_of=0.01) = 1.0
28 amplitude: confloat(ge=0.0, lt=10.0, multiple_of=0.01) = 5.0
29 phase: confloat(ge=-180.0, le=180.0, multiple_of=0.1) = 0.0
30 offset: confloat(ge=-5.0, lt=5.0, multiple_of=0.01) = 0.0
31
32 def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame:
33 frm = ConfigControlFrame(parent, borderwidth=1, relief='raised')
34
35 ttk.Label(frm, text='Frequency:').grid(row=0, column=0)
36 self.ui_create_freq(frm).grid(row=0, column=1)
37
38 ttk.Label(frm, text='Amplitude:').grid(row=1, column=0)
39 self.ui_create_amplitude(frm).grid(row=1, column=1)
40
41 ttk.Label(frm, text='Phase:').grid(row=2, column=0)
42 self.ui_create_phase(frm).grid(row=2, column=1)
43 ttk.Label(frm, text='°').grid(row=2, column=2)
44
45 ttk.Label(frm, text='Offset:').grid(row=3, column=0)
46 self.ui_create_offset(frm).grid(row=3, column=1)
47
48 return frm
49
50 def calc_signal(self, t: np.ndarray) -> np.ndarray:
51 phasor = self.amplitude * np.exp(1j * self.phase * np.pi / 180)
52 phi = np.exp(1j * 2 * np.pi * self.freq * t)
53 return np.real(self.offset + (phasor * phi))
54
55 def make_title(self):
56 return f'n={self.freq}, {self.amplitude}, {self.phase}°'
57
58
59class QuantizationMethod(str, Enum):
60 Off = 'Off'
61 Linear = 'Linear'
62
63
64@ui_create
65class Quantization(ConfigObject):
66 method: QuantizationMethod = QuantizationMethod.Off
67 adc_min: confloat(ge=-50.0, lt=0.0, multiple_of=0.1) = -5.0
68 adc_max: confloat(ge=0.0, lt=50.0, multiple_of=0.1) = 5.0
69 adc_bits: conint(ge=1, lt=9) = 2
70
71 def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame:
72 frm = ConfigControlFrame(parent)
73
74 ttk.Label(frm, text='Method:').grid(row=0, column=0)
75 w = self.ui_create_method_dropdown(frm)
76 frm.add_widget(w)
77 w.grid(row=0, column=1)
78
79 ttk.Label(frm, text='ADC Min. Cut-off:').grid(row=1, column=0)
80 w = self.ui_create_adc_min(frm)
81 frm.add_widget(w)
82 w.grid(row=1, column=1)
83
84 ttk.Label(frm, text='ADC Max. Cut-off:').grid(row=2, column=0)
85 w = self.ui_create_adc_max(frm)
86 frm.add_widget(w)
87 w.grid(row=2, column=1)
88
89 ttk.Label(frm, text='ADC Bits:').grid(row=3, column=0)
90 w = self.ui_create_adc_bits(frm)
91 frm.add_widget(w)
92 w.grid(row=3, column=1)
93
94 return frm
95
96 def discrete_vals(self) -> np.ndarray:
97 if self.method == QuantizationMethod.Linear:
98 return np.linspace(self.adc_min, self.adc_max, 2**self.adc_bits)
99 else:
100 return np.array([0])
101
102 def quantize(self, x: np.ndarray) -> np.ndarray:
103 q = np.zeros((len(x), 2))
104 if self.method == QuantizationMethod.Linear:
105 v = self.discrete_vals()
106 for idx in range(len(x)):
107 q[idx, 0] = np.unravel_index(np.argmin(np.abs(x[idx] - v)), v.shape)[0]
108 q[idx, 1] = v[int(q[idx, 0])]
109 else:
110 q[:, 0] = x
111 q[:, 1] = x
112 return q
113
114
115class ConfigCh04SamplingFrame(ConfigControlFrame):
116 wdg_sampling_freq: ttk.Spinbox
117 wdg_sampling_phase: ttk.Spinbox
118 wdg_funcs: Listbox
119 frame_quantization: ConfigControlFrame
120
121
122@ui_create
123class ConfigCh04Sampling(ConfigObject):
124 _KEY = 'ch04_sampling'
125
126 sampling_freq: confloat(ge=1.0, lt=128.0, multiple_of=0.01) = 1.0
127 sampling_phase: confloat(ge=-180.0, le=180.0, multiple_of=0.1) = 0.0
128 functions: List[Function] = [
129 Function(freq=1.0, amplitude=5.0),
130 Function(freq=1.5, amplitude=5.0),
131 Function(freq=10.0, amplitude=5.0),
132 ]
133 quantization: Quantization = Quantization()
134
135 def make_config_widget(self, parent: ttk.Widget) -> ConfigControlFrame:
136 frm = ConfigCh04SamplingFrame(parent, borderwidth=1, relief='raised')
137
138 frm1 = ttk.Frame(frm)
139 frm1.pack()
140
141 ttk.Label(frm1, text='Sampling Frequency:').grid(row=0, column=0)
142 frm.wdg_sampling_freq = self.ui_create_sampling_freq(frm1)
143 frm.wdg_sampling_freq.grid(row=0, column=1)
144
145 ttk.Label(frm1, text='Sampling Phase:').grid(row=1, column=0)
146 frm.wdg_sampling_phase = self.ui_create_sampling_phase(frm1)
147 frm.wdg_sampling_phase.grid(row=1, column=1)
148 ttk.Label(frm1, text='°').grid(row=1, column=2)
149
150 ttk.Label(frm, text='Functions:').pack()
151 frm.wdg_funcs = self.ui_create_functions_list(frm, lambda e: e.make_title())
152 frm.wdg_funcs.pack()
153
154 frm2 = ConfigCh04SamplingFrame(frm, borderwidth=1, relief='raised')
155 frm2.pack()
156 ttk.Label(frm2, text='Quantization:').pack()
157 frm.frame_quantization = self.quantization.make_config_widget(frm2)
158 frm.frame_quantization.pack()
159
160 return frm
161
162
163class Ch04SamplingFrame(BaseFrame):
164 def __init__(self, *args, **kwargs):
165 super().__init__(*args, **kwargs)
166
167 self._config: ConfigCh04Sampling = default_store().get_config(ConfigCh04Sampling)
168
169 self.quant_out = ttk.Label(self, text='')
170
171 ctrl_frm = self._create_control()
172 ctrl_frm.pack(side=LEFT)
173
174 signal_frm = self._create_signal_canvas()
175 signal_frm.pack(expand=True, fill=BOTH)
176
177 self.quant_out.pack(expand=True, fill=BOTH)
178
179 def _create_control(self) -> ConfigCh04SamplingFrame:
180 frm: ConfigCh04SamplingFrame = self._config.make_config_widget(self)
181 frm.wdg_sampling_freq.listen_change(self._on_change)
182 frm.wdg_sampling_phase.listen_change(self._on_change)
183 frm.wdg_funcs.listen_change(self._on_change)
184 frm.frame_quantization.widgets_on_change(self._on_change)
185 return frm
186
187 def _on_change(self, _, __, ___):
188 default_store().save()
189 self.draw_signal()
190
191 def _create_signal_canvas(self) -> ttk.Widget:
192 frm = ttk.Frame(self)
193
194 self._signal_fig = Figure(figsize=(12, 6), dpi=100)
195
196 self._signal_canvas = FigureCanvasTkAgg(self._signal_fig, frm)
197 self._signal_canvas.get_tk_widget().pack(expand=True, fill=BOTH)
198
199 self.draw_signal()
200
201 return frm
202
203 def draw_signal(self):
204 LENGTH = 512
205
206 self._signal_fig.clear()
207 ax_analog = self._signal_fig.add_subplot(2, 1, 1)
208 ax_analog.set_xlim(-1.2, 1.2)
209 ax_analog.set_xlabel('time')
210 ax_analog.set_ylabel('value')
211 ax_analog.set_title('Analogue Signal')
212 ax_digital = self._signal_fig.add_subplot(2, 1, 2)
213 ax_digital.set_xlim(-1.2, 1.2)
214 ax_digital.set_xlabel('time')
215 ax_digital.set_ylabel('value')
216 if self._config.quantization.method == QuantizationMethod.Off:
217 ax_digital.set_title('Sampled Signal')
218 else:
219 ax_digital.set_title('Digital Signal')
220
221 t = np.linspace(-1.0, 1.01, LENGTH)
222 t_sampled = np.arange(-1.0 + (self._config.sampling_phase/(self._config.sampling_freq * 360)), 1.01, 1/(self._config.sampling_freq))
223
224 x = np.zeros((len(self._config.functions), len(t)))
225 x_sampled = np.zeros((len(self._config.functions), len(t_sampled)))
226
227 for index, func in enumerate(self._config.functions):
228 x[index, :] = func.calc_signal(t)
229 x_sampled[index, :] = func.calc_signal(t_sampled)
230 func = np.sum(x, axis=0)
231 func_sampled = np.sum(x_sampled, axis=0)
232
233 quant_val = self._config.quantization.discrete_vals()
234 quant_val = np.array([quant_val, quant_val])
235 func_quant = self._config.quantization.quantize(func_sampled)
236
237 if len(t_sampled) > 5:
238 x_interp = make_interp_spline(t_sampled, func_quant[:, 1])
239 t_interp = np.linspace(t_sampled.min(), t_sampled.max(), LENGTH)
240 func_interp = x_interp(t_interp)
241 else:
242 t_interp = np.zeros((0,))
243 func_interp = np.zeros((0,))
244
245 ax_analog.plot(t, func, label='Function', linestyle='solid', linewidth=1)
246 ax_analog.plot(t_sampled, func_sampled, label='Sampled', marker='x', linestyle='none', linewidth=1)
247 ax_analog.legend()
248
249 point_label = 'Sampled' if self._config.quantization.method == QuantizationMethod.Off else 'Quantized'
250
251 ax_digital.plot(t_interp, func_interp, label='Interpolated', linestyle='dashed', linewidth=1)
252 ax_digital.plot(t_sampled, func_quant[:, 1], label=point_label, marker='x', linestyle='none', linewidth=1)
253 ax_digital.legend()
254
255 if self._config.quantization.method != QuantizationMethod.Off:
256 ax_analog.plot(np.array([-1, 1]), quant_val, label='Quantization Value', linestyle='dotted', linewidth=1)
257 ax_digital.plot(np.array([-1, 1]), quant_val, label='Quantization Value', linestyle='dotted', linewidth=1)
258
259 v_str = ', '.join([str(int(x)) for x in list(func_quant[:, 0])])
260 self.quant_out.configure(text=f'Quantized = [{v_str}]')
261 else:
262 self.quant_out.configure(text='')
263
264 self._signal_canvas.draw()
265
266
267class Ch04SamplingWindow(Window):
268 GROUP = Ch04Group
269 TITLE = 'Sampling'
270 FRAME = Ch04SamplingFrame
271
272
273if __name__ == '__main__':
274 Ch04SamplingWindow.main()
275