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