-
Notifications
You must be signed in to change notification settings - Fork 0
/
ListItem.py
395 lines (312 loc) · 13 KB
/
ListItem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# ListItem.py
# by Robin Prillwitz
# 16.3.2020
#
from PyQt5 import QtGui, QtCore, QtWidgets
from scipy import integrate
from scipy.signal import decimate
from scipy.interpolate import make_interp_spline
from scipy.ndimage.filters import gaussian_filter1d
import pyqtgraph as pg
import numpy as np
import pandas as pd
import Config
import Graph
import Exporter
class ListItem(QtWidgets.QWidget):
sigUpdateUI = QtCore.pyqtSignal()
sigCalc = QtCore.pyqtSignal()
sigDeleteMe = QtCore.pyqtSignal(["QObject"])
def __init__(self, color, config=None, parent=None):
super().__init__()
self.parent = parent
if config:
self.config = config
else:
self.config = {
"highlight": False,
"enabled": True,
"cursorEnabled": True,
"zIndex": 0,
"xOffset": 0,
"yOffset": 0,
"xColumn": -1,
"yColumn": -1,
"seperator": Config.SEPERATOR,
"decimal": Config.DECIMAL,
"color": color,
"width": 3,
"interpolation": "linear",
"interpolationAmount": 100,
"integrate": 0,
"filter": 0
}
self.cursor = None
self.plot = None
self.modData = None
self.interpData = None
self.ignore = False
self.dataUpdated = False
self.plot = Graph.Graph(symbol='o', symbolSize=5)
self.plot.sigPositionDelta.connect(self.__applyDelta)
self.cursor = pg.InfiniteLine(angle=0, movable=False)
self.item = QtWidgets.QListWidgetItem()
self.frame = QtWidgets.QWidget()
self.frame.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.frame.customContextMenuRequested.connect(self.__contextMenuEvent)
def __copy__(self):
raise NotImplementedError
# ---------------------------------- private --------------------------------- #
def __applyDelta(self, dx, dy):
self.config["xOffset"] += dx
self.config["yOffset"] += dy
self.recalculate()
self.updateUI()
self.updatePlot()
def __showListItem(self):
raise NotImplementedError
def __contextMenuEvent(self, event):
menu = QtGui.QMenu(self.frame)
menu.addAction(QtGui.QAction('Interpolation Exportieren', self))
menu.addAction(QtGui.QAction('Modifikation Exportieren', self))
menu.addAction(QtGui.QAction('Wave Exportieren', self))
menu.addSeparator()
menu.addAction(QtGui.QAction('Löschen', self))
action = menu.exec_(self.frame.mapToGlobal(event))
if action:
if "Exportieren" in action.text():
Exporter.export(self, action.text())
# self.__export(action.text())
elif action.text() == "Löschen":
self.sigDeleteMe.emit(self)
# ----------------------------------- local ---------------------------------- #
def showError(self, title, message):
error_dialog = QtWidgets.QMessageBox()
with open(Config.getResource("assets/style.qss"), "r") as fh:
error_dialog.setStyleSheet(fh.read())
error_dialog.setIcon(QtWidgets.QMessageBox.Warning)
error_dialog.setWindowTitle("Error")
error_dialog.setText(title)
error_dialog.setInformativeText(message)
error_dialog.setStandardButtons(QtWidgets.QMessageBox.Ok)
for button in error_dialog.buttons():
button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
error_dialog.exec_()
def calculateCommon(self, dlg=None):
x = self.data[self.config["xColumn"]].copy()
y = self.data[self.config["yColumn"]].copy()
if dlg:
dlg += 10
# apply gaussian filter
if self.config["filter"] > 0:
y = gaussian_filter1d(y, sigma=self.config["filter"])
if dlg:
dlg += 5
# calculate numeric integration / differential
if self.config["integrate"] > 0:
for i in range(self.config["integrate"]):
for j, val in enumerate(x):
y[j] = integrate.quad(lambda _: y[j], 0, val)[0]
if dlg:
dlg += 1
elif self.config["integrate"] < 0:
for i in range(abs(self.config["integrate"])):
y = np.gradient(y, x[1] - x[0])
if dlg:
dlg += 1
# Add Offsets
x = x + self.config["xOffset"]
y = y + self.config["yOffset"]
if dlg:
dlg += 10
self.modData = pd.DataFrame({'x': x, 'y': y})
def recalculate(self):
raise NotImplementedError
def updateUI(self):
raise NotImplementedError
def updatePlot(self):
# Calculate all colors
color = QtGui.QColor()
color.setHsvF( self.config["color"][0] / 360,
self.config["color"][1] / 100,
self.config["color"][2] / 100)
pen = pg.mkPen(color=color, width=self.config["width"])
highlightColor = QtGui.QColor()
highlightColor.setHsvF( self.config["color"][0] / 360,
self.config["color"][1] / 100,
self.config["color"][2] / 100, 0.2)
highlightPen = pg.mkPen(color=highlightColor, width=self.config["width"] * 4 + 10)
# set cursors
if self.config["cursorEnabled"]:
self.cursor.setPen(pg.mkPen(color=color, width=max(1, self.config["width"] / 2)))
else:
self.cursor.setPen(pg.mkPen(color=(0, 0, 0, 0), width=0))
# hide if not enabled
if not self.config["enabled"]:
self.plot.setData(pen=None, symbolPen=None, symbolBrush=None, shadowPen=None)
else:
self.cursor.setZValue(self.config["zIndex"])
# set to appropritae interpolation with respect to highlighting
if self.config["interpolation"] == "keine":
if self.config["highlight"]:
self.plot.setData(pen=None, symbolPen=pen, symbolBrush=highlightColor, shadowPen=None)
else:
self.plot.setData(pen=None, symbolPen=pen, symbolBrush=color, shadowPen=None)
else:
self.plot.setData(pen=pen, symbolPen=None, symbolBrush=None, shadowPen=None)
if self.config["highlight"]:
self.plot.setData(shadowPen=highlightPen)
# set respective z indecies
if self.config["highlight"]:
self.cursor.setZValue(Config.Z_IDX_TOP)
self.plot.setZValue(Config.Z_IDX_TOP)
else:
self.cursor.setZValue(self.config["zIndex"])
self.plot.setZValue(self.config["zIndex"])
# if self.dataUpdated:
# self.plot.setData(self.interpData["x"], self.interpData["y"])
if self.config["enabled"]:
self.plot.setDownsampleData(self.interpData["x"], self.interpData["y"])
else:
self.plot.setDownsampleData([0, 0.001], [0, 0])
self.dataUpdated = False
def update(self):
self.recalculate()
self.updatePlot()
self.updateUI()
def applyChange(self, evt, who):
if who == "color":
color = QtGui.QColor()
color.setHsvF(self.config["color"][0] / 360, self.config["color"][1] / 100, self.config["color"][2] / 100)
colorPicker = QtWidgets.QColorDialog()
newColor = colorPicker.getColor(color).getHsvF()
colorPicker.close()
self.config["color"][0] = int(newColor[0] * 360)
self.config["color"][1] = int(newColor[1] * 100)
self.config["color"][2] = int(newColor[2] * 100)
self.settings.findChild(QtWidgets.QPushButton, "color_select_button").setStyleSheet(
"background-color: hsv({:d},{:d}%,{:d}%); color: black;".format(
self.config["color"][0], self.config["color"][1], self.config["color"][2]))
self.frame.findChild(QtWidgets.QCheckBox, "enable_checkbox").setStyleSheet(
"background-color: hsv({:d},{:d}%,{:d}%); color: black;".format(
self.config["color"][0], self.config["color"][1], self.config["color"][2]))
else:
self.config[who] = evt
self.update()
# -------------------------------- recoursive -------------------------------- #
def deselect(self):
if self.config["highlight"] == True:
self.setHighlight(False)
self.updatePlot()
def getSelected(self):
raise NotImplementedError
def getCount(self, i):
return i+1
def deleteSelected(self, plot, selected):
raise NotImplementedError
def updateCursor(self, mousePoint):
infoText = ""
if self.config.get("enabled") or self.config.get("cursorEnabled"):
# find nearest x-sample to mouse-x pos
index = np.clip(
np.searchsorted(self.interpData["x"],
[mousePoint.x()])[0],
0, len(self.interpData["y"]) - 1
)
if self.config.get("cursorEnabled"):
self.cursor.setPos(self.interpData["y"][index])
infoText = "\t <span style='color: hsv({:d},{:d}%,{:d}%);'>y={:5.3f}</span>".format(
self.config["color"][0],
self.config["color"][1],
self.config["color"][2],
self.interpData["y"][index])
return infoText
def autoscale(self):
if self.config["enabled"]:
return {
"xmin": self.interpData["x"][0],
"xmax": self.interpData["x"][len(self.interpData["x"])-1],
"ymin": self.interpData["y"].min(),
"ymax": self.interpData["y"].max()
}
else:
return {
"xmin": np.nan,
"xmax": np.nan,
"ymin": np.nan,
"ymax": np.nan
}
def setHighlight(self, highlight):
self.config["highlight"] = highlight
if isinstance(self.plot, Graph.Graph):
self.plot.setDraggable(highlight)
self.updatePlot()
def setEnabled(self, enabled):
self.config["enabled"] = enabled
self.config["cursorEnabled"] = enabled
self.updatePlot()
def setZIndex(self, zIndex):
raise NotImplementedError
# modified class from user Spencer at
# https://stackoverflow.com/questions/20922836/increases-decreases-qspinbox-value-when-click-drag-mouse-python-pyside
class SuperSpinner(QtWidgets.QLineEdit):
valueChanged = QtCore.pyqtSignal("float")
def __init__(self, parent=None):
super().__init__(parent)
self.setValidator(QtGui.QDoubleValidator(-100000, 100000, Config.PRECISION, parent=self))
self.editingFinished.connect(self.__handleChange)
self.setCursor(QtCore.Qt.SizeHorCursor)
self.beeingEdited = False
self.mouseStartPos = False
self.startValue = 0.0
self.value = 0.0
self.min = self.max = 0.0
self.setValue(0.0, True)
def __handleChange(self):
t = self.text()
if (self.beeingEdited or self.mouseStartPos) and t and float(t):
val = round(float(t), Config.PRECISION)
# self.valueChanged.emit(val)
self.setValue(val, True)
def setRange(self, min, max):
self.min = min
self.max = max
def setValue(self, val, override=False):
val = round(val, Config.PRECISION)
if (not self.beeingEdited or override) and (val != self.value):
self.setText(str(val))
self.value = val
self.valueChanged.emit(self.value)
def focusInEvent(self, QFocusEvent):
self.beeingEdited = True
return super().focusInEvent(QFocusEvent)
def focusOutEvent(self, QFocusEvent):
self.beeingEdited = False
return super().focusOutEvent(QFocusEvent)
def mouseDoubleClickEvent(self, e):
self.setValue(0.0, True)
self.valueChanged.emit(0.0)
def mousePressEvent(self, e):
super().mousePressEvent(e)
self.mouseStartPos = e.pos().x()
self.startValue = self.value
def mouseMoveEvent(self, e):
if self.mouseStartPos:
if e.modifiers() == QtCore.Qt.ShiftModifier:
multiplier = 10
elif e.modifiers() == QtCore.Qt.ControlModifier:
multiplier = 0.01
else:
multiplier = 0.1
valueOffset = ( self.mouseStartPos - e.pos().x() ) * multiplier
value = self.startValue - valueOffset
value = min((self.max, max((self.min, value))))
self.value = value
self.setText(str(value))
self.valueChanged.emit(self.value)
def mouseReleaseEvent(self, e):
super().mouseReleaseEvent(e)
self.mouseStartPos = False
# self.unsetCursor()
def toDict(self):
raise NotImplementedError