Debian Codegraph @

pymeasure/display/curves.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26
27 import numpy as np
28 import pyqtgraph as pg
29 from .Qt import QtCore, QtGui
30
31 log = logging.getLogger(__name__)
32 log.addHandler(logging.NullHandler())
33
34
35 class ResultsCurve(pg.PlotDataItem):
36 """ Creates a curve loaded dynamically from a file through the Results object. The data can
37 be forced to fully reload on each update, useful for cases when the data is changing across
38 the full file instead of just appending.
39 """
40
41 def __init__(self, results, x, y, force_reload=False, wdg=None, **kwargs):
42 super().__init__(**kwargs)
43 self.results = results
44 self.wdg = wdg
45 self.pen = kwargs.get('pen', None)
46 self.x, self.y = x, y
47 self.force_reload = force_reload
48 self.color = self.opts['pen'].color()
49
50 def update_data(self):
51 """Updates the data by polling the results"""
52 if self.force_reload:
53 self.results.reload()
54 data = self.results.data # get the current snapshot
55
56 # Set x-y data
57 self.setData(data[self.x], data[self.y])
58
59 def set_color(self, color):
60 self.pen.setColor(color)
61 self.color = self.opts['pen'].color()
62 self.updateItems(styleUpdate=True)
63
64 # TODO: Add method for changing x and y
65
66
67 class ResultsImage(pg.ImageItem):
68 """ Creates an image loaded dynamically from a file through the Results
69 object."""
70
71 def __init__(self, results, x, y, z, force_reload=False, wdg=None, **kwargs):
72 self.results = results
73 self.wdg = wdg
74 self.x = x
75 self.y = y
76 self.z = z
77 self.xstart = getattr(self.results.procedure, self.x + '_start')
78 self.xend = getattr(self.results.procedure, self.x + '_end')
79 self.xstep = getattr(self.results.procedure, self.x + '_step')
80 self.xsize = int(np.ceil((self.xend - self.xstart) / self.xstep)) + 1
81 self.ystart = getattr(self.results.procedure, self.y + '_start')
82 self.yend = getattr(self.results.procedure, self.y + '_end')
83 self.ystep = getattr(self.results.procedure, self.y + '_step')
84 self.ysize = int(np.ceil((self.yend - self.ystart) / self.ystep)) + 1
85 self.img_data = np.zeros((self.ysize, self.xsize, 4))
86 self.force_reload = force_reload
87 self.cm = pg.colormap.get('viridis')
88
89 super().__init__(image=self.img_data)
90
91 # Scale and translate image so that the pixels are in the correct
92 # position in "data coordinates"
93 tr = QtGui.QTransform()
94 tr.scale(self.xstep, self.ystep)
95 tr.translate(int(self.xstart / self.xstep) - 0.5,
96 int(self.ystart / self.ystep) - 0.5) # 0.5 so pixels centered
97 self.setTransform(tr)
98
99 def update_data(self):
100 if self.force_reload:
101 self.results.reload()
102
103 data = self.results.data
104 zmin = data[self.z].min()
105 zmax = data[self.z].max()
106
107 # populate the image array with the new data
108 for idx, row in data.iterrows():
109 xdat = row[self.x]
110 ydat = row[self.y]
111 xidx, yidx = self.find_img_index(xdat, ydat)
112 self.img_data[yidx, xidx, :] = self.colormap((row[self.z] - zmin) / (zmax - zmin))
113
114 # set image data, need to transpose since pyqtgraph assumes column-major order
115 self.setImage(image=np.transpose(self.img_data, axes=(1, 0, 2)))
116
117 def find_img_index(self, x, y):
118 """ Finds the integer image indices corresponding to the
119 closest x and y points of the data given some x and y data.
120 """
121
122 indices = [self.xsize - 1, self.ysize - 1] # default to the final pixel
123 if self.xstart <= x <= self.xend: # only change if within reasonable range
124 indices[0] = self.round_up((x - self.xstart) / self.xstep)
125 if self.ystart <= y <= self.yend:
126 indices[1] = self.round_up((y - self.ystart) / self.ystep)
127
128 return indices
129
130 def round_up(self, x):
131 """Convenience function since numpy rounds to even"""
132 if x % 1 >= 0.5:
133 return int(x) + 1
134 else:
135 return int(x)
136
137 def colormap(self, x):
138 """ Return mapped color as 0.0-1.0 floats RGBA """
139 return self.cm.map(x, mode='float')
140
141 # TODO: colormap selection
142
143
144 class BufferCurve(pg.PlotDataItem):
145 """ Creates a curve based on a predefined buffer size and allows data to be added dynamically.
146 """
147
148 data_updated = QtCore.Signal()
149
150 def __init__(self, **kwargs):
151 super().__init__(**kwargs)
152 self._buffer = None
153
154 def prepare(self, size, dtype=np.float32):
155 """ Prepares the buffer based on its size, data type """
156 self._buffer = np.empty((size, 2), dtype=dtype)
157 self._ptr = 0
158
159 def append(self, x, y):
160 """ Appends data to the curve with optional errors """
161 if self._buffer is None:
162 raise Exception("BufferCurve buffer must be prepared")
163 if len(self._buffer) <= self._ptr:
164 raise Exception("BufferCurve overflow")
165
166 # Set x-y data
167 self._buffer[self._ptr, :2] = [x, y]
168 self.setData(self._buffer[:self._ptr, :2])
169
170 self._ptr += 1
171 self.data_updated.emit()
172
173
174 class Crosshairs(QtCore.QObject):
175 """ Attaches crosshairs to the a plot and provides a signal with the
176 x and y graph coordinates
177 """
178
179 coordinates = QtCore.Signal(float, float)
180
181 def __init__(self, plot, pen=None):
182 """ Initiates the crosshars onto a plot given the pen style.
183
184 Example pen:
185 pen=pg.mkPen(color='#AAAAAA', style=QtCore.Qt.PenStyle.DashLine)
186 """
187 super().__init__()
188
189 self.vertical = pg.InfiniteLine(angle=90, movable=False, pen=pen)
190 self.horizontal = pg.InfiniteLine(angle=0, movable=False, pen=pen)
191 plot.addItem(self.vertical, ignoreBounds=True)
192 plot.addItem(self.horizontal, ignoreBounds=True)
193
194 self.position = None
195 self.proxy = pg.SignalProxy(plot.scene().sigMouseMoved, rateLimit=60,
196 slot=self.mouseMoved)
197 self.plot = plot
198
199 def hide(self):
200 self.vertical.hide()
201 self.horizontal.hide()
202
203 def show(self):
204 self.vertical.show()
205 self.horizontal.show()
206
207 def update(self):
208 """ Updates the mouse position based on the data in the plot. For
209 dynamic plots, this is called each time the data changes to ensure
210 the x and y values correspond to those on the display.
211 """
212 if self.position is not None:
213 mouse_point = self.plot.vb.mapSceneToView(self.position)
214 self.coordinates.emit(mouse_point.x(), mouse_point.y())
215 self.vertical.setPos(mouse_point.x())
216 self.horizontal.setPos(mouse_point.y())
217
218 def mouseMoved(self, event=None):
219 """ Updates the mouse position upon mouse movement """
220 if event is not None:
221 self.position = event[0]
222 self.update()
223 else:
224 raise Exception("Mouse location not known")