-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqcodes_device_annotator.py
More file actions
290 lines (236 loc) · 10.1 KB
/
qcodes_device_annotator.py
File metadata and controls
290 lines (236 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# A device image plotter
import sys
import os
import json
import glob
import qtpy.QtWidgets as qt
import qtpy.QtGui as gui
import qtpy.QtCore as core
from shutil import copyfile
class MakeDeviceImage(qt.QWidget):
"""
Class for clicking and adding labels
"""
def __init__(self, folder, station):
super().__init__()
self.folder = folder
self.station = station
# BACKEND
self._data = {}
self.filename = None
# FRONTEND
grid = qt.QGridLayout()
self.setLayout(grid)
self.imageCanvas = qt.QLabel()
self.loadButton = qt.QPushButton('Load image')
self.labelButton = qt.QRadioButton("Insert Label")
self.labelButton.setChecked(True)
self.annotButton = qt.QRadioButton('Place annotation')
self.okButton = qt.QPushButton('Save and close')
self.loadButton.clicked.connect(self.loadimage)
self.imageCanvas.mousePressEvent = self.set_label_or_annotation
self.imageCanvas.setStyleSheet('background-color: white')
self.okButton.clicked.connect(self.saveAndClose)
self.treeView = qt.QTreeView()
self.model = gui.QStandardItemModel()
self.model.setHorizontalHeaderLabels([self.tr("Instruments")])
self.addStation(self.model, station)
self.treeView.setModel(self.model)
grid.addWidget(self.imageCanvas, 0, 0, 4, 6)
grid.addWidget(self.loadButton, 4, 0)
grid.addWidget(self.labelButton, 4, 1)
grid.addWidget(self.annotButton, 4, 2)
grid.addWidget(self.okButton, 4, 9)
grid.addWidget(self.treeView, 0, 6, 4, 4)
self.resize(600, 400)
self.move(100, 100)
self.setWindowTitle('Generate annotated device image')
self.show()
def addStation(self, parent, station):
for inst in station.components:
item = gui.QStandardItem(inst)
item.setEditable(False)
item.setSelectable(False)
parent.appendRow(item)
for param in station[inst].parameters:
paramitem = gui.QStandardItem(param)
paramitem.setEditable(False)
item.appendRow(paramitem)
def loadimage(self):
"""
Select an image from disk.
"""
fd = qt.QFileDialog()
filename = fd.getOpenFileName(self, 'Select device image',
os.getcwd(),
"Image files(*.jpg *.png *.jpeg)")
self.filename = filename[0]
self.pixmap = gui.QPixmap(filename[0])
width = self.pixmap.width()
height = self.pixmap.height()
self.imageCanvas.setPixmap(self.pixmap)
# fix the image scale, so that the pixel values of the mouse are
# unambiguous
self.imageCanvas.setMaximumWidth(width)
self.imageCanvas.setMaximumHeight(height)
def set_label_or_annotation(self, event):
# verify valid
if not self.treeView.selectedIndexes():
return
selected = self.treeView.selectedIndexes()[0]
selected_instrument = selected.parent().data()
selected_parameter = selected.data()
self.click_x = event.pos().x()
self.click_y = event.pos().y()
# update the data
if selected_instrument not in self._data.keys():
self._data[selected_instrument] = {}
if selected_parameter not in self._data[selected_instrument].keys():
self._data[selected_instrument][selected_parameter] = {}
if self.labelButton.isChecked():
self._data[selected_instrument][selected_parameter]['labelpos'] = (self.click_x, self.click_y)
elif self.annotButton.isChecked():
self._data[selected_instrument][selected_parameter]['annotationpos'] = (self.click_x, self.click_y)
self._data[selected_instrument][selected_parameter]['value'] = 'NaN'
# draw it
self.imageCanvas, _ = self._renderImage(self._data,
self.imageCanvas,
self.filename)
def saveAndClose(self):
"""
Save and close
"""
if self.filename is None:
return
fileformat = self.filename.split('.')[-1]
rawpath = os.path.join(self.folder, 'deviceimage_raw.'+fileformat)
copyfile(self.filename, rawpath)
# Now forget about the original
self.filename = rawpath
self.close()
@staticmethod
def _renderImage(data, canvas, filename):
"""
Render an image
"""
pixmap = gui.QPixmap(filename)
width = pixmap.width()
height = pixmap.height()
label_size = min(height/30, width/30)
spacing = int(label_size * 0.2)
painter = gui.QPainter(pixmap)
for instrument, parameters in data.items():
for parameter, positions in parameters.items():
if 'labelpos' in positions:
label_string = "{}_{} ".format(instrument, parameter)
(lx, ly) = positions['labelpos']
painter.setBrush(gui.QColor(255, 255, 255, 100))
textfont = gui.QFont('Decorative', label_size)
textwidth = gui.QFontMetrics(textfont).width(label_string)
rectangle_start_x = lx - spacing
rectangle_start_y = ly - spacing
rectangle_width = textwidth+2*spacing
rectangle_height = label_size+2*spacing
painter.drawRect(rectangle_start_x,
rectangle_start_y,
rectangle_width,
rectangle_height)
painter.setBrush(gui.QColor(25, 25, 25))
painter.setFont(textfont)
painter.drawText(core.QRectF(rectangle_start_x, rectangle_start_y,
rectangle_width, rectangle_height),
core.Qt.AlignCenter,
label_string)
if 'annotationpos' in positions:
(ax, ay) = positions['annotationpos']
annotationstring = data[instrument][parameter]['value']
textfont = gui.QFont('Decorative', label_size)
textwidth = gui.QFontMetrics(textfont).width(annotationstring)
rectangle_start_x = ax - spacing
rectangle_start_y = ay - spacing
rectangle_width = textwidth + 2 * spacing
rectangle_height = label_size + 2 * spacing
painter.setBrush(gui.QColor(255, 255, 255, 100))
painter.drawRect(rectangle_start_x,
rectangle_start_y,
rectangle_width,
rectangle_height)
painter.setBrush(gui.QColor(50, 50, 50))
painter.setFont(textfont)
painter.drawText(core.QRectF(rectangle_start_x, rectangle_start_y,
rectangle_width, rectangle_height),
core.Qt.AlignCenter,
annotationstring)
canvas.setPixmap(pixmap)
return canvas, pixmap
class DeviceImage:
"""
Manage an image of a device
"""
def __init__(self, folder, station):
self._data = {}
self.filename = None
self.folder = folder
self.station = station
def annotateImage(self):
"""
Launch a Qt Widget to click
"""
if not qt.QApplication.instance():
app = qt.QApplication(sys.argv)
else:
app = qt.QApplication.instance()
imagedrawer = MakeDeviceImage(self.folder, self.station)
app.exec_()
imagedrawer.close()
self._data = imagedrawer._data
self.filename = imagedrawer.filename
self.saveAnnotations()
def saveAnnotations(self):
"""
Save annotated image to disk (image+instructions)
"""
filename = os.path.join(self.folder, 'deviceimage_annotations.json')
with open(filename, 'w') as fid:
json.dump(self._data, fid)
def loadAnnotations(self):
"""
Get the annotations. Only call this if the files exist
Need to load png/jpeg too
"""
json_filename = os.path.join(self.folder, 'deviceimage_annotations.json')
self.filename = glob.glob(os.path.join(self.folder, 'deviceimage_raw.*'))[0]
# this assumes there is only on of deviceimage_raw.*
with open(json_filename, 'r') as fid:
self._data = json.load(fid)
def updateValues(self, station):
"""
Update the data with actual voltages from the QDac
"""
for instrument, parameters in self._data.items():
for parameter in parameters.keys():
self._data[instrument][parameter]['value'] = str(station.components[instrument][parameter].get_latest())
def makePNG(self, counter, path=None):
"""
Render the image with new voltage values and save it to disk
Args:
counter (int): A counter for the experimental run number
"""
if self.filename is None:
raise ValueError('No image selected!')
if not qt.QApplication.instance():
app = qt.QApplication(sys.argv)
else:
app = qt.QApplication.instance()
win = qt.QWidget()
grid = qt.QGridLayout()
win.setLayout(grid)
win.imageCanvas = qt.QLabel()
grid.addWidget(win.imageCanvas)
win.imageCanvas, pixmap = MakeDeviceImage._renderImage(self._data,
win.imageCanvas,
self.filename)
filename = '{:03d}_deviceimage.png'.format(counter)
if path:
filename = os.path.join(path, filename)
pixmap.save(filename, 'png')