pvplot 1.3.4__tar.gz → 1.4.0__tar.gz

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.
@@ -1,11 +1,10 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: pvplot
3
- Version: 1.3.4
3
+ Version: 1.4.0
4
4
  Summary: Plotting tool for EPICS PVs, ADO and LITE parameters
5
5
  Project-URL: Homepage, https://github.com/ASukhanov/pvplot
6
6
  Project-URL: Bug Tracker, https://github.com/ASukhanov/pvplot/issues
7
7
  Author-email: Andrei Sukhanov <cyxandr@gmail.com>
8
- License-File: LICENSE
9
8
  Classifier: License :: OSI Approved :: MIT License
10
9
  Classifier: Operating System :: OS Independent
11
10
  Classifier: Programming Language :: Python :: 3
@@ -0,0 +1,1183 @@
1
+ #!/usr/bin/env python3
2
+ """Plotting package for EPICS PVs, ADO and LITE parameters.
3
+ """
4
+ __version__ = 'v1.4.0 2024-11-12'# fixed: changing dataOptions when plot is stopped
5
+ #TODO: if backend times out the gui is not responsive
6
+ #TODO: move Add Dataset to Dataset options
7
+ #TODO: add dataset arithmetics
8
+
9
+ import sys, os, time, datetime
10
+ timer = time.perf_counter
11
+ import numpy as np
12
+ from qtpy import QtWidgets as QW, QtGui, QtCore
13
+ from qtpy.QtWidgets import QApplication, QMainWindow, QGridLayout
14
+ import pyqtgraph as pg
15
+ from pyqtgraph.graphicsItems.ViewBox.ViewBoxMenu import ViewBoxMenu
16
+ from pyqtgraph import dockarea
17
+ from functools import partial
18
+ from collections import deque
19
+ import traceback
20
+ from importlib import import_module
21
+
22
+ #````````````````````````````Constants````````````````````````````````````````
23
+ X,Y = 0,1
24
+ Scale,Units = 0,1
25
+ TxtColor = (0,128,128)# color of the plot texts
26
+ class color:
27
+ PURPLE = '\033[95m'
28
+ CYAN = '\033[96m'
29
+ DARKCYAN = '\033[36m'
30
+ BLUE = '\033[94m'
31
+ GREEN = '\033[92m'
32
+ YELLOW = '\033[93m'
33
+ RED = '\033[91m'
34
+ BOLD = '\033[1m'
35
+ UNDERLINE = '\033[4m'
36
+ END = '\033[0m'
37
+ #````````````````````````````Helper methods```````````````````````````````````
38
+ def printTime(): return time.strftime("%m%d:%H%M%S")
39
+ def printi(msg): print((f'INFO_PVP@{printTime()}: '+msg))
40
+ def printw(msg): print((f'WARN_PVP@{printTime()}: '+msg))
41
+ def printe(msg): print((f'ERR_PVP@{printTime()}: '+msg))
42
+ def _printv(msg, level=0):
43
+ if PVPlot.pargs.verbose > level:
44
+ print((f'DBG{level}_PVP@{printTime()}: '+msg))
45
+ def printv(msg): _printv(msg, 0)
46
+ def printvv(msg): _printv(msg, 1)
47
+
48
+ def croppedText(txt, limit=200):
49
+ if len(txt) > limit:
50
+ txt = txt[:limit]+'...'
51
+ return txt
52
+ def prettyDict(rDict, lineLimit=75):
53
+ r=''
54
+ for dev,devVals in rDict.items():
55
+ r += dev+'\n'
56
+ for par, parVals in devVals.items():
57
+ r += ' '+par+':'
58
+ if isinstance(parVals,dict):
59
+ r += '\n'
60
+ for attr, attrVal in parVals.items():
61
+ r += croppedText(f' {attr}: {attrVal}',lineLimit)+'\n'
62
+ else:
63
+ r += croppedText(f' {parVals}',lineLimit)+'\n'
64
+ return r
65
+
66
+ try: from . import cad_epics as EPICSAccess
67
+ except Exception as e:
68
+ EPICSAccess = None
69
+ printw(f'EPICS devices are not supported on this host: {e}')
70
+ try:
71
+ import liteaccess as liteAccess
72
+ LITEAccess = liteAccess.Access
73
+ print(f'liteAccess {liteAccess.__version__}')
74
+ except Exception as e:
75
+ printw(f'LITE devices are not supported on this host: {e}')
76
+ LITEAccess = None
77
+ try:
78
+ from cad_io import adoaccess
79
+ ADOAccess = adoaccess.IORequest()
80
+ except Exception as e:
81
+ printw(f'ADO devices are not supported on this host: {e}')
82
+ ADOAccess = None
83
+
84
+ def get_pv(adopar:str, prop='value'):
85
+ #print(f'>get_pv {adopar}')
86
+ adopar, vslice = split_slice(adopar)
87
+ try:
88
+ access = PVPlot.access[adopar[:2]]
89
+ adopar = adopar[2:]
90
+ except:
91
+ access = PVPlot.ADOAccess
92
+ if access is None:
93
+ printe(f'No access method for `{adopar}`')
94
+ sys.exit(1)
95
+ pvTuple = tuple(adopar.rsplit(':',1))
96
+ rd = access.get(pvTuple)[pvTuple]
97
+ val = rd['value']
98
+ try:
99
+ shape = val.shape
100
+ if len(shape) > 2:
101
+ printe(f'2+dimensional arrays not supported for {dev,par}')
102
+ return None
103
+ except:
104
+ # val does not have attribute shape
105
+ pass
106
+ try:
107
+ ts = rd['timestamp']# EPICS and LITE
108
+ except: # ADO
109
+ ts = rd['timestampSeconds'] + rd['timestampNanoSeconds']*1.e-9
110
+
111
+ #printv(f"get_pv {adopar}: {rd['value']} {vslice}")
112
+ if vslice is not None:
113
+ val = val[vslice[0]:vslice[1]]
114
+ return val, ts
115
+
116
+ def change_plotOption(curveName,color=None,width=None,symbolSize=None):
117
+ dataset = MapOfDatasets.dtsDict[curveName]
118
+ if color != None:
119
+ dataset.pen.setColor(color)
120
+ if width != None:
121
+ dataset.width = width
122
+ dataset.pen.setWidth(width)
123
+ if symbolSize!=None:
124
+ dataset.symbolSize = symbolSize
125
+ dataset.plot(time.time())
126
+
127
+ def split_slice(parNameSlice):
128
+ """Decode 'name[n1:n2]' to 'name',[n1:n2]"""
129
+ devParSlice = parNameSlice.split('[',1)
130
+ if len(devParSlice) < 2:
131
+ return devParSlice[0], None
132
+ sliceStr = devParSlice[1].replace(']','')
133
+ vrange = sliceStr.split(':',1)
134
+ r0 = int(vrange[0])
135
+ if len(vrange) == 1:
136
+ vslice = (r0, r0+1)
137
+ else:
138
+ vslice = (r0, int(vrange[1]))
139
+ return devParSlice[0], vslice
140
+
141
+ def get_statistics():
142
+ statList = []
143
+ for dataset in MapOfDatasets.dtsDict.values():
144
+ #if dataset.dockNum != PVPlot.statDock:
145
+ # continue
146
+ s = dataset.get_statistics()
147
+ #print(f's: {s}')
148
+ if len(s) != 0:
149
+ for key,v in s.items():
150
+ statList.append([key, *v["xrange"],
151
+ f'{v["mean"]:.6g}', f'{v["std"]:.6g}',
152
+ f'{v["p2p"]:.6g}'])
153
+ return statList
154
+
155
+ class PopupHelp(QW.QWidget):
156
+ """ This "window" is a QWidget. If it has no parent, it
157
+ will appear as a free-floating window as we want.
158
+ Note: The created window will not be closed on app exit.
159
+ To make it happen, the MainWindow should call close this widget in its closeEvent()
160
+ """
161
+ def __init__(self):
162
+ super().__init__()
163
+ qr = PVPlot.qWin.geometry()
164
+ self.setGeometry(QtCore.QRect(qr.x(), qr.y(), 0, 0))
165
+ self.setWindowTitle('PVPlot short help')
166
+ layout = QW.QVBoxLayout()
167
+ self.label = QW.QLabel()
168
+ self.label.setTextInteractionFlags(QtCore.Qt.TextSelectableByMouse)
169
+ layout.addWidget(self.label)
170
+ self.setLayout(layout)
171
+
172
+ class TableModel(QtCore.QAbstractTableModel):
173
+ def __init__(self, data, headers):
174
+ super(TableModel, self).__init__()
175
+ self._data = data
176
+ self.headers = headers
177
+
178
+ def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role=QtCore.Qt.DisplayRole):
179
+ if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Horizontal:
180
+ try: r = self.headers[section]
181
+ except: r = f's{section+1}'
182
+ return r
183
+
184
+ def data(self, index, role):
185
+ if role == QtCore.Qt.DisplayRole:
186
+ # See below for the nested-list data structure.
187
+ # .row() indexes into the outer list,
188
+ # .column() indexes into the sub-list
189
+ return self._data[index.row()][index.column()]
190
+
191
+ def rowCount(self, parent=QtCore.QModelIndex()):
192
+ # The length of the outer list.
193
+ return len(self._data)
194
+
195
+ def columnCount(self, parent=QtCore.QModelIndex()):
196
+ # The following takes the first sub-list, and returns
197
+ # the length (only works if all rows are an equal length)
198
+ return len(self._data[0])
199
+
200
+ def refresh_data(self, data):
201
+ self._data = data
202
+ #print(f'>refresh_data: {self._data}')
203
+ topLeft = self.createIndex(0, 0)
204
+ bottomRight = self.createIndex(self.rowCount(), self.columnCount())
205
+ self.dataChanged.emit(topLeft, bottomRight)
206
+
207
+ class TableWindow(QW.QWidget):
208
+ """
209
+ This "window" is a QWidget. If it has no parent, it
210
+ will appear as a free-floating window.
211
+ """
212
+ def __init__(self, data, headers=[]):
213
+ super().__init__()
214
+ self.setWindowTitle('Statistics')
215
+ layout = QW.QVBoxLayout()
216
+ self.table = QW.QTableView()
217
+ self.model = TableModel(data, headers)
218
+ self.table.setModel(self.model)
219
+ hh = self.table.horizontalHeader()
220
+ #DNW#hh.setSectionResizeMode(QW.QHeaderView.ResizeToContents)
221
+ #hh.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
222
+ hh.setSectionResizeMode(0, QW.QHeaderView.ResizeMode.ResizeToContents)
223
+ hh.setSectionResizeMode(1, QW.QHeaderView.ResizeMode.ResizeToContents)
224
+ hh.setSectionResizeMode(2, QW.QHeaderView.ResizeMode.ResizeToContents)
225
+ layout.addWidget(self.table)
226
+ self.setLayout(layout)
227
+
228
+ qr = PVPlot.qWin.geometry()
229
+ '''
230
+ vh = self.table.verticalHeader()
231
+ extra = (30,30)
232
+ sz = (hh.length() + vh.width() + extra[X],
233
+ vh.length() + hh.height() + extra[Y])
234
+ self.setGeometry(QtCore.QRect(qr.x(), qr.y(), sz[0], sz[1]))
235
+ '''
236
+ self.move(qr.x(), qr.y())
237
+ self.table.setShowGrid(False)
238
+ self.table.setSizeAdjustPolicy(
239
+ QW.QAbstractScrollArea.AdjustToContents)
240
+ #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
241
+ def update_data():
242
+ """ called on QtCore.qTimer() event to update plots."""
243
+ tstart = timer()
244
+ tt = round(time.time(),6)
245
+
246
+ for dataset in MapOfDatasets.dtsDict.values():
247
+ dataset.update_plot()
248
+ if dataset.dataChanged:
249
+ if tt > dataset.lastPlotted + PVPlot.minPlottingPeriod:
250
+ dataset.lastPlotted = tt
251
+ dataset.plot(tt)
252
+
253
+ if PVPlot.perfmon:
254
+ v = timer()-tstart
255
+ print('update time:'+str(timer()-tstart))
256
+
257
+ def set_legend(dockNum:int, state:bool):
258
+ if state: # legend enabled
259
+ printv(f'add legends to dock{dockNum}')
260
+ widget = PVPlot.mapOfPlotWidgets[dockNum]
261
+ listOfItems = widget.getPlotItem().listDataItems()
262
+ l = pg.LegendItem((100,60), offset=(70,30), labelTextColor=TxtColor) # args are (size, offset)
263
+ l.setParentItem(widget.graphicsItem())
264
+ PVPlot.legend[dockNum] = l
265
+ for item in listOfItems:
266
+ iname = item.name()
267
+ printv(f'set_legend {iname} in dock{dockNum}')
268
+ l.addItem(item, iname)
269
+ else: # legend disabled
270
+ printv(f'remove legend from dock{dockNum}')
271
+ try:
272
+ PVPlot.legend[dockNum].scene().removeItem(PVPlot.legend[dockNum])
273
+ del PVPlot.legend[dockNum]
274
+ except Exception as e:
275
+ printe('failed to remove legend '+dockNum+':'+str(e))
276
+ #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
277
+ #```````````````````````````DateAxis class: time scale for bottom plot scale``
278
+ class DateAxis(pg.AxisItem):
279
+ def tickStrings(self, values, scale, spacing):
280
+ strns = []
281
+ if len(values) == 0:
282
+ return ''
283
+ rng = max(values)-min(values)
284
+ #if rng < 120:
285
+ # return pg.AxisItem.tickStrings(self, values, scale, spacing)
286
+ if rng < 3600*24:
287
+ string = '%H:%M:%S'
288
+ elif rng >= 3600*24 and rng < 3600*24*30:
289
+ string = '%d'
290
+ elif rng >= 3600*24*30 and rng < 3600*24*30*24:
291
+ string = '%b'
292
+ elif rng >=3600*24*30*24:
293
+ string = '%Y'
294
+ for x in values:
295
+ try:
296
+ strns.append(time.strftime(string, time.localtime(x)))
297
+ except ValueError: ## Windows can't handle dates before 1970
298
+ strns.append('')
299
+ return strns
300
+ #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
301
+ #````````````````````````````Datasets`````````````````````````````````````````
302
+ class Dataset():
303
+ """ dataset storage, keeps everything what is necessary to plot the curve.
304
+ """
305
+ def __init__(self, dockNum:int, name, paramAndCount):
306
+ self.dockNum = dockNum
307
+ self.name = name
308
+ self.adoPars = paramAndCount # list of max 2 of (adoPar,count)
309
+ self.plotItem = None # plotting object PlotDataItem
310
+ self.pen = None # current pen
311
+ self.width = 1 # pen width
312
+ self.lastTimePlotted = 0.
313
+ self.lastTimeUpdated = 0.
314
+ self.plotWidget = None
315
+ self.viewBox = None
316
+ # members for stripchart plot
317
+ self.viewXSize = 9E9# Wed Mar 14 2255 16:00:00
318
+ self.viewXRange = [0., 9E9]
319
+ self.scrolling = False
320
+
321
+ # plotting options, described in
322
+ # http://www.pyqtgraph.org/documentation/graphicsItems/plotdataitem.html#pyqtgraph.PlotDataItem
323
+ self.connect = None
324
+ self.shadowPen = None
325
+ self.fillLevel = None
326
+ self.fillBrush = None
327
+ self.stepMode = None
328
+ self.symbol = None
329
+ self.symbolPen = None
330
+ self.symbolBrush = None
331
+ self.symbolSize = None
332
+ self.pxMode = None
333
+ self.timeAxis = False
334
+ self.statistics = {}
335
+ self.enabled = True
336
+ self.lastPlotted = 0
337
+
338
+ # ``````````````````` Add plotItem ``````````````````````````````````````
339
+ #dockNum = name.split('.')[0]
340
+ printv('plotItem for: '+str([s for s in self.adoPars])+', name:'+str(dockNum))
341
+ initialWidth = 16
342
+ self.data = [np.empty(initialWidth),np.empty(initialWidth)]# [X,U] data storage
343
+ self.dataPtr = 0
344
+ count = self.adoPars[0][1] #
345
+ printv(f'adoPars,count: {self.adoPars,count}')
346
+ isCorrelationPlot = len(self.adoPars) >= 2
347
+
348
+ # assign the plotwidget
349
+ if dockNum in PVPlot.mapOfPlotWidgets:
350
+ # dock already exist, use the existing plotwidget
351
+ self.plotWidget = PVPlot.mapOfPlotWidgets[dockNum]
352
+ self.viewBox = self.plotWidget.getViewBox()
353
+ else:
354
+ # viewbox for new dock need to be created
355
+ # create vewBox with plotwidget
356
+ self.viewBox = CustomViewBox(dockNum, self)
357
+ self.viewBox.setMouseMode(self.viewBox.RectMode)
358
+ self.viewBox.sigRangeChangedManually.connect(self.xrangeChanged)
359
+ printv(f'Creating new dock{dockNum}')
360
+ title = None
361
+ if count == 1 and not isCorrelationPlot:
362
+ self.plotWidget = pg.PlotWidget(title=title, viewBox=self.viewBox,
363
+ axisItems={'bottom':DateAxis(orientation='bottom')})
364
+ self.timeAxis = True
365
+ if dockNum != 0:
366
+ self.plotWidget.setXLink(PVPlot.mapOfPlotWidgets[0])
367
+ else:
368
+ self.plotWidget = pg.PlotWidget(title=title, viewBox=self.viewBox)
369
+ #self.plotWidget.showGrid(True,True)
370
+ PVPlot.mapOfPlotWidgets[dockNum] = self.plotWidget
371
+ PVPlot.mapOfDocks[dockNum].addWidget(self.plotWidget)
372
+ printv(f'docks: {PVPlot.mapOfDocks.keys()}, widgets: {PVPlot.mapOfPlotWidgets.keys()}')
373
+
374
+ xl,yl = 'LabelX','LabelY'
375
+ try:
376
+ c = PVPlot.config
377
+ xl,yl = c.XLABEL,c.YLABEL
378
+ except: pass
379
+ #print(f'd:{self.dockNum}, X,Y: {xl,yl}')
380
+ if self.dockNum == 0 and yl != 'LabelY':
381
+ self.plotWidget.setLabel('left', yl)
382
+ if self.dockNum == 0 and xl != 'LabelX':
383
+ self.plotWidget.setLabel('bottom', xl)
384
+ else:
385
+ if isCorrelationPlot:
386
+ self.plotWidget.setLabel('bottom',self.adoPars[1][0])
387
+ elif count == 1:
388
+ self.plotWidget.setLabel('bottom','time', units='date', unitPrefix='')
389
+ else:
390
+ self.plotWidget.setLabel('bottom',PVPlot.scaleUnits[X][Units])
391
+
392
+ # set X and Y ranges
393
+ rangeMap = {X: (PVPlot.pargs.xrange, self.plotWidget.setXRange),
394
+ Y: (PVPlot.pargs.yrange, self.plotWidget.setYRange)}
395
+ for axis,v in rangeMap.items():
396
+ r,func = v
397
+ if r is None:
398
+ continue
399
+ r = [float(i) for i in v[0].split(':')]
400
+ func(*r)
401
+
402
+ # create plotItem with proper pen
403
+ lineNumber = len(PVPlot.mapOfPlotWidgets[self.dockNum].getPlotItem().listDataItems())
404
+ self.pen = pg.mkPen(lineNumber)
405
+ if self.adoPars[0][0] == '':
406
+ printv('no dataset - no plotItem')
407
+ else:
408
+ self.plotItem = pg.PlotDataItem(name=name, pen=self.pen)
409
+
410
+ if self.plotItem:
411
+ self.plotWidget.addItem(self.plotItem)
412
+ self.lastTimePlotted = 0.
413
+
414
+ def add_plot(self):
415
+ self.plotWidget.addItem(self.plotItem)
416
+
417
+ def remove_plot(self):
418
+ self.plotWidget.removeItem(self.plotItem)
419
+
420
+ def __str__(self):
421
+ return f'Dataset {self.name}, x: {self.data[X].shape}'
422
+
423
+ def xrangeChanged(self):
424
+ viewRange = self.viewBox.viewRange()
425
+ self.viewXRange = viewRange[X]
426
+ viewlimit = self.viewXRange[1]
427
+ self.viewXSize = viewlimit - self.viewXRange[0]
428
+ self.viewBox.rangestack.append(viewRange)
429
+ self.viewBox.unzooming = False
430
+ #print(f'>rangestack {len(self.viewBox.rangestack)}')
431
+ self.scrolling = (self.viewBox is not None)\
432
+ and viewlimit > self.data[X][self.dataPtr-1]
433
+ #print(f'scrolling: {self.scrolling}')
434
+
435
+ def shift_viewXRange(self):
436
+ if self.viewBox.state['autoRange'][X]:
437
+ return
438
+ dx = self.viewXSize*PVPlot.padding
439
+ self.viewXRange[0] += dx
440
+ self.viewXRange[1] += dx
441
+ #print(f'>shift_viewXRange: {self.viewXRange[0], self.viewXRange[1]}')
442
+ self.viewBox.setXRange(self.viewXRange[0], self.viewXRange[1])
443
+
444
+ def plot(self, ts):
445
+ # Plot the dataset. It may be several updates between these calls.
446
+ if self.lastTimePlotted == ts:
447
+ return
448
+ #printv(f'>plot: {self.name}')
449
+ self.lastTimePlotted = ts
450
+ #print(f'>plot: {self.name, {self.dataPtr}, round(ts,3)}')
451
+ x = self.data[X][:self.dataPtr]
452
+ y = self.data[Y][:self.dataPtr]
453
+ pen = self.pen if self.width else None
454
+ #printvv(f'x:{x}\ny:{y}')
455
+ self.plotItem.setData(x=x, y=y,
456
+ pen = pen,
457
+ #TODO:connect = self.connect,
458
+ #TODO:shadowPen = self.shadowPen,
459
+ #TODO:fillLevel = self.fillLevel,
460
+ #TODO:fillBrush = self.fillBrush,
461
+ #TODO:stepMode = self.stepMode,
462
+ symbol = self.symbol,
463
+ #TODO:symbolPen = self.symbolPen,
464
+ symbolPen = None,
465
+ symbolBrush = self.symbolBrush,
466
+ #TODO:symbolBrush = self.pen.color(),
467
+ symbolSize = self.symbolSize,
468
+ #TODO:pxMode = self.pxMode,
469
+ )
470
+
471
+ def update_plot(self):
472
+ curvePars = self.adoPars
473
+ yd,ts = None,None
474
+ try:
475
+ #Limitation: only one (first) curve will be plotted
476
+ yd, ts = get_pv(curvePars[0][0])
477
+ except Exception as e:
478
+ #printv('got '+str((yd,ts))+', from:'+str(curvePars[0][0])+', except:'+str(e))
479
+ printw(f'Exception getting {curvePars[0][0]}: {e}')
480
+ return
481
+ if ts:
482
+ if ts == self.lastTimeUpdated:
483
+ self.dataChanged = False
484
+ #printv(f'curve {self.name} did not change {round(ts,3)}')
485
+ return
486
+ printv(f'update_plot: {self.name,curvePars}')
487
+ self.dataChanged = True
488
+ self.lastTimeUpdated = ts
489
+ #print(f'update {self.name, round(ts,3), round(self.lastTimePlotted,3)}')
490
+ try:
491
+ l = len(yd)
492
+ if l == 1: yd = yd[0]
493
+ except:
494
+ l = 1
495
+
496
+ # Evaluate X and Y arrays
497
+ if l > 1:
498
+ #printv('Array plot')
499
+ self.data[Y] = np.array(yd)
500
+ if len(curvePars) > 1:
501
+ # use last item as horizontal axis
502
+ self.data[X],*_ = get_pv(curvePars[-1][0])
503
+ else:
504
+ # scaled sample number
505
+ self.data[X] = np.arange(len(yd))*PVPlot.scaleUnits[X][Scale]
506
+ self.dataPtr = len(yd)
507
+ self.plot(ts)
508
+ else:
509
+ # the plot is scrolling or correlation plot
510
+ ptr = self.dataPtr
511
+ if ptr >= PVPlot.pargs.limit:
512
+ # do not extent the data buffer, roll it over instead
513
+ self.data[X] = np.roll(self.data[X],-1)
514
+ self.data[Y] = np.roll(self.data[Y],-1)
515
+ ptr -= 1
516
+ self.data[Y][ptr] = yd
517
+ if len(curvePars) > 1:
518
+ #print('Correlation Plot')
519
+ printv(f'correlation plot: {curvePars[1][0]}')
520
+ try:
521
+ v,*_ = get_pv(curvePars[1][0])
522
+ try: v = v[0]
523
+ except: pass
524
+ self.data[X][ptr] = v
525
+ except Exception as e:
526
+ printe('no data from '+str(curvePars[1][0]))
527
+ else:
528
+ # scrolling plot with time scale
529
+ #print(f'ts: {round(ts,3), round(self.viewXRange[1],3)}')
530
+ if self.scrolling and ts > self.viewXRange[1]:
531
+ self.shift_viewXRange()
532
+ self.data[X][ptr] = ts
533
+ ptr += 1
534
+ self.dataPtr = ptr
535
+
536
+ # re-alocate arrays,if necessary
537
+ if (ptr >= self.data[Y].shape[0]):
538
+ #print(f'realllocate: ptr: {ptr,self.data[Y].shape[0]}')
539
+ tmp = self.data
540
+ self.data = [np.empty(self.data[Y].shape[0] * 2),
541
+ np.empty(self.data[Y].shape[0] * 2)]
542
+ self.data[Y][:tmp[Y].shape[0]] = tmp[Y]
543
+ self.data[X][:tmp[X].shape[0]] = tmp[X]
544
+ #printi(f'adjust {self.name} from {tmp[X].shape} to {self.data[X].shape}')
545
+
546
+ def _visibleRange(self):
547
+ npt = self.dataPtr
548
+ #print(f'viewRange={self.viewBox.viewRange()}')
549
+ xr = self.viewBox.viewRange()[X]
550
+ for ileft in range(npt):
551
+ if self.data[X][ileft] > xr[0]:
552
+ break
553
+ #print(f'last={self.data[X][npt-2], self.data[X][npt-1]}')
554
+ for i in range(npt):
555
+ if self.data[X][npt-i-1] < xr[1]:
556
+ break
557
+ iright = npt -i
558
+ return ileft,iright
559
+
560
+ def show_yProjection(self):
561
+ ileft,iright = self._visibleRange()
562
+ h = np.histogram(self.data[Y][ileft:iright],100)
563
+ PVPlot.yProjectionPlotItem.setData(h[1],h[0],pen='b',stepMode=True)
564
+
565
+ def get_statistics(self):
566
+ ileft,iright = self._visibleRange()
567
+ parname = self.adoPars[0][0]
568
+ r = {parname:{}}
569
+ rp = r[parname]
570
+ rp['xrange'] = (ileft,iright)
571
+ y = np.array(self.data[Y][ileft:iright])
572
+ rp['mean'] = y.mean().astype('f4')
573
+ rp['std'] = y.std().astype('f4')
574
+ rp['p2p'] = (y.max() - y.min()).astype('f4')
575
+ return r
576
+
577
+ def get_visibleData(self):
578
+ ileft,iright = self._visibleRange()
579
+ r = (self.data[X][ileft:iright], self.data[Y][ileft:iright])
580
+ return r
581
+
582
+ class MapOfDatasets():
583
+ """Global dictionary of Datasets, provides safe methods to add and remove
584
+ the datasets"""
585
+ dtsDict = {} #{curveName:dataset,,,}
586
+
587
+ def add(dockNum:int, mapOfCurves):
588
+ """add new datasets, the adoPars is the space delimited string of
589
+ source ado:parameters."""
590
+ printv(f'>MapOfDatasets.add({dockNum, mapOfCurves})')
591
+ for i, kv in enumerate(mapOfCurves.items()):
592
+ curveName,devList = kv
593
+ printv(f'curveName: {curveName,devList}')
594
+ if isinstance(devList,str):
595
+ devList = [devList]
596
+ else:
597
+ devList = list(devList)
598
+ devList.reverse()
599
+ pnameAndCount = []
600
+ for adoPar in devList:
601
+ adoPar = adoPar.lstrip()#remove leading whitespaces
602
+ printv(f'adoPar: {adoPar}')
603
+ if adoPar.startswith('device('):
604
+ e = adoPar.index(')')
605
+ rest = adoPar[e+1:]# it could be arithmetics
606
+ adoPar = adoPar[7:e]
607
+ try:
608
+ printv(f'check if {adoPar}, is alive')
609
+ valts = get_pv(adoPar) # check if parameter is alive
610
+ if valts is None:
611
+ printw('Could not add {adoPar}')
612
+ return 2
613
+ except Exception as e:
614
+ printw(f'Exception in getting parameter {adoPar}: {e}')
615
+ return 1
616
+ val,ts = valts
617
+ try: count = len(val)
618
+ except: count = 1
619
+ pnameAndCount.append((adoPar,count))
620
+ printv('adding '+str(pnameAndCount)+' to datasets['+curveName+']')
621
+ MapOfDatasets.dtsDict[curveName] = Dataset(dockNum, curveName, pnameAndCount)
622
+ PVPlot.mapOfCurves[dockNum].append(curveName)
623
+ printv(f'MapOfDatasets: {[(k,v.adoPars) for k ,v in MapOfDatasets.dtsDict.items()]}')
624
+ return 0
625
+
626
+ def remove(name):
627
+ printv('MapOfDatasets.remove '+name)
628
+ dataset = MapOfDatasets.dtsDict[name]
629
+ dataset.plotWidget.removeItem(dataset.plotItem)
630
+ del MapOfDatasets.dtsDict[dataset.name]
631
+ #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
632
+ #`````````````````````````````````````````````````````````````````````````````
633
+ class CustomViewBox(pg.ViewBox):
634
+ """ defines actions, activated on the right mouse click in the dock
635
+ """
636
+ def __init__(self, dockNum:int, dataset):
637
+ #self.dockNum = kwds['name'] # cannot use name due to an issue in demo
638
+ #del kwds['name'] # the name in ViewBox.init fails in demo
639
+ self.dockNum = dockNum
640
+ self.dataset = dataset# master dataset, it defines horizontal axis
641
+ #print('CustomViewBox: '+str(self.dockNum))
642
+
643
+ # call the init method of the parent class
644
+ super(CustomViewBox, self).__init__()
645
+ self.setDefaultPadding(0.)# standard is 0.02
646
+
647
+ # IMPORTANT: menu creation is deferred because it is expensive
648
+ # and often the user will never see the menu anyway.
649
+ self.menu = None
650
+ self.cursors = set()
651
+ self.unzooming = False
652
+ self.rangestack = deque([],10) #stack of 10 of view ranges
653
+
654
+ #v32#def mouseClickEvent(self, ev) removed, due to blank exports
655
+
656
+ def raiseContextMenu(self, ev):
657
+ # Let the scene add on to the end of our context menu
658
+ menuIn = self.getContextMenus()
659
+ menu = self.scene().addParentContextMenus(self, menuIn, ev)
660
+ menu.popup(ev.screenPos().toPoint())
661
+ return True
662
+
663
+ def getContextMenus(self, event=None):
664
+ """ This method will be called when this item's children want to raise
665
+ a context menu that includes their parents' menus.
666
+ """
667
+ if self.menu:
668
+ printv('menu exist')
669
+ return self.menu
670
+ printv('getContextMenus for '+str(self.dockNum))
671
+ self.menu = ViewBoxMenu(self)
672
+ self.menu.setTitle(f'dock{self.dockNum} options..')
673
+
674
+ # unzoom last
675
+ unzoom = self.menu.addAction("&UnZoom")
676
+ unzoom.triggered.connect(lambda: self.unzoom())
677
+
678
+ # Datasets options dialog
679
+ setDatasets = self.menu.addAction('Datasets &Options')
680
+ setDatasets.triggered.connect(self.changed_datasetOptions)
681
+
682
+ _statistics = self.menu.addAction('Show &Mean,sigma')
683
+ _statistics.triggered.connect(self.show_statistics)
684
+
685
+ _yProjection = self.menu.addAction('Show &YProjection')
686
+ _yProjection.triggered.connect(self.show_yProjection)
687
+
688
+ cursorMenu = self.menu.addMenu('Add &Cursor')
689
+ for cursor in ['Vertical','Horizontal']:
690
+ action = cursorMenu.addAction(cursor)
691
+ action.triggered.connect(partial(self.cursorAction,cursor))
692
+
693
+ # popup help
694
+ phelp = self.menu.addAction("&help")
695
+ phelp.triggered.connect(lambda: PVPlot.actionHelp())
696
+
697
+ # Labels
698
+ labelX = QW.QWidgetAction(self.menu)
699
+ self.labelXGui = QW.QLineEdit('LabelX')
700
+ self.labelXGui.returnPressed.connect(
701
+ lambda: self.set_label('bottom',self.labelXGui))
702
+ labelX.setDefaultWidget(self.labelXGui)
703
+ self.menu.addAction(labelX)
704
+ labelY = QW.QWidgetAction(self.menu)
705
+ self.labelYGui = QW.QLineEdit('LabelY')
706
+ self.labelYGui.returnPressed.connect(
707
+ lambda: self.set_label('left',self.labelYGui))
708
+ labelY.setDefaultWidget(self.labelYGui)
709
+ self.menu.addAction(labelY)
710
+
711
+ backgroundAction = QW.QWidgetAction(self.menu)
712
+ backgroundGui = QW.QCheckBox('Black background')
713
+ backgroundGui.stateChanged.connect(
714
+ lambda x: self.setBackgroundColor(\
715
+ 'k' if x == QtCore.Qt.Checked else 'w'))
716
+ backgroundAction.setDefaultWidget(backgroundGui)
717
+ self.menu.addAction(backgroundAction)
718
+
719
+ legenAction = QW.QWidgetAction(self.menu)
720
+ legendGui = QW.QCheckBox('Legend')
721
+ legendGui.setChecked(True)
722
+ legendGui.stateChanged.connect(lambda x: self.set_legend(x))
723
+ legenAction.setDefaultWidget(legendGui)
724
+ self.menu.addAction(legenAction)
725
+
726
+ runAction = QW.QWidgetAction(self.menu)
727
+ runWidget = QW.QCheckBox('&Stop')
728
+ runWidget.setChecked(PVPlot.stopped)
729
+ runWidget.stateChanged.connect(lambda x: self.set_stop(x))
730
+ runAction.setDefaultWidget(runWidget)
731
+ self.menu.addAction(runAction)
732
+
733
+ sleepTimeMenu = self.menu.addMenu('Sleep&Time')
734
+ sleepTimeAction = QW.QWidgetAction(sleepTimeMenu)
735
+ sleepTimeWidget = QW.QDoubleSpinBox()
736
+ sleepTimeWidget.setValue(PVPlot.pargs.sleepTime)
737
+ sleepTimeWidget.setRange(0.001,100)
738
+ sleepTimeWidget.setSuffix(' s')
739
+ sleepTimeWidget.setSingleStep(.1)
740
+ sleepTimeWidget.valueChanged.connect(lambda x: self.set_sleepTime(x))
741
+ sleepTimeAction.setDefaultWidget(sleepTimeWidget)
742
+ sleepTimeMenu.addAction(sleepTimeAction)
743
+ return self.menu
744
+
745
+ def cursor_text(self, pos, horizontal):
746
+ #print(f'timeAxis = {self.dataset.timeAxis}')
747
+ if (not horizontal) and self.dataset.timeAxis:
748
+ txt = datetime.datetime.fromtimestamp(pos).strftime('%H:%M:%S')
749
+ else:
750
+ txt = f'{pos:.4g}'
751
+ return txt
752
+
753
+ def cursorAction(self, direction):
754
+ angle = {'Vertical':90, 'Horizontal':0}[direction]
755
+ pwidget = PVPlot.mapOfPlotWidgets[self.dockNum]
756
+ vid = {'Vertical':0, 'Horizontal':1}[direction]
757
+ vr = pwidget.getPlotItem().viewRange()
758
+ #print(f'vid: {vid,vr[vid]}')
759
+ pos = (vr[vid][1] + vr[vid][0])/2.
760
+ pen = pg.mkPen(color='b', width=1, style=QtCore.Qt.DotLine)
761
+ cursor = pg.InfiniteLine(pos=pos, pen=pen, movable=True, angle=angle
762
+ , label=self.cursor_text(pos,vid), labelOpts={'color':TxtColor})#,'fill':(0,255,255)})
763
+ cursor.sigPositionChangeFinished.connect(\
764
+ (partial(self.cursorPositionChanged,cursor)))
765
+ self.cursors.add(cursor)
766
+ pwidget.addItem(cursor)
767
+ self.cursorPositionChanged(cursor)
768
+
769
+ def cursorPositionChanged(self, cursor):
770
+ pos = cursor.value()
771
+ horizontal = cursor.angle == 0.
772
+ pwidget = PVPlot.mapOfPlotWidgets[self.dockNum]
773
+ viewRange = pwidget.getPlotItem().viewRange()[horizontal]
774
+ if pos > viewRange[1]:
775
+ pwidget.removeItem(cursor)
776
+ self.cursors.remove(cursor)
777
+ else:
778
+ cursor.label.setText(self.cursor_text(pos, horizontal))
779
+
780
+ def changed_datasetOptions(self):
781
+ """Dialog Plotting Options"""
782
+ dlg = QW.QDialog()
783
+ dlg.setWindowTitle(f"Dataset of dock{self.dockNum}")
784
+ dlg.setWindowModality(QtCore.Qt.ApplicationModal)
785
+ rowCount,columnCount = 0,8
786
+ tbl = QW.QTableWidget(rowCount, columnCount, dlg)
787
+ tbl.setHorizontalHeaderLabels(
788
+ ['','Name','PV','Color','Width','Symbol','Size',''])
789
+ widths = (10, 50, 100, 20, 80, 35, 80,80)
790
+ for column,width in enumerate(widths):
791
+ tbl.setColumnWidth(column, width)
792
+ tbl.setShowGrid(False)
793
+ tbl.setSizeAdjustPolicy(
794
+ QW.QAbstractScrollArea.AdjustToContents)
795
+
796
+ for row,curveName in enumerate(PVPlot.mapOfCurves[self.dockNum]):
797
+ tbl.insertRow(row)
798
+ printv(f'curveName:{curveName}')
799
+ dataset = MapOfDatasets.dtsDict[curveName]
800
+ col = 0
801
+ cbox = QW.QCheckBox()
802
+ cbox.setChecked(dataset.enabled)
803
+ cbox.stateChanged.connect(self.enable_dataset)
804
+ cbox.setObjectName(curveName)
805
+ tbl.setCellWidget(row, col, cbox)
806
+
807
+ col+=1
808
+ adoparName = dataset.adoPars[0][0]
809
+ item = QW.QTableWidgetItem(curveName)
810
+ #item.setTextAlignment(QtCore.Qt.AlignRight)
811
+ tbl.setItem(row, col, item)
812
+
813
+ col+=1
814
+ printv(f'dataset:{adoparName}')
815
+ txt = adoparName[-24:]
816
+ txt = txt[:12]+'\n'+txt[12:]
817
+ item = QW.QTableWidgetItem(txt)
818
+ tbl.setItem(row, col, QW.QTableWidgetItem(item))
819
+
820
+ col+=1
821
+ # color button for line
822
+ colorButton = pg.ColorButton(color=dataset.pen.color())
823
+ colorButton.setObjectName(curveName)
824
+ colorButton.sigColorChanging.connect(lambda x:
825
+ change_plotOption(str(self.sender().objectName()),color=x.color()))
826
+ tbl.setCellWidget(row, col, colorButton)
827
+
828
+ col+=1
829
+ # slider for changing the line width
830
+ widthSlider = QW.QSlider()
831
+ widthSlider.setObjectName(curveName)
832
+ widthSlider.setOrientation(QtCore.Qt.Horizontal)
833
+ widthSlider.setMaximum(10)
834
+ widthSlider.setValue(1)
835
+ widthSlider.valueChanged.connect(lambda x:
836
+ change_plotOption(str(self.sender().objectName()),width=x))
837
+ tbl.setCellWidget(row, col, widthSlider)
838
+
839
+ col+=1
840
+ # symbol, selected from a comboBox
841
+ self.symbol = QW.QComboBox() # TODO: why self?
842
+ for symbol in ' ostd+x': self.symbol.addItem(symbol)
843
+ self.symbol.setObjectName(curveName)
844
+ self.symbol.currentIndexChanged.connect(self.set_symbol)
845
+ tbl.setCellWidget(row, col, self.symbol)
846
+
847
+ col+=1
848
+ # slider for changing symbol size
849
+ symbolSizeSlider = QW.QSlider()
850
+ symbolSizeSlider.setObjectName(curveName)
851
+ symbolSizeSlider.setOrientation(QtCore.Qt.Horizontal)
852
+ symbolSizeSlider.setMaximum(10)
853
+ symbolSizeSlider.setValue(1)
854
+ symbolSizeSlider.valueChanged.connect(lambda x:
855
+ change_plotOption(str(self.sender().objectName()),symbolSize=x))
856
+ tbl.setCellWidget(row, col, symbolSizeSlider)
857
+
858
+ #dlg.resize(tbl.width(),tbl.height())
859
+ dialogWidth = tbl.horizontalHeader().length() + 24
860
+ dialogHeight= tbl.verticalHeader().length() + 24
861
+ dlg.setMinimumSize(dialogWidth, dialogHeight)
862
+ dlg.exec_()
863
+
864
+ def set_symbol(self, x):
865
+ """ Change symbol of the scatter plot. The size and color are taken
866
+ from the curve setting"""
867
+ dtsetName = str(self.sender().objectName())
868
+ symbol = str(self.sender().itemText(x))
869
+ dataset = MapOfDatasets.dtsDict[dtsetName]
870
+ #print(f'set_symbol for {dtsetName} to {symbol} {dataset.pen.color()}')
871
+ if symbol != ' ':
872
+ dataset.symbol = symbol
873
+ if not dataset.symbolSize:
874
+ dataset.symbolSize = 4 # default size
875
+ dataset.symbolBrush = dataset.pen.color() # symbol color = line color
876
+ dataset.plot(time.time())#ISSUE: the dataset.plotItem.setSymbol does not work
877
+ else:
878
+ # no symbols - remove the scatter plot
879
+ dataset.symbol = None
880
+ pass
881
+
882
+ def set_label(self,side,labelGui):
883
+ dock,label = self.dockNum,str(labelGui.text())
884
+ printv('changed_label '+side+': '+str((dock,label)))
885
+ PVPlot.mapOfPlotWidgets[dock].setLabel(side,label, units='')
886
+ # it might be useful to return the prompt back:
887
+ #labelGui.setText('LabelX' if side=='bottom' else 'LabelY')
888
+
889
+ def set_legend(self, state):
890
+ state = (state==QtCore.Qt.Checked)
891
+ set_legend(self.dockNum, state)
892
+
893
+ def set_stop(self, state):
894
+ PVPlot.stop(state == QtCore.Qt.Checked)
895
+
896
+ def set_sleepTime(self, itemData):
897
+ #print('setting SleepTime to: '+str(itemData))
898
+ PVPlot.pargs.sleepTime = itemData
899
+ PVPlot.qTimer.stop()
900
+ PVPlot.qTimer.start(int(PVPlot.pargs.sleepTime*1000))
901
+
902
+ def unzoom(self):
903
+ #print('>unzoom')
904
+ try:
905
+ if not self.unzooming:
906
+ self.rangestack.pop()
907
+ self.unzooming = True
908
+ viewRange = self.rangestack.pop()
909
+ except IndexError:
910
+ #printw(f'nothing to unzoom')
911
+ self.enableAutoRange()
912
+ return
913
+ #print(f'<rangestack {len(self.rangestack)}')
914
+ self.setRange(xRange=viewRange[X], yRange=viewRange[Y], padding=None,
915
+ update=True, disableAutoRange=True)
916
+
917
+ def show_statistics(self):
918
+ #print(f'print statistics for {self.dockNum}')
919
+ #PVPlot.statDock = self.dockNum
920
+ PVPlot.actionStatistics()
921
+
922
+ def show_yProjection(self):
923
+ if PVPlot.yProjectionWindow is None:
924
+ PVPlot.yProjectionWindow = pg.PlotWidget()
925
+ PVPlot.yProjectionPlotItem = pg.PlotDataItem()
926
+ PVPlot.yProjectionWindow.addItem(PVPlot.yProjectionPlotItem)
927
+
928
+ PVPlot.yProjectionWindow.show()
929
+ PVPlot.yProjectionWindow.setWindowTitle(
930
+ f'Vertical projection of {self.dataset.name}')
931
+ self.dataset.show_yProjection()
932
+
933
+ def enable_dataset(self, state):
934
+ dtsetName = str(self.sender().objectName())
935
+ #print(f'enable_dataset {dtsetName, (state==QtCore.Qt.Checked)}')
936
+ dataset = MapOfDatasets.dtsDict[dtsetName]
937
+ enabled = (state==QtCore.Qt.Checked)
938
+ dataset.enabled = enabled
939
+ dataset.add_plot() if enabled else dataset.remove_plot()
940
+ #set_legend(self.dockNum, enabled)# deletes all legend items
941
+ #,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
942
+
943
+ def callback(args):
944
+ #print(f'cb: {args}')
945
+ for hostDevPar, pardict in args.items():
946
+ try:
947
+ axis,units = PVPlot.subscribedParMap[(hostDevPar)]
948
+ except Exception as e:
949
+ printw(f'callback exception for {hostDevPar}: {e}')
950
+ #print(f'map: {PVPlot.subscribedParMap}')
951
+ continue
952
+ scale = pardict['value'][0]
953
+ printv(f'axis={axis}, units={units}, scale={scale}')
954
+ PVPlot.scaleUnits[axis][Scale] = scale
955
+
956
+ def add_curves(dockNum:int, curveMap:str):
957
+ # if dock name is new then create new dock, otherwise extend the
958
+ # existing one with new curve
959
+
960
+ #curves = [x for x in MapOfDatasets.dtsDict]
961
+ #docks = [x.split('.')[0] for x in curves]
962
+ curves = MapOfDatasets.dtsDict.keys()
963
+ docks = PVPlot.mapOfDocks.keys()
964
+ printv(f'>addcurves curves {curveMap} to {curves,docks}')
965
+ if dockNum not in docks:
966
+ printv(f'adding new dock{dockNum}')
967
+ PVPlot.mapOfDocks[dockNum] = dockarea.Dock(str(dockNum),
968
+ size=(500,200), hideTitle=True)
969
+ if dockNum == 0:
970
+ PVPlot.dockArea.addDock(PVPlot.mapOfDocks[dockNum], 'right',
971
+ closable=True)
972
+ else:
973
+ PVPlot.dockArea.addDock(PVPlot.mapOfDocks[dockNum],
974
+ 'top', PVPlot.mapOfDocks[0], closable=True) #TODO:closable does not work
975
+ PVPlot.mapOfCurves[dockNum] = []
976
+ if MapOfDatasets.add(dockNum, curveMap):
977
+ printe(f'in add_curves: {dockNum, curveMap}')
978
+
979
+ def excepthook(exc_type, exc_value, exc_tb):
980
+ """To uncover exceptions, missed in Qt"""
981
+ tb = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
982
+ print("error caught!:")
983
+ print("error message:\n", tb)
984
+ QApplication.quit()
985
+ # or QApplication.exit(0)
986
+
987
+ class tmpClass():
988
+ DOCKS = [{}]
989
+
990
+ def parse_input_parameters(pargs):
991
+ fn = pargs.file
992
+ if fn:
993
+ sys.path.append(pargs.configDir)
994
+ printv(f'importing {fn}')
995
+ try:
996
+ ConfigModule = import_module(fn)
997
+ configFormat = ConfigModule.configFormat
998
+ except ModuleNotFoundError as e:
999
+ printe(f'Trying to import {pargs.configDir}/{fn}: {e}')
1000
+ sys.exit(0)
1001
+ return ConfigModule
1002
+ else:
1003
+ for parm in pargs.parms.split():
1004
+ parms = (pargs.prefix+parm).split(',')
1005
+ if len(parms) == 2:
1006
+ parms = (parms[0],pargs.prefix+parms[1])
1007
+ tmpClass.DOCKS[0][parm] = parms
1008
+ return tmpClass
1009
+
1010
+ class MainWindow(QW.QMainWindow):
1011
+ def closeEvent(self,event):
1012
+ print('Closing all windows')
1013
+ try: PVPlot.statisticsWindow.close()
1014
+ except: pass
1015
+ try: PVPlot.helpWin.close()
1016
+ except: pass
1017
+ event.accept()
1018
+
1019
+ class PVPlot():
1020
+ config = None
1021
+ pargs = None
1022
+ mapOfPlotWidgets = {}# active plotItems
1023
+ mapOfDocks = {}# dockAreas
1024
+ mapOfCurves = {}
1025
+ padding = 0.1
1026
+ scaleUnits = [[1,'Sample'],[1,'Count']]
1027
+ subscribedParMap = {}
1028
+ perfmon = False # option for performance monitoring
1029
+ legend = {}# unfortunately we have to keep track of legends
1030
+ access = {'E:':EPICSAccess, 'L:':LITEAccess}
1031
+ qWin = None
1032
+ qTimer = QtCore.QTimer()
1033
+ dockArea = None
1034
+ minPlottingPeriod = 1/10.# the data will not be plotted faster than that limit.
1035
+ lastPlotTime = 0.
1036
+ statisticsWindow = None
1037
+ yProjectionWindow = None
1038
+ yProjectionPlotItem = None
1039
+ stopped = False
1040
+ #statDock = 0
1041
+
1042
+ def addAccess(prefix:str, access):
1043
+ # Method to add external access object.
1044
+ PVPlot[prefix] = access
1045
+
1046
+ def start():
1047
+ pargs = PVPlot.pargs
1048
+ printv(f'pargs: {PVPlot.pargs}')
1049
+
1050
+ try: os.environ["QT_SCALE_FACTOR"] = str(pargs.zoomin)
1051
+ except: pass
1052
+ qApp = QApplication([])
1053
+ PVPlot.qWin = MainWindow()
1054
+ PVPlot.dockArea = dockarea.DockArea()
1055
+ PVPlot.qWin.setCentralWidget(PVPlot.dockArea)
1056
+ PVPlot.qWin.resize(1000,500)
1057
+ ## Switch to using white background and black foreground
1058
+ pg.setConfigOption('background', 'w')
1059
+ pg.setConfigOption('foreground', 'k')
1060
+
1061
+ # Shortcuts
1062
+ shortcut = QW.QShortcut(QtGui.QKeySequence("Ctrl+H"), PVPlot.qWin)
1063
+ shortcut.activated.connect(PVPlot.actionHelp)
1064
+ shortcut = QW.QShortcut(QtGui.QKeySequence("Ctrl+M"), PVPlot.qWin)
1065
+ shortcut.activated.connect(partial(PVPlot.actionStatistics))
1066
+ #shortcut = QW.QShortcut(QtGui.QKeySequence("Ctrl+O"), PVPlot.qWin)
1067
+ #shortcut.activated.connect(partial(PVPlot.actionDatasetOptions))
1068
+ shortcut = QW.QShortcut(QtGui.QKeySequence("Ctrl+S"), PVPlot.qWin)
1069
+ shortcut.activated.connect(partial(PVPlot.actionStop))
1070
+ shortcut = QW.QShortcut(QtGui.QKeySequence("Ctrl+U"), PVPlot.qWin)
1071
+ shortcut.activated.connect(PVPlot.actionUnzoom)
1072
+ from . import helptxt
1073
+ PVPlot.helptxt = helptxt.txt
1074
+
1075
+ #``````````process configuration file
1076
+ if pargs.file is not None:
1077
+ PVPlot.config = parse_input_parameters(pargs)
1078
+
1079
+ try: pargs.limit = PVPlot.config.POINTS
1080
+ except: pass
1081
+
1082
+ try: title = PVPlot.config.TITLE
1083
+ except: title = title = f'pvplot {pargs.parms}'
1084
+ PVPlot.qWin.setWindowTitle(title)
1085
+ dockList = PVPlot.config.DOCKS
1086
+ for dockNum,curveMap in enumerate(dockList):
1087
+ printv(f'add_curves to dock{dockNum}, {curveMap}')
1088
+ add_curves(dockNum, curveMap)
1089
+ #,,,,,,,,,,
1090
+ else:
1091
+ if pargs.dock:
1092
+ for par in pargs.dock:
1093
+ dockNum = par[0][0]
1094
+ adopar = par[0][1:].lstrip()
1095
+ add_curves(dockNum, {adopar:adopar})
1096
+ else:
1097
+ # plots for the main dock
1098
+ if not ',' in pargs.parms:
1099
+ for parName in pargs.parms.split():
1100
+ add_curves(0, {parName:pargs.prefix+parName})
1101
+ else:
1102
+ x,y = pargs.parms.split(',')
1103
+ add_curves(0, {f'{y} vs {x}': (pargs.prefix+x, pargs.prefix+y)})
1104
+
1105
+ if len(MapOfDatasets.dtsDict) == 0:
1106
+ printe(f'No datasets created')
1107
+ sys.exit(1)
1108
+
1109
+ for dockNum in PVPlot.mapOfDocks:
1110
+ set_legend(dockNum, True)
1111
+
1112
+ # Subscriptions. Only LITE system is supported.
1113
+ if pargs.xscale is not None:
1114
+ print(f'infra: {pargs.prefix}')
1115
+ infrastructure = pargs.prefix[:2]
1116
+ if infrastructure != 'L:':
1117
+ printe(f'The --xscale option is supported only for LITE infrastucture')
1118
+ sys.exit(1)
1119
+ hostDev = pargs.prefix[2:]
1120
+ if hostDev[-1] == ':':
1121
+ hostDev = hostDev[:-1]
1122
+ par = pargs.xscale
1123
+ printv(f'subscribing: {hostDev,par}')
1124
+ info = LITEAccess.info((hostDev,par))
1125
+ printv(f'info of {hostDev,par}: {info}')
1126
+ units = info[par].get('units','')
1127
+ PVPlot.scaleUnits[X][1] = units
1128
+ LITEAccess.subscribe(callback, (hostDev,par))
1129
+ PVPlot.subscribedParMap[(hostDev,par)] = [X, units]
1130
+
1131
+ sys.excepthook = excepthook
1132
+
1133
+ update_data()
1134
+
1135
+ ## Start a timer to rapidly update the plot in pw
1136
+ PVPlot.qTimer.timeout.connect(update_data)
1137
+ PVPlot.qTimer.start(int(pargs.sleepTime*1000))
1138
+
1139
+ PVPlot.qWin.show()
1140
+ PVPlot.qWin.resize(640,480)
1141
+
1142
+ # start GUI
1143
+ ret = qApp.instance().exec_()
1144
+ print('Application exited')
1145
+ sys.exit(ret)
1146
+
1147
+ def stop(state):
1148
+ PVPlot.stopped = state
1149
+ suffix = ' is stopped'
1150
+ if state == True:
1151
+ PVPlot.qTimer.stop()
1152
+ title = PVPlot.qWin.windowTitle()+suffix
1153
+ else:
1154
+ PVPlot.qTimer.start(int(PVPlot.pargs.sleepTime*1000))
1155
+ title = PVPlot.qWin.windowTitle().replace(suffix,'')
1156
+ PVPlot.qWin.setWindowTitle(title)
1157
+
1158
+ #``````````Shorthcut handlers
1159
+ def actionHelp():
1160
+ PVPlot.helpWin = PopupHelp()
1161
+ PVPlot.helpWin.label.setText(PVPlot.helptxt)
1162
+ PVPlot.helpWin.show()
1163
+
1164
+ def actionStop():
1165
+ PVPlot.stopped = not PVPlot.stopped
1166
+ PVPlot.stop(PVPlot.stopped)
1167
+
1168
+ def actionUnzoom():
1169
+ md = PVPlot.mapOfDocks
1170
+ docks = md.keys()
1171
+ for dockNum in docks:
1172
+ vb = PVPlot.mapOfPlotWidgets[dockNum].getPlotItem().getViewBox()
1173
+ vb.unzoom()
1174
+
1175
+ def actionStatistics():
1176
+ #print(f'>actionStatistics {PVPlot.statDock}')
1177
+ sl = get_statistics()
1178
+ if PVPlot.statisticsWindow is None:
1179
+ header = ['Parameter','XMin','XMax','Mean','StDev','Peak2Peak']
1180
+ PVPlot.statisticsWindow = TableWindow(sl, header)
1181
+ PVPlot.statisticsWindow.model.refresh_data(sl)
1182
+ PVPlot.statisticsWindow.show()
1183
+
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python3
2
2
  """Plotting package for EPICS PVs, ADO and LITE parameters.
3
3
  """
4
- __version__ = 'v1.3.4 2024-08-30'# Statistics is table, time2plot corrected, close all windows on exit.
4
+ __version__ = 'v1.3.4 2024-11-11'# removed handling of prefixlength in PVPlot
5
5
  #TODO: if backend times out the gui is not responsive
6
6
  #TODO: move Add Dataset to Dataset options
7
7
  #TODO: add dataset arithmetics
@@ -87,13 +87,15 @@ def cprint(msg):
87
87
  def get_pv(adopar:str, prop='value'):
88
88
  #print(f'>get_pv {adopar}')
89
89
  adopar, vslice = split_slice(adopar)
90
- access = PVPlot.access.get(adopar[:2], (ADOAccess,0))
91
- access,prefixLength = PVPlot.access.get(adopar[:2], (ADOAccess,0))
90
+ try:
91
+ access = PVPlot.access[adopar[:2]]
92
+ adopar = adopar[2:]
93
+ except:
94
+ access = PVPlot.ADOAccess
92
95
  if access is None:
93
96
  printe(f'No access method for `{adopar}`')
94
97
  sys.exit(1)
95
-
96
- pvTuple = tuple(adopar[prefixLength:].rsplit(':',1))
98
+ pvTuple = tuple(adopar.rsplit(':',1))
97
99
  rd = access.get(pvTuple)[pvTuple]
98
100
  val = rd['value']
99
101
  try:
@@ -1031,7 +1033,7 @@ class PVPlot():
1031
1033
  subscribedParMap = {}
1032
1034
  perfmon = False # option for performance monitoring
1033
1035
  legend = {}# unfortunately we have to keep track of legends
1034
- access = {'E:':(EPICSAccess,2), 'L:':(LITEAccess,2)}
1036
+ access = {'E:':EPICSAccess, 'L:':LITEAccess}
1035
1037
  qWin = None
1036
1038
  qTimer = QtCore.QTimer()
1037
1039
  dockArea = None
@@ -1043,6 +1045,10 @@ class PVPlot():
1043
1045
  stopped = False
1044
1046
  #statDock = 0
1045
1047
 
1048
+ def addAccess(prefix:str, access):
1049
+ # Method to add external access object.
1050
+ PVPlot[prefix] = access
1051
+
1046
1052
  def start():
1047
1053
  pargs = PVPlot.pargs
1048
1054
  printv(f'pargs: {PVPlot.pargs}')
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pvplot"
7
- version = "1.3.4"
7
+ version = "1.4.0"
8
8
  authors = [
9
9
  { name="Andrei Sukhanov", email="cyxandr@gmail.com" },
10
10
  ]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes