cicwave 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cicwave/__init__.py +25 -0
- cicwave/cli.py +176 -0
- cicwave/command.py +71 -0
- cicwave/ngraw.py +105 -0
- cicwave/pivot.py +240 -0
- cicwave/theme.py +108 -0
- cicwave/wave_pg.py +3962 -0
- cicwave/wavefiles.py +935 -0
- cicwave-0.5.0.dist-info/METADATA +242 -0
- cicwave-0.5.0.dist-info/RECORD +14 -0
- cicwave-0.5.0.dist-info/WHEEL +5 -0
- cicwave-0.5.0.dist-info/entry_points.txt +5 -0
- cicwave-0.5.0.dist-info/licenses/LICENSE +21 -0
- cicwave-0.5.0.dist-info/top_level.txt +1 -0
cicwave/wave_pg.py
ADDED
|
@@ -0,0 +1,3962 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Waveform viewer using PySide6 + pyqtgraph.
|
|
5
|
+
|
|
6
|
+
Install: pip install PySide6 pyqtgraph
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
import re
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
from importlib.metadata import version as _pkg_version
|
|
15
|
+
|
|
16
|
+
from PySide6.QtWidgets import (
|
|
17
|
+
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
|
|
18
|
+
QSplitter, QTreeWidget, QTreeWidgetItem, QLineEdit, QTabWidget,
|
|
19
|
+
QPushButton, QLabel, QCheckBox, QTextEdit, QFileDialog, QDialog,
|
|
20
|
+
QInputDialog, QMenu, QComboBox, QTableWidget, QTableWidgetItem,
|
|
21
|
+
QHeaderView, QAbstractItemView, QMessageBox)
|
|
22
|
+
from PySide6 import QtCore
|
|
23
|
+
from PySide6.QtCore import Qt, Signal, QEvent, QSettings, QTimer
|
|
24
|
+
from PySide6.QtGui import (QKeySequence, QFont, QFontDatabase, QShortcut,
|
|
25
|
+
QPainter, QColor, QPalette)
|
|
26
|
+
|
|
27
|
+
import pyqtgraph as pg
|
|
28
|
+
|
|
29
|
+
from .wavefiles import WaveFile, WaveFiles, parse_unit_from_name
|
|
30
|
+
from .theme import THEMES, _get_theme, _set_active_theme
|
|
31
|
+
from matplotlib.ticker import EngFormatter
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _mono_font(size):
|
|
35
|
+
"""Return the system fixed-width font at the given point size."""
|
|
36
|
+
f = QFontDatabase.systemFont(QFontDatabase.FixedFont)
|
|
37
|
+
f.setPointSize(size)
|
|
38
|
+
return f
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
ZOOM_FACTOR = 1.3
|
|
42
|
+
|
|
43
|
+
PLOT_STYLES = ['Lines', 'Markers', 'Lines+Markers', 'Steps']
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _read_saved_default_xaxis():
|
|
47
|
+
"""Column name persisted via Edit → Default X Axis (empty = auto)."""
|
|
48
|
+
s = QSettings("cicwave", "cicwave")
|
|
49
|
+
v = s.value("default_x_axis", "")
|
|
50
|
+
if not v:
|
|
51
|
+
return None
|
|
52
|
+
t = str(v).strip()
|
|
53
|
+
return t or None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _write_saved_default_xaxis(name):
|
|
57
|
+
s = QSettings("cicwave", "cicwave")
|
|
58
|
+
s.setValue("default_x_axis", name or "")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _apply_grid(plot_item):
|
|
62
|
+
"""Apply theme-aware grid to a PlotItem."""
|
|
63
|
+
theme = _get_theme()
|
|
64
|
+
r, g, b, a = theme['grid_pen']
|
|
65
|
+
pen = pg.mkPen(QColor(r, g, b, a), width=1)
|
|
66
|
+
for axis_name in ('bottom', 'left'):
|
|
67
|
+
ax = plot_item.getAxis(axis_name)
|
|
68
|
+
ax.setGrid(a)
|
|
69
|
+
ax.setPen(pen)
|
|
70
|
+
ax.setTextPen(pg.mkPen(theme['pg_foreground']))
|
|
71
|
+
plot_item.update()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _style_kwargs(color, style, width=2):
|
|
75
|
+
"""Return PlotDataItem keyword args for the given plot style."""
|
|
76
|
+
pen = pg.mkPen(color, width=width)
|
|
77
|
+
if style == 'Markers':
|
|
78
|
+
return dict(pen=None, symbol='o', symbolSize=6,
|
|
79
|
+
symbolPen=pg.mkPen(color, width=width), symbolBrush=color)
|
|
80
|
+
if style == 'Lines+Markers':
|
|
81
|
+
return dict(pen=pen, symbol='o', symbolSize=5,
|
|
82
|
+
symbolPen=pg.mkPen(color, width=width), symbolBrush=color)
|
|
83
|
+
if style == 'Steps':
|
|
84
|
+
return dict(pen=pen, stepMode='left')
|
|
85
|
+
return dict(pen=pen)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
_eng_cache = {}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _eng(value, unit=""):
|
|
92
|
+
fmt = _eng_cache.get(unit)
|
|
93
|
+
if fmt is None:
|
|
94
|
+
fmt = EngFormatter(unit=unit)
|
|
95
|
+
_eng_cache[unit] = fmt
|
|
96
|
+
return fmt(value)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _to_numeric(arr):
|
|
100
|
+
"""Convert array to float. For string data, return (indices, labels)."""
|
|
101
|
+
try:
|
|
102
|
+
return np.real(np.array(arr, dtype=float)), None
|
|
103
|
+
except (ValueError, TypeError):
|
|
104
|
+
labels = [str(v) for v in arr]
|
|
105
|
+
return np.arange(len(labels), dtype=float), labels
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _RotatedAxisItem(pg.AxisItem):
|
|
109
|
+
"""AxisItem that draws tick labels rotated 90 degrees."""
|
|
110
|
+
|
|
111
|
+
def drawPicture(self, p, axisSpec, tickSpecs, textSpecs):
|
|
112
|
+
super().drawPicture(p, axisSpec, tickSpecs, [])
|
|
113
|
+
for rect, flags, text in textSpecs:
|
|
114
|
+
p.save()
|
|
115
|
+
p.translate(rect.center())
|
|
116
|
+
p.rotate(-90)
|
|
117
|
+
p.drawText(
|
|
118
|
+
QtCore.QRectF(-rect.height() / 2, -rect.width() / 2,
|
|
119
|
+
rect.height(), rect.width()),
|
|
120
|
+
Qt.AlignCenter, text)
|
|
121
|
+
p.restore()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _apply_rotated_ticks(plot_item, axis_name, ticks):
|
|
125
|
+
"""Replace an axis on a PlotItem with a rotated-label version."""
|
|
126
|
+
old_ax = plot_item.getAxis(axis_name)
|
|
127
|
+
new_ax = _RotatedAxisItem(axis_name)
|
|
128
|
+
new_ax.setTicks([ticks])
|
|
129
|
+
max_len = max((len(t[1]) for t in ticks), default=5)
|
|
130
|
+
new_ax.setHeight(max(60, 7 * max_len))
|
|
131
|
+
new_ax.linkToView(plot_item.vb)
|
|
132
|
+
if old_ax.scene():
|
|
133
|
+
old_ax.scene().removeItem(old_ax)
|
|
134
|
+
plot_item.layout.removeItem(old_ax)
|
|
135
|
+
plot_item.axes[axis_name]['item'] = new_ax
|
|
136
|
+
plot_item.layout.addItem(new_ax, 3 if axis_name == 'bottom' else 1, 1)
|
|
137
|
+
new_ax.setZValue(-1000)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class _SignalPickerDialog(QDialog):
|
|
141
|
+
"""Modal dialog with regex-filtered signal list (Signal + File columns)."""
|
|
142
|
+
|
|
143
|
+
def __init__(self, parent, title, names, file_label=None):
|
|
144
|
+
super().__init__(parent)
|
|
145
|
+
self.setWindowTitle(title)
|
|
146
|
+
self.resize(640, 500)
|
|
147
|
+
self._names = list(names)
|
|
148
|
+
if file_label is None:
|
|
149
|
+
self._file_labels = [''] * len(self._names)
|
|
150
|
+
elif isinstance(file_label, (list, tuple)):
|
|
151
|
+
self._file_labels = list(file_label)
|
|
152
|
+
if len(self._file_labels) < len(self._names):
|
|
153
|
+
self._file_labels.extend(
|
|
154
|
+
[''] * (len(self._names) - len(self._file_labels)))
|
|
155
|
+
else:
|
|
156
|
+
self._file_labels = [str(file_label)] * len(self._names)
|
|
157
|
+
|
|
158
|
+
layout = QVBoxLayout(self)
|
|
159
|
+
self._search = QLineEdit()
|
|
160
|
+
self._search.setPlaceholderText("Regex filter…")
|
|
161
|
+
self._search.textChanged.connect(self._filter)
|
|
162
|
+
layout.addWidget(self._search)
|
|
163
|
+
|
|
164
|
+
self._table = QTableWidget(len(self._names), 2)
|
|
165
|
+
self._table.setHorizontalHeaderLabels(["Signal", "File"])
|
|
166
|
+
hdr = self._table.horizontalHeader()
|
|
167
|
+
hdr.setStretchLastSection(True)
|
|
168
|
+
hdr.setSectionResizeMode(0, QHeaderView.Stretch)
|
|
169
|
+
self._table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
|
170
|
+
self._table.setSelectionMode(QAbstractItemView.SingleSelection)
|
|
171
|
+
self._table.setAlternatingRowColors(True)
|
|
172
|
+
for i, n in enumerate(self._names):
|
|
173
|
+
self._table.setItem(i, 0, QTableWidgetItem(n))
|
|
174
|
+
self._table.setItem(i, 1, QTableWidgetItem(self._file_labels[i]))
|
|
175
|
+
self._table.itemDoubleClicked.connect(lambda _: self.accept())
|
|
176
|
+
layout.addWidget(self._table)
|
|
177
|
+
|
|
178
|
+
row = QHBoxLayout()
|
|
179
|
+
ok = QPushButton("OK")
|
|
180
|
+
ok.clicked.connect(self.accept)
|
|
181
|
+
cancel = QPushButton("Cancel")
|
|
182
|
+
cancel.clicked.connect(self.reject)
|
|
183
|
+
row.addWidget(ok)
|
|
184
|
+
row.addWidget(cancel)
|
|
185
|
+
layout.addLayout(row)
|
|
186
|
+
|
|
187
|
+
def _filter(self, text):
|
|
188
|
+
try:
|
|
189
|
+
pat = re.compile(text, re.IGNORECASE)
|
|
190
|
+
except re.error:
|
|
191
|
+
pat = None
|
|
192
|
+
for i in range(self._table.rowCount()):
|
|
193
|
+
sig = self._table.item(i, 0)
|
|
194
|
+
fil = self._table.item(i, 1)
|
|
195
|
+
s1 = sig.text() if sig else ""
|
|
196
|
+
s2 = fil.text() if fil else ""
|
|
197
|
+
ok = not pat or pat.search(s1) or pat.search(s2)
|
|
198
|
+
self._table.setRowHidden(i, not ok)
|
|
199
|
+
|
|
200
|
+
def selected(self):
|
|
201
|
+
cr = self._table.currentRow()
|
|
202
|
+
if cr >= 0 and not self._table.isRowHidden(cr):
|
|
203
|
+
it = self._table.item(cr, 0)
|
|
204
|
+
if it:
|
|
205
|
+
return it.text()
|
|
206
|
+
for i in range(self._table.rowCount()):
|
|
207
|
+
if not self._table.isRowHidden(i):
|
|
208
|
+
it = self._table.item(i, 0)
|
|
209
|
+
if it:
|
|
210
|
+
return it.text()
|
|
211
|
+
return None
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class PgWave:
|
|
215
|
+
"""Associates a WaveFile column with a pyqtgraph PlotDataItem."""
|
|
216
|
+
|
|
217
|
+
#- Display formats for vector digital signals.
|
|
218
|
+
DIGITAL_FORMATS = ('hex', 'dec', 'bin')
|
|
219
|
+
|
|
220
|
+
def __init__(self, wfile, key, xaxis):
|
|
221
|
+
self.wfile = wfile
|
|
222
|
+
self.key = key
|
|
223
|
+
self.xaxis = xaxis
|
|
224
|
+
self.x = None
|
|
225
|
+
self.y = None
|
|
226
|
+
self.xlabel = "Samples"
|
|
227
|
+
self.xunit = ""
|
|
228
|
+
#- Digital metadata, populated from df.attrs['cicwave_vcd'] when
|
|
229
|
+
#- the source is a VCD file. ``digital_kind`` is one of
|
|
230
|
+
#- 'bit' / 'vector' / None; ``digital_width`` is the bit width
|
|
231
|
+
#- (1 for bits); ``digital_format`` selects how vector samples
|
|
232
|
+
#- are displayed in tooltips/labels ('hex' / 'dec' / 'bin').
|
|
233
|
+
self.digital_kind = None
|
|
234
|
+
self.digital_width = 1
|
|
235
|
+
self.digital_format = 'hex'
|
|
236
|
+
#- Whether to render this wave in the dedicated digital pane
|
|
237
|
+
#- (one row per signal, gtkwave/surfer-style). Off by default;
|
|
238
|
+
#- the user opts in via the wave-tree right-click menu.
|
|
239
|
+
self.show_as_digital = False
|
|
240
|
+
#- Original (string/int) values for digital signals, kept so we
|
|
241
|
+
#- can re-render labels when the format changes.
|
|
242
|
+
self._digital_raw = None
|
|
243
|
+
self.yunit, self._yscale, self._yclean = self._infer_unit(
|
|
244
|
+
key, default="V" if self._is_v(key)
|
|
245
|
+
else "A" if self._is_i(key) else "")
|
|
246
|
+
self.ylabel = "%s (%s)" % (self._yclean or key, wfile.name)
|
|
247
|
+
self.logx = False
|
|
248
|
+
self.tag = wfile.getTag(key)
|
|
249
|
+
self.curve = None
|
|
250
|
+
self.color = None
|
|
251
|
+
self._xlabels = None
|
|
252
|
+
self._ylabels = None
|
|
253
|
+
self.reload()
|
|
254
|
+
|
|
255
|
+
@staticmethod
|
|
256
|
+
def _is_v(key):
|
|
257
|
+
kl = (key or "").lower()
|
|
258
|
+
return kl.startswith("v(") or kl.startswith("v-")
|
|
259
|
+
|
|
260
|
+
@staticmethod
|
|
261
|
+
def _is_i(key):
|
|
262
|
+
kl = (key or "").lower()
|
|
263
|
+
return kl.startswith("i(") or kl.startswith("i-")
|
|
264
|
+
|
|
265
|
+
@staticmethod
|
|
266
|
+
def _infer_unit(key, default=""):
|
|
267
|
+
"""Return ``(unit, scale, clean_label)`` for ``key``.
|
|
268
|
+
|
|
269
|
+
Tries the suffix parser first (handles ``Foo_dBm``, ``Bar [MHz]``,
|
|
270
|
+
``Baz (V)`` etc); falls back to ``default`` when no suffix is
|
|
271
|
+
recognised.
|
|
272
|
+
"""
|
|
273
|
+
parsed = parse_unit_from_name(key)
|
|
274
|
+
if parsed is not None:
|
|
275
|
+
scale, unit, clean = parsed
|
|
276
|
+
return unit, scale, clean
|
|
277
|
+
return default, 1.0, key
|
|
278
|
+
|
|
279
|
+
@staticmethod
|
|
280
|
+
def _infer_yunit(key):
|
|
281
|
+
# Kept for backwards compatibility (used by older code paths /
|
|
282
|
+
# tests). Prefer ``_infer_unit``.
|
|
283
|
+
unit, _scale, _clean = PgWave._infer_unit(
|
|
284
|
+
key, default="V" if PgWave._is_v(key)
|
|
285
|
+
else "A" if PgWave._is_i(key) else "")
|
|
286
|
+
return unit
|
|
287
|
+
|
|
288
|
+
def _set_x_from_column(self, col, label, unit, logx=False):
|
|
289
|
+
arr = self.wfile.df[col].to_numpy()
|
|
290
|
+
# Auto-rescale prefixed-SI columns so EngFormatter shows nice
|
|
291
|
+
# prefixes regardless of the unit the data was stored in.
|
|
292
|
+
parsed = parse_unit_from_name(col)
|
|
293
|
+
if parsed is not None:
|
|
294
|
+
scale, base_unit, clean = parsed
|
|
295
|
+
arr = arr * scale if scale != 1.0 else arr
|
|
296
|
+
self.x = arr
|
|
297
|
+
self.xlabel = clean or label
|
|
298
|
+
self.xunit = base_unit
|
|
299
|
+
else:
|
|
300
|
+
self.x = arr
|
|
301
|
+
self.xlabel = label
|
|
302
|
+
self.xunit = unit
|
|
303
|
+
self.logx = logx
|
|
304
|
+
|
|
305
|
+
def reload(self):
|
|
306
|
+
self.wfile.reload()
|
|
307
|
+
keys = self.wfile.df.columns
|
|
308
|
+
|
|
309
|
+
if "time" in keys:
|
|
310
|
+
self._set_x_from_column("time", "Time", "s")
|
|
311
|
+
elif "frequency" in keys:
|
|
312
|
+
self._set_x_from_column("frequency", "Frequency", "Hz",
|
|
313
|
+
logx=True)
|
|
314
|
+
elif "v(v-sweep)" in keys:
|
|
315
|
+
self._set_x_from_column("v(v-sweep)", "Voltage", "V")
|
|
316
|
+
elif "i(i-sweep)" in keys:
|
|
317
|
+
self._set_x_from_column("i(i-sweep)", "Current", "A")
|
|
318
|
+
elif "temp-sweep" in keys:
|
|
319
|
+
self._set_x_from_column("temp-sweep", "Temperature", "°C")
|
|
320
|
+
elif self.xaxis and self.xaxis in keys:
|
|
321
|
+
self._set_x_from_column(self.xaxis, self.xaxis, "")
|
|
322
|
+
else:
|
|
323
|
+
# No known x-axis name; pick the first column that carries a
|
|
324
|
+
# parseable unit suffix and isn't the y-key itself.
|
|
325
|
+
for col in keys:
|
|
326
|
+
if col == self.key:
|
|
327
|
+
continue
|
|
328
|
+
if parse_unit_from_name(col) is not None:
|
|
329
|
+
self._set_x_from_column(col, col, "")
|
|
330
|
+
break
|
|
331
|
+
|
|
332
|
+
if self.key in keys:
|
|
333
|
+
y = self.wfile.df[self.key].to_numpy()
|
|
334
|
+
if self._yscale != 1.0 and self._yscale != 1:
|
|
335
|
+
try:
|
|
336
|
+
y = y * self._yscale
|
|
337
|
+
except TypeError:
|
|
338
|
+
pass # non-numeric (digital) data; ignore scale
|
|
339
|
+
self.y = y
|
|
340
|
+
|
|
341
|
+
self._maybe_apply_digital_kind()
|
|
342
|
+
|
|
343
|
+
if self.curve and self.x is not None and self.y is not None:
|
|
344
|
+
x, _ = _to_numeric(self.x)
|
|
345
|
+
y, _ = _to_numeric(self.y)
|
|
346
|
+
self.curve.setData(x, y)
|
|
347
|
+
|
|
348
|
+
def _maybe_apply_digital_kind(self):
|
|
349
|
+
"""If this signal comes from a digital source (VCD), record the
|
|
350
|
+
kind/width and convert ``self.y`` into a numeric step trace.
|
|
351
|
+
|
|
352
|
+
The original strings/ints are kept on ``self._digital_raw`` so
|
|
353
|
+
we can re-render labels when the user switches hex/dec/bin.
|
|
354
|
+
"""
|
|
355
|
+
attrs = getattr(self.wfile.df, 'attrs', {}) or {}
|
|
356
|
+
meta = attrs.get('cicwave_vcd')
|
|
357
|
+
if not meta:
|
|
358
|
+
return
|
|
359
|
+
kinds = meta.get('kinds', {}) or {}
|
|
360
|
+
widths = meta.get('widths', {}) or {}
|
|
361
|
+
kind = kinds.get(self.key)
|
|
362
|
+
if kind not in ('bit', 'vector'):
|
|
363
|
+
return
|
|
364
|
+
|
|
365
|
+
self.digital_kind = kind
|
|
366
|
+
self.digital_width = int(widths.get(self.key, 1) or 1)
|
|
367
|
+
self._digital_raw = self.y
|
|
368
|
+
|
|
369
|
+
if kind == 'bit':
|
|
370
|
+
#- Map '0' -> 0.0, '1' -> 1.0, anything else (x/z/h/l) -> NaN
|
|
371
|
+
#- so the curve has visible breaks for unknown states.
|
|
372
|
+
yn = np.full(len(self.y), np.nan, dtype=np.float64)
|
|
373
|
+
for i, v in enumerate(self.y):
|
|
374
|
+
if v == '1' or v == 1:
|
|
375
|
+
yn[i] = 1.0
|
|
376
|
+
elif v == '0' or v == 0:
|
|
377
|
+
yn[i] = 0.0
|
|
378
|
+
self.y = yn
|
|
379
|
+
self.yunit = "bit"
|
|
380
|
+
self._yclean = self.key
|
|
381
|
+
self.ylabel = "%s (bit, %s)" % (self.key, self.wfile.name)
|
|
382
|
+
else:
|
|
383
|
+
#- Vector: numeric value (or NaN for unknown).
|
|
384
|
+
yn = np.full(len(self.y), np.nan, dtype=np.float64)
|
|
385
|
+
for i, v in enumerate(self.y):
|
|
386
|
+
if isinstance(v, (int, np.integer)):
|
|
387
|
+
yn[i] = float(v)
|
|
388
|
+
elif isinstance(v, float) and not np.isnan(v):
|
|
389
|
+
yn[i] = v
|
|
390
|
+
self.y = yn
|
|
391
|
+
unit = "u%d" % self.digital_width # e.g. "u8"
|
|
392
|
+
self.yunit = unit
|
|
393
|
+
self._yclean = self.key
|
|
394
|
+
self.ylabel = "%s [%s, %s]" % (
|
|
395
|
+
self.key, unit, self.wfile.name)
|
|
396
|
+
|
|
397
|
+
def setDigitalFormat(self, fmt):
|
|
398
|
+
"""Switch how vector samples are displayed (hex/dec/bin)."""
|
|
399
|
+
if fmt not in self.DIGITAL_FORMATS:
|
|
400
|
+
return
|
|
401
|
+
self.digital_format = fmt
|
|
402
|
+
|
|
403
|
+
def synthesizeDigitalBits(self, hysteresis_frac=0.05):
|
|
404
|
+
"""Return a ``"0"/"1"/"x"`` array derived from analog ``self.y``.
|
|
405
|
+
|
|
406
|
+
The mid-amplitude threshold ``(min+max)/2`` decides high vs low.
|
|
407
|
+
A small hysteresis band (default 5% of the peak-to-peak swing)
|
|
408
|
+
on either side of the threshold prevents repeated false
|
|
409
|
+
transitions from noise crossing the line. Samples that fall
|
|
410
|
+
inside the hysteresis band hold the previous state. NaN /
|
|
411
|
+
non-finite samples become ``"x"``.
|
|
412
|
+
|
|
413
|
+
Caches the result on ``self._digital_raw`` so the digital pane
|
|
414
|
+
doesn't recompute on every redraw.
|
|
415
|
+
"""
|
|
416
|
+
y = self.y
|
|
417
|
+
if y is None or len(y) == 0:
|
|
418
|
+
return np.array([], dtype=object)
|
|
419
|
+
try:
|
|
420
|
+
yf = np.asarray(y, dtype=float)
|
|
421
|
+
except (TypeError, ValueError):
|
|
422
|
+
return np.array(['x'] * len(y), dtype=object)
|
|
423
|
+
finite_mask = np.isfinite(yf)
|
|
424
|
+
if not finite_mask.any():
|
|
425
|
+
return np.array(['x'] * len(yf), dtype=object)
|
|
426
|
+
ymin = float(np.min(yf[finite_mask]))
|
|
427
|
+
ymax = float(np.max(yf[finite_mask]))
|
|
428
|
+
span = ymax - ymin
|
|
429
|
+
if span <= 0:
|
|
430
|
+
#- Constant signal: report a single state.
|
|
431
|
+
out = np.array(['1' if ymax > 0 else '0'] * len(yf),
|
|
432
|
+
dtype=object)
|
|
433
|
+
return out
|
|
434
|
+
mid = (ymin + ymax) / 2.0
|
|
435
|
+
hyst = max(span * float(hysteresis_frac), 0.0)
|
|
436
|
+
hi_th = mid + hyst
|
|
437
|
+
lo_th = mid - hyst
|
|
438
|
+
|
|
439
|
+
out = np.empty(len(yf), dtype=object)
|
|
440
|
+
state = 'x' # before the first finite sample
|
|
441
|
+
for i, v in enumerate(yf):
|
|
442
|
+
if not np.isfinite(v):
|
|
443
|
+
out[i] = 'x'
|
|
444
|
+
continue
|
|
445
|
+
if state == 'x':
|
|
446
|
+
state = '1' if v >= mid else '0'
|
|
447
|
+
elif state == '0' and v >= hi_th:
|
|
448
|
+
state = '1'
|
|
449
|
+
elif state == '1' and v <= lo_th:
|
|
450
|
+
state = '0'
|
|
451
|
+
#- else: inside the hysteresis band -> hold state.
|
|
452
|
+
out[i] = state
|
|
453
|
+
return out
|
|
454
|
+
|
|
455
|
+
def formatDigitalValue(self, raw):
|
|
456
|
+
"""Render a raw vector sample with the current format.
|
|
457
|
+
|
|
458
|
+
``raw`` may be the original VCD string ('x', 'z', '0', '1') or
|
|
459
|
+
the numeric value we put in ``self.y`` (0.0 / 1.0 / NaN / int).
|
|
460
|
+
"""
|
|
461
|
+
if raw is None or (isinstance(raw, float) and np.isnan(raw)):
|
|
462
|
+
return "x"
|
|
463
|
+
if isinstance(raw, str):
|
|
464
|
+
return raw # 'x' / 'z' / lowercase bits
|
|
465
|
+
if self.digital_kind == 'bit':
|
|
466
|
+
try:
|
|
467
|
+
return "1" if int(round(float(raw))) else "0"
|
|
468
|
+
except (TypeError, ValueError):
|
|
469
|
+
return str(raw)
|
|
470
|
+
try:
|
|
471
|
+
iv = int(round(float(raw)))
|
|
472
|
+
except (TypeError, ValueError):
|
|
473
|
+
return str(raw)
|
|
474
|
+
w = max(1, int(self.digital_width or 1))
|
|
475
|
+
if self.digital_format == 'hex':
|
|
476
|
+
digits = max(1, (w + 3) // 4)
|
|
477
|
+
return ("%0*x" % (digits, iv & ((1 << w) - 1))).lower() + "h"
|
|
478
|
+
if self.digital_format == 'bin':
|
|
479
|
+
return ("{:0%db}" % w).format(iv & ((1 << w) - 1)) + "b"
|
|
480
|
+
return str(iv)
|
|
481
|
+
|
|
482
|
+
@staticmethod
|
|
483
|
+
def _apply_render_opts(curve):
|
|
484
|
+
"""Per-curve options safe to apply at construction time.
|
|
485
|
+
|
|
486
|
+
``autoDownsample`` and ``clipToView`` are NOT set here -- they
|
|
487
|
+
slice the data array using the ViewBox's current rect, but at
|
|
488
|
+
construction the ViewBox still holds its default
|
|
489
|
+
``(-0.5, -0.5, 1, 1)`` rect (autoRange has not run yet because
|
|
490
|
+
the first curve is still being added). With a 7e-6 s data span
|
|
491
|
+
and a 1.0 unit view rect, autoDownsample picks a downsample
|
|
492
|
+
factor of ~300 000, collapsing the curve to a single point;
|
|
493
|
+
clipToView then keeps it that way. The resulting empty plot is
|
|
494
|
+
what users saw on macOS. Those options are applied by
|
|
495
|
+
:meth:`_enable_view_dependent_opts` after ``autoRange()``.
|
|
496
|
+
|
|
497
|
+
``setDynamicRangeLimit`` IS safe at construction: it clamps
|
|
498
|
+
y-values relative to the view rect at draw time (not at
|
|
499
|
+
``setData`` time), so it never collapses the data. Setting it
|
|
500
|
+
here suppresses Qt's "Painter path exceeds +/-32767 pixels"
|
|
501
|
+
warnings that fire when a curve has tall spikes (e.g. a power
|
|
502
|
+
rail transient) and the user zooms in: without dynamic range
|
|
503
|
+
limiting the painter receives y-coords millions of pixels
|
|
504
|
+
outside the viewport, which exceeds Qt's int16 path range.
|
|
505
|
+
"""
|
|
506
|
+
if curve is None:
|
|
507
|
+
return
|
|
508
|
+
try:
|
|
509
|
+
#- 1e6 is pyqtgraph's own default; we set it explicitly so
|
|
510
|
+
#- the limiter is active even on PlotDataItem subclasses
|
|
511
|
+
#- that may have it disabled, and to make the intent
|
|
512
|
+
#- visible. Tightening below 1e6 risks visible clipping
|
|
513
|
+
#- on legitimate large-dynamic-range signals.
|
|
514
|
+
curve.setDynamicRangeLimit(1e6)
|
|
515
|
+
except Exception:
|
|
516
|
+
pass
|
|
517
|
+
return
|
|
518
|
+
|
|
519
|
+
@staticmethod
|
|
520
|
+
def _enable_view_dependent_opts(curve):
|
|
521
|
+
"""Enable ``setDownsampling(auto=True)`` and ``clipToView`` once
|
|
522
|
+
the ViewBox has a real view rect.
|
|
523
|
+
|
|
524
|
+
Must be invoked after ``autoRange()`` so the visible-range slice
|
|
525
|
+
actually contains data; otherwise the curve renders empty.
|
|
526
|
+
Silently no-ops on items that don't support these options
|
|
527
|
+
(e.g. ``InfiniteLine``, ``PlotCurveItem``).
|
|
528
|
+
"""
|
|
529
|
+
if curve is None:
|
|
530
|
+
return
|
|
531
|
+
try:
|
|
532
|
+
curve.setDownsampling(auto=True, method='subsample')
|
|
533
|
+
except Exception:
|
|
534
|
+
pass
|
|
535
|
+
try:
|
|
536
|
+
curve.setClipToView(True)
|
|
537
|
+
except Exception:
|
|
538
|
+
opts = getattr(curve, 'opts', None)
|
|
539
|
+
if isinstance(opts, dict):
|
|
540
|
+
opts['clipToView'] = True
|
|
541
|
+
#- Dynamic range limit: see ``_apply_render_opts``. Also set
|
|
542
|
+
#- here so digital-pane PlotDataItems (which skip the
|
|
543
|
+
#- ``Wave.plot`` path) get the same Qt 16-bit-painter
|
|
544
|
+
#- protection.
|
|
545
|
+
try:
|
|
546
|
+
curve.setDynamicRangeLimit(1e6)
|
|
547
|
+
except Exception:
|
|
548
|
+
pass
|
|
549
|
+
|
|
550
|
+
def plot(self, target, color='w', style='Lines', width=2):
|
|
551
|
+
"""Plot on a PlotItem or ViewBox. Returns the curve or None."""
|
|
552
|
+
if self.y is None:
|
|
553
|
+
return None
|
|
554
|
+
y, self._ylabels = _to_numeric(self.y)
|
|
555
|
+
x, self._xlabels = _to_numeric(self.x) if self.x is not None else (np.arange(len(y)), None)
|
|
556
|
+
self.color = color
|
|
557
|
+
self.style = style
|
|
558
|
+
self._width = width
|
|
559
|
+
kw = _style_kwargs(color, style, width=width)
|
|
560
|
+
if self.digital_kind is not None:
|
|
561
|
+
#- Digital signals look right only as left-step plots; we
|
|
562
|
+
#- also disable antialiasing so transitions stay sharp.
|
|
563
|
+
kw['stepMode'] = 'left'
|
|
564
|
+
kw['connect'] = 'finite'
|
|
565
|
+
self.curve = pg.PlotDataItem(x, y, name=self.ylabel, **kw)
|
|
566
|
+
target.addItem(self.curve)
|
|
567
|
+
self._apply_render_opts(self.curve)
|
|
568
|
+
return self.curve
|
|
569
|
+
|
|
570
|
+
def setStyle(self, style):
|
|
571
|
+
if self.curve is None:
|
|
572
|
+
return
|
|
573
|
+
self.style = style
|
|
574
|
+
vb = self.curve.getViewBox()
|
|
575
|
+
vb.removeItem(self.curve)
|
|
576
|
+
y, _ = _to_numeric(self.y)
|
|
577
|
+
x, _ = _to_numeric(self.x) if self.x is not None else (np.arange(len(y)), None)
|
|
578
|
+
kw = _style_kwargs(self.color, style, width=self._width)
|
|
579
|
+
self.curve = pg.PlotDataItem(x, y, name=self.ylabel, **kw)
|
|
580
|
+
vb.addItem(self.curve)
|
|
581
|
+
self._apply_render_opts(self.curve)
|
|
582
|
+
|
|
583
|
+
def setWidth(self, width):
|
|
584
|
+
if self.curve is None:
|
|
585
|
+
return
|
|
586
|
+
self._width = width
|
|
587
|
+
vb = self.curve.getViewBox()
|
|
588
|
+
vb.removeItem(self.curve)
|
|
589
|
+
y, _ = _to_numeric(self.y)
|
|
590
|
+
x, _ = _to_numeric(self.x) if self.x is not None else (np.arange(len(y)), None)
|
|
591
|
+
kw = _style_kwargs(self.color, self.style, width=width)
|
|
592
|
+
self.curve = pg.PlotDataItem(x, y, name=self.ylabel, **kw)
|
|
593
|
+
vb.addItem(self.curve)
|
|
594
|
+
self._apply_render_opts(self.curve)
|
|
595
|
+
|
|
596
|
+
def remove(self):
|
|
597
|
+
if self.curve:
|
|
598
|
+
self.curve.getViewBox().removeItem(self.curve)
|
|
599
|
+
self.curve = None
|
|
600
|
+
self.color = None
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
class _DropUrlTree(QTreeWidget):
|
|
604
|
+
"""File / wave lists: accept external file drops (viewport-safe)."""
|
|
605
|
+
|
|
606
|
+
def __init__(self, parent=None):
|
|
607
|
+
super().__init__(parent)
|
|
608
|
+
self.setAcceptDrops(True)
|
|
609
|
+
self.viewport().setAcceptDrops(True)
|
|
610
|
+
|
|
611
|
+
def dragEnterEvent(self, event):
|
|
612
|
+
if event.mimeData().hasUrls():
|
|
613
|
+
for url in event.mimeData().urls():
|
|
614
|
+
p = url.toLocalFile()
|
|
615
|
+
if p and os.path.isfile(p):
|
|
616
|
+
event.acceptProposedAction()
|
|
617
|
+
return
|
|
618
|
+
super().dragEnterEvent(event)
|
|
619
|
+
|
|
620
|
+
def dragMoveEvent(self, event):
|
|
621
|
+
if event.mimeData().hasUrls():
|
|
622
|
+
for url in event.mimeData().urls():
|
|
623
|
+
p = url.toLocalFile()
|
|
624
|
+
if p and os.path.isfile(p):
|
|
625
|
+
event.acceptProposedAction()
|
|
626
|
+
return
|
|
627
|
+
super().dragMoveEvent(event)
|
|
628
|
+
|
|
629
|
+
def dropEvent(self, event):
|
|
630
|
+
win = self.window()
|
|
631
|
+
if hasattr(win, '_handle_file_drop'):
|
|
632
|
+
win._handle_file_drop(event)
|
|
633
|
+
else:
|
|
634
|
+
event.ignore()
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
class PgWaveBrowser(QWidget):
|
|
638
|
+
waveSelected = Signal(object)
|
|
639
|
+
waveRemoveRequested = Signal(object)
|
|
640
|
+
analysisRequested = Signal(str, object) # (analysis_type, wave)
|
|
641
|
+
styleChanged = Signal(str)
|
|
642
|
+
fileRemoveRequested = Signal(str)
|
|
643
|
+
wavePlotAllRequested = Signal(str)
|
|
644
|
+
wavePlotAllVisibleRequested = Signal()
|
|
645
|
+
|
|
646
|
+
def __init__(self, xaxis, parent=None):
|
|
647
|
+
super().__init__(parent)
|
|
648
|
+
self.xaxis = xaxis
|
|
649
|
+
self.files = WaveFiles()
|
|
650
|
+
self._wave_cache = {}
|
|
651
|
+
self._tag_to_item = {}
|
|
652
|
+
|
|
653
|
+
layout = QVBoxLayout(self)
|
|
654
|
+
layout.setContentsMargins(2, 2, 2, 2)
|
|
655
|
+
|
|
656
|
+
self.file_tree = _DropUrlTree()
|
|
657
|
+
self.file_tree.setHeaderLabel("Files")
|
|
658
|
+
self.file_tree.currentItemChanged.connect(self._file_selected)
|
|
659
|
+
#- Allow shift/ctrl/cmd-click multi-select so the user can close
|
|
660
|
+
#- many files at once via the context menu.
|
|
661
|
+
self.file_tree.setSelectionMode(
|
|
662
|
+
QAbstractItemView.ExtendedSelection)
|
|
663
|
+
self.file_tree.setContextMenuPolicy(Qt.CustomContextMenu)
|
|
664
|
+
self.file_tree.customContextMenuRequested.connect(
|
|
665
|
+
self._file_context_menu)
|
|
666
|
+
|
|
667
|
+
style_row = QHBoxLayout()
|
|
668
|
+
style_row.addWidget(QLabel("Style:"))
|
|
669
|
+
self.style_cb = QComboBox()
|
|
670
|
+
self.style_cb.addItems(PLOT_STYLES)
|
|
671
|
+
self.style_cb.setToolTip("Plot style for all waves")
|
|
672
|
+
self.style_cb.currentTextChanged.connect(self.styleChanged.emit)
|
|
673
|
+
style_row.addWidget(self.style_cb)
|
|
674
|
+
style_row.addStretch()
|
|
675
|
+
|
|
676
|
+
search_row = QHBoxLayout()
|
|
677
|
+
self.search = QLineEdit()
|
|
678
|
+
self.search.setPlaceholderText("Regex filter...")
|
|
679
|
+
self.search.setToolTip(
|
|
680
|
+
"Regex search filter\n"
|
|
681
|
+
"───────────────────\n"
|
|
682
|
+
". any character\n"
|
|
683
|
+
".* match anything\n"
|
|
684
|
+
"^abc starts with abc\n"
|
|
685
|
+
"abc$ ends with abc\n"
|
|
686
|
+
"[abc] a, b, or c\n"
|
|
687
|
+
"a|b a or b\n"
|
|
688
|
+
"\\( literal (\n"
|
|
689
|
+
"Examples:\n"
|
|
690
|
+
" v\\(.*out match v(...out\n"
|
|
691
|
+
" ^i\\( current signals"
|
|
692
|
+
)
|
|
693
|
+
self.search.textChanged.connect(self._fill_waves)
|
|
694
|
+
self._flat_mode = False
|
|
695
|
+
self.flat_cb = QCheckBox("Flat")
|
|
696
|
+
self.flat_cb.setToolTip("Show flat list instead of hierarchy")
|
|
697
|
+
self.flat_cb.toggled.connect(self._toggle_flat)
|
|
698
|
+
search_row.addWidget(self.search)
|
|
699
|
+
search_row.addWidget(self.flat_cb)
|
|
700
|
+
|
|
701
|
+
self.wave_tree = _DropUrlTree()
|
|
702
|
+
self.wave_tree.setHeaderLabel("Waves")
|
|
703
|
+
self.wave_tree.itemDoubleClicked.connect(self._wave_clicked)
|
|
704
|
+
self.wave_tree.setContextMenuPolicy(Qt.CustomContextMenu)
|
|
705
|
+
self.wave_tree.customContextMenuRequested.connect(self._wave_context)
|
|
706
|
+
|
|
707
|
+
layout.addWidget(self.file_tree, 1)
|
|
708
|
+
layout.addLayout(style_row)
|
|
709
|
+
layout.addLayout(search_row)
|
|
710
|
+
layout.addWidget(self.wave_tree, 3)
|
|
711
|
+
|
|
712
|
+
@property
|
|
713
|
+
def plotStyle(self):
|
|
714
|
+
return self.style_cb.currentText()
|
|
715
|
+
|
|
716
|
+
def openFile(self, fname, sheet_name=None):
|
|
717
|
+
sheet = sheet_name if sheet_name is not None else 0
|
|
718
|
+
f = self.files.open(fname, self.xaxis, sheet_name=sheet)
|
|
719
|
+
key = self.files.current
|
|
720
|
+
item = QTreeWidgetItem([f.name])
|
|
721
|
+
item.setData(0, Qt.UserRole, key)
|
|
722
|
+
self.file_tree.addTopLevelItem(item)
|
|
723
|
+
self.file_tree.setCurrentItem(item)
|
|
724
|
+
self._fill_waves()
|
|
725
|
+
|
|
726
|
+
def openDataFrame(self, df, name, pivot_spec_path=None,
|
|
727
|
+
original_path=None):
|
|
728
|
+
f = self.files.openDataFrame(df, name, self.xaxis)
|
|
729
|
+
if pivot_spec_path:
|
|
730
|
+
f._pivot_spec_path = pivot_spec_path
|
|
731
|
+
if original_path:
|
|
732
|
+
f._original_path = original_path
|
|
733
|
+
key = self.files.current
|
|
734
|
+
item = QTreeWidgetItem([f.name])
|
|
735
|
+
item.setData(0, Qt.UserRole, key)
|
|
736
|
+
self.file_tree.addTopLevelItem(item)
|
|
737
|
+
self.file_tree.setCurrentItem(item)
|
|
738
|
+
self._fill_waves()
|
|
739
|
+
|
|
740
|
+
def setWaveColor(self, tag, color):
|
|
741
|
+
"""Color a wave tree item to match its plot line."""
|
|
742
|
+
item = self._tag_to_item.get(tag)
|
|
743
|
+
if item:
|
|
744
|
+
from PySide6.QtGui import QColor
|
|
745
|
+
item.setForeground(0, QColor(color))
|
|
746
|
+
|
|
747
|
+
def clearWaveColor(self, tag):
|
|
748
|
+
"""Reset a wave tree item color back to default."""
|
|
749
|
+
item = self._tag_to_item.get(tag)
|
|
750
|
+
if item:
|
|
751
|
+
from PySide6.QtGui import QColor
|
|
752
|
+
item.setForeground(0, QColor(_get_theme()['tree_default_fg']))
|
|
753
|
+
|
|
754
|
+
def _file_selected(self, current, previous):
|
|
755
|
+
if current:
|
|
756
|
+
fname = current.data(0, Qt.UserRole)
|
|
757
|
+
self.files.select(fname)
|
|
758
|
+
self._fill_waves()
|
|
759
|
+
|
|
760
|
+
def _file_context_menu(self, pos):
|
|
761
|
+
item = self.file_tree.itemAt(pos)
|
|
762
|
+
if not item:
|
|
763
|
+
return
|
|
764
|
+
#- If the user right-clicks on an unselected item, treat it as
|
|
765
|
+
#- a single-item action (don't carry over a stale selection).
|
|
766
|
+
#- If they right-click on one of several already-selected items,
|
|
767
|
+
#- act on the whole selection.
|
|
768
|
+
selected = self.file_tree.selectedItems()
|
|
769
|
+
if item not in selected:
|
|
770
|
+
self.file_tree.clearSelection()
|
|
771
|
+
item.setSelected(True)
|
|
772
|
+
selected = [item]
|
|
773
|
+
|
|
774
|
+
keys = [it.data(0, Qt.UserRole) for it in selected
|
|
775
|
+
if it.data(0, Qt.UserRole)]
|
|
776
|
+
if not keys:
|
|
777
|
+
return
|
|
778
|
+
|
|
779
|
+
menu = QMenu(self)
|
|
780
|
+
label = ("Close" if len(keys) == 1
|
|
781
|
+
else "Close %d files" % len(keys))
|
|
782
|
+
menu.addAction(
|
|
783
|
+
label,
|
|
784
|
+
lambda ks=tuple(keys): [
|
|
785
|
+
self.fileRemoveRequested.emit(k) for k in ks])
|
|
786
|
+
menu.exec(self.file_tree.viewport().mapToGlobal(pos))
|
|
787
|
+
|
|
788
|
+
def _purge_wave_cache_for_wfile(self, wf):
|
|
789
|
+
for yname in wf.getWaveNames():
|
|
790
|
+
self._wave_cache.pop(wf.getTag(yname), None)
|
|
791
|
+
|
|
792
|
+
def remove_file_entry(self, key):
|
|
793
|
+
"""Remove a file from the model and file tree (plots/cache cleared elsewhere)."""
|
|
794
|
+
self.files.remove(key)
|
|
795
|
+
for i in range(self.file_tree.topLevelItemCount()):
|
|
796
|
+
it = self.file_tree.topLevelItem(i)
|
|
797
|
+
if it.data(0, Qt.UserRole) == key:
|
|
798
|
+
self.file_tree.takeTopLevelItem(i)
|
|
799
|
+
break
|
|
800
|
+
self._sync_file_selection_after_remove()
|
|
801
|
+
|
|
802
|
+
def _sync_file_selection_after_remove(self):
|
|
803
|
+
cur = self.files.current
|
|
804
|
+
if cur is None:
|
|
805
|
+
self.wave_tree.clear()
|
|
806
|
+
self._tag_to_item = {}
|
|
807
|
+
return
|
|
808
|
+
for i in range(self.file_tree.topLevelItemCount()):
|
|
809
|
+
it = self.file_tree.topLevelItem(i)
|
|
810
|
+
if it.data(0, Qt.UserRole) == cur:
|
|
811
|
+
self.file_tree.setCurrentItem(it)
|
|
812
|
+
break
|
|
813
|
+
self._fill_waves()
|
|
814
|
+
|
|
815
|
+
def _toggle_flat(self, checked):
|
|
816
|
+
self._flat_mode = checked
|
|
817
|
+
self._fill_waves()
|
|
818
|
+
|
|
819
|
+
@staticmethod
|
|
820
|
+
def _parse_hierarchy(name):
|
|
821
|
+
"""Split a hierarchical signal name into its scope path.
|
|
822
|
+
|
|
823
|
+
Examples:
|
|
824
|
+
``v(xdut.x1.node)`` -> ``['xdut', 'x1', 'v(node)']``
|
|
825
|
+
``i(M1.d)`` -> ``['M1', 'i(d)']``
|
|
826
|
+
``test.dut_ana.PWRUP_1V8`` -> ``['test', 'dut_ana', 'PWRUP_1V8']``
|
|
827
|
+
``count`` -> ``['count']``
|
|
828
|
+
|
|
829
|
+
Plain dot-separated names (VCD-style scoped signals) are split
|
|
830
|
+
the same way. Names with no dots stay at the top level.
|
|
831
|
+
"""
|
|
832
|
+
m = re.match(r'^([vi])\((.+)\)$', name)
|
|
833
|
+
if m:
|
|
834
|
+
prefix = m.group(1)
|
|
835
|
+
inner = m.group(2)
|
|
836
|
+
parts = inner.split('.')
|
|
837
|
+
if len(parts) > 1:
|
|
838
|
+
leaf = "%s(%s)" % (prefix, parts[-1])
|
|
839
|
+
return parts[:-1] + [leaf]
|
|
840
|
+
return [name]
|
|
841
|
+
if '.' in name and not any(c in name for c in '()/[] '):
|
|
842
|
+
#- Plain dotted path (VCD/Verilog-style hierarchy). We only
|
|
843
|
+
#- treat it as hierarchy when there are no parens/brackets/
|
|
844
|
+
#- spaces, so SPICE-style names like ``v(net.node)`` aren't
|
|
845
|
+
#- accidentally split a second time.
|
|
846
|
+
parts = name.split('.')
|
|
847
|
+
return parts
|
|
848
|
+
return [name]
|
|
849
|
+
|
|
850
|
+
def _visible_wave_names(self):
|
|
851
|
+
"""Wave names that match the regex filter (shown in the browser tree)."""
|
|
852
|
+
f = self.files.getSelected()
|
|
853
|
+
if f is None:
|
|
854
|
+
return []
|
|
855
|
+
pattern = self.search.text()
|
|
856
|
+
return [n for n in f.getWaveNames()
|
|
857
|
+
if not pattern or re.search(pattern, n, re.IGNORECASE)]
|
|
858
|
+
|
|
859
|
+
def _fill_waves(self):
|
|
860
|
+
self.wave_tree.clear()
|
|
861
|
+
self._tag_to_item = {}
|
|
862
|
+
f = self.files.getSelected()
|
|
863
|
+
if f is None:
|
|
864
|
+
return
|
|
865
|
+
|
|
866
|
+
names = self._visible_wave_names()
|
|
867
|
+
|
|
868
|
+
if self._flat_mode:
|
|
869
|
+
for name in sorted(names):
|
|
870
|
+
item = QTreeWidgetItem([name])
|
|
871
|
+
item.setData(0, Qt.UserRole, name)
|
|
872
|
+
self.wave_tree.addTopLevelItem(item)
|
|
873
|
+
self._color_if_plotted(item, f, name)
|
|
874
|
+
return
|
|
875
|
+
|
|
876
|
+
root = {}
|
|
877
|
+
for name in names:
|
|
878
|
+
parts = self._parse_hierarchy(name)
|
|
879
|
+
node = root
|
|
880
|
+
for part in parts[:-1]:
|
|
881
|
+
if part not in node:
|
|
882
|
+
node[part] = {}
|
|
883
|
+
elif isinstance(node[part], str):
|
|
884
|
+
node[part] = {None: node[part]}
|
|
885
|
+
node = node[part]
|
|
886
|
+
leaf_key = parts[-1]
|
|
887
|
+
if leaf_key in node and isinstance(node[leaf_key], dict):
|
|
888
|
+
node[leaf_key][None] = name
|
|
889
|
+
else:
|
|
890
|
+
node[leaf_key] = name
|
|
891
|
+
|
|
892
|
+
self._build_tree(self.wave_tree, root, f)
|
|
893
|
+
|
|
894
|
+
def _build_tree(self, parent, node, wfile):
|
|
895
|
+
for key in sorted(node.keys()):
|
|
896
|
+
if key is None:
|
|
897
|
+
continue
|
|
898
|
+
value = node[key]
|
|
899
|
+
if isinstance(value, str):
|
|
900
|
+
item = QTreeWidgetItem([key])
|
|
901
|
+
item.setData(0, Qt.UserRole, value)
|
|
902
|
+
self._attach(parent, item)
|
|
903
|
+
self._color_if_plotted(item, wfile, value)
|
|
904
|
+
else:
|
|
905
|
+
item = QTreeWidgetItem([key])
|
|
906
|
+
if None in value:
|
|
907
|
+
item.setData(0, Qt.UserRole, value[None])
|
|
908
|
+
self._color_if_plotted(item, wfile, value[None])
|
|
909
|
+
self._attach(parent, item)
|
|
910
|
+
self._build_tree(item, value, wfile)
|
|
911
|
+
|
|
912
|
+
@staticmethod
|
|
913
|
+
def _attach(parent, item):
|
|
914
|
+
if isinstance(parent, QTreeWidget):
|
|
915
|
+
parent.addTopLevelItem(item)
|
|
916
|
+
else:
|
|
917
|
+
parent.addChild(item)
|
|
918
|
+
|
|
919
|
+
def _color_if_plotted(self, item, wfile, name):
|
|
920
|
+
tag = wfile.getTag(name)
|
|
921
|
+
self._tag_to_item[tag] = item
|
|
922
|
+
if tag in self._wave_cache:
|
|
923
|
+
wave = self._wave_cache[tag]
|
|
924
|
+
if wave.color:
|
|
925
|
+
from PySide6.QtGui import QColor
|
|
926
|
+
item.setForeground(0, QColor(wave.color))
|
|
927
|
+
|
|
928
|
+
def _wave_clicked(self, item, column):
|
|
929
|
+
yname = item.data(0, Qt.UserRole)
|
|
930
|
+
if not yname:
|
|
931
|
+
item.setExpanded(not item.isExpanded())
|
|
932
|
+
return
|
|
933
|
+
f = self.files.getSelected()
|
|
934
|
+
tag = f.getTag(yname)
|
|
935
|
+
if tag not in self._wave_cache:
|
|
936
|
+
self._wave_cache[tag] = PgWave(f, yname, self.xaxis)
|
|
937
|
+
wave = self._wave_cache[tag]
|
|
938
|
+
if wave.curve is not None:
|
|
939
|
+
self.waveRemoveRequested.emit(wave)
|
|
940
|
+
return
|
|
941
|
+
wave.reload()
|
|
942
|
+
self.waveSelected.emit(wave)
|
|
943
|
+
|
|
944
|
+
def currentWave(self):
|
|
945
|
+
"""Return the wave currently focused in the wave tree, or
|
|
946
|
+
``None`` if no signal row is selected."""
|
|
947
|
+
item = self.wave_tree.currentItem()
|
|
948
|
+
if item is None:
|
|
949
|
+
return None
|
|
950
|
+
yname = item.data(0, Qt.UserRole)
|
|
951
|
+
if not yname:
|
|
952
|
+
return None
|
|
953
|
+
f = self.files.getSelected()
|
|
954
|
+
if f is None:
|
|
955
|
+
return None
|
|
956
|
+
tag = f.getTag(yname)
|
|
957
|
+
if tag not in self._wave_cache:
|
|
958
|
+
self._wave_cache[tag] = PgWave(f, yname, self.xaxis)
|
|
959
|
+
return self._wave_cache[tag]
|
|
960
|
+
|
|
961
|
+
def togglePlotAsDigital(self):
|
|
962
|
+
"""Toggle ``show_as_digital`` on the focused wave and request
|
|
963
|
+
a re-plot. Triggered by the ``D`` keyboard shortcut."""
|
|
964
|
+
wave = self.currentWave()
|
|
965
|
+
if wave is None:
|
|
966
|
+
return
|
|
967
|
+
wave.show_as_digital = not wave.show_as_digital
|
|
968
|
+
#- Bounce off the current pane (no-op if it wasn't plotted)
|
|
969
|
+
#- and re-add: routing is decided by show_as_digital.
|
|
970
|
+
self.waveRemoveRequested.emit(wave)
|
|
971
|
+
self.waveSelected.emit(wave)
|
|
972
|
+
|
|
973
|
+
def _wave_context(self, pos):
|
|
974
|
+
item = self.wave_tree.itemAt(pos)
|
|
975
|
+
f = self.files.getSelected()
|
|
976
|
+
if f is None:
|
|
977
|
+
return
|
|
978
|
+
visible = self._visible_wave_names()
|
|
979
|
+
if not visible:
|
|
980
|
+
return
|
|
981
|
+
|
|
982
|
+
def _plot_all_visible():
|
|
983
|
+
self.wavePlotAllVisibleRequested.emit()
|
|
984
|
+
|
|
985
|
+
if not item:
|
|
986
|
+
menu = QMenu(self)
|
|
987
|
+
menu.addAction("Plot all visible waves", _plot_all_visible)
|
|
988
|
+
menu.exec(self.wave_tree.viewport().mapToGlobal(pos))
|
|
989
|
+
return
|
|
990
|
+
|
|
991
|
+
yname = item.data(0, Qt.UserRole)
|
|
992
|
+
if not yname:
|
|
993
|
+
menu = QMenu(self)
|
|
994
|
+
menu.addAction("Plot all visible waves", _plot_all_visible)
|
|
995
|
+
menu.exec(self.wave_tree.viewport().mapToGlobal(pos))
|
|
996
|
+
return
|
|
997
|
+
|
|
998
|
+
tag = f.getTag(yname)
|
|
999
|
+
|
|
1000
|
+
if tag not in self._wave_cache:
|
|
1001
|
+
self._wave_cache[tag] = PgWave(f, yname, self.xaxis)
|
|
1002
|
+
|
|
1003
|
+
wave = self._wave_cache[tag]
|
|
1004
|
+
wave.reload()
|
|
1005
|
+
|
|
1006
|
+
menu = QMenu(self)
|
|
1007
|
+
menu.addAction("Plot", lambda: self.waveSelected.emit(wave))
|
|
1008
|
+
menu.addAction(
|
|
1009
|
+
"Plot for all files",
|
|
1010
|
+
lambda n=yname: self.wavePlotAllRequested.emit(n))
|
|
1011
|
+
menu.addAction("Plot all visible waves", _plot_all_visible)
|
|
1012
|
+
if wave.curve:
|
|
1013
|
+
menu.addAction("Remove from plot",
|
|
1014
|
+
lambda: self.waveRemoveRequested.emit(wave))
|
|
1015
|
+
style_menu = menu.addMenu("Style")
|
|
1016
|
+
for s in PLOT_STYLES:
|
|
1017
|
+
def _set_style(st=s):
|
|
1018
|
+
if wave.curve:
|
|
1019
|
+
wave.setStyle(st)
|
|
1020
|
+
else:
|
|
1021
|
+
self.style_cb.setCurrentText(st)
|
|
1022
|
+
self.waveSelected.emit(wave)
|
|
1023
|
+
style_menu.addAction(s, _set_style)
|
|
1024
|
+
#- "Show as digital" toggles routing to the dedicated digital
|
|
1025
|
+
#- pane. Always offered: VCD bit/vector signals plot with their
|
|
1026
|
+
#- true sampled values; analog signals (e.g. SPICE .raw) get a
|
|
1027
|
+
#- synthesized bit trace based on a (min+max)/2 threshold +
|
|
1028
|
+
#- small hysteresis to suppress noise around the cross point.
|
|
1029
|
+
digi_label = ("✓ Show as digital" if wave.show_as_digital
|
|
1030
|
+
else "Show as digital")
|
|
1031
|
+
|
|
1032
|
+
def _toggle_digital(w=wave):
|
|
1033
|
+
w.show_as_digital = not w.show_as_digital
|
|
1034
|
+
#- If the wave is already on a plot, re-route it to the
|
|
1035
|
+
#- other pane by removing then re-adding it. The plot
|
|
1036
|
+
#- knows whether it has the wave via ``wave_data`` so
|
|
1037
|
+
#- both analog and digital removals are handled.
|
|
1038
|
+
self.waveRemoveRequested.emit(w)
|
|
1039
|
+
self.waveSelected.emit(w)
|
|
1040
|
+
menu.addAction(digi_label, _toggle_digital)
|
|
1041
|
+
if wave.digital_kind == 'vector':
|
|
1042
|
+
#- Hex / Dec / Bin only matter for multi-bit digital signals.
|
|
1043
|
+
digital_menu = menu.addMenu("Digital format")
|
|
1044
|
+
for fmt in PgWave.DIGITAL_FORMATS:
|
|
1045
|
+
fmt_label = fmt.capitalize()
|
|
1046
|
+
if wave.digital_format == fmt:
|
|
1047
|
+
fmt_label = "● " + fmt_label
|
|
1048
|
+
|
|
1049
|
+
def _set_fmt(w=wave, f=fmt):
|
|
1050
|
+
w.setDigitalFormat(f)
|
|
1051
|
+
self.waveSelected.emit(w)
|
|
1052
|
+
digital_menu.addAction(fmt_label, _set_fmt)
|
|
1053
|
+
menu.addSeparator()
|
|
1054
|
+
for label, atype in [("FFT / PSD", "fft"),
|
|
1055
|
+
("Histogram", "histogram"),
|
|
1056
|
+
("Differentiate (dy/dx)", "differentiate"),
|
|
1057
|
+
("X vs Y...", "xvy")]:
|
|
1058
|
+
menu.addAction(label, lambda t=atype: self.analysisRequested.emit(
|
|
1059
|
+
t, wave))
|
|
1060
|
+
menu.exec(self.wave_tree.viewport().mapToGlobal(pos))
|
|
1061
|
+
|
|
1062
|
+
|
|
1063
|
+
class PgWavePlot(QWidget):
|
|
1064
|
+
"""A single plot tab with automatic dual Y-axes, cursors, and readout."""
|
|
1065
|
+
|
|
1066
|
+
def __init__(self, parent=None):
|
|
1067
|
+
super().__init__(parent)
|
|
1068
|
+
layout = QVBoxLayout(self)
|
|
1069
|
+
layout.setContentsMargins(2, 2, 2, 2)
|
|
1070
|
+
|
|
1071
|
+
self.gw = pg.GraphicsLayoutWidget()
|
|
1072
|
+
layout.addWidget(self.gw, 1)
|
|
1073
|
+
|
|
1074
|
+
font = _mono_font(9)
|
|
1075
|
+
self.readout = QTextEdit()
|
|
1076
|
+
self.readout.setReadOnly(True)
|
|
1077
|
+
self.readout.setMaximumHeight(120)
|
|
1078
|
+
self.readout.setFont(font)
|
|
1079
|
+
layout.addWidget(self.readout)
|
|
1080
|
+
|
|
1081
|
+
self.status = QLabel("")
|
|
1082
|
+
self.status.setFont(font)
|
|
1083
|
+
layout.addWidget(self.status)
|
|
1084
|
+
|
|
1085
|
+
self._apply_panel_style()
|
|
1086
|
+
|
|
1087
|
+
self.plot = self.gw.addPlot(row=0, col=0)
|
|
1088
|
+
self.plot.showGrid(x=True, y=True)
|
|
1089
|
+
_apply_grid(self.plot)
|
|
1090
|
+
self.plot.vb.wheelEvent = lambda ev: self._on_wheel(ev)
|
|
1091
|
+
self._orig_mouseDragEvent = self.plot.vb.mouseDragEvent
|
|
1092
|
+
self.plot.vb.mouseDragEvent = self._on_mouse_drag
|
|
1093
|
+
|
|
1094
|
+
#- Digital pane below the analog plot. One row per digital
|
|
1095
|
+
#- signal, fixed pixel height per row, x-axis linked to the
|
|
1096
|
+
#- analog plot. Hidden when no digital signals are plotted.
|
|
1097
|
+
self._digital_row_height = 28 # pixels per signal row
|
|
1098
|
+
self._digital_row_spacing = 4 # pixels between rows
|
|
1099
|
+
self._digital_padding = 8 # top/bottom padding
|
|
1100
|
+
self.digital_plot = self.gw.addPlot(row=1, col=0)
|
|
1101
|
+
self._init_digital_plot()
|
|
1102
|
+
#- One entry per visible digital wave: (wave, items_dict)
|
|
1103
|
+
#- where items_dict has the curve / labels / row index.
|
|
1104
|
+
self._digital_waves = {}
|
|
1105
|
+
|
|
1106
|
+
self._unit_vb = {}
|
|
1107
|
+
#- Per-unit bookkeeping so we can demote the descriptive part of
|
|
1108
|
+
#- an axis label when a second curve with a different name is
|
|
1109
|
+
#- added to the same axis (only the unit is meaningful then).
|
|
1110
|
+
self._unit_axis_side = {}
|
|
1111
|
+
self._unit_axis_label = {}
|
|
1112
|
+
self._right_vb = None
|
|
1113
|
+
self._logx = False
|
|
1114
|
+
self._has_rotated_x = False
|
|
1115
|
+
|
|
1116
|
+
self.wave_data = {}
|
|
1117
|
+
self._color_index = 0
|
|
1118
|
+
self._line_width = 2
|
|
1119
|
+
self._font_size = 9
|
|
1120
|
+
self._legend_visible = False
|
|
1121
|
+
self._legend = None
|
|
1122
|
+
|
|
1123
|
+
self.cursor_a = None
|
|
1124
|
+
self.cursor_b = None
|
|
1125
|
+
self._cursor_a_lines = []
|
|
1126
|
+
self._cursor_b_lines = []
|
|
1127
|
+
self._delta_texts = []
|
|
1128
|
+
self._last_x = None
|
|
1129
|
+
self._annotations = []
|
|
1130
|
+
|
|
1131
|
+
self.custom_xlabel = None
|
|
1132
|
+
self.custom_ylabel = None
|
|
1133
|
+
self.custom_title = None
|
|
1134
|
+
|
|
1135
|
+
# Wheel-zoom coalescing: rapid wheel ticks (touchpad / high-rate
|
|
1136
|
+
# mice) are accumulated into a single deferred range update so we
|
|
1137
|
+
# don't trigger per-curve downsampling re-computation on every tick.
|
|
1138
|
+
self._wheel_pending_x_scale = 1.0
|
|
1139
|
+
self._wheel_pending_y_scale = 1.0
|
|
1140
|
+
self._wheel_pending_pos = None
|
|
1141
|
+
self._wheel_timer = QTimer(self)
|
|
1142
|
+
self._wheel_timer.setSingleShot(True)
|
|
1143
|
+
self._wheel_timer.setInterval(16) # ~one frame at 60 Hz
|
|
1144
|
+
self._wheel_timer.timeout.connect(self._apply_pending_wheel_zoom)
|
|
1145
|
+
|
|
1146
|
+
self.gw.scene().sigMouseMoved.connect(self._on_mouse_moved)
|
|
1147
|
+
|
|
1148
|
+
def _apply_panel_style(self):
|
|
1149
|
+
theme = _get_theme()
|
|
1150
|
+
ss = "background-color: %s; color: %s;" % (
|
|
1151
|
+
theme['panel_bg'], theme['panel_fg'])
|
|
1152
|
+
self.readout.setStyleSheet(ss)
|
|
1153
|
+
self.status.setStyleSheet(ss + " padding: 2px;")
|
|
1154
|
+
|
|
1155
|
+
# ------------------------------------------------------------------
|
|
1156
|
+
# Dual Y-axis management
|
|
1157
|
+
# ------------------------------------------------------------------
|
|
1158
|
+
|
|
1159
|
+
def _all_viewboxes(self):
|
|
1160
|
+
vbs = [self.plot.vb]
|
|
1161
|
+
if self._right_vb is not None:
|
|
1162
|
+
vbs.append(self._right_vb)
|
|
1163
|
+
return vbs
|
|
1164
|
+
|
|
1165
|
+
def _get_or_create_vb(self, yunit, ylabel_text=""):
|
|
1166
|
+
"""Return the ViewBox for a given yunit, creating axes as needed.
|
|
1167
|
+
|
|
1168
|
+
``ylabel_text`` is the descriptive name used as the axis title text
|
|
1169
|
+
(e.g. ``"Amplitude"`` cleaned from ``"Amplitude_dBm"``). If empty
|
|
1170
|
+
the axis shows only the unit, as before.
|
|
1171
|
+
|
|
1172
|
+
When a second wave with a *different* descriptive name lands on
|
|
1173
|
+
an existing axis, the descriptive part of the label is dropped
|
|
1174
|
+
so the axis only shows the unit (it would otherwise look like
|
|
1175
|
+
the axis only describes the first curve, which is misleading).
|
|
1176
|
+
"""
|
|
1177
|
+
if yunit in self._unit_vb:
|
|
1178
|
+
self._maybe_demote_axis_label(yunit, ylabel_text)
|
|
1179
|
+
return self._unit_vb[yunit]
|
|
1180
|
+
|
|
1181
|
+
if not self._unit_vb:
|
|
1182
|
+
self._unit_vb[yunit] = self.plot.vb
|
|
1183
|
+
self._unit_axis_side[yunit] = 'left'
|
|
1184
|
+
self._unit_axis_label[yunit] = ylabel_text or ""
|
|
1185
|
+
if yunit or ylabel_text:
|
|
1186
|
+
self.plot.setLabel('left', ylabel_text, units=yunit)
|
|
1187
|
+
return self.plot.vb
|
|
1188
|
+
|
|
1189
|
+
if self._right_vb is None:
|
|
1190
|
+
self._right_vb = pg.ViewBox()
|
|
1191
|
+
self.plot.showAxis('right')
|
|
1192
|
+
self.plot.scene().addItem(self._right_vb)
|
|
1193
|
+
self.plot.getAxis('right').linkToView(self._right_vb)
|
|
1194
|
+
self._right_vb.setXLink(self.plot)
|
|
1195
|
+
self.plot.vb.sigResized.connect(self._sync_right_vb)
|
|
1196
|
+
self._sync_right_vb()
|
|
1197
|
+
self._right_vb.wheelEvent = lambda ev: self._on_wheel(ev)
|
|
1198
|
+
self._right_vb.mouseDragEvent = self._on_mouse_drag
|
|
1199
|
+
|
|
1200
|
+
self._unit_vb[yunit] = self._right_vb
|
|
1201
|
+
self._unit_axis_side[yunit] = 'right'
|
|
1202
|
+
self._unit_axis_label[yunit] = ylabel_text or ""
|
|
1203
|
+
if yunit or ylabel_text:
|
|
1204
|
+
self.plot.setLabel('right', ylabel_text, units=yunit)
|
|
1205
|
+
|
|
1206
|
+
self._ensure_cursors_on_right_vb()
|
|
1207
|
+
return self._right_vb
|
|
1208
|
+
|
|
1209
|
+
def _maybe_demote_axis_label(self, yunit, new_label):
|
|
1210
|
+
"""If a second curve on the same axis has a different name, drop
|
|
1211
|
+
the descriptive label so the axis only shows the unit."""
|
|
1212
|
+
side = self._unit_axis_side.get(yunit)
|
|
1213
|
+
if side is None:
|
|
1214
|
+
return
|
|
1215
|
+
existing = self._unit_axis_label.get(yunit, "")
|
|
1216
|
+
new_label = new_label or ""
|
|
1217
|
+
if not existing or existing == "<unit-only>":
|
|
1218
|
+
return
|
|
1219
|
+
if new_label and new_label != existing:
|
|
1220
|
+
self.plot.setLabel(side, "", units=yunit)
|
|
1221
|
+
self._unit_axis_label[yunit] = "<unit-only>"
|
|
1222
|
+
|
|
1223
|
+
def _sync_right_vb(self):
|
|
1224
|
+
if self._right_vb:
|
|
1225
|
+
self._right_vb.setGeometry(self.plot.vb.sceneBoundingRect())
|
|
1226
|
+
|
|
1227
|
+
def _ensure_cursors_on_right_vb(self):
|
|
1228
|
+
if self._right_vb is None:
|
|
1229
|
+
return
|
|
1230
|
+
theme = _get_theme()
|
|
1231
|
+
vbs = self._all_viewboxes()
|
|
1232
|
+
for i, vb in enumerate(vbs):
|
|
1233
|
+
if self.cursor_a is not None and i >= len(self._cursor_a_lines):
|
|
1234
|
+
line = self._make_cursor_line(
|
|
1235
|
+
self.cursor_a, theme['cursor_a'], 'a')
|
|
1236
|
+
vb.addItem(line)
|
|
1237
|
+
self._cursor_a_lines.append(line)
|
|
1238
|
+
if self.cursor_b is not None and i >= len(self._cursor_b_lines):
|
|
1239
|
+
line = self._make_cursor_line(
|
|
1240
|
+
self.cursor_b, theme['cursor_b'], 'b')
|
|
1241
|
+
vb.addItem(line)
|
|
1242
|
+
self._cursor_b_lines.append(line)
|
|
1243
|
+
|
|
1244
|
+
# ------------------------------------------------------------------
|
|
1245
|
+
# Digital pane (under the analog x-axis)
|
|
1246
|
+
# ------------------------------------------------------------------
|
|
1247
|
+
|
|
1248
|
+
def _init_digital_plot(self):
|
|
1249
|
+
"""Set up the digital pane: link x to the analog plot, hide most
|
|
1250
|
+
chrome, and start hidden until a digital signal is added."""
|
|
1251
|
+
dp = self.digital_plot
|
|
1252
|
+
dp.hideButtons()
|
|
1253
|
+
dp.showAxis('left')
|
|
1254
|
+
dp.showAxis('bottom', False)
|
|
1255
|
+
dp.getAxis('left').setStyle(showValues=False)
|
|
1256
|
+
dp.getAxis('left').setTicks([])
|
|
1257
|
+
dp.getAxis('left').setWidth(self.plot.getAxis('left').width())
|
|
1258
|
+
dp.setMouseEnabled(x=True, y=False)
|
|
1259
|
+
dp.setMenuEnabled(False)
|
|
1260
|
+
dp.setXLink(self.plot)
|
|
1261
|
+
dp.vb.setLimits(yMin=0) # rows live in [0, n_rows]
|
|
1262
|
+
dp.setVisible(False)
|
|
1263
|
+
#- Forward our wheel/drag handlers so the digital pane behaves
|
|
1264
|
+
#- like the analog plot for x-axis interaction.
|
|
1265
|
+
dp.vb.wheelEvent = lambda ev: self._on_wheel(ev)
|
|
1266
|
+
dp.vb.mouseDragEvent = self._on_mouse_drag
|
|
1267
|
+
#- Throttled label refresh on x-range changes: a wide view of
|
|
1268
|
+
#- a 16k-transition vector would otherwise create 16k TextItems
|
|
1269
|
+
#- and freeze the UI. We render at most ``_DIGITAL_MAX_LABELS``
|
|
1270
|
+
#- labels per signal, only for transitions inside the current
|
|
1271
|
+
#- view rect, and refresh on demand.
|
|
1272
|
+
from PySide6.QtCore import QTimer as _QT
|
|
1273
|
+
self._digital_label_timer = _QT()
|
|
1274
|
+
self._digital_label_timer.setSingleShot(True)
|
|
1275
|
+
self._digital_label_timer.setInterval(60)
|
|
1276
|
+
self._digital_label_timer.timeout.connect(
|
|
1277
|
+
self._update_visible_digital_labels)
|
|
1278
|
+
dp.vb.sigXRangeChanged.connect(
|
|
1279
|
+
lambda *_: self._digital_label_timer.start())
|
|
1280
|
+
|
|
1281
|
+
#- Maximum number of value labels to draw per vector signal. A
|
|
1282
|
+
#- handful is plenty at any zoom level; more would only overlap.
|
|
1283
|
+
_DIGITAL_MAX_LABELS = 80
|
|
1284
|
+
|
|
1285
|
+
def _digital_total_rows(self):
|
|
1286
|
+
return len(self._digital_waves)
|
|
1287
|
+
|
|
1288
|
+
def _digital_row_pixel_height(self):
|
|
1289
|
+
n = self._digital_total_rows()
|
|
1290
|
+
if n == 0:
|
|
1291
|
+
return 0
|
|
1292
|
+
return (n * self._digital_row_height
|
|
1293
|
+
+ max(0, n - 1) * self._digital_row_spacing
|
|
1294
|
+
+ 2 * self._digital_padding)
|
|
1295
|
+
|
|
1296
|
+
def _refresh_digital_pane_geometry(self):
|
|
1297
|
+
"""Resize the digital pane to ``rows * row_height`` (pixels)."""
|
|
1298
|
+
n = self._digital_total_rows()
|
|
1299
|
+
dp = self.digital_plot
|
|
1300
|
+
if n == 0:
|
|
1301
|
+
dp.setVisible(False)
|
|
1302
|
+
return
|
|
1303
|
+
dp.setVisible(True)
|
|
1304
|
+
h = self._digital_row_pixel_height()
|
|
1305
|
+
dp.setMaximumHeight(h)
|
|
1306
|
+
dp.setMinimumHeight(h)
|
|
1307
|
+
dp.setYRange(0, n, padding=0)
|
|
1308
|
+
|
|
1309
|
+
def _add_digital_wave(self, wave, color):
|
|
1310
|
+
"""Place a digital signal in its own row in the digital pane."""
|
|
1311
|
+
row_idx = self._digital_total_rows() # bottom-up new row
|
|
1312
|
+
slot_top = row_idx + 1
|
|
1313
|
+
slot_bot = row_idx
|
|
1314
|
+
items = self._build_digital_items(wave, slot_bot, slot_top, color)
|
|
1315
|
+
self._digital_waves[wave.tag] = {
|
|
1316
|
+
'wave': wave, 'row': row_idx, 'items': items,
|
|
1317
|
+
'color': color, 'slot': (slot_bot, slot_top),
|
|
1318
|
+
}
|
|
1319
|
+
self._refresh_digital_pane_geometry()
|
|
1320
|
+
self._refresh_digital_left_axis()
|
|
1321
|
+
#- Re-apply view-dependent rendering opts now that the digital
|
|
1322
|
+
#- pane has a real y-range; otherwise auto-downsample would
|
|
1323
|
+
#- have computed a bogus factor against the default unit rect.
|
|
1324
|
+
for it in items.get('lines', []):
|
|
1325
|
+
PgWave._enable_view_dependent_opts(it)
|
|
1326
|
+
#- Render initial labels for the current view immediately so the
|
|
1327
|
+
#- user doesn't have to wait for the throttle timer.
|
|
1328
|
+
self._update_visible_digital_labels()
|
|
1329
|
+
|
|
1330
|
+
_DIGITAL_AXIS_MAX_CHARS = 14
|
|
1331
|
+
|
|
1332
|
+
def _refresh_digital_left_axis(self):
|
|
1333
|
+
"""Show signal names on the left axis of the digital pane,
|
|
1334
|
+
one tick per row, centered vertically in the row.
|
|
1335
|
+
|
|
1336
|
+
Names longer than ``_DIGITAL_AXIS_MAX_CHARS`` are truncated
|
|
1337
|
+
with an ellipsis ("…") so the axis stays narrow but every
|
|
1338
|
+
signal still gets *some* label. The axis width grows enough
|
|
1339
|
+
to comfortably fit the longest (truncated) label."""
|
|
1340
|
+
ax = self.digital_plot.getAxis('left')
|
|
1341
|
+
ticks = []
|
|
1342
|
+
max_len = 0
|
|
1343
|
+
for info in self._digital_waves.values():
|
|
1344
|
+
row = info['row']
|
|
1345
|
+
wave = info['wave']
|
|
1346
|
+
short = self._short_signal_name(wave.key)
|
|
1347
|
+
short = self._truncate_axis_label(short)
|
|
1348
|
+
max_len = max(max_len, len(short))
|
|
1349
|
+
ticks.append(((row + 0.5), short))
|
|
1350
|
+
ax.setTicks([ticks])
|
|
1351
|
+
ax.setStyle(showValues=True)
|
|
1352
|
+
#- ~7 px per char for the default axis font + padding.
|
|
1353
|
+
wanted = 12 + 7 * max_len
|
|
1354
|
+
ax.setWidth(max(80, wanted, self.plot.getAxis('left').width()))
|
|
1355
|
+
|
|
1356
|
+
@classmethod
|
|
1357
|
+
def _truncate_axis_label(cls, name):
|
|
1358
|
+
"""Truncate ``name`` to ``_DIGITAL_AXIS_MAX_CHARS`` keeping the
|
|
1359
|
+
leading and trailing characters. ``osc_temp_1v8`` (12 chars)
|
|
1360
|
+
passes through; ``a_very_long_signal_name`` becomes
|
|
1361
|
+
``a_very_…name``. The trailing chars are usually the most
|
|
1362
|
+
identifying part (numeric suffix, leaf name)."""
|
|
1363
|
+
n = cls._DIGITAL_AXIS_MAX_CHARS
|
|
1364
|
+
if len(name) <= n:
|
|
1365
|
+
return name
|
|
1366
|
+
head = (n - 1) // 2
|
|
1367
|
+
tail = n - 1 - head
|
|
1368
|
+
return name[:head] + "…" + name[-tail:]
|
|
1369
|
+
|
|
1370
|
+
@staticmethod
|
|
1371
|
+
def _short_signal_name(name):
|
|
1372
|
+
"""Compact label for the digital pane left axis.
|
|
1373
|
+
|
|
1374
|
+
``test.dut_ana.osc`` -> ``osc``
|
|
1375
|
+
``v(xdut.done)`` -> ``done``
|
|
1376
|
+
``v(out)`` -> ``out``
|
|
1377
|
+
``i(vdd)`` -> ``i(vdd)`` (current probes keep prefix)
|
|
1378
|
+
|
|
1379
|
+
For digital rows we strip the ``v(...)`` wrapper entirely --
|
|
1380
|
+
the analog/voltage distinction is meaningless when we're
|
|
1381
|
+
showing 0/1 transitions, and the bare leaf name reads better
|
|
1382
|
+
next to gtkwave-style traces. Current probes (``i(...)``)
|
|
1383
|
+
keep their prefix because the ``i`` carries information.
|
|
1384
|
+
"""
|
|
1385
|
+
m = re.match(r'^([vi])\((.+)\)$', name)
|
|
1386
|
+
if m:
|
|
1387
|
+
inner = m.group(2)
|
|
1388
|
+
leaf = inner.rsplit('.', 1)[-1]
|
|
1389
|
+
if m.group(1) == 'v':
|
|
1390
|
+
return leaf
|
|
1391
|
+
return "%s(%s)" % (m.group(1), leaf)
|
|
1392
|
+
if '.' in name:
|
|
1393
|
+
return name.rsplit('.', 1)[-1]
|
|
1394
|
+
return name
|
|
1395
|
+
|
|
1396
|
+
def _build_digital_items(self, wave, y_lo, y_hi, color):
|
|
1397
|
+
"""Construct the GraphicsItems for a digital wave row.
|
|
1398
|
+
|
|
1399
|
+
Returns a dict with the items (so they can be removed later).
|
|
1400
|
+
|
|
1401
|
+
Three cases:
|
|
1402
|
+
- true bit signal (VCD): use ``wave._digital_raw`` directly.
|
|
1403
|
+
- true vector signal (VCD): bus shape with on-demand labels.
|
|
1404
|
+
- any other waveform: synthesize a 0/1 trace from the analog
|
|
1405
|
+
data via :meth:`PgWave.synthesizeDigitalBits` and treat it
|
|
1406
|
+
as a bit signal.
|
|
1407
|
+
|
|
1408
|
+
The ``color`` argument is ignored for the digital pane: traces
|
|
1409
|
+
are drawn in the theme's foreground color (white on dark,
|
|
1410
|
+
black on light) so the gtkwave/surfer-style waveforms read at
|
|
1411
|
+
a glance and don't compete with the analog rainbow above.
|
|
1412
|
+
"""
|
|
1413
|
+
synth_kind = wave.digital_kind
|
|
1414
|
+
raw = wave._digital_raw
|
|
1415
|
+
if synth_kind not in ('bit', 'vector'):
|
|
1416
|
+
#- Analog wave: synthesize a bit trace.
|
|
1417
|
+
raw = wave.synthesizeDigitalBits()
|
|
1418
|
+
wave._digital_raw = raw # cache for label refreshes
|
|
1419
|
+
synth_kind = 'bit'
|
|
1420
|
+
|
|
1421
|
+
x_arr, _ = _to_numeric(wave.x) if wave.x is not None else (
|
|
1422
|
+
np.arange(len(raw or [])), None)
|
|
1423
|
+
items = {'lines': [], 'labels': []}
|
|
1424
|
+
if x_arr is None or len(x_arr) == 0 or raw is None:
|
|
1425
|
+
return items
|
|
1426
|
+
|
|
1427
|
+
theme = _get_theme()
|
|
1428
|
+
mono = theme.get('pg_foreground', 'w')
|
|
1429
|
+
|
|
1430
|
+
if synth_kind == 'bit':
|
|
1431
|
+
#- Bit row: standard step trace from y_lo (=0) to y_lo+0.8
|
|
1432
|
+
#- of the slot, with NaN for x/z so the line breaks.
|
|
1433
|
+
yvals = np.full(len(raw), np.nan, dtype=np.float64)
|
|
1434
|
+
mid = y_lo + 0.5
|
|
1435
|
+
top = y_lo + 0.85
|
|
1436
|
+
bot = y_lo + 0.15
|
|
1437
|
+
for i, v in enumerate(raw):
|
|
1438
|
+
if v == '1' or v == 1:
|
|
1439
|
+
yvals[i] = top
|
|
1440
|
+
elif v == '0' or v == 0:
|
|
1441
|
+
yvals[i] = bot
|
|
1442
|
+
#- x/z/h/l left as NaN -> draws a gap.
|
|
1443
|
+
curve = pg.PlotDataItem(
|
|
1444
|
+
x_arr, yvals,
|
|
1445
|
+
pen=pg.mkPen(mono, width=1.0),
|
|
1446
|
+
stepMode='left', connect='finite')
|
|
1447
|
+
self.digital_plot.addItem(curve)
|
|
1448
|
+
PgWave._enable_view_dependent_opts(curve)
|
|
1449
|
+
items['lines'].append(curve)
|
|
1450
|
+
#- Mid baseline so the row is visible even if all-x.
|
|
1451
|
+
base = pg.InfiniteLine(
|
|
1452
|
+
pos=mid, angle=0,
|
|
1453
|
+
pen=pg.mkPen(mono, width=0.5,
|
|
1454
|
+
style=Qt.DotLine))
|
|
1455
|
+
self.digital_plot.addItem(base)
|
|
1456
|
+
items['lines'].append(base)
|
|
1457
|
+
else:
|
|
1458
|
+
#- Vector row: bus shape (two parallel lines forming a
|
|
1459
|
+
#- hexagon-like outline). Labels and vertical ticks are
|
|
1460
|
+
#- NOT drawn here; they are created on demand by
|
|
1461
|
+
#- :meth:`_update_visible_digital_labels` so we never
|
|
1462
|
+
#- materialise more than _DIGITAL_MAX_LABELS items per
|
|
1463
|
+
#- signal regardless of the underlying transition count.
|
|
1464
|
+
top = y_lo + 0.85
|
|
1465
|
+
bot = y_lo + 0.15
|
|
1466
|
+
top_y = np.full(len(raw), top, dtype=np.float64)
|
|
1467
|
+
bot_y = np.full(len(raw), bot, dtype=np.float64)
|
|
1468
|
+
#- Mark unknown ranges with NaN so the outline breaks.
|
|
1469
|
+
for i, v in enumerate(raw):
|
|
1470
|
+
if v is None or isinstance(v, str):
|
|
1471
|
+
top_y[i] = np.nan
|
|
1472
|
+
bot_y[i] = np.nan
|
|
1473
|
+
top_curve = pg.PlotDataItem(
|
|
1474
|
+
x_arr, top_y, pen=pg.mkPen(mono, width=1.0),
|
|
1475
|
+
stepMode='left', connect='finite')
|
|
1476
|
+
bot_curve = pg.PlotDataItem(
|
|
1477
|
+
x_arr, bot_y, pen=pg.mkPen(mono, width=1.0),
|
|
1478
|
+
stepMode='left', connect='finite')
|
|
1479
|
+
self.digital_plot.addItem(top_curve)
|
|
1480
|
+
self.digital_plot.addItem(bot_curve)
|
|
1481
|
+
PgWave._enable_view_dependent_opts(top_curve)
|
|
1482
|
+
PgWave._enable_view_dependent_opts(bot_curve)
|
|
1483
|
+
items['lines'].append(top_curve)
|
|
1484
|
+
items['lines'].append(bot_curve)
|
|
1485
|
+
#- Single curve carrying ALL transition ticks via
|
|
1486
|
+
#- ``connect='pairs'``: x = [t0_lo, t0_hi, t1_lo, t1_hi,...]
|
|
1487
|
+
#- with the y-array alternating bot/top. This replaces N
|
|
1488
|
+
#- per-tick PlotDataItems (which made pan/zoom slow when
|
|
1489
|
+
#- there are tens of thousands of transitions).
|
|
1490
|
+
ticks_curve = pg.PlotCurveItem(
|
|
1491
|
+
x=np.array([], dtype=np.float64),
|
|
1492
|
+
y=np.array([], dtype=np.float64),
|
|
1493
|
+
pen=pg.mkPen(mono, width=0.6),
|
|
1494
|
+
connect='pairs')
|
|
1495
|
+
self.digital_plot.addItem(ticks_curve)
|
|
1496
|
+
items['lines'].append(ticks_curve)
|
|
1497
|
+
items['ticks_curve'] = ticks_curve
|
|
1498
|
+
#- Pre-compute the transition index list so label refresh
|
|
1499
|
+
#- is just a binary search per refresh.
|
|
1500
|
+
items['transitions'] = self._vector_transitions(raw)
|
|
1501
|
+
items['x_arr'] = x_arr
|
|
1502
|
+
items['raw'] = raw
|
|
1503
|
+
items['y_mid'] = (top + bot) / 2.0
|
|
1504
|
+
items['y_lo'] = bot
|
|
1505
|
+
items['y_hi'] = top
|
|
1506
|
+
items['color'] = mono
|
|
1507
|
+
items['label_pool'] = [] # reused TextItems
|
|
1508
|
+
|
|
1509
|
+
return items
|
|
1510
|
+
|
|
1511
|
+
@staticmethod
|
|
1512
|
+
def _vector_transitions(raw):
|
|
1513
|
+
"""Indices in ``raw`` where the vector value changes (incl. 0)."""
|
|
1514
|
+
out = [0]
|
|
1515
|
+
prev = raw[0] if len(raw) else None
|
|
1516
|
+
for i in range(1, len(raw)):
|
|
1517
|
+
v = raw[i]
|
|
1518
|
+
if v != prev:
|
|
1519
|
+
out.append(i)
|
|
1520
|
+
prev = v
|
|
1521
|
+
return out
|
|
1522
|
+
|
|
1523
|
+
def _remove_digital_wave(self, tag):
|
|
1524
|
+
info = self._digital_waves.pop(tag, None)
|
|
1525
|
+
if info is None:
|
|
1526
|
+
return
|
|
1527
|
+
self._destroy_digital_items(info)
|
|
1528
|
+
#- Re-pack remaining rows so there are no gaps.
|
|
1529
|
+
remaining = list(self._digital_waves.values())
|
|
1530
|
+
self._digital_waves = {}
|
|
1531
|
+
for old in remaining:
|
|
1532
|
+
self._destroy_digital_items(old)
|
|
1533
|
+
self._add_digital_wave(old['wave'], old['color'])
|
|
1534
|
+
if not self._digital_waves:
|
|
1535
|
+
self._refresh_digital_pane_geometry()
|
|
1536
|
+
else:
|
|
1537
|
+
self._update_visible_digital_labels()
|
|
1538
|
+
|
|
1539
|
+
def _destroy_digital_items(self, info):
|
|
1540
|
+
d = info.get('items') or {}
|
|
1541
|
+
for it in d.get('lines', []):
|
|
1542
|
+
self.digital_plot.removeItem(it)
|
|
1543
|
+
for lbl in d.get('label_pool', []):
|
|
1544
|
+
self.digital_plot.removeItem(lbl)
|
|
1545
|
+
|
|
1546
|
+
def _refresh_digital_labels(self, wave):
|
|
1547
|
+
"""Re-render value labels for a digital vector wave (after a
|
|
1548
|
+
format change). Just retriggers the on-demand label updater so
|
|
1549
|
+
every visible label gets rebuilt with the new format."""
|
|
1550
|
+
info = self._digital_waves.get(wave.tag)
|
|
1551
|
+
if info is None or wave.digital_kind != 'vector':
|
|
1552
|
+
return
|
|
1553
|
+
self._update_visible_digital_labels()
|
|
1554
|
+
|
|
1555
|
+
def _update_visible_digital_labels(self):
|
|
1556
|
+
"""Render value labels and transition ticks for the transitions
|
|
1557
|
+
currently inside the digital pane's view rect.
|
|
1558
|
+
|
|
1559
|
+
- Vertical ticks for ALL visible transitions are drawn as a
|
|
1560
|
+
single ``PlotCurveItem`` with ``connect='pairs'`` (one buffer
|
|
1561
|
+
update vs N item creations -- much faster on pan/zoom).
|
|
1562
|
+
- Value labels are pooled and capped at
|
|
1563
|
+
``_DIGITAL_MAX_LABELS`` per signal; pool entries past the
|
|
1564
|
+
visible count are hidden, never destroyed.
|
|
1565
|
+
"""
|
|
1566
|
+
if not self._digital_waves:
|
|
1567
|
+
return
|
|
1568
|
+
try:
|
|
1569
|
+
xlo, xhi = self.digital_plot.vb.viewRange()[0]
|
|
1570
|
+
except Exception:
|
|
1571
|
+
return
|
|
1572
|
+
theme = _get_theme()
|
|
1573
|
+
label_color = theme.get('text_color', 'w')
|
|
1574
|
+
for tag, info in self._digital_waves.items():
|
|
1575
|
+
wave = info['wave']
|
|
1576
|
+
if wave.digital_kind != 'vector':
|
|
1577
|
+
continue
|
|
1578
|
+
d = info['items']
|
|
1579
|
+
transitions = d.get('transitions') or []
|
|
1580
|
+
x_arr = d.get('x_arr')
|
|
1581
|
+
raw = d.get('raw')
|
|
1582
|
+
ticks_curve = d.get('ticks_curve')
|
|
1583
|
+
if (x_arr is None or raw is None or not transitions
|
|
1584
|
+
or ticks_curve is None):
|
|
1585
|
+
continue
|
|
1586
|
+
|
|
1587
|
+
#- Find transitions inside [xlo, xhi]. Each transition is
|
|
1588
|
+
#- an index into x_arr; transitions are sorted, so use a
|
|
1589
|
+
#- numpy search rather than scanning.
|
|
1590
|
+
t_x = x_arr[np.asarray(transitions, dtype=np.int64)]
|
|
1591
|
+
lo_i = int(np.searchsorted(t_x, xlo, side='left'))
|
|
1592
|
+
hi_i = int(np.searchsorted(t_x, xhi, side='right'))
|
|
1593
|
+
visible_full = transitions[lo_i:hi_i]
|
|
1594
|
+
|
|
1595
|
+
y_mid = d['y_mid']
|
|
1596
|
+
y_lo = d['y_lo']
|
|
1597
|
+
y_hi = d['y_hi']
|
|
1598
|
+
|
|
1599
|
+
#- Update the vertical-ticks curve: 2 points per transition,
|
|
1600
|
+
#- alternating (x, y_lo) / (x, y_hi). This handles thousands
|
|
1601
|
+
#- of ticks in a single draw call.
|
|
1602
|
+
if visible_full:
|
|
1603
|
+
vis_x = x_arr[np.asarray(visible_full, dtype=np.int64)]
|
|
1604
|
+
xs = np.repeat(vis_x, 2)
|
|
1605
|
+
ys = np.tile([y_lo, y_hi], len(visible_full))
|
|
1606
|
+
ticks_curve.setData(xs, ys, connect='pairs')
|
|
1607
|
+
else:
|
|
1608
|
+
ticks_curve.setData([], [])
|
|
1609
|
+
|
|
1610
|
+
#- Always render up to _DIGITAL_MAX_LABELS visible
|
|
1611
|
+
#- transitions in order. We deliberately do NOT filter by
|
|
1612
|
+
#- segment-vs-text width: a too-aggressive width filter
|
|
1613
|
+
#- silently dropped every long label (e.g. multi-digit
|
|
1614
|
+
#- hex), which was the user-visible "long text doesn't
|
|
1615
|
+
#- show" bug. Letting wide labels overhang into the next
|
|
1616
|
+
#- cell matches gtkwave/surfer behaviour and is what users
|
|
1617
|
+
#- expect.
|
|
1618
|
+
pool = d.setdefault('label_pool', [])
|
|
1619
|
+
font = _mono_font(self._font_size - 1)
|
|
1620
|
+
|
|
1621
|
+
visible_lbl = []
|
|
1622
|
+
for ti in visible_full[:self._DIGITAL_MAX_LABELS]:
|
|
1623
|
+
visible_lbl.append((ti, wave.formatDigitalValue(raw[ti])))
|
|
1624
|
+
|
|
1625
|
+
#- Grow the pool lazily.
|
|
1626
|
+
while len(pool) < len(visible_lbl):
|
|
1627
|
+
lbl = pg.TextItem(text="", color=label_color,
|
|
1628
|
+
anchor=(0, 0.5))
|
|
1629
|
+
lbl.setFont(font)
|
|
1630
|
+
self.digital_plot.addItem(lbl)
|
|
1631
|
+
pool.append(lbl)
|
|
1632
|
+
|
|
1633
|
+
for i, (ti, txt) in enumerate(visible_lbl):
|
|
1634
|
+
xv = float(x_arr[ti])
|
|
1635
|
+
lbl = pool[i]
|
|
1636
|
+
lbl.setText(txt)
|
|
1637
|
+
lbl.setPos(xv, y_mid)
|
|
1638
|
+
lbl.show()
|
|
1639
|
+
for i in range(len(visible_lbl), len(pool)):
|
|
1640
|
+
pool[i].hide()
|
|
1641
|
+
|
|
1642
|
+
# ------------------------------------------------------------------
|
|
1643
|
+
# Public API
|
|
1644
|
+
# ------------------------------------------------------------------
|
|
1645
|
+
|
|
1646
|
+
def show_wave(self, wave, style='Lines'):
|
|
1647
|
+
"""Plot a wave. Returns (tag, color) on success, else None.
|
|
1648
|
+
|
|
1649
|
+
Digital signals (bit / vector, detected from VCD metadata) are
|
|
1650
|
+
placed in the dedicated digital pane below the analog x-axis
|
|
1651
|
+
rather than on the analog Y axes; everything else uses the
|
|
1652
|
+
usual axis-per-unit logic.
|
|
1653
|
+
"""
|
|
1654
|
+
if wave.tag in self.wave_data:
|
|
1655
|
+
return None
|
|
1656
|
+
|
|
1657
|
+
yunit = wave.yunit or ""
|
|
1658
|
+
# Cleaned-up name (e.g. "Amplitude" from "Amplitude_dBm"); falls
|
|
1659
|
+
# back to the raw key.
|
|
1660
|
+
yname = getattr(wave, "_yclean", None) or wave.key
|
|
1661
|
+
|
|
1662
|
+
if not self.wave_data:
|
|
1663
|
+
xlabel = wave.xlabel or ""
|
|
1664
|
+
if wave.xunit or xlabel:
|
|
1665
|
+
self.plot.setLabel('bottom', xlabel, units=wave.xunit or "")
|
|
1666
|
+
if wave.logx:
|
|
1667
|
+
self.plot.setLogMode(x=True)
|
|
1668
|
+
self._logx = True
|
|
1669
|
+
|
|
1670
|
+
theme = _get_theme()
|
|
1671
|
+
wcolors = theme['wave_colors']
|
|
1672
|
+
color = wcolors[self._color_index % len(wcolors)]
|
|
1673
|
+
self._color_index += 1
|
|
1674
|
+
|
|
1675
|
+
if wave.show_as_digital:
|
|
1676
|
+
#- Route to the digital pane when the user has explicitly
|
|
1677
|
+
#- requested it (right-click "Show as digital"). Works for
|
|
1678
|
+
#- both true digital signals (VCD bit/vector) and analog
|
|
1679
|
+
#- waveforms (a synthesized bit trace is computed via a
|
|
1680
|
+
#- mid-amplitude threshold + small hysteresis to suppress
|
|
1681
|
+
#- noise around the cross point).
|
|
1682
|
+
self._add_digital_wave(wave, color)
|
|
1683
|
+
self.wave_data[wave.tag] = (wave, yunit)
|
|
1684
|
+
try:
|
|
1685
|
+
xr = self.plot.vb.viewRange()[0]
|
|
1686
|
+
self.digital_plot.vb.setXRange(*xr, padding=0)
|
|
1687
|
+
except Exception:
|
|
1688
|
+
pass
|
|
1689
|
+
self._update_readout()
|
|
1690
|
+
return (wave.tag, color)
|
|
1691
|
+
|
|
1692
|
+
vb = self._get_or_create_vb(yunit, ylabel_text=yname)
|
|
1693
|
+
|
|
1694
|
+
if vb is self.plot.vb:
|
|
1695
|
+
curve = wave.plot(self.plot, color=color, style=style,
|
|
1696
|
+
width=self._line_width)
|
|
1697
|
+
else:
|
|
1698
|
+
curve = wave.plot(vb, color=color, style=style,
|
|
1699
|
+
width=self._line_width)
|
|
1700
|
+
if self._logx and curve:
|
|
1701
|
+
curve.setLogMode(True, False)
|
|
1702
|
+
|
|
1703
|
+
if curve is None:
|
|
1704
|
+
return None
|
|
1705
|
+
|
|
1706
|
+
self.wave_data[wave.tag] = (wave, yunit)
|
|
1707
|
+
|
|
1708
|
+
if wave._xlabels and not self._has_rotated_x:
|
|
1709
|
+
ticks = list(zip(range(len(wave._xlabels)), wave._xlabels))
|
|
1710
|
+
_apply_rotated_ticks(self.plot, 'bottom', ticks)
|
|
1711
|
+
self._has_rotated_x = True
|
|
1712
|
+
|
|
1713
|
+
if vb is self.plot.vb:
|
|
1714
|
+
self.plot.vb.enableAutoRange()
|
|
1715
|
+
self.plot.vb.autoRange()
|
|
1716
|
+
else:
|
|
1717
|
+
vb.enableAutoRange()
|
|
1718
|
+
vb.autoRange()
|
|
1719
|
+
|
|
1720
|
+
#- Enable autoDownsample and clipToView only AFTER autoRange so
|
|
1721
|
+
#- the curve has a valid view rect; otherwise the first display
|
|
1722
|
+
#- would clip / over-downsample against the empty default rect
|
|
1723
|
+
#- (~300 000x downsample for transient data) and render no
|
|
1724
|
+
#- points -- the bug that made macOS plots appear blank.
|
|
1725
|
+
PgWave._enable_view_dependent_opts(curve)
|
|
1726
|
+
|
|
1727
|
+
self._update_readout()
|
|
1728
|
+
return (wave.tag, color)
|
|
1729
|
+
|
|
1730
|
+
def removeLine(self, wave):
|
|
1731
|
+
"""Remove a single wave from the plot. Returns the tag if removed."""
|
|
1732
|
+
tag = wave.tag
|
|
1733
|
+
if tag in self.wave_data:
|
|
1734
|
+
self._remove_wave(tag)
|
|
1735
|
+
self._update_readout()
|
|
1736
|
+
return tag
|
|
1737
|
+
return None
|
|
1738
|
+
|
|
1739
|
+
def removeAll(self):
|
|
1740
|
+
tags = list(self.wave_data.keys())
|
|
1741
|
+
for tag in tags:
|
|
1742
|
+
self._remove_wave(tag)
|
|
1743
|
+
self._reset_axes()
|
|
1744
|
+
self._update_readout()
|
|
1745
|
+
return tags
|
|
1746
|
+
|
|
1747
|
+
def remove_waves_for_wfile(self, wf):
|
|
1748
|
+
"""Remove all traces that belong to WaveFile *wf* (same object identity)."""
|
|
1749
|
+
tags = [tag for tag, (wave, _) in self.wave_data.items()
|
|
1750
|
+
if wave.wfile is wf]
|
|
1751
|
+
for tag in tags:
|
|
1752
|
+
self._remove_wave(tag)
|
|
1753
|
+
if not self.wave_data:
|
|
1754
|
+
self._reset_axes()
|
|
1755
|
+
self._update_readout()
|
|
1756
|
+
return tags
|
|
1757
|
+
|
|
1758
|
+
def autoSize(self):
|
|
1759
|
+
"""Fit every axis to its full data extent.
|
|
1760
|
+
|
|
1761
|
+
``clipToView`` and ``autoDownsample`` both make
|
|
1762
|
+
:meth:`PlotCurveItem.dataBounds` report only the *currently
|
|
1763
|
+
displayed* slice, so a naive ``autoRange()`` after a zoom-in
|
|
1764
|
+
would just refit to that slice (looking like a one-step undo).
|
|
1765
|
+
Temporarily disable both options on every curve, refit, then
|
|
1766
|
+
restore them so the next viewport change still gets the
|
|
1767
|
+
rendering optimisations.
|
|
1768
|
+
"""
|
|
1769
|
+
curves = []
|
|
1770
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
1771
|
+
if wave.curve is not None:
|
|
1772
|
+
curves.append(wave.curve)
|
|
1773
|
+
|
|
1774
|
+
saved = []
|
|
1775
|
+
for c in curves:
|
|
1776
|
+
saved.append((c,
|
|
1777
|
+
c.opts.get('clipToView', False),
|
|
1778
|
+
c.opts.get('autoDownsample', False)))
|
|
1779
|
+
try:
|
|
1780
|
+
c.setClipToView(False)
|
|
1781
|
+
except Exception:
|
|
1782
|
+
c.opts['clipToView'] = False
|
|
1783
|
+
try:
|
|
1784
|
+
c.setDownsampling(auto=False)
|
|
1785
|
+
except Exception:
|
|
1786
|
+
pass
|
|
1787
|
+
|
|
1788
|
+
try:
|
|
1789
|
+
for vb in self._all_viewboxes():
|
|
1790
|
+
vb.enableAutoRange()
|
|
1791
|
+
vb.autoRange()
|
|
1792
|
+
finally:
|
|
1793
|
+
for c, clip, ads in saved:
|
|
1794
|
+
if ads:
|
|
1795
|
+
try:
|
|
1796
|
+
c.setDownsampling(auto=True, method='subsample')
|
|
1797
|
+
except Exception:
|
|
1798
|
+
pass
|
|
1799
|
+
if clip:
|
|
1800
|
+
try:
|
|
1801
|
+
c.setClipToView(True)
|
|
1802
|
+
except Exception:
|
|
1803
|
+
c.opts['clipToView'] = True
|
|
1804
|
+
|
|
1805
|
+
def zoomIn(self):
|
|
1806
|
+
self._keyboard_zoom(1.0 / ZOOM_FACTOR)
|
|
1807
|
+
|
|
1808
|
+
def zoomOut(self):
|
|
1809
|
+
self._keyboard_zoom(ZOOM_FACTOR)
|
|
1810
|
+
|
|
1811
|
+
def _keyboard_zoom(self, scale):
|
|
1812
|
+
vr = self.plot.vb.viewRange()
|
|
1813
|
+
xlo, xhi = vr[0]
|
|
1814
|
+
xmid = (xlo + xhi) / 2.0
|
|
1815
|
+
self.plot.vb.setXRange(
|
|
1816
|
+
xmid - (xmid - xlo) * scale,
|
|
1817
|
+
xmid + (xhi - xmid) * scale, padding=0)
|
|
1818
|
+
for vb in self._all_viewboxes():
|
|
1819
|
+
vr = vb.viewRange()
|
|
1820
|
+
ylo, yhi = vr[1]
|
|
1821
|
+
ymid = (ylo + yhi) / 2.0
|
|
1822
|
+
vb.setYRange(
|
|
1823
|
+
ymid - (ymid - ylo) * scale,
|
|
1824
|
+
ymid + (yhi - ymid) * scale, padding=0)
|
|
1825
|
+
|
|
1826
|
+
def reloadAll(self):
|
|
1827
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
1828
|
+
wave.reload()
|
|
1829
|
+
self.autoSize()
|
|
1830
|
+
|
|
1831
|
+
def setAllStyles(self, style):
|
|
1832
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
1833
|
+
wave.setStyle(style)
|
|
1834
|
+
|
|
1835
|
+
def setLineWidth(self, width):
|
|
1836
|
+
self._line_width = width
|
|
1837
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
1838
|
+
wave.setWidth(width)
|
|
1839
|
+
|
|
1840
|
+
def setFontSize(self, size):
|
|
1841
|
+
self._font_size = size
|
|
1842
|
+
font = _mono_font(size)
|
|
1843
|
+
self.readout.setFont(font)
|
|
1844
|
+
self.status.setFont(font)
|
|
1845
|
+
for axis_name in ['bottom', 'left', 'right']:
|
|
1846
|
+
ax = self.plot.getAxis(axis_name)
|
|
1847
|
+
ax.setTickFont(font)
|
|
1848
|
+
ax.setStyle(tickFont=font)
|
|
1849
|
+
|
|
1850
|
+
def toggleLegend(self):
|
|
1851
|
+
self._legend_visible = not self._legend_visible
|
|
1852
|
+
if self._legend:
|
|
1853
|
+
self._legend.scene().removeItem(self._legend)
|
|
1854
|
+
self._legend = None
|
|
1855
|
+
if self._legend_visible:
|
|
1856
|
+
self._legend = pg.LegendItem(offset=(30, 10))
|
|
1857
|
+
self._legend.setParentItem(self.plot.vb)
|
|
1858
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
1859
|
+
if wave.curve:
|
|
1860
|
+
self._legend.addItem(wave.curve, wave.ylabel)
|
|
1861
|
+
|
|
1862
|
+
def exportPdf(self):
|
|
1863
|
+
fname, _ = QFileDialog.getSaveFileName(
|
|
1864
|
+
self, "Export PDF", os.getcwd(),
|
|
1865
|
+
"PDF files (*.pdf);;PNG files (*.png);;SVG files (*.svg)")
|
|
1866
|
+
if not fname:
|
|
1867
|
+
return
|
|
1868
|
+
self._export_matplotlib(fname)
|
|
1869
|
+
|
|
1870
|
+
def _export_matplotlib(self, fname):
|
|
1871
|
+
import matplotlib.pyplot as plt
|
|
1872
|
+
from matplotlib.ticker import EngFormatter
|
|
1873
|
+
from matplotlib.gridspec import GridSpec
|
|
1874
|
+
|
|
1875
|
+
if not self.wave_data:
|
|
1876
|
+
return
|
|
1877
|
+
|
|
1878
|
+
#- Two-pane layout: analog on top, digital strip below (only
|
|
1879
|
+
#- if there are digital waves). Height ratio mirrors the live
|
|
1880
|
+
#- viewer where each digital row is a thin strip.
|
|
1881
|
+
n_digital = len(self._digital_waves)
|
|
1882
|
+
if n_digital > 0:
|
|
1883
|
+
digital_h = 0.35 * n_digital # inches per row
|
|
1884
|
+
fig = plt.figure(figsize=(10, 5 + digital_h))
|
|
1885
|
+
gs = GridSpec(2, 1, height_ratios=[5, digital_h], figure=fig,
|
|
1886
|
+
hspace=0.05)
|
|
1887
|
+
ax = fig.add_subplot(gs[0, 0])
|
|
1888
|
+
ax_dig = fig.add_subplot(gs[1, 0], sharex=ax)
|
|
1889
|
+
else:
|
|
1890
|
+
fig, ax = plt.subplots(figsize=(10, 5))
|
|
1891
|
+
ax_dig = None
|
|
1892
|
+
|
|
1893
|
+
units_left = set()
|
|
1894
|
+
units_right = set()
|
|
1895
|
+
ax_right = None
|
|
1896
|
+
tags = [t for t in self.wave_data.keys()
|
|
1897
|
+
if t not in self._digital_waves]
|
|
1898
|
+
|
|
1899
|
+
theme = _get_theme()
|
|
1900
|
+
ecolors = theme['export_colors']
|
|
1901
|
+
|
|
1902
|
+
for i, tag in enumerate(tags):
|
|
1903
|
+
wave, yunit = self.wave_data[tag]
|
|
1904
|
+
if wave.x is None or wave.y is None:
|
|
1905
|
+
continue
|
|
1906
|
+
x, xlabels = _to_numeric(wave.x)
|
|
1907
|
+
y, _ = _to_numeric(wave.y)
|
|
1908
|
+
color = ecolors[i % len(ecolors)]
|
|
1909
|
+
style = getattr(wave, 'style', 'Lines')
|
|
1910
|
+
|
|
1911
|
+
is_right = (self._right_vb is not None
|
|
1912
|
+
and yunit in self._unit_vb
|
|
1913
|
+
and self._unit_vb[yunit] is self._right_vb)
|
|
1914
|
+
|
|
1915
|
+
target = ax
|
|
1916
|
+
if is_right:
|
|
1917
|
+
if ax_right is None:
|
|
1918
|
+
ax_right = ax.twinx()
|
|
1919
|
+
target = ax_right
|
|
1920
|
+
units_right.add(yunit)
|
|
1921
|
+
else:
|
|
1922
|
+
units_left.add(yunit)
|
|
1923
|
+
|
|
1924
|
+
kw = dict(color=color, linewidth=1.5, label=wave.key)
|
|
1925
|
+
if style == 'Markers':
|
|
1926
|
+
kw.update(linestyle='none', marker='o', markersize=4)
|
|
1927
|
+
elif style == 'Lines+Markers':
|
|
1928
|
+
kw.update(marker='o', markersize=3)
|
|
1929
|
+
elif style == 'Steps':
|
|
1930
|
+
kw.update(drawstyle='steps-mid')
|
|
1931
|
+
|
|
1932
|
+
if self._logx:
|
|
1933
|
+
target.semilogx(x, y, **kw)
|
|
1934
|
+
else:
|
|
1935
|
+
target.plot(x, y, **kw)
|
|
1936
|
+
|
|
1937
|
+
if xlabels:
|
|
1938
|
+
ax.set_xticks(x)
|
|
1939
|
+
ax.set_xticklabels(xlabels, rotation=45, ha='right')
|
|
1940
|
+
|
|
1941
|
+
if self.custom_xlabel:
|
|
1942
|
+
ax.set_xlabel(self.custom_xlabel)
|
|
1943
|
+
else:
|
|
1944
|
+
xunit = self._get_xunit()
|
|
1945
|
+
xlabel = ""
|
|
1946
|
+
for wave, _ in self.wave_data.values():
|
|
1947
|
+
if wave.xlabel:
|
|
1948
|
+
xlabel = wave.xlabel
|
|
1949
|
+
break
|
|
1950
|
+
if xunit:
|
|
1951
|
+
ax.set_xlabel("%s [%s]" % (xlabel, xunit) if xlabel else xunit)
|
|
1952
|
+
ax.xaxis.set_major_formatter(EngFormatter(unit=xunit))
|
|
1953
|
+
elif xlabel:
|
|
1954
|
+
ax.set_xlabel(xlabel)
|
|
1955
|
+
|
|
1956
|
+
if self.custom_ylabel:
|
|
1957
|
+
ax.set_ylabel(self.custom_ylabel)
|
|
1958
|
+
else:
|
|
1959
|
+
for yu in units_left:
|
|
1960
|
+
if yu:
|
|
1961
|
+
ax.set_ylabel("[%s]" % yu)
|
|
1962
|
+
ax.yaxis.set_major_formatter(EngFormatter(unit=yu))
|
|
1963
|
+
if ax_right:
|
|
1964
|
+
for yu in units_right:
|
|
1965
|
+
if yu:
|
|
1966
|
+
ax_right.set_ylabel("[%s]" % yu)
|
|
1967
|
+
ax_right.yaxis.set_major_formatter(EngFormatter(unit=yu))
|
|
1968
|
+
|
|
1969
|
+
if self.custom_title:
|
|
1970
|
+
ax.set_title(self.custom_title)
|
|
1971
|
+
|
|
1972
|
+
for ann in self._annotations:
|
|
1973
|
+
ax.annotate(
|
|
1974
|
+
ann['text'], xy=(ann['x'], ann['y']),
|
|
1975
|
+
fontsize=8, color=theme['export_annotation_color'],
|
|
1976
|
+
bbox=dict(boxstyle='round,pad=0.3',
|
|
1977
|
+
fc=theme['export_annotation_bg'],
|
|
1978
|
+
ec=theme['export_annotation_ec'], alpha=0.9),
|
|
1979
|
+
arrowprops=dict(arrowstyle='->', color='#555555'))
|
|
1980
|
+
|
|
1981
|
+
stats = self.getStats()
|
|
1982
|
+
if stats:
|
|
1983
|
+
stat_lines = []
|
|
1984
|
+
for s in stats:
|
|
1985
|
+
u = s['unit']
|
|
1986
|
+
stat_lines.append("%s: μ=%s σ=%s" % (
|
|
1987
|
+
s['key'], _eng(s['mean'], u), _eng(s['std'], u)))
|
|
1988
|
+
fig.text(0.01, 0.01, " | ".join(stat_lines),
|
|
1989
|
+
fontsize=6, color=theme['export_stats_color'],
|
|
1990
|
+
va='bottom')
|
|
1991
|
+
|
|
1992
|
+
lines, labels = ax.get_legend_handles_labels()
|
|
1993
|
+
if ax_right:
|
|
1994
|
+
r_lines, r_labels = ax_right.get_legend_handles_labels()
|
|
1995
|
+
lines += r_lines
|
|
1996
|
+
labels += r_labels
|
|
1997
|
+
if labels:
|
|
1998
|
+
ax.legend(lines, labels, fontsize=7, loc='best')
|
|
1999
|
+
|
|
2000
|
+
ax.grid(True, alpha=0.3)
|
|
2001
|
+
|
|
2002
|
+
#- Mirror the live viewer's zoom: read the X (and Y) ranges
|
|
2003
|
+
#- from the analog ViewBox and apply them to the matplotlib
|
|
2004
|
+
#- axes. Without this, matplotlib auto-ranges to the full
|
|
2005
|
+
#- data extent and the export ignores whatever the user had
|
|
2006
|
+
#- panned/zoomed to.
|
|
2007
|
+
try:
|
|
2008
|
+
xr = self.plot.vb.viewRange()[0]
|
|
2009
|
+
yr = self.plot.vb.viewRange()[1]
|
|
2010
|
+
ax.set_xlim(xr[0], xr[1])
|
|
2011
|
+
ax.set_ylim(yr[0], yr[1])
|
|
2012
|
+
except Exception:
|
|
2013
|
+
pass
|
|
2014
|
+
if ax_right is not None and self._right_vb is not None:
|
|
2015
|
+
try:
|
|
2016
|
+
yrr = self._right_vb.viewRange()[1]
|
|
2017
|
+
ax_right.set_ylim(yrr[0], yrr[1])
|
|
2018
|
+
except Exception:
|
|
2019
|
+
pass
|
|
2020
|
+
|
|
2021
|
+
if ax_dig is not None:
|
|
2022
|
+
self._export_digital_pane(ax_dig, ax)
|
|
2023
|
+
#- Hide the analog x-tick labels because they're shown on
|
|
2024
|
+
#- the digital pane (which sits below and shares the axis).
|
|
2025
|
+
plt.setp(ax.get_xticklabels(), visible=False)
|
|
2026
|
+
ax.set_xlabel("")
|
|
2027
|
+
|
|
2028
|
+
fig.tight_layout()
|
|
2029
|
+
fig.subplots_adjust(bottom=max(0.15, fig.subplotpars.bottom))
|
|
2030
|
+
dpi = 150 if fname.lower().endswith('.png') else None
|
|
2031
|
+
fig.savefig(fname, dpi=dpi, facecolor='white')
|
|
2032
|
+
plt.close(fig)
|
|
2033
|
+
|
|
2034
|
+
# ------------------------------------------------------------------
|
|
2035
|
+
# Data export (plotted waveforms -> CSV/TSV/Parquet/Feather/HDF5)
|
|
2036
|
+
# ------------------------------------------------------------------
|
|
2037
|
+
|
|
2038
|
+
#- Extension -> (pandas writer attribute, kwargs, format label)
|
|
2039
|
+
#- HDF5 needs a key; Feather/Parquet are columnar and lossless.
|
|
2040
|
+
_EXPORT_DATA_WRITERS = {
|
|
2041
|
+
'.csv': ('to_csv', {'index': False}),
|
|
2042
|
+
'.tsv': ('to_csv', {'index': False, 'sep': '\t'}),
|
|
2043
|
+
'.txt': ('to_csv', {'index': False, 'sep': '\t'}),
|
|
2044
|
+
'.parquet': ('to_parquet', {'index': False}),
|
|
2045
|
+
'.feather': ('to_feather', {}),
|
|
2046
|
+
'.h5': ('to_hdf', {'key': 'cicwave', 'mode': 'w'}),
|
|
2047
|
+
'.hdf5': ('to_hdf', {'key': 'cicwave', 'mode': 'w'}),
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
def exportData(self):
|
|
2051
|
+
"""Save the currently plotted analog waves to a data file.
|
|
2052
|
+
|
|
2053
|
+
Writes one column per (X, Y) pair side-by-side so heterogeneous
|
|
2054
|
+
x-grids are preserved without resampling. The current x-view
|
|
2055
|
+
range is honoured (zoom in to export a region). Digital pane
|
|
2056
|
+
traces are skipped — those are better viewed than tabulated.
|
|
2057
|
+
"""
|
|
2058
|
+
exts = ";;".join([
|
|
2059
|
+
"CSV (*.csv)",
|
|
2060
|
+
"TSV (*.tsv)",
|
|
2061
|
+
"Parquet (*.parquet)",
|
|
2062
|
+
"Feather (*.feather)",
|
|
2063
|
+
"HDF5 (*.h5)",
|
|
2064
|
+
])
|
|
2065
|
+
fname, _ = QFileDialog.getSaveFileName(
|
|
2066
|
+
self, "Export Plotted Data", os.getcwd(),
|
|
2067
|
+
exts + ";;All Files (*)")
|
|
2068
|
+
if not fname:
|
|
2069
|
+
return
|
|
2070
|
+
try:
|
|
2071
|
+
n_traces, n_rows = self._export_data_to(fname)
|
|
2072
|
+
except Exception as e:
|
|
2073
|
+
QMessageBox.critical(
|
|
2074
|
+
self, "Export failed",
|
|
2075
|
+
"Could not write %s:\n%s" % (fname, e))
|
|
2076
|
+
return
|
|
2077
|
+
QMessageBox.information(
|
|
2078
|
+
self, "Export complete",
|
|
2079
|
+
"Wrote %d trace(s), %d row(s) to:\n%s"
|
|
2080
|
+
% (n_traces, n_rows, fname))
|
|
2081
|
+
|
|
2082
|
+
def _export_data_to(self, fname):
|
|
2083
|
+
"""Write plotted-wave data to ``fname``. Returns (n_traces, n_rows).
|
|
2084
|
+
|
|
2085
|
+
``n_rows`` is the longest column length (others are NaN-padded
|
|
2086
|
+
to fit a rectangular DataFrame; the original arrays are
|
|
2087
|
+
preserved exactly within their length).
|
|
2088
|
+
"""
|
|
2089
|
+
ext = os.path.splitext(fname)[1].lower()
|
|
2090
|
+
spec = self._EXPORT_DATA_WRITERS.get(ext)
|
|
2091
|
+
if spec is None:
|
|
2092
|
+
raise ValueError(
|
|
2093
|
+
"Unsupported export extension %r. Use one of: %s"
|
|
2094
|
+
% (ext, ", ".join(sorted(self._EXPORT_DATA_WRITERS))))
|
|
2095
|
+
writer_attr, kwargs = spec
|
|
2096
|
+
|
|
2097
|
+
#- Skip the digital pane: it has its own representation
|
|
2098
|
+
#- (string '0'/'1'/'x' or vector ints) that doesn't round-trip
|
|
2099
|
+
#- cleanly into a numeric data file.
|
|
2100
|
+
tags = [t for t in self.wave_data.keys()
|
|
2101
|
+
if t not in self._digital_waves]
|
|
2102
|
+
if not tags:
|
|
2103
|
+
raise ValueError("No analog waves to export.")
|
|
2104
|
+
|
|
2105
|
+
#- Honour the current x-zoom so "zoom in, export" gives the
|
|
2106
|
+
#- region of interest rather than the whole capture. Wrap in
|
|
2107
|
+
#- try/except: viewRange may raise on freshly-built plots in
|
|
2108
|
+
#- headless tests.
|
|
2109
|
+
try:
|
|
2110
|
+
xlo, xhi = self.plot.vb.viewRange()[0]
|
|
2111
|
+
except Exception:
|
|
2112
|
+
xlo, xhi = (None, None)
|
|
2113
|
+
|
|
2114
|
+
columns = {} # ordered insertion = preserved column order
|
|
2115
|
+
used_names = set()
|
|
2116
|
+
max_len = 0
|
|
2117
|
+
for tag in tags:
|
|
2118
|
+
wave, _yunit = self.wave_data[tag]
|
|
2119
|
+
if wave.x is None or wave.y is None:
|
|
2120
|
+
continue
|
|
2121
|
+
x = np.asarray(wave.x)
|
|
2122
|
+
y = np.asarray(wave.y)
|
|
2123
|
+
n = min(len(x), len(y))
|
|
2124
|
+
if n == 0:
|
|
2125
|
+
continue
|
|
2126
|
+
x = x[:n]
|
|
2127
|
+
y = y[:n]
|
|
2128
|
+
if xlo is not None and np.issubdtype(x.dtype, np.number):
|
|
2129
|
+
mask = (x >= xlo) & (x <= xhi)
|
|
2130
|
+
if mask.any():
|
|
2131
|
+
x = x[mask]
|
|
2132
|
+
y = y[mask]
|
|
2133
|
+
|
|
2134
|
+
#- Make column names unique even if two waves share a key.
|
|
2135
|
+
xname = self._unique_col(
|
|
2136
|
+
wave.xlabel or "x", wave.xunit, used_names)
|
|
2137
|
+
yname = self._unique_col(
|
|
2138
|
+
wave.key or wave.ylabel or "y", wave.yunit, used_names)
|
|
2139
|
+
columns[xname] = x
|
|
2140
|
+
columns[yname] = y
|
|
2141
|
+
max_len = max(max_len, len(x))
|
|
2142
|
+
|
|
2143
|
+
if not columns:
|
|
2144
|
+
raise ValueError("No exportable samples in current view.")
|
|
2145
|
+
|
|
2146
|
+
#- Pad to a rectangular shape. NaN in unused tail rows is the
|
|
2147
|
+
#- least-surprising filler for numeric columns.
|
|
2148
|
+
padded = {}
|
|
2149
|
+
for name, arr in columns.items():
|
|
2150
|
+
if len(arr) < max_len:
|
|
2151
|
+
pad = np.full(max_len - len(arr), np.nan, dtype=float)
|
|
2152
|
+
padded[name] = np.concatenate([arr.astype(float), pad])
|
|
2153
|
+
else:
|
|
2154
|
+
padded[name] = arr
|
|
2155
|
+
df = pd.DataFrame(padded)
|
|
2156
|
+
|
|
2157
|
+
getattr(df, writer_attr)(fname, **kwargs)
|
|
2158
|
+
return len(columns) // 2, max_len
|
|
2159
|
+
|
|
2160
|
+
@staticmethod
|
|
2161
|
+
def _unique_col(base, unit, used):
|
|
2162
|
+
"""Build a column name like ``time (s)`` and disambiguate
|
|
2163
|
+
collisions with ``__1``, ``__2``, ... suffixes."""
|
|
2164
|
+
name = base
|
|
2165
|
+
if unit:
|
|
2166
|
+
name = "%s (%s)" % (base, unit)
|
|
2167
|
+
candidate = name
|
|
2168
|
+
i = 1
|
|
2169
|
+
while candidate in used:
|
|
2170
|
+
candidate = "%s__%d" % (name, i)
|
|
2171
|
+
i += 1
|
|
2172
|
+
used.add(candidate)
|
|
2173
|
+
return candidate
|
|
2174
|
+
|
|
2175
|
+
def _export_digital_pane(self, ax, ax_main):
|
|
2176
|
+
"""Render the digital pane into ``ax`` for export.
|
|
2177
|
+
|
|
2178
|
+
Mirrors the live viewer: bit signals as 0/1 step traces,
|
|
2179
|
+
vectors as bus outlines with value labels at every transition
|
|
2180
|
+
inside the current x-view.
|
|
2181
|
+
"""
|
|
2182
|
+
if not self._digital_waves:
|
|
2183
|
+
return
|
|
2184
|
+
theme = _get_theme()
|
|
2185
|
+
mono = 'black' # export background is white -> use black ink
|
|
2186
|
+
|
|
2187
|
+
#- Use the analog axis x-range so the two panes align even if
|
|
2188
|
+
#- the user had zoomed the live view. matplotlib will sync via
|
|
2189
|
+
#- sharex once we set it on the main axis below.
|
|
2190
|
+
try:
|
|
2191
|
+
xlo, xhi = ax_main.get_xlim()
|
|
2192
|
+
if xhi <= xlo:
|
|
2193
|
+
xlo, xhi = self.plot.vb.viewRange()[0]
|
|
2194
|
+
except Exception:
|
|
2195
|
+
xlo, xhi = self.plot.vb.viewRange()[0]
|
|
2196
|
+
|
|
2197
|
+
ax.set_xlim(xlo, xhi)
|
|
2198
|
+
n_rows = len(self._digital_waves)
|
|
2199
|
+
ax.set_ylim(0, n_rows)
|
|
2200
|
+
ax.set_yticks([])
|
|
2201
|
+
ax.grid(True, axis='x', alpha=0.2)
|
|
2202
|
+
for spine in ('top', 'right'):
|
|
2203
|
+
ax.spines[spine].set_visible(False)
|
|
2204
|
+
|
|
2205
|
+
yticks = []
|
|
2206
|
+
yticklabels = []
|
|
2207
|
+
for info in self._digital_waves.values():
|
|
2208
|
+
wave = info['wave']
|
|
2209
|
+
row = info['row']
|
|
2210
|
+
slot_bot = row
|
|
2211
|
+
slot_top = row + 1
|
|
2212
|
+
yticks.append(row + 0.5)
|
|
2213
|
+
yticklabels.append(self._truncate_axis_label(
|
|
2214
|
+
self._short_signal_name(wave.key)))
|
|
2215
|
+
self._export_one_digital(ax, wave, slot_bot, slot_top, mono,
|
|
2216
|
+
xlo, xhi)
|
|
2217
|
+
|
|
2218
|
+
ax.set_yticks(yticks)
|
|
2219
|
+
ax.set_yticklabels(yticklabels, fontsize=8)
|
|
2220
|
+
|
|
2221
|
+
#- Forward x-axis formatting from the analog axis so units
|
|
2222
|
+
#- (e.g. seconds) show up the same way on the bottom strip.
|
|
2223
|
+
try:
|
|
2224
|
+
xfmt = ax_main.xaxis.get_major_formatter()
|
|
2225
|
+
ax.xaxis.set_major_formatter(xfmt)
|
|
2226
|
+
except Exception:
|
|
2227
|
+
pass
|
|
2228
|
+
|
|
2229
|
+
def _export_one_digital(self, ax, wave, y_lo, y_hi, color, xlo, xhi):
|
|
2230
|
+
"""Draw a single digital row into ``ax``."""
|
|
2231
|
+
synth_kind = wave.digital_kind
|
|
2232
|
+
raw = wave._digital_raw
|
|
2233
|
+
if synth_kind not in ('bit', 'vector'):
|
|
2234
|
+
raw = wave.synthesizeDigitalBits()
|
|
2235
|
+
synth_kind = 'bit'
|
|
2236
|
+
if raw is None or wave.x is None:
|
|
2237
|
+
return
|
|
2238
|
+
x_arr, _ = _to_numeric(wave.x)
|
|
2239
|
+
if x_arr is None or len(x_arr) == 0:
|
|
2240
|
+
return
|
|
2241
|
+
|
|
2242
|
+
if synth_kind == 'bit':
|
|
2243
|
+
top = y_lo + 0.85
|
|
2244
|
+
bot = y_lo + 0.15
|
|
2245
|
+
yvals = np.full(len(raw), np.nan, dtype=np.float64)
|
|
2246
|
+
for i, v in enumerate(raw):
|
|
2247
|
+
if v == '1' or v == 1:
|
|
2248
|
+
yvals[i] = top
|
|
2249
|
+
elif v == '0' or v == 0:
|
|
2250
|
+
yvals[i] = bot
|
|
2251
|
+
ax.step(x_arr, yvals, where='post', color=color, linewidth=1.0)
|
|
2252
|
+
ax.axhline((top + bot) / 2.0, xmin=0, xmax=1,
|
|
2253
|
+
color=color, linewidth=0.4, linestyle=':')
|
|
2254
|
+
return
|
|
2255
|
+
|
|
2256
|
+
#- Vector: draw bus outline + transition ticks + labels.
|
|
2257
|
+
top = y_lo + 0.85
|
|
2258
|
+
bot = y_lo + 0.15
|
|
2259
|
+
mid = (top + bot) / 2.0
|
|
2260
|
+
top_y = np.full(len(raw), top, dtype=np.float64)
|
|
2261
|
+
bot_y = np.full(len(raw), bot, dtype=np.float64)
|
|
2262
|
+
for i, v in enumerate(raw):
|
|
2263
|
+
if v is None or isinstance(v, str):
|
|
2264
|
+
top_y[i] = np.nan
|
|
2265
|
+
bot_y[i] = np.nan
|
|
2266
|
+
ax.step(x_arr, top_y, where='post', color=color, linewidth=1.0)
|
|
2267
|
+
ax.step(x_arr, bot_y, where='post', color=color, linewidth=1.0)
|
|
2268
|
+
|
|
2269
|
+
transitions = self._vector_transitions(raw)
|
|
2270
|
+
if not transitions:
|
|
2271
|
+
return
|
|
2272
|
+
t_x = x_arr[np.asarray(transitions, dtype=np.int64)]
|
|
2273
|
+
lo_i = int(np.searchsorted(t_x, xlo, side='left'))
|
|
2274
|
+
hi_i = int(np.searchsorted(t_x, xhi, side='right'))
|
|
2275
|
+
visible = list(range(max(0, lo_i - 1), min(len(transitions), hi_i)))
|
|
2276
|
+
|
|
2277
|
+
fontsize = 6
|
|
2278
|
+
for vi in visible[:self._DIGITAL_MAX_LABELS]:
|
|
2279
|
+
idx = transitions[vi]
|
|
2280
|
+
tx = float(x_arr[idx])
|
|
2281
|
+
ax.plot([tx, tx], [bot, top], color=color, linewidth=0.5)
|
|
2282
|
+
txt = wave.formatDigitalValue(raw[idx])
|
|
2283
|
+
#- Anchor at the left edge of the segment (matches the
|
|
2284
|
+
#- live viewer's ``anchor=(0, 0.5)``). ``clip_on=False`` so
|
|
2285
|
+
#- a wide label can overhang the cell and still render.
|
|
2286
|
+
ax.text(tx, mid, " " + txt, fontsize=fontsize, color=color,
|
|
2287
|
+
ha='left', va='center', clip_on=False)
|
|
2288
|
+
|
|
2289
|
+
def clearCursors(self):
|
|
2290
|
+
for line in self._cursor_a_lines:
|
|
2291
|
+
line.getViewBox().removeItem(line)
|
|
2292
|
+
for line in self._cursor_b_lines:
|
|
2293
|
+
line.getViewBox().removeItem(line)
|
|
2294
|
+
self._cursor_a_lines.clear()
|
|
2295
|
+
self._cursor_b_lines.clear()
|
|
2296
|
+
self.cursor_a = None
|
|
2297
|
+
self.cursor_b = None
|
|
2298
|
+
self._clear_delta_texts()
|
|
2299
|
+
self._update_readout()
|
|
2300
|
+
|
|
2301
|
+
def placeCursorA(self):
|
|
2302
|
+
if self._last_x is not None:
|
|
2303
|
+
self._set_cursor('a', self._last_x)
|
|
2304
|
+
|
|
2305
|
+
def placeCursorB(self):
|
|
2306
|
+
if self._last_x is not None:
|
|
2307
|
+
self._set_cursor('b', self._last_x)
|
|
2308
|
+
|
|
2309
|
+
# ------------------------------------------------------------------
|
|
2310
|
+
# Internal
|
|
2311
|
+
# ------------------------------------------------------------------
|
|
2312
|
+
|
|
2313
|
+
def _remove_wave(self, tag):
|
|
2314
|
+
if tag in self.wave_data:
|
|
2315
|
+
wave, _ = self.wave_data[tag]
|
|
2316
|
+
#- Dispatch on actual placement, not digital_kind: a
|
|
2317
|
+
#- synthesized digital trace (analog source, show_as_digital
|
|
2318
|
+
#- on) lives in the digital pane but has digital_kind=None.
|
|
2319
|
+
if tag in self._digital_waves:
|
|
2320
|
+
self._remove_digital_wave(tag)
|
|
2321
|
+
else:
|
|
2322
|
+
wave.remove()
|
|
2323
|
+
del self.wave_data[tag]
|
|
2324
|
+
|
|
2325
|
+
def _reset_axes(self):
|
|
2326
|
+
self._unit_vb.clear()
|
|
2327
|
+
self._unit_axis_side.clear()
|
|
2328
|
+
self._unit_axis_label.clear()
|
|
2329
|
+
if self._right_vb is not None:
|
|
2330
|
+
self.plot.scene().removeItem(self._right_vb)
|
|
2331
|
+
self._right_vb = None
|
|
2332
|
+
self.plot.hideAxis('right')
|
|
2333
|
+
self.plot.setLabel('left', '')
|
|
2334
|
+
self.plot.setLabel('right', '')
|
|
2335
|
+
self._logx = False
|
|
2336
|
+
self._has_rotated_x = False
|
|
2337
|
+
|
|
2338
|
+
# --- Cursors ---
|
|
2339
|
+
|
|
2340
|
+
def _make_cursor_line(self, x, color, which):
|
|
2341
|
+
line = pg.InfiniteLine(
|
|
2342
|
+
pos=x, angle=90, movable=True,
|
|
2343
|
+
pen=pg.mkPen(color, width=1, style=Qt.DashLine))
|
|
2344
|
+
line.sigPositionChanged.connect(
|
|
2345
|
+
lambda l, w=which: self._cursor_dragged(w, l))
|
|
2346
|
+
return line
|
|
2347
|
+
|
|
2348
|
+
def _set_cursor(self, which, x):
|
|
2349
|
+
theme = _get_theme()
|
|
2350
|
+
color = theme['cursor_a'] if which == 'a' else theme['cursor_b']
|
|
2351
|
+
lines = self._cursor_a_lines if which == 'a' else self._cursor_b_lines
|
|
2352
|
+
|
|
2353
|
+
if not lines:
|
|
2354
|
+
for vb in self._all_viewboxes():
|
|
2355
|
+
line = self._make_cursor_line(x, color, which)
|
|
2356
|
+
vb.addItem(line)
|
|
2357
|
+
lines.append(line)
|
|
2358
|
+
else:
|
|
2359
|
+
for line in lines:
|
|
2360
|
+
line.blockSignals(True)
|
|
2361
|
+
line.setValue(x)
|
|
2362
|
+
line.blockSignals(False)
|
|
2363
|
+
|
|
2364
|
+
if which == 'a':
|
|
2365
|
+
self.cursor_a = x
|
|
2366
|
+
else:
|
|
2367
|
+
self.cursor_b = x
|
|
2368
|
+
self._update_readout()
|
|
2369
|
+
self._update_delta_texts()
|
|
2370
|
+
|
|
2371
|
+
def _cursor_dragged(self, which, line):
|
|
2372
|
+
x = line.value()
|
|
2373
|
+
lines = self._cursor_a_lines if which == 'a' else self._cursor_b_lines
|
|
2374
|
+
for l in lines:
|
|
2375
|
+
if l is not line:
|
|
2376
|
+
l.blockSignals(True)
|
|
2377
|
+
l.setValue(x)
|
|
2378
|
+
l.blockSignals(False)
|
|
2379
|
+
if which == 'a':
|
|
2380
|
+
self.cursor_a = x
|
|
2381
|
+
else:
|
|
2382
|
+
self.cursor_b = x
|
|
2383
|
+
self._update_readout()
|
|
2384
|
+
self._update_delta_texts()
|
|
2385
|
+
|
|
2386
|
+
# --- Scroll zoom (coalesced; matches tk implementation) ---
|
|
2387
|
+
|
|
2388
|
+
def _on_wheel(self, event, axis=None):
|
|
2389
|
+
delta = event.delta()
|
|
2390
|
+
if delta == 0:
|
|
2391
|
+
return
|
|
2392
|
+
|
|
2393
|
+
scale = 1.0 / ZOOM_FACTOR if delta > 0 else ZOOM_FACTOR
|
|
2394
|
+
modifiers = event.modifiers()
|
|
2395
|
+
|
|
2396
|
+
# Anchor the zoom on the position of the FIRST event in a burst so
|
|
2397
|
+
# accumulated scaling happens around a stable point.
|
|
2398
|
+
if not self._wheel_timer.isActive():
|
|
2399
|
+
self._wheel_pending_pos = event.pos()
|
|
2400
|
+
self._wheel_pending_x_scale = 1.0
|
|
2401
|
+
self._wheel_pending_y_scale = 1.0
|
|
2402
|
+
|
|
2403
|
+
if modifiers & Qt.ShiftModifier:
|
|
2404
|
+
self._wheel_pending_y_scale *= scale
|
|
2405
|
+
else:
|
|
2406
|
+
self._wheel_pending_x_scale *= scale
|
|
2407
|
+
|
|
2408
|
+
self._wheel_timer.start()
|
|
2409
|
+
event.accept()
|
|
2410
|
+
|
|
2411
|
+
def _apply_pending_wheel_zoom(self):
|
|
2412
|
+
pos = self._wheel_pending_pos
|
|
2413
|
+
if pos is None:
|
|
2414
|
+
return
|
|
2415
|
+
sx = self._wheel_pending_x_scale
|
|
2416
|
+
sy = self._wheel_pending_y_scale
|
|
2417
|
+
self._wheel_pending_x_scale = 1.0
|
|
2418
|
+
self._wheel_pending_y_scale = 1.0
|
|
2419
|
+
|
|
2420
|
+
if sy != 1.0:
|
|
2421
|
+
for vb in self._all_viewboxes():
|
|
2422
|
+
vr = vb.viewRange()
|
|
2423
|
+
ylo, yhi = vr[1]
|
|
2424
|
+
pt = vb.mapSceneToView(pos)
|
|
2425
|
+
ydata = pt.y()
|
|
2426
|
+
new_lo = ydata - (ydata - ylo) * sy
|
|
2427
|
+
new_hi = ydata + (yhi - ydata) * sy
|
|
2428
|
+
vb.setYRange(new_lo, new_hi, padding=0)
|
|
2429
|
+
|
|
2430
|
+
if sx != 1.0:
|
|
2431
|
+
mouse_point = self.plot.vb.mapSceneToView(pos)
|
|
2432
|
+
vr = self.plot.vb.viewRange()
|
|
2433
|
+
xlo, xhi = vr[0]
|
|
2434
|
+
xdata = mouse_point.x()
|
|
2435
|
+
new_lo = xdata - (xdata - xlo) * sx
|
|
2436
|
+
new_hi = xdata + (xhi - xdata) * sx
|
|
2437
|
+
self.plot.vb.setXRange(new_lo, new_hi, padding=0)
|
|
2438
|
+
|
|
2439
|
+
def _on_mouse_drag(self, ev, axis=None):
|
|
2440
|
+
mods = ev.modifiers()
|
|
2441
|
+
if ev.button() == Qt.RightButton:
|
|
2442
|
+
#- Right-drag always draws a rubber band. Modifiers constrain
|
|
2443
|
+
#- the resulting zoom to a single axis:
|
|
2444
|
+
#- plain -> rectangle, zoom both x and y
|
|
2445
|
+
#- Shift -> band spans full plot height, zoom x only
|
|
2446
|
+
#- Ctrl (or Cmd on Mac) -> band spans full plot width, zoom y only
|
|
2447
|
+
#- On macOS Qt swaps the physical Ctrl and Meta keys by
|
|
2448
|
+
#- default, so accept either modifier to mean "y-only".
|
|
2449
|
+
ctrl_like = (Qt.ControlModifier | Qt.MetaModifier)
|
|
2450
|
+
if mods & Qt.ShiftModifier:
|
|
2451
|
+
self._right_drag_rubber_band(ev, constrain='x')
|
|
2452
|
+
elif mods & ctrl_like:
|
|
2453
|
+
self._right_drag_rubber_band(ev, constrain='y')
|
|
2454
|
+
else:
|
|
2455
|
+
self._right_drag_rubber_band(ev, constrain=None)
|
|
2456
|
+
else:
|
|
2457
|
+
self._orig_mouseDragEvent(ev, axis)
|
|
2458
|
+
|
|
2459
|
+
def _right_drag_rubber_band(self, ev, constrain=None):
|
|
2460
|
+
"""Right-drag draws a rubber-band rectangle and zooms to it on
|
|
2461
|
+
release. Reuses pyqtgraph's built-in scale-box machinery so the
|
|
2462
|
+
rectangle styling and zoom history match RectMode.
|
|
2463
|
+
|
|
2464
|
+
``constrain`` restricts the zoom (and the visible band) to one
|
|
2465
|
+
axis: ``'x'`` extends the band over the full plot height and
|
|
2466
|
+
only zooms x; ``'y'`` extends it over the full width and only
|
|
2467
|
+
zooms y; ``None`` is the original two-axis behaviour.
|
|
2468
|
+
"""
|
|
2469
|
+
ev.accept()
|
|
2470
|
+
vb = self.plot.vb
|
|
2471
|
+
from PySide6.QtCore import QRectF, QPointF
|
|
2472
|
+
from pyqtgraph import Point
|
|
2473
|
+
|
|
2474
|
+
down_pos = ev.buttonDownPos(Qt.RightButton)
|
|
2475
|
+
cur_pos = ev.pos()
|
|
2476
|
+
|
|
2477
|
+
#- Build the on-screen (parent-coords) rectangle with the chosen
|
|
2478
|
+
#- constraint applied. We extend the band to the full vb extent
|
|
2479
|
+
#- on the locked axis so the user sees what's being kept.
|
|
2480
|
+
vb_rect = vb.rect() # in vb's parent coords (item-local origin)
|
|
2481
|
+
if constrain == 'x':
|
|
2482
|
+
top = vb_rect.top()
|
|
2483
|
+
bot = vb_rect.bottom()
|
|
2484
|
+
screen_rect = QRectF(QPointF(down_pos.x(), top),
|
|
2485
|
+
QPointF(cur_pos.x(), bot))
|
|
2486
|
+
elif constrain == 'y':
|
|
2487
|
+
left = vb_rect.left()
|
|
2488
|
+
right = vb_rect.right()
|
|
2489
|
+
screen_rect = QRectF(QPointF(left, down_pos.y()),
|
|
2490
|
+
QPointF(right, cur_pos.y()))
|
|
2491
|
+
else:
|
|
2492
|
+
screen_rect = QRectF(Point(down_pos), Point(cur_pos))
|
|
2493
|
+
|
|
2494
|
+
if ev.isFinish():
|
|
2495
|
+
try:
|
|
2496
|
+
vb.rbScaleBox.hide()
|
|
2497
|
+
except Exception:
|
|
2498
|
+
pass
|
|
2499
|
+
#- Ignore tiny rectangles (treat as a click, not a drag).
|
|
2500
|
+
min_extent = 3
|
|
2501
|
+
if constrain == 'x':
|
|
2502
|
+
if abs(screen_rect.width()) < min_extent:
|
|
2503
|
+
return
|
|
2504
|
+
elif constrain == 'y':
|
|
2505
|
+
if abs(screen_rect.height()) < min_extent:
|
|
2506
|
+
return
|
|
2507
|
+
else:
|
|
2508
|
+
if (abs(screen_rect.width()) < min_extent or
|
|
2509
|
+
abs(screen_rect.height()) < min_extent):
|
|
2510
|
+
return
|
|
2511
|
+
|
|
2512
|
+
data_rect = vb.childGroup.mapRectFromParent(screen_rect)
|
|
2513
|
+
|
|
2514
|
+
if constrain == 'x':
|
|
2515
|
+
#- Keep current y range, zoom only x.
|
|
2516
|
+
vb.setXRange(data_rect.left(), data_rect.right(), padding=0)
|
|
2517
|
+
#- Apply the same x-zoom to any linked viewbox so a
|
|
2518
|
+
#- right-axis curve stays in sync.
|
|
2519
|
+
for vbox in self._all_viewboxes():
|
|
2520
|
+
if vbox is vb:
|
|
2521
|
+
continue
|
|
2522
|
+
vbox.setXRange(data_rect.left(), data_rect.right(),
|
|
2523
|
+
padding=0)
|
|
2524
|
+
elif constrain == 'y':
|
|
2525
|
+
#- Map y-range through every viewbox individually so each
|
|
2526
|
+
#- axis (left/right) zooms to its own data coordinates.
|
|
2527
|
+
for vbox in self._all_viewboxes():
|
|
2528
|
+
dr = vbox.childGroup.mapRectFromParent(screen_rect)
|
|
2529
|
+
vbox.setYRange(dr.top(), dr.bottom(), padding=0)
|
|
2530
|
+
else:
|
|
2531
|
+
vb.showAxRect(data_rect)
|
|
2532
|
+
#- Push onto the built-in axis history so the View menu's
|
|
2533
|
+
#- axis-history navigation still works as expected.
|
|
2534
|
+
try:
|
|
2535
|
+
vb.axHistoryPointer += 1
|
|
2536
|
+
vb.axHistory = (vb.axHistory[:vb.axHistoryPointer]
|
|
2537
|
+
+ [data_rect])
|
|
2538
|
+
except Exception:
|
|
2539
|
+
pass
|
|
2540
|
+
else:
|
|
2541
|
+
#- pyqtgraph's updateScaleBox takes two scene/parent points
|
|
2542
|
+
#- and draws a rectangle between them; pass the constrained
|
|
2543
|
+
#- corners so the user sees an axis-aligned band.
|
|
2544
|
+
vb.updateScaleBox(screen_rect.topLeft(),
|
|
2545
|
+
screen_rect.bottomRight())
|
|
2546
|
+
|
|
2547
|
+
# --- Delta text on plot ---
|
|
2548
|
+
|
|
2549
|
+
def _clear_delta_texts(self):
|
|
2550
|
+
for item in self._delta_texts:
|
|
2551
|
+
item.getViewBox().removeItem(item)
|
|
2552
|
+
self._delta_texts.clear()
|
|
2553
|
+
|
|
2554
|
+
def _update_delta_texts(self):
|
|
2555
|
+
self._clear_delta_texts()
|
|
2556
|
+
if self.cursor_a is None or self.cursor_b is None:
|
|
2557
|
+
return
|
|
2558
|
+
|
|
2559
|
+
xunit = self._get_xunit()
|
|
2560
|
+
xa = self._view_to_data_x(self.cursor_a)
|
|
2561
|
+
xb = self._view_to_data_x(self.cursor_b)
|
|
2562
|
+
dx = xb - xa
|
|
2563
|
+
mid_x = (self.cursor_a + self.cursor_b) / 2.0
|
|
2564
|
+
|
|
2565
|
+
parts = ["ΔX: %s" % _eng(dx, xunit)]
|
|
2566
|
+
if dx != 0 and xunit == 's':
|
|
2567
|
+
parts[0] += " (1/ΔX: %s)" % _eng(1.0 / abs(dx), 'Hz')
|
|
2568
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
2569
|
+
ya = self._interp_y(wave, self.cursor_a)
|
|
2570
|
+
yb = self._interp_y(wave, self.cursor_b)
|
|
2571
|
+
if ya is not None and yb is not None:
|
|
2572
|
+
parts.append("Δ%s: %s" % (wave.key, _eng(yb - ya, wave.yunit)))
|
|
2573
|
+
|
|
2574
|
+
theme = _get_theme()
|
|
2575
|
+
text_item = pg.TextItem(
|
|
2576
|
+
text="\n".join(parts), color=theme['text_color'], anchor=(0.5, 0),
|
|
2577
|
+
fill=pg.mkBrush(*theme['overlay_fill']))
|
|
2578
|
+
text_item.setFont(_mono_font(8))
|
|
2579
|
+
self.plot.addItem(text_item)
|
|
2580
|
+
vr = self.plot.viewRange()
|
|
2581
|
+
text_item.setPos(mid_x, vr[1][1])
|
|
2582
|
+
self._delta_texts.append(text_item)
|
|
2583
|
+
|
|
2584
|
+
# --- Mouse / readout ---
|
|
2585
|
+
|
|
2586
|
+
def _on_mouse_moved(self, pos):
|
|
2587
|
+
vb = self.plot.vb
|
|
2588
|
+
if vb.sceneBoundingRect().contains(pos):
|
|
2589
|
+
pt = vb.mapSceneToView(pos)
|
|
2590
|
+
self._last_x = pt.x()
|
|
2591
|
+
xu = self._get_xunit()
|
|
2592
|
+
data_x = self._view_to_data_x(pt.x())
|
|
2593
|
+
self.status.setText("x: %s y: %.6g" % (_eng(data_x, xu), pt.y()))
|
|
2594
|
+
else:
|
|
2595
|
+
self.status.setText("")
|
|
2596
|
+
|
|
2597
|
+
def _interp_gradient(self, wave, view_x):
|
|
2598
|
+
if wave.x is None or wave.y is None or view_x is None:
|
|
2599
|
+
return None
|
|
2600
|
+
try:
|
|
2601
|
+
xd = np.real(wave.x)
|
|
2602
|
+
yd = np.real(wave.y)
|
|
2603
|
+
data_x = self._view_to_data_x(view_x)
|
|
2604
|
+
grad = np.gradient(yd, xd)
|
|
2605
|
+
return float(np.interp(data_x, xd, grad))
|
|
2606
|
+
except Exception:
|
|
2607
|
+
return None
|
|
2608
|
+
|
|
2609
|
+
def _get_xunit(self):
|
|
2610
|
+
for wave, _ in self.wave_data.values():
|
|
2611
|
+
if wave.xunit:
|
|
2612
|
+
return wave.xunit
|
|
2613
|
+
return ""
|
|
2614
|
+
|
|
2615
|
+
def _is_logx(self):
|
|
2616
|
+
for wave, _ in self.wave_data.values():
|
|
2617
|
+
if wave.logx:
|
|
2618
|
+
return True
|
|
2619
|
+
return False
|
|
2620
|
+
|
|
2621
|
+
def _view_to_data_x(self, x):
|
|
2622
|
+
"""Convert x from view coordinates to data coordinates (undo log10)."""
|
|
2623
|
+
if x is None:
|
|
2624
|
+
return None
|
|
2625
|
+
return 10.0 ** x if self._is_logx() else x
|
|
2626
|
+
|
|
2627
|
+
def _interp_y(self, wave, x):
|
|
2628
|
+
if wave.x is None or x is None:
|
|
2629
|
+
return None
|
|
2630
|
+
try:
|
|
2631
|
+
data_x = self._view_to_data_x(x)
|
|
2632
|
+
return float(np.interp(data_x, np.real(wave.x), np.real(wave.y)))
|
|
2633
|
+
except Exception:
|
|
2634
|
+
return None
|
|
2635
|
+
|
|
2636
|
+
def getStats(self):
|
|
2637
|
+
"""Return per-wave statistics as a list of dicts."""
|
|
2638
|
+
stats = []
|
|
2639
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
2640
|
+
if wave.y is None:
|
|
2641
|
+
continue
|
|
2642
|
+
y = np.real(wave.y)
|
|
2643
|
+
y = y[np.isfinite(y)]
|
|
2644
|
+
if len(y) == 0:
|
|
2645
|
+
continue
|
|
2646
|
+
stats.append({
|
|
2647
|
+
'key': wave.key, 'unit': wave.yunit,
|
|
2648
|
+
'file': wave.wfile.name,
|
|
2649
|
+
'min': float(np.min(y)), 'max': float(np.max(y)),
|
|
2650
|
+
'mean': float(np.mean(y)), 'std': float(np.std(y)),
|
|
2651
|
+
'pp': float(np.max(y) - np.min(y)),
|
|
2652
|
+
})
|
|
2653
|
+
return stats
|
|
2654
|
+
|
|
2655
|
+
def _show_stats(self):
|
|
2656
|
+
stats = self.getStats()
|
|
2657
|
+
if not stats:
|
|
2658
|
+
self.readout.clear()
|
|
2659
|
+
return
|
|
2660
|
+
lines = []
|
|
2661
|
+
for s in stats:
|
|
2662
|
+
u = s['unit']
|
|
2663
|
+
lines.append(
|
|
2664
|
+
" %-22s min: %-12s max: %-12s μ: %-12s σ: %-12s pp: %-12s %s"
|
|
2665
|
+
% (s['key'], _eng(s['min'], u), _eng(s['max'], u),
|
|
2666
|
+
_eng(s['mean'], u), _eng(s['std'], u), _eng(s['pp'], u),
|
|
2667
|
+
s.get('file', '')))
|
|
2668
|
+
self.readout.setPlainText("\n".join(lines))
|
|
2669
|
+
|
|
2670
|
+
def addAnnotation(self, x, y, text):
|
|
2671
|
+
theme = _get_theme()
|
|
2672
|
+
item = pg.TextItem(text=text, color=theme['text_color'], anchor=(0, 1),
|
|
2673
|
+
fill=pg.mkBrush(*theme['annotation_fill']),
|
|
2674
|
+
border=theme['annotation_border'])
|
|
2675
|
+
item.setFont(_mono_font(9))
|
|
2676
|
+
item.setPos(x, y)
|
|
2677
|
+
self.plot.addItem(item)
|
|
2678
|
+
self._annotations.append({'text': text, 'x': x, 'y': y, 'item': item})
|
|
2679
|
+
|
|
2680
|
+
def removeAnnotations(self):
|
|
2681
|
+
for ann in self._annotations:
|
|
2682
|
+
if ann.get('item'):
|
|
2683
|
+
self.plot.removeItem(ann['item'])
|
|
2684
|
+
self._annotations.clear()
|
|
2685
|
+
|
|
2686
|
+
def _update_readout(self):
|
|
2687
|
+
if self.cursor_a is None and self.cursor_b is None:
|
|
2688
|
+
self._show_stats()
|
|
2689
|
+
return
|
|
2690
|
+
|
|
2691
|
+
xunit = self._get_xunit()
|
|
2692
|
+
xa = self._view_to_data_x(self.cursor_a)
|
|
2693
|
+
xb = self._view_to_data_x(self.cursor_b)
|
|
2694
|
+
lines = []
|
|
2695
|
+
parts = []
|
|
2696
|
+
if xa is not None:
|
|
2697
|
+
parts.append("A: %s" % _eng(xa, xunit))
|
|
2698
|
+
if xb is not None:
|
|
2699
|
+
parts.append("B: %s" % _eng(xb, xunit))
|
|
2700
|
+
if xa is not None and xb is not None:
|
|
2701
|
+
dx = xb - xa
|
|
2702
|
+
parts.append("ΔX: %s" % _eng(dx, xunit))
|
|
2703
|
+
if dx != 0:
|
|
2704
|
+
if xunit == 's':
|
|
2705
|
+
parts.append("(1/ΔX: %s)" % _eng(1.0 / abs(dx), 'Hz'))
|
|
2706
|
+
else:
|
|
2707
|
+
parts.append("(1/ΔX: %s)" % _eng(1.0 / abs(dx)))
|
|
2708
|
+
lines.append(" ".join(parts))
|
|
2709
|
+
|
|
2710
|
+
for tag, (wave, _) in self.wave_data.items():
|
|
2711
|
+
yu = wave.yunit
|
|
2712
|
+
du = "%s/%s" % (yu, wave.xunit) if yu and wave.xunit else ""
|
|
2713
|
+
wparts = [" %-22s" % wave.key]
|
|
2714
|
+
ya = self._interp_y(wave, self.cursor_a)
|
|
2715
|
+
yb = self._interp_y(wave, self.cursor_b)
|
|
2716
|
+
ga = self._interp_gradient(wave, self.cursor_a)
|
|
2717
|
+
gb = self._interp_gradient(wave, self.cursor_b)
|
|
2718
|
+
if wave.digital_kind == 'vector':
|
|
2719
|
+
#- Show formatted vector samples (hex/dec/bin) instead
|
|
2720
|
+
#- of engineering-notation floats.
|
|
2721
|
+
if ya is not None:
|
|
2722
|
+
wparts.append("A: %-14s" % wave.formatDigitalValue(ya))
|
|
2723
|
+
if yb is not None:
|
|
2724
|
+
wparts.append("B: %-14s" % wave.formatDigitalValue(yb))
|
|
2725
|
+
if ya is not None and yb is not None:
|
|
2726
|
+
try:
|
|
2727
|
+
d = int(round(yb - ya))
|
|
2728
|
+
wparts.append("Δ: %-14d" % d)
|
|
2729
|
+
except (TypeError, ValueError):
|
|
2730
|
+
pass
|
|
2731
|
+
elif wave.digital_kind == 'bit':
|
|
2732
|
+
if ya is not None:
|
|
2733
|
+
wparts.append("A: %-14s" % wave.formatDigitalValue(ya))
|
|
2734
|
+
if yb is not None:
|
|
2735
|
+
wparts.append("B: %-14s" % wave.formatDigitalValue(yb))
|
|
2736
|
+
else:
|
|
2737
|
+
if ya is not None:
|
|
2738
|
+
wparts.append("A: %-14s" % _eng(ya, yu))
|
|
2739
|
+
if yb is not None:
|
|
2740
|
+
wparts.append("B: %-14s" % _eng(yb, yu))
|
|
2741
|
+
if ya is not None and yb is not None:
|
|
2742
|
+
wparts.append("Δ: %-14s" % _eng(yb - ya, yu))
|
|
2743
|
+
if xa is not None and xb is not None and (xb - xa) != 0:
|
|
2744
|
+
slope = (yb - ya) / (xb - xa)
|
|
2745
|
+
wparts.append("Δ/ΔX: %-14s" % _eng(slope, du))
|
|
2746
|
+
if ga is not None:
|
|
2747
|
+
wparts.append("dA: %-14s" % _eng(ga, du))
|
|
2748
|
+
if gb is not None:
|
|
2749
|
+
wparts.append("dB: %-14s" % _eng(gb, du))
|
|
2750
|
+
lines.append("%s %s" % ("".join(wparts), wave.wfile.name))
|
|
2751
|
+
|
|
2752
|
+
self.readout.setPlainText("\n".join(lines))
|
|
2753
|
+
|
|
2754
|
+
|
|
2755
|
+
class PgAnalysisPlot(QWidget):
|
|
2756
|
+
"""Lightweight analysis tab with basic A/B cursors and readout."""
|
|
2757
|
+
|
|
2758
|
+
def __init__(self, parent=None):
|
|
2759
|
+
super().__init__(parent)
|
|
2760
|
+
layout = QVBoxLayout(self)
|
|
2761
|
+
layout.setContentsMargins(2, 2, 2, 2)
|
|
2762
|
+
|
|
2763
|
+
self.pw = pg.PlotWidget()
|
|
2764
|
+
self.pw.showGrid(x=True, y=True)
|
|
2765
|
+
_apply_grid(self.pw.plotItem)
|
|
2766
|
+
vb = self.pw.plotItem.vb
|
|
2767
|
+
vb.wheelEvent = self._on_wheel
|
|
2768
|
+
self._orig_drag = vb.mouseDragEvent
|
|
2769
|
+
vb.mouseDragEvent = self._on_mouse_drag
|
|
2770
|
+
layout.addWidget(self.pw, 1)
|
|
2771
|
+
|
|
2772
|
+
font = _mono_font(9)
|
|
2773
|
+
self.readout = QTextEdit()
|
|
2774
|
+
self.readout.setReadOnly(True)
|
|
2775
|
+
self.readout.setMaximumHeight(80)
|
|
2776
|
+
self.readout.setFont(font)
|
|
2777
|
+
layout.addWidget(self.readout)
|
|
2778
|
+
|
|
2779
|
+
self.status = QLabel("")
|
|
2780
|
+
self.status.setFont(font)
|
|
2781
|
+
layout.addWidget(self.status)
|
|
2782
|
+
|
|
2783
|
+
self._apply_panel_style()
|
|
2784
|
+
|
|
2785
|
+
self.cursor_a = None
|
|
2786
|
+
self.cursor_b = None
|
|
2787
|
+
self._cursor_a_line = None
|
|
2788
|
+
self._cursor_b_line = None
|
|
2789
|
+
self._last_x = None
|
|
2790
|
+
self._curves = []
|
|
2791
|
+
self._logx = False
|
|
2792
|
+
self._xunit = ""
|
|
2793
|
+
self._yunit = ""
|
|
2794
|
+
|
|
2795
|
+
self.pw.scene().sigMouseMoved.connect(self._on_mouse_moved)
|
|
2796
|
+
|
|
2797
|
+
def _apply_panel_style(self):
|
|
2798
|
+
theme = _get_theme()
|
|
2799
|
+
ss = "background-color: %s; color: %s;" % (
|
|
2800
|
+
theme['panel_bg'], theme['panel_fg'])
|
|
2801
|
+
self.readout.setStyleSheet(ss)
|
|
2802
|
+
self.status.setStyleSheet(ss + " padding: 2px;")
|
|
2803
|
+
|
|
2804
|
+
def plot(self, x, y, **kwargs):
|
|
2805
|
+
curve = self.pw.plot(x, y, **kwargs)
|
|
2806
|
+
self._curves.append((x, y))
|
|
2807
|
+
return curve
|
|
2808
|
+
|
|
2809
|
+
def addItem(self, item, **kwargs):
|
|
2810
|
+
self.pw.addItem(item, **kwargs)
|
|
2811
|
+
|
|
2812
|
+
def setLabel(self, axis, text='', units=''):
|
|
2813
|
+
self.pw.setLabel(axis, text, units=units)
|
|
2814
|
+
if axis == 'bottom':
|
|
2815
|
+
self._xunit = units or text
|
|
2816
|
+
elif axis == 'left':
|
|
2817
|
+
self._yunit = units or text
|
|
2818
|
+
|
|
2819
|
+
def setLogMode(self, x=False, y=False):
|
|
2820
|
+
self.pw.setLogMode(x=x, y=y)
|
|
2821
|
+
self._logx = x
|
|
2822
|
+
|
|
2823
|
+
@property
|
|
2824
|
+
def sigRangeChanged(self):
|
|
2825
|
+
return self.pw.sigRangeChanged
|
|
2826
|
+
|
|
2827
|
+
def viewRange(self):
|
|
2828
|
+
return self.pw.viewRange()
|
|
2829
|
+
|
|
2830
|
+
def _view_to_data_x(self, x):
|
|
2831
|
+
return 10 ** x if self._logx else x
|
|
2832
|
+
|
|
2833
|
+
def placeCursorA(self):
|
|
2834
|
+
if self._last_x is not None:
|
|
2835
|
+
self._set_cursor('a', self._last_x)
|
|
2836
|
+
|
|
2837
|
+
def placeCursorB(self):
|
|
2838
|
+
if self._last_x is not None:
|
|
2839
|
+
self._set_cursor('b', self._last_x)
|
|
2840
|
+
|
|
2841
|
+
def clearCursors(self):
|
|
2842
|
+
for line in [self._cursor_a_line, self._cursor_b_line]:
|
|
2843
|
+
if line:
|
|
2844
|
+
self.pw.removeItem(line)
|
|
2845
|
+
self._cursor_a_line = self._cursor_b_line = None
|
|
2846
|
+
self.cursor_a = self.cursor_b = None
|
|
2847
|
+
self.readout.clear()
|
|
2848
|
+
|
|
2849
|
+
def autoSize(self):
|
|
2850
|
+
self.pw.enableAutoRange()
|
|
2851
|
+
|
|
2852
|
+
def zoomIn(self):
|
|
2853
|
+
self._keyboard_zoom(1.0 / ZOOM_FACTOR)
|
|
2854
|
+
|
|
2855
|
+
def zoomOut(self):
|
|
2856
|
+
self._keyboard_zoom(ZOOM_FACTOR)
|
|
2857
|
+
|
|
2858
|
+
def _keyboard_zoom(self, scale):
|
|
2859
|
+
vb = self.pw.plotItem.vb
|
|
2860
|
+
vr = vb.viewRange()
|
|
2861
|
+
xlo, xhi = vr[0]
|
|
2862
|
+
xmid = (xlo + xhi) / 2.0
|
|
2863
|
+
vb.setXRange(xmid - (xmid - xlo) * scale,
|
|
2864
|
+
xmid + (xhi - xmid) * scale, padding=0)
|
|
2865
|
+
ylo, yhi = vr[1]
|
|
2866
|
+
ymid = (ylo + yhi) / 2.0
|
|
2867
|
+
vb.setYRange(ymid - (ymid - ylo) * scale,
|
|
2868
|
+
ymid + (yhi - ymid) * scale, padding=0)
|
|
2869
|
+
|
|
2870
|
+
def setFontSize(self, size):
|
|
2871
|
+
font = _mono_font(size)
|
|
2872
|
+
self.readout.setFont(font)
|
|
2873
|
+
self.status.setFont(font)
|
|
2874
|
+
for axis_name in ['bottom', 'left']:
|
|
2875
|
+
ax = self.pw.plotItem.getAxis(axis_name)
|
|
2876
|
+
ax.setTickFont(font)
|
|
2877
|
+
ax.setStyle(tickFont=font)
|
|
2878
|
+
|
|
2879
|
+
def _set_cursor(self, which, x):
|
|
2880
|
+
pen = pg.mkPen('y' if which == 'a' else 'g',
|
|
2881
|
+
width=1, style=Qt.DashLine)
|
|
2882
|
+
attr_line = '_cursor_%s_line' % which
|
|
2883
|
+
old = getattr(self, attr_line)
|
|
2884
|
+
if old:
|
|
2885
|
+
self.pw.removeItem(old)
|
|
2886
|
+
line = pg.InfiniteLine(pos=x, angle=90, pen=pen, movable=True)
|
|
2887
|
+
self.pw.addItem(line)
|
|
2888
|
+
setattr(self, attr_line, line)
|
|
2889
|
+
setattr(self, 'cursor_%s' % which, x)
|
|
2890
|
+
line.sigPositionChanged.connect(
|
|
2891
|
+
lambda l, w=which: self._on_cursor_moved(w, l))
|
|
2892
|
+
self._update_readout()
|
|
2893
|
+
|
|
2894
|
+
def _on_cursor_moved(self, which, line):
|
|
2895
|
+
setattr(self, 'cursor_%s' % which, line.value())
|
|
2896
|
+
self._update_readout()
|
|
2897
|
+
|
|
2898
|
+
def _on_wheel(self, event, axis=None):
|
|
2899
|
+
delta = event.delta()
|
|
2900
|
+
if delta == 0:
|
|
2901
|
+
return
|
|
2902
|
+
scale = 1.0 / ZOOM_FACTOR if delta > 0 else ZOOM_FACTOR
|
|
2903
|
+
vb = self.pw.plotItem.vb
|
|
2904
|
+
pos = event.pos()
|
|
2905
|
+
mouse_point = vb.mapSceneToView(pos)
|
|
2906
|
+
modifiers = event.modifiers()
|
|
2907
|
+
if modifiers & Qt.ShiftModifier:
|
|
2908
|
+
vr = vb.viewRange()
|
|
2909
|
+
ylo, yhi = vr[1]
|
|
2910
|
+
yd = mouse_point.y()
|
|
2911
|
+
vb.setYRange(yd - (yd - ylo) * scale,
|
|
2912
|
+
yd + (yhi - yd) * scale, padding=0)
|
|
2913
|
+
else:
|
|
2914
|
+
vr = vb.viewRange()
|
|
2915
|
+
xlo, xhi = vr[0]
|
|
2916
|
+
xd = mouse_point.x()
|
|
2917
|
+
vb.setXRange(xd - (xd - xlo) * scale,
|
|
2918
|
+
xd + (xhi - xd) * scale, padding=0)
|
|
2919
|
+
event.accept()
|
|
2920
|
+
|
|
2921
|
+
def _on_mouse_drag(self, ev, axis=None):
|
|
2922
|
+
mods = ev.modifiers()
|
|
2923
|
+
if ev.button() == Qt.RightButton and (
|
|
2924
|
+
mods & Qt.ShiftModifier or mods & Qt.ControlModifier):
|
|
2925
|
+
ev.accept()
|
|
2926
|
+
if ev.isFinish():
|
|
2927
|
+
return
|
|
2928
|
+
delta = ev.pos() - ev.lastPos()
|
|
2929
|
+
vb = self.pw.plotItem.vb
|
|
2930
|
+
vr = vb.viewRange()
|
|
2931
|
+
w = vb.width()
|
|
2932
|
+
h = vb.height()
|
|
2933
|
+
if mods & Qt.ShiftModifier:
|
|
2934
|
+
dx = delta.x() / w
|
|
2935
|
+
xlo, xhi = vr[0]
|
|
2936
|
+
xspan = xhi - xlo
|
|
2937
|
+
vb.setXRange(xlo + dx * xspan, xhi - dx * xspan, padding=0)
|
|
2938
|
+
elif mods & Qt.ControlModifier:
|
|
2939
|
+
dy = delta.y() / h
|
|
2940
|
+
ylo, yhi = vr[1]
|
|
2941
|
+
yspan = yhi - ylo
|
|
2942
|
+
vb.setYRange(ylo - dy * yspan, yhi + dy * yspan, padding=0)
|
|
2943
|
+
else:
|
|
2944
|
+
self._orig_drag(ev, axis)
|
|
2945
|
+
|
|
2946
|
+
def _on_mouse_moved(self, pos):
|
|
2947
|
+
vb = self.pw.plotItem.vb
|
|
2948
|
+
if not vb.sceneBoundingRect().contains(pos):
|
|
2949
|
+
return
|
|
2950
|
+
mp = vb.mapSceneToView(pos)
|
|
2951
|
+
self._last_x = mp.x()
|
|
2952
|
+
data_x = self._view_to_data_x(mp.x())
|
|
2953
|
+
self.status.setText("x: %s" % _eng(data_x, self._xunit))
|
|
2954
|
+
|
|
2955
|
+
def _update_readout(self):
|
|
2956
|
+
xa_raw = self.cursor_a
|
|
2957
|
+
xb_raw = self.cursor_b
|
|
2958
|
+
xa = self._view_to_data_x(xa_raw) if xa_raw is not None else None
|
|
2959
|
+
xb = self._view_to_data_x(xb_raw) if xb_raw is not None else None
|
|
2960
|
+
parts = []
|
|
2961
|
+
if xa is not None:
|
|
2962
|
+
parts.append("A: %s" % _eng(xa, self._xunit))
|
|
2963
|
+
if xb is not None:
|
|
2964
|
+
parts.append("B: %s" % _eng(xb, self._xunit))
|
|
2965
|
+
if xa is not None and xb is not None:
|
|
2966
|
+
dx = xb - xa
|
|
2967
|
+
parts.append("ΔX: %s" % _eng(dx, self._xunit))
|
|
2968
|
+
|
|
2969
|
+
lines = [" ".join(parts)]
|
|
2970
|
+
for xd, yd in self._curves:
|
|
2971
|
+
grad = np.gradient(yd, xd)
|
|
2972
|
+
wparts = []
|
|
2973
|
+
if xa is not None:
|
|
2974
|
+
ya = np.interp(self._view_to_data_x(xa_raw), xd, yd)
|
|
2975
|
+
ga = np.interp(self._view_to_data_x(xa_raw), xd, grad)
|
|
2976
|
+
wparts.append("A: %-14s dA: %-14s" % (
|
|
2977
|
+
_eng(ya, self._yunit), _eng(ga)))
|
|
2978
|
+
if xb is not None:
|
|
2979
|
+
yb = np.interp(self._view_to_data_x(xb_raw), xd, yd)
|
|
2980
|
+
gb = np.interp(self._view_to_data_x(xb_raw), xd, grad)
|
|
2981
|
+
wparts.append("B: %-14s dB: %-14s" % (
|
|
2982
|
+
_eng(yb, self._yunit), _eng(gb)))
|
|
2983
|
+
if xa is not None and xb is not None:
|
|
2984
|
+
wparts.append("Δ: %s" % _eng(yb - ya, self._yunit))
|
|
2985
|
+
if (xb - xa) != 0:
|
|
2986
|
+
slope = (yb - ya) / (xb - xa)
|
|
2987
|
+
wparts.append("Δ/ΔX: %s" % _eng(slope))
|
|
2988
|
+
lines.append(" ".join(wparts))
|
|
2989
|
+
self.readout.setPlainText("\n".join(lines))
|
|
2990
|
+
|
|
2991
|
+
|
|
2992
|
+
class PgWaveWindow(QMainWindow):
|
|
2993
|
+
def __init__(self, xaxis):
|
|
2994
|
+
super().__init__()
|
|
2995
|
+
try:
|
|
2996
|
+
ver = _pkg_version("cicwave")
|
|
2997
|
+
except Exception:
|
|
2998
|
+
ver = "?"
|
|
2999
|
+
self.setWindowTitle("cIcWave v%s: %s" % (ver, os.getcwd()))
|
|
3000
|
+
self.resize(1200, 700)
|
|
3001
|
+
|
|
3002
|
+
splitter = QSplitter(Qt.Horizontal)
|
|
3003
|
+
self.setCentralWidget(splitter)
|
|
3004
|
+
|
|
3005
|
+
self.browser = PgWaveBrowser(xaxis)
|
|
3006
|
+
self.tab_widget = QTabWidget()
|
|
3007
|
+
self.tab_widget.setTabsClosable(True)
|
|
3008
|
+
self.tab_widget.tabCloseRequested.connect(self._close_tab)
|
|
3009
|
+
|
|
3010
|
+
splitter.addWidget(self.browser)
|
|
3011
|
+
splitter.addWidget(self.tab_widget)
|
|
3012
|
+
splitter.setSizes([250, 950])
|
|
3013
|
+
|
|
3014
|
+
self._line_width = 2
|
|
3015
|
+
self._font_size = 9
|
|
3016
|
+
self.plot_index = 0
|
|
3017
|
+
self._add_plot_tab()
|
|
3018
|
+
|
|
3019
|
+
self.browser.waveSelected.connect(self._on_wave_selected)
|
|
3020
|
+
self.browser.waveRemoveRequested.connect(self._on_wave_remove)
|
|
3021
|
+
self.browser.analysisRequested.connect(self._on_analysis)
|
|
3022
|
+
self.browser.styleChanged.connect(self._on_style_changed)
|
|
3023
|
+
self.browser.fileRemoveRequested.connect(self._on_file_remove)
|
|
3024
|
+
self.browser.wavePlotAllRequested.connect(self._plot_wave_all_files)
|
|
3025
|
+
self.browser.wavePlotAllVisibleRequested.connect(
|
|
3026
|
+
self._plot_all_visible_waves)
|
|
3027
|
+
|
|
3028
|
+
self._drops_delegate_trees = (
|
|
3029
|
+
self.browser.file_tree,
|
|
3030
|
+
self.browser.wave_tree,
|
|
3031
|
+
self.browser.file_tree.viewport(),
|
|
3032
|
+
self.browser.wave_tree.viewport(),
|
|
3033
|
+
)
|
|
3034
|
+
|
|
3035
|
+
self._setup_menus()
|
|
3036
|
+
self._setup_shortcuts()
|
|
3037
|
+
self._install_drop_filters()
|
|
3038
|
+
|
|
3039
|
+
def _install_drop_filters(self):
|
|
3040
|
+
"""Accept file drops on any child (plots, browser, etc.)."""
|
|
3041
|
+
self._attach_drop_filter_subtree(self.centralWidget())
|
|
3042
|
+
|
|
3043
|
+
def _attach_drop_filter_subtree(self, root):
|
|
3044
|
+
if root is None:
|
|
3045
|
+
return
|
|
3046
|
+
root.installEventFilter(self)
|
|
3047
|
+
for w in root.findChildren(QWidget):
|
|
3048
|
+
w.installEventFilter(self)
|
|
3049
|
+
|
|
3050
|
+
def eventFilter(self, obj, event):
|
|
3051
|
+
et = event.type()
|
|
3052
|
+
if et in (QEvent.DragEnter, QEvent.DragMove, QEvent.Drop):
|
|
3053
|
+
if obj in self._drops_delegate_trees:
|
|
3054
|
+
return False
|
|
3055
|
+
if et == QEvent.DragEnter or et == QEvent.DragMove:
|
|
3056
|
+
if self._drop_mime_has_files(event.mimeData()):
|
|
3057
|
+
event.acceptProposedAction()
|
|
3058
|
+
return True
|
|
3059
|
+
elif et == QEvent.Drop:
|
|
3060
|
+
self._handle_file_drop(event)
|
|
3061
|
+
return True
|
|
3062
|
+
return super().eventFilter(obj, event)
|
|
3063
|
+
|
|
3064
|
+
@staticmethod
|
|
3065
|
+
def _drop_mime_has_files(mime_data):
|
|
3066
|
+
if not mime_data.hasUrls():
|
|
3067
|
+
return False
|
|
3068
|
+
for url in mime_data.urls():
|
|
3069
|
+
p = url.toLocalFile()
|
|
3070
|
+
if p and os.path.isfile(p):
|
|
3071
|
+
return True
|
|
3072
|
+
return False
|
|
3073
|
+
|
|
3074
|
+
def _handle_file_drop(self, event):
|
|
3075
|
+
paths = []
|
|
3076
|
+
for url in event.mimeData().urls():
|
|
3077
|
+
p = url.toLocalFile()
|
|
3078
|
+
if p and os.path.isfile(p):
|
|
3079
|
+
paths.append(os.path.normpath(p))
|
|
3080
|
+
if not paths:
|
|
3081
|
+
event.ignore()
|
|
3082
|
+
return
|
|
3083
|
+
event.acceptProposedAction()
|
|
3084
|
+
for path in paths:
|
|
3085
|
+
if path.lower().endswith('.cicwave.yaml'):
|
|
3086
|
+
self.applySession(path)
|
|
3087
|
+
else:
|
|
3088
|
+
self.browser.openFile(path)
|
|
3089
|
+
|
|
3090
|
+
def _setup_menus(self):
|
|
3091
|
+
mb = self.menuBar()
|
|
3092
|
+
|
|
3093
|
+
m = mb.addMenu("File")
|
|
3094
|
+
m.addAction("Open File Ctrl+O", self._open_file)
|
|
3095
|
+
m.addAction("Remove All Files", self._remove_all_files)
|
|
3096
|
+
m.addAction("Save Session Ctrl+S", self._save_session)
|
|
3097
|
+
m.addAction("Load Session", self._load_session)
|
|
3098
|
+
m.addSeparator()
|
|
3099
|
+
m.addAction("Export PDF Ctrl+P", self._export_pdf)
|
|
3100
|
+
m.addAction("Export Data... Ctrl+E", self._export_data)
|
|
3101
|
+
m.addSeparator()
|
|
3102
|
+
m.addAction("Quit Ctrl+Q", self.close)
|
|
3103
|
+
|
|
3104
|
+
m = mb.addMenu("Edit")
|
|
3105
|
+
m.addAction("New Plot Ctrl+N", self._add_plot_tab)
|
|
3106
|
+
m.addAction("Close Tab Ctrl+W", self._close_current_tab)
|
|
3107
|
+
m.addSeparator()
|
|
3108
|
+
m.addAction("Set Axis Labels Ctrl+L", self._set_axis_labels)
|
|
3109
|
+
m.addAction("Default X Axis...", self._edit_default_xaxis)
|
|
3110
|
+
m.addAction("Add Annotation Ctrl+T", self._add_annotation)
|
|
3111
|
+
m.addAction("Clear Annotations", self._clear_annotations)
|
|
3112
|
+
m.addSeparator()
|
|
3113
|
+
m.addAction("Reload All R", self._reload)
|
|
3114
|
+
m.addAction("Auto Scale F", self._auto_size)
|
|
3115
|
+
m.addAction("Zoom In Shift+Z", self._zoom_in)
|
|
3116
|
+
m.addAction("Zoom Out Ctrl+Z", self._zoom_out)
|
|
3117
|
+
m.addSeparator()
|
|
3118
|
+
m.addAction("Remove All", self._remove_all)
|
|
3119
|
+
|
|
3120
|
+
m = mb.addMenu("View")
|
|
3121
|
+
m.addAction("Set Cursor A A", self._cursor_a)
|
|
3122
|
+
m.addAction("Set Cursor B B", self._cursor_b)
|
|
3123
|
+
m.addAction("Clear Cursors Escape", self._clear_cursors)
|
|
3124
|
+
m.addSeparator()
|
|
3125
|
+
m.addAction("Toggle Legend L", self._toggle_legend)
|
|
3126
|
+
m.addSeparator()
|
|
3127
|
+
m.addAction("Increase Line Width Ctrl+Up", self._inc_line_width)
|
|
3128
|
+
m.addAction("Decrease Line Width Ctrl+Down", self._dec_line_width)
|
|
3129
|
+
m.addSeparator()
|
|
3130
|
+
m.addAction("Increase Font Size Ctrl+=", self._inc_font_size)
|
|
3131
|
+
m.addAction("Decrease Font Size Ctrl+-", self._dec_font_size)
|
|
3132
|
+
m.addSeparator()
|
|
3133
|
+
m.addAction("Dark Theme", lambda: self._set_theme('dark'))
|
|
3134
|
+
m.addAction("Light Theme", lambda: self._set_theme('light'))
|
|
3135
|
+
|
|
3136
|
+
m = mb.addMenu("Help")
|
|
3137
|
+
m.addAction("Keyboard Shortcuts", self._show_help)
|
|
3138
|
+
|
|
3139
|
+
def _setup_shortcuts(self):
|
|
3140
|
+
for seq, func in [
|
|
3141
|
+
("Ctrl+O", self._open_file),
|
|
3142
|
+
("Ctrl+S", self._save_session),
|
|
3143
|
+
("Ctrl+P", self._export_pdf),
|
|
3144
|
+
("Ctrl+E", self._export_data),
|
|
3145
|
+
("Ctrl+Q", self.close),
|
|
3146
|
+
("Ctrl+N", self._add_plot_tab),
|
|
3147
|
+
("Ctrl+W", self._close_current_tab),
|
|
3148
|
+
("Ctrl+L", self._set_axis_labels),
|
|
3149
|
+
("Ctrl+T", self._add_annotation),
|
|
3150
|
+
("Ctrl+Up", self._inc_line_width),
|
|
3151
|
+
("Ctrl+Down", self._dec_line_width),
|
|
3152
|
+
("Ctrl+=", self._inc_font_size),
|
|
3153
|
+
("Ctrl+-", self._dec_font_size),
|
|
3154
|
+
("Escape", self._clear_cursors),
|
|
3155
|
+
]:
|
|
3156
|
+
QShortcut(QKeySequence(seq), self, func)
|
|
3157
|
+
#- Single-letter shortcuts that should fire even while the
|
|
3158
|
+
#- wave/file tree has focus. ``ApplicationShortcut`` context
|
|
3159
|
+
#- bypasses the QTreeWidget's keyboard-search swallowing.
|
|
3160
|
+
from PySide6.QtCore import Qt as _Qt
|
|
3161
|
+
d_sc = QShortcut(QKeySequence("D"), self,
|
|
3162
|
+
self.browser.togglePlotAsDigital)
|
|
3163
|
+
d_sc.setContext(_Qt.ApplicationShortcut)
|
|
3164
|
+
|
|
3165
|
+
def keyPressEvent(self, event):
|
|
3166
|
+
if isinstance(self.focusWidget(), QLineEdit):
|
|
3167
|
+
super().keyPressEvent(event)
|
|
3168
|
+
return
|
|
3169
|
+
p = self._current()
|
|
3170
|
+
key = event.text()
|
|
3171
|
+
mods = event.modifiers()
|
|
3172
|
+
ctrl_like = (Qt.ControlModifier | Qt.MetaModifier)
|
|
3173
|
+
if p and key == 'z' and not (mods & ctrl_like) and hasattr(p, 'zoomIn'):
|
|
3174
|
+
p.zoomIn()
|
|
3175
|
+
elif p and key == 'Z' and hasattr(p, 'zoomOut'):
|
|
3176
|
+
#- Shift+z (uppercase Z) zooms out. Ctrl+z still works as a
|
|
3177
|
+
#- secondary binding for muscle-memory parity with Shift+Z.
|
|
3178
|
+
p.zoomOut()
|
|
3179
|
+
elif p and key.lower() == 'z' and mods & ctrl_like and hasattr(p, 'zoomOut'):
|
|
3180
|
+
p.zoomOut()
|
|
3181
|
+
elif p and key.lower() == 'a' and hasattr(p, 'placeCursorA'):
|
|
3182
|
+
p.placeCursorA()
|
|
3183
|
+
elif p and key.lower() == 'b' and hasattr(p, 'placeCursorB'):
|
|
3184
|
+
p.placeCursorB()
|
|
3185
|
+
elif p and key.lower() == 'f' and hasattr(p, 'autoSize'):
|
|
3186
|
+
p.autoSize()
|
|
3187
|
+
elif p and key.lower() == 'r' and hasattr(p, 'reloadAll'):
|
|
3188
|
+
p.reloadAll()
|
|
3189
|
+
elif p and key.lower() == 'l' and hasattr(p, 'toggleLegend'):
|
|
3190
|
+
p.toggleLegend()
|
|
3191
|
+
else:
|
|
3192
|
+
super().keyPressEvent(event)
|
|
3193
|
+
|
|
3194
|
+
def _current(self):
|
|
3195
|
+
return self.tab_widget.currentWidget()
|
|
3196
|
+
|
|
3197
|
+
def _add_plot_tab(self):
|
|
3198
|
+
plot = PgWavePlot()
|
|
3199
|
+
plot.setLineWidth(self._line_width)
|
|
3200
|
+
plot.setFontSize(self._font_size)
|
|
3201
|
+
self.tab_widget.addTab(plot, "Plot %d" % self.plot_index)
|
|
3202
|
+
self.plot_index += 1
|
|
3203
|
+
self.tab_widget.setCurrentWidget(plot)
|
|
3204
|
+
self._attach_drop_filter_subtree(plot)
|
|
3205
|
+
|
|
3206
|
+
def _on_wave_selected(self, wave):
|
|
3207
|
+
p = self._current()
|
|
3208
|
+
if p:
|
|
3209
|
+
result = p.show_wave(wave, style=self.browser.plotStyle)
|
|
3210
|
+
if result:
|
|
3211
|
+
tag, color = result
|
|
3212
|
+
self.browser.setWaveColor(tag, color)
|
|
3213
|
+
else:
|
|
3214
|
+
#- Already plotted: still poke the readout so a digital
|
|
3215
|
+
#- format change (or other wave-side option) shows up
|
|
3216
|
+
#- without requiring a cursor move.
|
|
3217
|
+
if hasattr(p, '_refresh_digital_labels'):
|
|
3218
|
+
p._refresh_digital_labels(wave)
|
|
3219
|
+
if hasattr(p, '_update_readout'):
|
|
3220
|
+
p._update_readout()
|
|
3221
|
+
|
|
3222
|
+
def _on_wave_remove(self, wave):
|
|
3223
|
+
p = self._current()
|
|
3224
|
+
if p:
|
|
3225
|
+
tag = p.removeLine(wave)
|
|
3226
|
+
if tag:
|
|
3227
|
+
self.browser.clearWaveColor(tag)
|
|
3228
|
+
|
|
3229
|
+
def _on_file_remove(self, key):
|
|
3230
|
+
if key not in self.browser.files:
|
|
3231
|
+
return
|
|
3232
|
+
wf = self.browser.files[key]
|
|
3233
|
+
for ti in range(self.tab_widget.count()):
|
|
3234
|
+
w = self.tab_widget.widget(ti)
|
|
3235
|
+
if isinstance(w, PgWavePlot):
|
|
3236
|
+
tags = w.remove_waves_for_wfile(wf)
|
|
3237
|
+
for tag in tags:
|
|
3238
|
+
self.browser.clearWaveColor(tag)
|
|
3239
|
+
self.browser._purge_wave_cache_for_wfile(wf)
|
|
3240
|
+
self.browser.remove_file_entry(key)
|
|
3241
|
+
|
|
3242
|
+
def _remove_all_files(self):
|
|
3243
|
+
if not self.browser.files:
|
|
3244
|
+
return
|
|
3245
|
+
for ti in range(self.tab_widget.count()):
|
|
3246
|
+
w = self.tab_widget.widget(ti)
|
|
3247
|
+
if isinstance(w, PgWavePlot):
|
|
3248
|
+
tags = w.removeAll()
|
|
3249
|
+
for tag in tags:
|
|
3250
|
+
self.browser.clearWaveColor(tag)
|
|
3251
|
+
self.browser._wave_cache.clear()
|
|
3252
|
+
self.browser.file_tree.clear()
|
|
3253
|
+
self.browser.wave_tree.clear()
|
|
3254
|
+
self.browser._tag_to_item = {}
|
|
3255
|
+
self.browser.files.clear_all()
|
|
3256
|
+
|
|
3257
|
+
def _plot_wave_all_files(self, yname):
|
|
3258
|
+
p = self._current()
|
|
3259
|
+
if not isinstance(p, PgWavePlot):
|
|
3260
|
+
return
|
|
3261
|
+
style = self.browser.plotStyle
|
|
3262
|
+
for wf in self.browser.files.values():
|
|
3263
|
+
if yname not in wf.getWaveNames():
|
|
3264
|
+
continue
|
|
3265
|
+
tag = wf.getTag(yname)
|
|
3266
|
+
if tag not in self.browser._wave_cache:
|
|
3267
|
+
self.browser._wave_cache[tag] = PgWave(wf, yname, self.browser.xaxis)
|
|
3268
|
+
wave = self.browser._wave_cache[tag]
|
|
3269
|
+
wave.reload()
|
|
3270
|
+
result = p.show_wave(wave, style=style)
|
|
3271
|
+
if result:
|
|
3272
|
+
tag2, color = result
|
|
3273
|
+
self.browser.setWaveColor(tag2, color)
|
|
3274
|
+
|
|
3275
|
+
def _plot_all_visible_waves(self):
|
|
3276
|
+
p = self._current()
|
|
3277
|
+
if not isinstance(p, PgWavePlot):
|
|
3278
|
+
return
|
|
3279
|
+
f = self.browser.files.getSelected()
|
|
3280
|
+
if f is None:
|
|
3281
|
+
return
|
|
3282
|
+
style = self.browser.plotStyle
|
|
3283
|
+
for yname in sorted(self.browser._visible_wave_names()):
|
|
3284
|
+
tag = f.getTag(yname)
|
|
3285
|
+
if tag not in self.browser._wave_cache:
|
|
3286
|
+
self.browser._wave_cache[tag] = PgWave(f, yname, self.browser.xaxis)
|
|
3287
|
+
wave = self.browser._wave_cache[tag]
|
|
3288
|
+
wave.reload()
|
|
3289
|
+
result = p.show_wave(wave, style=style)
|
|
3290
|
+
if result:
|
|
3291
|
+
tag2, color = result
|
|
3292
|
+
self.browser.setWaveColor(tag2, color)
|
|
3293
|
+
|
|
3294
|
+
def _on_style_changed(self, style):
|
|
3295
|
+
p = self._current()
|
|
3296
|
+
if p and hasattr(p, 'setAllStyles'):
|
|
3297
|
+
p.setAllStyles(style)
|
|
3298
|
+
|
|
3299
|
+
def _open_file(self):
|
|
3300
|
+
fname, _ = QFileDialog.getOpenFileName(
|
|
3301
|
+
self, "Open File", os.getcwd(),
|
|
3302
|
+
"All Supported (*.raw *.vcd *.csv *.tsv *.txt *.xlsx *.xls *.ods *.pkl *.pickle *.json *.parquet *.feather *.h5 *.hdf5);;Raw Files (*.raw);;VCD Files (*.vcd);;CSV/TSV (*.csv *.tsv *.txt);;Excel (*.xlsx *.xls *.ods);;Pickle (*.pkl *.pickle);;JSON (*.json);;Parquet (*.parquet);;Feather (*.feather);;HDF5 (*.h5 *.hdf5);;All Files (*)")
|
|
3303
|
+
if fname:
|
|
3304
|
+
self.browser.openFile(fname)
|
|
3305
|
+
|
|
3306
|
+
def _export_pdf(self):
|
|
3307
|
+
p = self._current()
|
|
3308
|
+
if p and hasattr(p, 'exportPdf'):
|
|
3309
|
+
p.exportPdf()
|
|
3310
|
+
|
|
3311
|
+
def _export_data(self):
|
|
3312
|
+
p = self._current()
|
|
3313
|
+
if p and hasattr(p, 'exportData'):
|
|
3314
|
+
p.exportData()
|
|
3315
|
+
|
|
3316
|
+
def _reload(self):
|
|
3317
|
+
p = self._current()
|
|
3318
|
+
if p and hasattr(p, 'reloadAll'):
|
|
3319
|
+
p.reloadAll()
|
|
3320
|
+
|
|
3321
|
+
def _auto_size(self):
|
|
3322
|
+
p = self._current()
|
|
3323
|
+
if p and hasattr(p, 'autoSize'):
|
|
3324
|
+
p.autoSize()
|
|
3325
|
+
|
|
3326
|
+
def _zoom_in(self):
|
|
3327
|
+
p = self._current()
|
|
3328
|
+
if p and hasattr(p, 'zoomIn'):
|
|
3329
|
+
p.zoomIn()
|
|
3330
|
+
|
|
3331
|
+
def _zoom_out(self):
|
|
3332
|
+
p = self._current()
|
|
3333
|
+
if p and hasattr(p, 'zoomOut'):
|
|
3334
|
+
p.zoomOut()
|
|
3335
|
+
|
|
3336
|
+
def _inc_line_width(self):
|
|
3337
|
+
self._line_width = min(self._line_width + 1, 10)
|
|
3338
|
+
self._apply_line_width()
|
|
3339
|
+
|
|
3340
|
+
def _dec_line_width(self):
|
|
3341
|
+
self._line_width = max(self._line_width - 1, 1)
|
|
3342
|
+
self._apply_line_width()
|
|
3343
|
+
|
|
3344
|
+
def _apply_line_width(self):
|
|
3345
|
+
for ti in range(self.tab_widget.count()):
|
|
3346
|
+
w = self.tab_widget.widget(ti)
|
|
3347
|
+
if hasattr(w, 'setLineWidth'):
|
|
3348
|
+
w.setLineWidth(self._line_width)
|
|
3349
|
+
|
|
3350
|
+
def _inc_font_size(self):
|
|
3351
|
+
self._font_size = min(self._font_size + 1, 24)
|
|
3352
|
+
self._apply_font_size()
|
|
3353
|
+
|
|
3354
|
+
def _dec_font_size(self):
|
|
3355
|
+
self._font_size = max(self._font_size - 1, 6)
|
|
3356
|
+
self._apply_font_size()
|
|
3357
|
+
|
|
3358
|
+
def _apply_font_size(self):
|
|
3359
|
+
for ti in range(self.tab_widget.count()):
|
|
3360
|
+
w = self.tab_widget.widget(ti)
|
|
3361
|
+
if hasattr(w, 'setFontSize'):
|
|
3362
|
+
w.setFontSize(self._font_size)
|
|
3363
|
+
|
|
3364
|
+
def _remove_all(self):
|
|
3365
|
+
p = self._current()
|
|
3366
|
+
if p:
|
|
3367
|
+
tags = p.removeAll()
|
|
3368
|
+
for tag in tags:
|
|
3369
|
+
self.browser.clearWaveColor(tag)
|
|
3370
|
+
|
|
3371
|
+
def _cursor_a(self):
|
|
3372
|
+
p = self._current()
|
|
3373
|
+
if p and hasattr(p, 'placeCursorA'):
|
|
3374
|
+
p.placeCursorA()
|
|
3375
|
+
|
|
3376
|
+
def _cursor_b(self):
|
|
3377
|
+
p = self._current()
|
|
3378
|
+
if p and hasattr(p, 'placeCursorB'):
|
|
3379
|
+
p.placeCursorB()
|
|
3380
|
+
|
|
3381
|
+
def _clear_cursors(self):
|
|
3382
|
+
p = self._current()
|
|
3383
|
+
if p and hasattr(p, 'clearCursors'):
|
|
3384
|
+
p.clearCursors()
|
|
3385
|
+
|
|
3386
|
+
def _toggle_legend(self):
|
|
3387
|
+
p = self._current()
|
|
3388
|
+
if p and hasattr(p, 'toggleLegend'):
|
|
3389
|
+
p.toggleLegend()
|
|
3390
|
+
|
|
3391
|
+
def _set_theme(self, theme_name):
|
|
3392
|
+
app = QApplication.instance()
|
|
3393
|
+
_apply_theme(app, theme_name)
|
|
3394
|
+
theme = _get_theme()
|
|
3395
|
+
for ti in range(self.tab_widget.count()):
|
|
3396
|
+
w = self.tab_widget.widget(ti)
|
|
3397
|
+
if hasattr(w, '_apply_panel_style'):
|
|
3398
|
+
w._apply_panel_style()
|
|
3399
|
+
if hasattr(w, 'gw'):
|
|
3400
|
+
w.gw.setBackground(theme['pg_background'])
|
|
3401
|
+
_apply_grid(w.plot)
|
|
3402
|
+
if hasattr(w, 'pw'):
|
|
3403
|
+
w.pw.setBackground(theme['pg_background'])
|
|
3404
|
+
_apply_grid(w.pw.plotItem)
|
|
3405
|
+
|
|
3406
|
+
def _show_help(self):
|
|
3407
|
+
dlg = QDialog(self)
|
|
3408
|
+
dlg.setWindowTitle("Keyboard Shortcuts")
|
|
3409
|
+
layout = QVBoxLayout(dlg)
|
|
3410
|
+
text = QLabel(
|
|
3411
|
+
"Keyboard Shortcuts\n"
|
|
3412
|
+
"══════════════════════════════\n"
|
|
3413
|
+
"\n"
|
|
3414
|
+
"File\n"
|
|
3415
|
+
" Ctrl+O Open file\n"
|
|
3416
|
+
" Ctrl+S Save session\n"
|
|
3417
|
+
" Ctrl+P Export PDF/PNG/SVG\n"
|
|
3418
|
+
" Ctrl+E Export plotted data (CSV/Parquet/...)\n"
|
|
3419
|
+
" Ctrl+Q Quit\n"
|
|
3420
|
+
"\n"
|
|
3421
|
+
"Edit\n"
|
|
3422
|
+
" Ctrl+N New plot tab\n"
|
|
3423
|
+
" Ctrl+W Close current tab\n"
|
|
3424
|
+
" Ctrl+L Set axis labels\n"
|
|
3425
|
+
" Ctrl+T Add annotation\n"
|
|
3426
|
+
" R Reload all waves\n"
|
|
3427
|
+
" F Fit all (auto scale)\n"
|
|
3428
|
+
" Z Zoom in\n"
|
|
3429
|
+
" Shift+Z Zoom out\n"
|
|
3430
|
+
" Ctrl+Z Zoom out (alias)\n"
|
|
3431
|
+
"\n"
|
|
3432
|
+
"Cursors\n"
|
|
3433
|
+
" A Set cursor A at mouse\n"
|
|
3434
|
+
" B Set cursor B at mouse\n"
|
|
3435
|
+
" Escape Clear cursors\n"
|
|
3436
|
+
" Drag cursor Move cursor\n"
|
|
3437
|
+
"\n"
|
|
3438
|
+
"View\n"
|
|
3439
|
+
" L Toggle legend\n"
|
|
3440
|
+
" D Toggle focused wave on the digital pane\n"
|
|
3441
|
+
" Ctrl+Up Increase line width\n"
|
|
3442
|
+
" Ctrl+Down Decrease line width\n"
|
|
3443
|
+
" Ctrl+= Increase font size\n"
|
|
3444
|
+
" Ctrl+- Decrease font size\n"
|
|
3445
|
+
"\n"
|
|
3446
|
+
"Mouse\n"
|
|
3447
|
+
" Left-drag Pan\n"
|
|
3448
|
+
" Scroll Zoom x-axis\n"
|
|
3449
|
+
" Shift+Scroll Zoom y-axis\n"
|
|
3450
|
+
" Shift+Right-drag Zoom x-axis\n"
|
|
3451
|
+
" Ctrl+Right-drag Zoom y-axis\n"
|
|
3452
|
+
"\n"
|
|
3453
|
+
"Browser\n"
|
|
3454
|
+
" Double-click Add to plot\n"
|
|
3455
|
+
" Right-click Context menu\n"
|
|
3456
|
+
"\n"
|
|
3457
|
+
"Analysis (right-click menu)\n"
|
|
3458
|
+
" FFT / PSD Spectral density\n"
|
|
3459
|
+
" Histogram Distribution + fit\n"
|
|
3460
|
+
" Differentiate Numerical dy/dx\n"
|
|
3461
|
+
" X vs Y Parametric plot\n"
|
|
3462
|
+
)
|
|
3463
|
+
text.setFont(_mono_font(11))
|
|
3464
|
+
theme = _get_theme()
|
|
3465
|
+
text.setStyleSheet(
|
|
3466
|
+
"background-color: %s; color: %s; padding: 16px;" % (
|
|
3467
|
+
theme['panel_bg'], theme['panel_fg']))
|
|
3468
|
+
layout.addWidget(text)
|
|
3469
|
+
btn = QPushButton("Close")
|
|
3470
|
+
btn.clicked.connect(dlg.accept)
|
|
3471
|
+
layout.addWidget(btn)
|
|
3472
|
+
dlg.exec()
|
|
3473
|
+
|
|
3474
|
+
# ------------------------------------------------------------------
|
|
3475
|
+
# Default X axis (new loads + persistence)
|
|
3476
|
+
# ------------------------------------------------------------------
|
|
3477
|
+
|
|
3478
|
+
def _edit_default_xaxis(self):
|
|
3479
|
+
text, ok = QInputDialog.getText(
|
|
3480
|
+
self, "Default X Axis",
|
|
3481
|
+
"Column name used as X when the file has no standard axis "
|
|
3482
|
+
"(time, frequency, sweeps, …).\n"
|
|
3483
|
+
"Leave empty for automatic detection.\n"
|
|
3484
|
+
"Applies to newly opened files; saved for later sessions.",
|
|
3485
|
+
QLineEdit.Normal,
|
|
3486
|
+
self.browser.xaxis or "")
|
|
3487
|
+
if not ok:
|
|
3488
|
+
return
|
|
3489
|
+
col = text.strip() or None
|
|
3490
|
+
self.browser.xaxis = col
|
|
3491
|
+
_write_saved_default_xaxis(col)
|
|
3492
|
+
|
|
3493
|
+
# ------------------------------------------------------------------
|
|
3494
|
+
# Axis labels dialog
|
|
3495
|
+
# ------------------------------------------------------------------
|
|
3496
|
+
|
|
3497
|
+
def _set_axis_labels(self):
|
|
3498
|
+
p = self._current()
|
|
3499
|
+
if not isinstance(p, PgWavePlot):
|
|
3500
|
+
return
|
|
3501
|
+
dlg = QDialog(self)
|
|
3502
|
+
dlg.setWindowTitle("Set Axis Labels")
|
|
3503
|
+
form = QVBoxLayout(dlg)
|
|
3504
|
+
|
|
3505
|
+
def _row(label_text, default):
|
|
3506
|
+
row = QHBoxLayout()
|
|
3507
|
+
row.addWidget(QLabel(label_text))
|
|
3508
|
+
le = QLineEdit(default or "")
|
|
3509
|
+
row.addWidget(le)
|
|
3510
|
+
form.addLayout(row)
|
|
3511
|
+
return le
|
|
3512
|
+
|
|
3513
|
+
title_le = _row("Title:", p.custom_title)
|
|
3514
|
+
xlabel_le = _row("X-axis:", p.custom_xlabel)
|
|
3515
|
+
ylabel_le = _row("Y-axis:", p.custom_ylabel)
|
|
3516
|
+
|
|
3517
|
+
btn = QPushButton("Apply")
|
|
3518
|
+
btn.clicked.connect(dlg.accept)
|
|
3519
|
+
form.addWidget(btn)
|
|
3520
|
+
|
|
3521
|
+
if dlg.exec() != QDialog.Accepted:
|
|
3522
|
+
return
|
|
3523
|
+
p.custom_title = title_le.text().strip() or None
|
|
3524
|
+
p.custom_xlabel = xlabel_le.text().strip() or None
|
|
3525
|
+
p.custom_ylabel = ylabel_le.text().strip() or None
|
|
3526
|
+
if p.custom_title:
|
|
3527
|
+
p.plot.setTitle(p.custom_title,
|
|
3528
|
+
color=_get_theme()['title_color'], size='11pt')
|
|
3529
|
+
else:
|
|
3530
|
+
p.plot.setTitle(None)
|
|
3531
|
+
if p.custom_xlabel:
|
|
3532
|
+
p.plot.setLabel('bottom', p.custom_xlabel)
|
|
3533
|
+
if p.custom_ylabel:
|
|
3534
|
+
p.plot.setLabel('left', p.custom_ylabel)
|
|
3535
|
+
|
|
3536
|
+
# ------------------------------------------------------------------
|
|
3537
|
+
# Annotations
|
|
3538
|
+
# ------------------------------------------------------------------
|
|
3539
|
+
|
|
3540
|
+
def _add_annotation(self):
|
|
3541
|
+
p = self._current()
|
|
3542
|
+
if not isinstance(p, PgWavePlot):
|
|
3543
|
+
return
|
|
3544
|
+
if p._last_x is None:
|
|
3545
|
+
return
|
|
3546
|
+
text, ok = QInputDialog.getText(self, "Add Annotation",
|
|
3547
|
+
"Text:")
|
|
3548
|
+
if not ok or not text.strip():
|
|
3549
|
+
return
|
|
3550
|
+
vr = p.plot.viewRange()
|
|
3551
|
+
y = (vr[1][0] + vr[1][1]) / 2.0
|
|
3552
|
+
p.addAnnotation(p._last_x, y, text.strip())
|
|
3553
|
+
|
|
3554
|
+
def _clear_annotations(self):
|
|
3555
|
+
p = self._current()
|
|
3556
|
+
if isinstance(p, PgWavePlot):
|
|
3557
|
+
p.removeAnnotations()
|
|
3558
|
+
|
|
3559
|
+
# ------------------------------------------------------------------
|
|
3560
|
+
# Session save / load
|
|
3561
|
+
# ------------------------------------------------------------------
|
|
3562
|
+
|
|
3563
|
+
def _build_session(self):
|
|
3564
|
+
"""Collect current GUI state into a serialisable dict."""
|
|
3565
|
+
files = []
|
|
3566
|
+
wf_to_idx = {}
|
|
3567
|
+
for fkey, wf in self.browser.files.items():
|
|
3568
|
+
idx = len(files)
|
|
3569
|
+
orig = getattr(wf, '_original_path', None) or wf.fname
|
|
3570
|
+
entry = {'path': os.path.abspath(orig)}
|
|
3571
|
+
pivot_path = getattr(wf, '_pivot_spec_path', None)
|
|
3572
|
+
if pivot_path:
|
|
3573
|
+
entry['pivot'] = pivot_path
|
|
3574
|
+
files.append(entry)
|
|
3575
|
+
wf_to_idx[id(wf)] = idx
|
|
3576
|
+
|
|
3577
|
+
plots = []
|
|
3578
|
+
for ti in range(self.tab_widget.count()):
|
|
3579
|
+
widget = self.tab_widget.widget(ti)
|
|
3580
|
+
if not isinstance(widget, PgWavePlot):
|
|
3581
|
+
continue
|
|
3582
|
+
tab_name = self.tab_widget.tabText(ti)
|
|
3583
|
+
waves = []
|
|
3584
|
+
for tag, (wave, yunit) in widget.wave_data.items():
|
|
3585
|
+
fi = wf_to_idx.get(id(wave.wfile))
|
|
3586
|
+
waves.append({
|
|
3587
|
+
'file': fi,
|
|
3588
|
+
'name': wave.key,
|
|
3589
|
+
'style': getattr(wave, 'style', 'Lines'),
|
|
3590
|
+
})
|
|
3591
|
+
plot_dict = {'name': tab_name, 'waves': waves}
|
|
3592
|
+
if widget.custom_xlabel:
|
|
3593
|
+
plot_dict['xlabel'] = widget.custom_xlabel
|
|
3594
|
+
if widget.custom_ylabel:
|
|
3595
|
+
plot_dict['ylabel'] = widget.custom_ylabel
|
|
3596
|
+
if widget.custom_title:
|
|
3597
|
+
plot_dict['title'] = widget.custom_title
|
|
3598
|
+
if widget._annotations:
|
|
3599
|
+
plot_dict['annotations'] = [
|
|
3600
|
+
{'text': a['text'], 'x': float(a['x']),
|
|
3601
|
+
'y': float(a['y'])}
|
|
3602
|
+
for a in widget._annotations
|
|
3603
|
+
]
|
|
3604
|
+
plots.append(plot_dict)
|
|
3605
|
+
|
|
3606
|
+
return {'files': files, 'plots': plots}
|
|
3607
|
+
|
|
3608
|
+
def _save_session(self):
|
|
3609
|
+
import yaml
|
|
3610
|
+
fname, _ = QFileDialog.getSaveFileName(
|
|
3611
|
+
self, "Save Session", os.getcwd(),
|
|
3612
|
+
"Session files (*.cicwave.yaml);;YAML files (*.yaml);;All Files (*)")
|
|
3613
|
+
if not fname:
|
|
3614
|
+
return
|
|
3615
|
+
session = self._build_session()
|
|
3616
|
+
session_dir = os.path.dirname(os.path.abspath(fname))
|
|
3617
|
+
for fe in session.get('files', []):
|
|
3618
|
+
fe['path'] = os.path.relpath(fe['path'], session_dir)
|
|
3619
|
+
if 'pivot' in fe:
|
|
3620
|
+
fe['pivot'] = os.path.relpath(fe['pivot'], session_dir)
|
|
3621
|
+
|
|
3622
|
+
with open(fname, 'w') as fh:
|
|
3623
|
+
yaml.dump(session, fh, default_flow_style=False, sort_keys=False)
|
|
3624
|
+
|
|
3625
|
+
def _load_session(self):
|
|
3626
|
+
fname, _ = QFileDialog.getOpenFileName(
|
|
3627
|
+
self, "Load Session", os.getcwd(),
|
|
3628
|
+
"Session files (*.cicwave.yaml *.yaml);;All Files (*)")
|
|
3629
|
+
if not fname:
|
|
3630
|
+
return
|
|
3631
|
+
self.applySession(fname)
|
|
3632
|
+
|
|
3633
|
+
def applySession(self, session_path):
|
|
3634
|
+
"""Load a session file and restore the GUI state."""
|
|
3635
|
+
import yaml
|
|
3636
|
+
with open(session_path) as fh:
|
|
3637
|
+
session = yaml.safe_load(fh)
|
|
3638
|
+
|
|
3639
|
+
session_dir = os.path.dirname(os.path.abspath(session_path))
|
|
3640
|
+
|
|
3641
|
+
for fe in session.get('files', []):
|
|
3642
|
+
fpath = fe['path']
|
|
3643
|
+
if not os.path.isabs(fpath):
|
|
3644
|
+
fpath = os.path.normpath(os.path.join(session_dir, fpath))
|
|
3645
|
+
pivot_path = fe.get('pivot')
|
|
3646
|
+
if pivot_path and not os.path.isabs(pivot_path):
|
|
3647
|
+
pivot_path = os.path.normpath(
|
|
3648
|
+
os.path.join(session_dir, pivot_path))
|
|
3649
|
+
|
|
3650
|
+
if pivot_path:
|
|
3651
|
+
from .pivot import load_spec, apply_pivot
|
|
3652
|
+
from .wavefiles import WaveFile
|
|
3653
|
+
spec = load_spec(pivot_path)
|
|
3654
|
+
xaxis = self.browser.xaxis or spec.get('columns', '')
|
|
3655
|
+
if not self.browser.xaxis and spec.get('columns'):
|
|
3656
|
+
self.browser.xaxis = spec['columns']
|
|
3657
|
+
wf = WaveFile(fpath, xaxis)
|
|
3658
|
+
pivoted = apply_pivot(wf.df, spec)
|
|
3659
|
+
name = "pivot(%s)" % os.path.basename(fpath)
|
|
3660
|
+
self.browser.openDataFrame(pivoted, name)
|
|
3661
|
+
else:
|
|
3662
|
+
self.browser.openFile(fpath)
|
|
3663
|
+
|
|
3664
|
+
for pd in session.get('plots', []):
|
|
3665
|
+
tab_idx = self.tab_widget.count() - 1
|
|
3666
|
+
p = self.tab_widget.widget(tab_idx)
|
|
3667
|
+
if p is None or (isinstance(p, PgWavePlot) and p.wave_data):
|
|
3668
|
+
self._add_plot_tab()
|
|
3669
|
+
tab_idx = self.tab_widget.count() - 1
|
|
3670
|
+
p = self.tab_widget.widget(tab_idx)
|
|
3671
|
+
|
|
3672
|
+
if pd.get('name'):
|
|
3673
|
+
self.tab_widget.setTabText(tab_idx, pd['name'])
|
|
3674
|
+
|
|
3675
|
+
for wd in pd.get('waves', []):
|
|
3676
|
+
wave_name = wd.get('name')
|
|
3677
|
+
style = wd.get('style', 'Lines')
|
|
3678
|
+
wave = self._find_wave(wave_name)
|
|
3679
|
+
if wave:
|
|
3680
|
+
result = p.show_wave(wave, style=style)
|
|
3681
|
+
if result:
|
|
3682
|
+
tag, color = result
|
|
3683
|
+
self.browser.setWaveColor(tag, color)
|
|
3684
|
+
|
|
3685
|
+
if pd.get('xlabel'):
|
|
3686
|
+
p.custom_xlabel = pd['xlabel']
|
|
3687
|
+
p.plot.setLabel('bottom', pd['xlabel'])
|
|
3688
|
+
if pd.get('ylabel'):
|
|
3689
|
+
p.custom_ylabel = pd['ylabel']
|
|
3690
|
+
p.plot.setLabel('left', pd['ylabel'])
|
|
3691
|
+
if pd.get('title'):
|
|
3692
|
+
p.custom_title = pd['title']
|
|
3693
|
+
p.plot.setTitle(pd['title'],
|
|
3694
|
+
color=_get_theme()['title_color'],
|
|
3695
|
+
size='11pt')
|
|
3696
|
+
|
|
3697
|
+
for ann in pd.get('annotations', []):
|
|
3698
|
+
p.addAnnotation(ann['x'], ann['y'], ann['text'])
|
|
3699
|
+
|
|
3700
|
+
def _find_wave(self, name):
|
|
3701
|
+
"""Look up a PgWave by column name across all loaded files."""
|
|
3702
|
+
for fkey, wf in self.browser.files.items():
|
|
3703
|
+
for wn in wf.getWaveNames():
|
|
3704
|
+
if wn == name:
|
|
3705
|
+
tag = wf.getTag(wn)
|
|
3706
|
+
if tag in self.browser._wave_cache:
|
|
3707
|
+
return self.browser._wave_cache[tag]
|
|
3708
|
+
wave = PgWave(wf, wn, self.browser.xaxis)
|
|
3709
|
+
self.browser._wave_cache[tag] = wave
|
|
3710
|
+
return wave
|
|
3711
|
+
return None
|
|
3712
|
+
|
|
3713
|
+
def _close_tab(self, index):
|
|
3714
|
+
widget = self.tab_widget.widget(index)
|
|
3715
|
+
if widget:
|
|
3716
|
+
if isinstance(widget, PgWavePlot):
|
|
3717
|
+
tags = widget.removeAll()
|
|
3718
|
+
for tag in tags:
|
|
3719
|
+
self.browser.clearWaveColor(tag)
|
|
3720
|
+
self.tab_widget.removeTab(index)
|
|
3721
|
+
widget.deleteLater()
|
|
3722
|
+
if self.tab_widget.count() == 0:
|
|
3723
|
+
self._add_plot_tab()
|
|
3724
|
+
|
|
3725
|
+
def _close_current_tab(self):
|
|
3726
|
+
idx = self.tab_widget.currentIndex()
|
|
3727
|
+
if idx >= 0:
|
|
3728
|
+
self._close_tab(idx)
|
|
3729
|
+
|
|
3730
|
+
def _on_analysis(self, atype, wave):
|
|
3731
|
+
wave.reload()
|
|
3732
|
+
x, _ = _to_numeric(wave.x)
|
|
3733
|
+
y, _ = _to_numeric(wave.y)
|
|
3734
|
+
|
|
3735
|
+
if atype == "fft":
|
|
3736
|
+
self._do_fft(wave.key, x, y, wave.xunit, wave.yunit)
|
|
3737
|
+
elif atype == "histogram":
|
|
3738
|
+
self._do_histogram(wave.key, y, wave.yunit)
|
|
3739
|
+
elif atype == "differentiate":
|
|
3740
|
+
self._do_differentiate(wave.key, x, y, wave.xunit, wave.yunit)
|
|
3741
|
+
elif atype == "xvy":
|
|
3742
|
+
self._do_xvy_dialog(wave)
|
|
3743
|
+
|
|
3744
|
+
def _add_analysis_tab(self, title):
|
|
3745
|
+
w = PgAnalysisPlot()
|
|
3746
|
+
w.setFontSize(self._font_size)
|
|
3747
|
+
self.tab_widget.addTab(w, title)
|
|
3748
|
+
self.tab_widget.setCurrentWidget(w)
|
|
3749
|
+
return w
|
|
3750
|
+
|
|
3751
|
+
def _do_fft(self, name, x, y, xunit, yunit):
|
|
3752
|
+
n = len(y)
|
|
3753
|
+
if n < 2:
|
|
3754
|
+
return
|
|
3755
|
+
|
|
3756
|
+
dt = np.mean(np.diff(x))
|
|
3757
|
+
if dt <= 0:
|
|
3758
|
+
return
|
|
3759
|
+
|
|
3760
|
+
window = np.hanning(n)
|
|
3761
|
+
yw = y * window
|
|
3762
|
+
Y = np.fft.rfft(yw)
|
|
3763
|
+
freqs = np.fft.rfftfreq(n, d=dt)
|
|
3764
|
+
|
|
3765
|
+
psd = np.abs(Y) ** 2
|
|
3766
|
+
psd[psd < 1e-300] = 1e-300
|
|
3767
|
+
psd_db = 10.0 * np.log10(psd / np.max(psd))
|
|
3768
|
+
|
|
3769
|
+
freqs = freqs[1:]
|
|
3770
|
+
psd_db = psd_db[1:]
|
|
3771
|
+
|
|
3772
|
+
w = self._add_analysis_tab("FFT: %s" % name)
|
|
3773
|
+
w.plot(freqs, psd_db, pen=pg.mkPen('c', width=2))
|
|
3774
|
+
w.setLabel('bottom', 'Frequency', units='Hz')
|
|
3775
|
+
w.setLabel('left', 'PSD', units='dB')
|
|
3776
|
+
if len(freqs) > 1 and freqs[0] > 0:
|
|
3777
|
+
w.setLogMode(x=True, y=False)
|
|
3778
|
+
|
|
3779
|
+
def _do_histogram(self, name, y, yunit):
|
|
3780
|
+
n = len(y)
|
|
3781
|
+
if n < 2:
|
|
3782
|
+
return
|
|
3783
|
+
|
|
3784
|
+
nbins = max(10, n // 100)
|
|
3785
|
+
counts, edges = np.histogram(y, bins=nbins)
|
|
3786
|
+
centers = (edges[:-1] + edges[1:]) / 2.0
|
|
3787
|
+
|
|
3788
|
+
mu = np.mean(y)
|
|
3789
|
+
sigma = np.std(y)
|
|
3790
|
+
|
|
3791
|
+
w = self._add_analysis_tab("Hist: %s" % name)
|
|
3792
|
+
bar = pg.BarGraphItem(x=centers, height=counts,
|
|
3793
|
+
width=(edges[1] - edges[0]) * 0.85,
|
|
3794
|
+
brush='c', pen='w')
|
|
3795
|
+
w.addItem(bar)
|
|
3796
|
+
|
|
3797
|
+
if sigma > 0:
|
|
3798
|
+
xfit = np.linspace(edges[0], edges[-1], 200)
|
|
3799
|
+
scale = np.max(counts)
|
|
3800
|
+
gauss = scale * np.exp(-0.5 * ((xfit - mu) / sigma) ** 2)
|
|
3801
|
+
w.plot(xfit, gauss, pen=pg.mkPen('r', width=2))
|
|
3802
|
+
|
|
3803
|
+
w.setLabel('bottom', yunit if yunit else name)
|
|
3804
|
+
w.setLabel('left', 'Count')
|
|
3805
|
+
txt = pg.TextItem("μ = %s\nσ = %s" % (_eng(mu, yunit), _eng(sigma, yunit)),
|
|
3806
|
+
color=_get_theme()['text_color'], anchor=(0, 1))
|
|
3807
|
+
w.addItem(txt, ignoreBounds=True)
|
|
3808
|
+
|
|
3809
|
+
_busy = [False]
|
|
3810
|
+
|
|
3811
|
+
def _reposition():
|
|
3812
|
+
if _busy[0]:
|
|
3813
|
+
return
|
|
3814
|
+
_busy[0] = True
|
|
3815
|
+
vr = w.viewRange()
|
|
3816
|
+
txt.setPos(vr[0][0] + 0.02 * (vr[0][1] - vr[0][0]),
|
|
3817
|
+
vr[1][1] - 0.02 * (vr[1][1] - vr[1][0]))
|
|
3818
|
+
_busy[0] = False
|
|
3819
|
+
w.sigRangeChanged.connect(_reposition)
|
|
3820
|
+
_reposition()
|
|
3821
|
+
|
|
3822
|
+
def _do_differentiate(self, name, x, y, xunit, yunit):
|
|
3823
|
+
if len(x) < 2:
|
|
3824
|
+
return
|
|
3825
|
+
dydx = np.gradient(y, x)
|
|
3826
|
+
dy_unit = ""
|
|
3827
|
+
if yunit and xunit:
|
|
3828
|
+
dy_unit = "%s/%s" % (yunit, xunit)
|
|
3829
|
+
|
|
3830
|
+
w = self._add_analysis_tab("d/dx: %s" % name)
|
|
3831
|
+
w.plot(x, dydx, pen=pg.mkPen('m', width=2))
|
|
3832
|
+
w.setLabel('bottom', xunit if xunit else 'x')
|
|
3833
|
+
w.setLabel('left', dy_unit if dy_unit else "d(%s)/dx" % name)
|
|
3834
|
+
|
|
3835
|
+
def _do_xvy_dialog(self, wave_y):
|
|
3836
|
+
f = self.browser.files.getSelected()
|
|
3837
|
+
if not f:
|
|
3838
|
+
return
|
|
3839
|
+
names = list(f.getWaveNames())
|
|
3840
|
+
dlg = _SignalPickerDialog(self, "Select X-axis signal", names,
|
|
3841
|
+
file_label=f.name)
|
|
3842
|
+
if dlg.exec() != QDialog.Accepted:
|
|
3843
|
+
return
|
|
3844
|
+
chosen = dlg.selected()
|
|
3845
|
+
if not chosen:
|
|
3846
|
+
return
|
|
3847
|
+
xwave = PgWave(f, chosen, self.browser.xaxis)
|
|
3848
|
+
xwave.reload()
|
|
3849
|
+
xx, xlabels = _to_numeric(xwave.y)
|
|
3850
|
+
yy, ylabels = _to_numeric(wave_y.y)
|
|
3851
|
+
min_len = min(len(xx), len(yy))
|
|
3852
|
+
xx, yy = xx[:min_len], yy[:min_len]
|
|
3853
|
+
|
|
3854
|
+
w = self._add_analysis_tab("%s vs %s" % (wave_y.key, chosen))
|
|
3855
|
+
w.plot(xx, yy, pen=pg.mkPen('y', width=2))
|
|
3856
|
+
w.setLabel('bottom', chosen)
|
|
3857
|
+
w.setLabel('left', wave_y.key)
|
|
3858
|
+
if xlabels:
|
|
3859
|
+
ticks = list(zip(xx[:min_len], xlabels[:min_len]))
|
|
3860
|
+
_apply_rotated_ticks(w.pw.plotItem, 'bottom', ticks)
|
|
3861
|
+
if ylabels:
|
|
3862
|
+
ticks = list(zip(yy[:min_len], ylabels[:min_len]))
|
|
3863
|
+
w.pw.getAxis('left').setTicks([ticks])
|
|
3864
|
+
|
|
3865
|
+
def openFile(self, fname, sheet_name=None):
|
|
3866
|
+
self.browser.openFile(fname, sheet_name=sheet_name)
|
|
3867
|
+
|
|
3868
|
+
def openDataFrame(self, df, name, **kwargs):
|
|
3869
|
+
self.browser.openDataFrame(df, name, **kwargs)
|
|
3870
|
+
|
|
3871
|
+
|
|
3872
|
+
def _apply_theme(app, theme_name='dark'):
|
|
3873
|
+
_set_active_theme(theme_name)
|
|
3874
|
+
theme = _get_theme()
|
|
3875
|
+
app.setStyle("Fusion")
|
|
3876
|
+
p = QPalette()
|
|
3877
|
+
for role_name, rgb in theme['palette'].items():
|
|
3878
|
+
p.setColor(getattr(QPalette, role_name), QColor(*rgb))
|
|
3879
|
+
p.setColor(QPalette.Disabled, QPalette.Text, QColor(128, 128, 128))
|
|
3880
|
+
p.setColor(QPalette.Disabled, QPalette.ButtonText, QColor(128, 128, 128))
|
|
3881
|
+
app.setPalette(p)
|
|
3882
|
+
pg.setConfigOptions(background=theme['pg_background'],
|
|
3883
|
+
foreground=theme['pg_foreground'])
|
|
3884
|
+
|
|
3885
|
+
|
|
3886
|
+
def _detect_opengl():
|
|
3887
|
+
"""Return True if pyqtgraph's OpenGL backend should be enabled.
|
|
3888
|
+
|
|
3889
|
+
PyOpenGL must be importable (pyqtgraph needs it for the GL-accelerated
|
|
3890
|
+
renderer); without it we stay on the raster backend.
|
|
3891
|
+
|
|
3892
|
+
OpenGL is enabled by default on every platform when PyOpenGL is
|
|
3893
|
+
available. On macOS we additionally log a one-time warning because
|
|
3894
|
+
some pyqtgraph + Qt + Cocoa combinations render an empty plot
|
|
3895
|
+
canvas; the user can disable GL with ``CICSIM_USE_OPENGL=0`` if
|
|
3896
|
+
they hit that. ``CICSIM_USE_OPENGL=1`` force-enables on any
|
|
3897
|
+
platform (still requires PyOpenGL).
|
|
3898
|
+
"""
|
|
3899
|
+
env = os.environ.get("CICSIM_USE_OPENGL")
|
|
3900
|
+
if env == "0":
|
|
3901
|
+
return False
|
|
3902
|
+
try:
|
|
3903
|
+
import OpenGL # noqa: F401
|
|
3904
|
+
except Exception:
|
|
3905
|
+
return False
|
|
3906
|
+
if env == "1":
|
|
3907
|
+
return True
|
|
3908
|
+
if sys.platform == "darwin" and not _detect_opengl._mac_warned:
|
|
3909
|
+
import logging
|
|
3910
|
+
logging.getLogger("cicwave").warning(
|
|
3911
|
+
"Enabling pyqtgraph OpenGL backend on macOS. Some Qt/Cocoa "
|
|
3912
|
+
"builds render an empty plot canvas with OpenGL; if you see "
|
|
3913
|
+
"blank plots, run again with CICSIM_USE_OPENGL=0 to fall "
|
|
3914
|
+
"back to the raster renderer."
|
|
3915
|
+
)
|
|
3916
|
+
_detect_opengl._mac_warned = True
|
|
3917
|
+
return True
|
|
3918
|
+
|
|
3919
|
+
|
|
3920
|
+
_detect_opengl._mac_warned = False
|
|
3921
|
+
|
|
3922
|
+
|
|
3923
|
+
class CmdWavePg:
|
|
3924
|
+
def __init__(self, xaxis, theme='dark'):
|
|
3925
|
+
self.app = QApplication.instance() or QApplication(sys.argv)
|
|
3926
|
+
# Enable OpenGL when available: gives a large speedup when many
|
|
3927
|
+
# curves are on screen (e.g. one curve per file across hundreds of
|
|
3928
|
+
# files). Falls back silently to raster when PyOpenGL is missing
|
|
3929
|
+
# or on platforms where it renders blank plots (macOS).
|
|
3930
|
+
use_gl = _detect_opengl()
|
|
3931
|
+
pg.setConfigOptions(antialias=False, useOpenGL=use_gl)
|
|
3932
|
+
_apply_theme(self.app, theme)
|
|
3933
|
+
effective = xaxis
|
|
3934
|
+
if not effective:
|
|
3935
|
+
effective = _read_saved_default_xaxis()
|
|
3936
|
+
self.xaxis = effective if effective else None
|
|
3937
|
+
self.win = PgWaveWindow(self.xaxis)
|
|
3938
|
+
|
|
3939
|
+
def openFile(self, fname, sheet_name=None):
|
|
3940
|
+
self.win.openFile(fname, sheet_name=sheet_name)
|
|
3941
|
+
|
|
3942
|
+
def openDataFrame(self, df, name, **kwargs):
|
|
3943
|
+
self.win.openDataFrame(df, name, **kwargs)
|
|
3944
|
+
|
|
3945
|
+
def run(self):
|
|
3946
|
+
self.win.show()
|
|
3947
|
+
self.app.exec()
|
|
3948
|
+
|
|
3949
|
+
def exportAndExit(self, fname):
|
|
3950
|
+
"""Export the current plot to a file without showing the GUI."""
|
|
3951
|
+
for ti in range(self.win.tab_widget.count()):
|
|
3952
|
+
widget = self.win.tab_widget.widget(ti)
|
|
3953
|
+
if isinstance(widget, PgWavePlot) and widget.wave_data:
|
|
3954
|
+
if self.win.tab_widget.count() > 1:
|
|
3955
|
+
base, ext = os.path.splitext(fname)
|
|
3956
|
+
out = "%s_%d%s" % (base, ti, ext) if ti > 0 else fname
|
|
3957
|
+
else:
|
|
3958
|
+
out = fname
|
|
3959
|
+
widget._export_matplotlib(out)
|
|
3960
|
+
print("Exported: %s" % out)
|
|
3961
|
+
break
|
|
3962
|
+
self.app.quit()
|