Debian Codegraph @

pymeasure/display/widgets/estimator_widget.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 from inspect import signature
28 from datetime import datetime, timedelta
29
30 from ..thread import StoppableQThread
31 from ..Qt import QtCore, QtWidgets
32 from .sequencer_widget import SequenceEvaluationError
33
34 log = logging.getLogger(__name__)
35 log.addHandler(logging.NullHandler())
36
37
38 class EstimatorThread(StoppableQThread):
39 new_estimates = QtCore.Signal(list)
40
41 def __init__(self, get_estimates_callable):
42 StoppableQThread.__init__(self)
43
44 self._get_estimates = get_estimates_callable
45
46 self.delay = 2
47
48 def __del__(self):
49 self.wait()
50
51 def run(self):
52 self._should_stop.clear()
53
54 while not self._should_stop.wait(self.delay):
55 estimates = self._get_estimates()
56 self.new_estimates.emit(estimates)
57
58
59 class EstimatorWidget(QtWidgets.QWidget):
60 """
61 Widget that allows to display up-front estimates of the measurement
62 procedure.
63
64 This widget relies on a `get_estimates` method of the
65 :class:`Procedure<pymeasure.experiment.procedure.Procedure>` class.
66 `get_estimates` is expected to return a list of tuples, where each tuple
67 contains two strings: a label and the estimate.
68
69 If the :class:`SequencerWidget<pymeasure.display.widgets.sequencer_widget.SequencerWidget>`
70 is also used, it is possible to ask for the current sequencer or its length by
71 asking for two keyword arguments in the Implementation of the `get_estimates` function:
72 `sequence` and `sequence_length`, respectively.
73
74 """
75 provide_sequence = False
76 provide_sequence_length = False
77 number_of_estimates = 0
78 sequencer = None
79
80 def __init__(self, parent=None):
81 super().__init__(parent)
82 self._parent = parent
83
84 self.check_get_estimates_signature()
85
86 self.update_thread = EstimatorThread(self.get_estimates)
87 self.update_thread.new_estimates.connect(self.display_estimates)
88
89 self._setup_ui()
90 self._layout()
91
92 self.update_estimates()
93
94 self.update_box.setCheckState(QtCore.Qt.CheckState.PartiallyChecked)
95
96 def check_get_estimates_signature(self):
97 """ Method that checks the signature of the get_estimates function.
98 It checks which input arguments are allowed and, if the output is
99 correct for the EstimatorWidget, stores the number of estimates.
100 """
101
102 # Check function arguments
103 proc = self._parent.make_procedure()
104 call_signature = signature(proc.get_estimates)
105
106 if "sequence" in call_signature.parameters:
107 self.provide_sequence = True
108
109 if "sequence_length" in call_signature.parameters:
110 self.provide_sequence_length = True
111
112 estimates = self.get_estimates()
113
114 # Check if the output of the function is acceptable
115 raise_error = True
116 if isinstance(estimates, (list, tuple)):
117 if all([isinstance(est, (tuple, list)) for est in estimates]):
118 if all([len(est) == 2 for est in estimates]):
119 raise_error = False
120
121 if raise_error:
122 raise TypeError(
123 "If implemented, the get_estimates function is expected to"
124 "return an int or float representing the estimated duration,"
125 "or a list of tuples of strings, where each tuple represents"
126 "an estimate containing two string: the first is a label for"
127 "the estimate, the second is the estimate itself."
128 )
129
130 # Store the number of estimates
131 self.number_of_estimates = len(estimates)
132
133 def _setup_ui(self):
134 self.line_edits = list()
135 for idx in range(self.number_of_estimates):
136 qlb = QtWidgets.QLabel(self)
137
138 qle = QtWidgets.QLineEdit(self)
139 qle.setEnabled(False)
140 qle.setAlignment(QtCore.Qt.AlignmentFlag.AlignRight)
141
142 self.line_edits.append((qlb, qle))
143
144 # Add a checkbox for continuous updating
145 self.update_box = QtWidgets.QCheckBox(self)
146 self.update_box.setTristate(True)
147 self.update_box.stateChanged.connect(self._set_continuous_updating)
148
149 # Add a button for instant updating
150 self.update_button = QtWidgets.QPushButton("Update", self)
151 self.update_button.clicked.connect(self.update_estimates)
152
153 def _layout(self):
154 f_layout = QtWidgets.QFormLayout(self)
155 for row in self.line_edits:
156 f_layout.addRow(*row)
157
158 update_hbox = QtWidgets.QHBoxLayout()
159 update_hbox.addWidget(self.update_box)
160 update_hbox.addWidget(self.update_button)
161 f_layout.addRow("Update continuously", update_hbox)
162
163 def get_estimates(self):
164 """ Method that makes a procedure with the currently entered
165 parameters and returns the estimates for these parameters.
166 """
167 # Make a procedure
168 procedure = self._parent.make_procedure()
169
170 kwargs = dict()
171
172 sequence = None
173 sequence_length = None
174 if hasattr(self._parent, "sequencer"):
175 try:
176 sequence = self._parent.sequencer.get_sequence()
177 except SequenceEvaluationError:
178 sequence_length = 0
179 else:
180 sequence_length = len(sequence)
181
182 if self.provide_sequence:
183 kwargs["sequence"] = sequence
184
185 if self.provide_sequence_length:
186 kwargs["sequence_length"] = sequence_length
187
188 estimates = procedure.get_estimates(**kwargs)
189
190 if isinstance(estimates, (int, float)):
191 estimates = self._estimates_from_duration(estimates, sequence_length)
192
193 return estimates
194
195 def update_estimates(self):
196 """ Method that gets and displays the estimates.
197 Implemented for connecting to the 'update'-button.
198 """
199 estimates = self.get_estimates()
200 self.display_estimates(estimates)
201
202 def display_estimates(self, estimates):
203 """ Method that updates the shown estimates for the given set of
204 estimates.
205
206 :param estimates: The set of estimates to be shown in the form of a
207 list of tuples of (2) strings
208 """
209 if len(estimates) != self.number_of_estimates:
210 raise ValueError(
211 "Number of estimates changed after initialisation "
212 "(from %d to %d)." % (self.number_of_estimates, len(estimates))
213 )
214
215 for idx, estimate in enumerate(estimates):
216 self.line_edits[idx][0].setText(estimate[0])
217 self.line_edits[idx][1].setText(estimate[1])
218
219 def _estimates_from_duration(self, duration, sequence_length):
220 estimates = list()
221
222 estimates.append(("Duration", "%d s" % int(duration)))
223
224 if hasattr(self._parent, "sequencer"):
225 estimates.append(("Sequence length", str(sequence_length)))
226 estimates.append(("Sequence duration", "%d s" % int(sequence_length * duration)))
227
228 estimates.append(('Measurement finished at', str(datetime.now() + timedelta(
229 seconds=duration))[:-7]))
230
231 if hasattr(self._parent, "sequencer"):
232 estimates.append(('Sequence finished at', str(datetime.now() + timedelta(
233 seconds=duration * sequence_length))[:-7]))
234
235 return estimates
236
237 def _set_continuous_updating(self):
238 state = self.update_box.checkState()
239
240 self.update_thread.stop()
241 self.update_thread.join()
242
243 if state == QtCore.Qt.CheckState.Unchecked:
244 pass
245 elif state == QtCore.Qt.CheckState.PartiallyChecked:
246 self.update_thread.delay = 2
247 self.update_thread.start()
248 elif state == QtCore.Qt.CheckState.Checked:
249 self.update_thread.delay = 0.1
250 self.update_thread.start()