Debian Codegraph @

pymeasure/experiment/parameters.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
26 class Parameter:
27 """ Encapsulates the information for an experiment parameter
28 with information about the name, and units if supplied.
29
30 :var value: The value of the parameter
31
32 :param name: The parameter name
33 :param default: The default value
34 :param ui_class: A Qt class to use for the UI of this parameter
35 :param group_by: Defines the Parameter(s) that controls the visibility
36 of the associated input; can be a string containing the Parameter
37 name, a list of strings with multiple Parameter names, or a dict
38 containing {"Parameter name": condition} pairs.
39 :param group_condition: The condition for the group_by Parameter
40 that controls the visibility of this parameter, provided as a value
41 or a (lambda)function. If the group_by argument is provided as a
42 list of strings, this argument can be either a single condition or
43 a list of conditions. If the group_by argument is provided as a dict
44 this argument is ignored.
45 """
46
47 def __init__(self, name, default=None, ui_class=None, group_by=None, group_condition=True):
48 self.name = name
49 separator = ": "
50 if separator in name:
51 raise ValueError(f"The provided name argument '{name}' contains the "
52 f"separator '{separator}'.")
53
54 self._value = None
55 if default is not None:
56 self.value = default
57 self.default = default
58 self.ui_class = ui_class
59 self._help_fields = [('units are', 'units'), 'default']
60
61 self.group_by = {}
62 if isinstance(group_by, dict):
63 self.group_by = group_by
64 elif isinstance(group_by, str):
65 self.group_by = {group_by: group_condition}
66 elif isinstance(group_by, (list, tuple)) and all(isinstance(e, str) for e in group_by):
67 if isinstance(group_condition, (list, tuple)):
68 self.group_by = {g: c for g, c in zip(group_by, group_condition)}
69 else:
70 self.group_by = {g: group_condition for g in group_by}
71 elif group_by is not None:
72 raise TypeError("The provided group_by argument is not valid, should be either a "
73 "string, a list of strings, or a dict with {string: condition} pairs.")
74
75 @property
76 def value(self):
77 if self.is_set():
78 return self._value
79 else:
80 raise ValueError("Parameter value is not set")
81
82 @value.setter
83 def value(self, value):
84 self._value = self.convert(value)
85
86 @property
87 def cli_args(self):
88 """ helper for command line interface parsing of parameters
89
90 This property returns a list of data to help formatting a command line
91 interface interpreter, the list is composed of the following elements:
92 - index 0: default value
93 - index 1: List of value to format an help string, that is either,
94 the name of the fields to be documented or a tuple with (helps_string,
95 field)
96 - index 2: type
97 """
98 return (self.default, self._help_fields, self.convert)
99
100 def is_set(self):
101 """ Returns True if the Parameter value is set
102 """
103 return self._value is not None
104
105 def convert(self, value):
106 """ Convert user input to python data format
107
108 Subclasses are expected to customize this method.
109 Default implementation is the identity function
110
111 :param value: value to be converted
112
113 :return: converted value
114 """
115
116 return value
117
118 def __str__(self):
119 return str(self._value) if self.is_set() else ''
120
121 def __repr__(self):
122 return "<{}(name={},value={},default={})>".format(
123 self.__class__.__name__, self.name, self._value, self.default)
124
125
126 class IntegerParameter(Parameter):
127 """ :class:`.Parameter` sub-class that uses the integer type to
128 store the value.
129
130 :var value: The integer value of the parameter
131
132 :param name: The parameter name
133 :param units: The units of measure for the parameter
134 :param minimum: The minimum allowed value (default: -1e9)
135 :param maximum: The maximum allowed value (default: 1e9)
136 :param default: The default integer value
137 :param ui_class: A Qt class to use for the UI of this parameter
138 :param step: int step size for parameter's UI spinbox. If None, spinbox will have step disabled
139 """
140
141 def __init__(self, name, units=None, minimum=-1e9, maximum=1e9, step=None, **kwargs):
142 self.units = units
143 self.minimum = int(minimum)
144 self.maximum = int(maximum)
145 super().__init__(name, **kwargs)
146 self.step = int(step) if step else None
147 self._help_fields.append('minimum')
148 self._help_fields.append('maximum')
149
150 def convert(self, value):
151 if isinstance(value, str):
152 value, _, units = value.strip().partition(" ")
153 if units != "" and units != self.units:
154 raise ValueError("Units included in string (%s) do not match"
155 "the units of the IntegerParameter (%s)" % (units, self.units))
156
157 try:
158 value = int(value)
159 except ValueError:
160 raise ValueError("IntegerParameter given non-integer value of "
161 "type '%s'" % type(value))
162 if value < self.minimum:
163 raise ValueError("IntegerParameter value is below the minimum")
164 elif value > self.maximum:
165 raise ValueError("IntegerParameter value is above the maximum")
166
167 return value
168
169 def __str__(self):
170 if not self.is_set():
171 return ''
172 result = "%d" % self._value
173 if self.units:
174 result += " %s" % self.units
175 return result
176
177 def __repr__(self):
178 return "<{}(name={},value={},units={},default={})>".format(
179 self.__class__.__name__, self.name, self._value, self.units, self.default)
180
181
182 class BooleanParameter(Parameter):
183 """ :class:`.Parameter` sub-class that uses the boolean type to
184 store the value.
185
186 :var value: The boolean value of the parameter
187
188 :param name: The parameter name
189 :param default: The default boolean value
190 :param ui_class: A Qt class to use for the UI of this parameter
191 """
192
193 def convert(self, value):
194 if isinstance(value, str):
195 if value.lower() == "true":
196 value = True
197 elif value.lower() == "false":
198 value = False
199 else:
200 raise ValueError("BooleanParameter given string value of '%s'" % value)
201 elif isinstance(value, (int, float)) and value in [0, 1]:
202 value = bool(value)
203 elif isinstance(value, bool):
204 value = value
205 else:
206 raise ValueError("BooleanParameter given non-boolean value of "
207 "type '%s'" % type(value))
208 return value
209
210
211 class FloatParameter(Parameter):
212 """ :class:`.Parameter` sub-class that uses the floating point
213 type to store the value.
214
215 :var value: The floating point value of the parameter
216
217 :param name: The parameter name
218 :param units: The units of measure for the parameter
219 :param minimum: The minimum allowed value (default: -1e9)
220 :param maximum: The maximum allowed value (default: 1e9)
221 :param decimals: The number of decimals considered (default: 15)
222 :param default: The default floating point value
223 :param ui_class: A Qt class to use for the UI of this parameter
224 :param step: step size for parameter's UI spinbox. If None, spinbox will have step disabled
225 """
226
227 def __init__(self, name, units=None, minimum=-1e9, maximum=1e9,
228 decimals=15, step=None, **kwargs):
229 self.units = units
230 self.minimum = minimum
231 self.maximum = maximum
232 super().__init__(name, **kwargs)
233 self.decimals = decimals
234 self.step = step
235 self._help_fields.append('decimals')
236
237 def convert(self, value):
238 if isinstance(value, str):
239 value, _, units = value.strip().partition(" ")
240 if units != "" and units != self.units:
241 raise ValueError("Units included in string (%s) do not match"
242 "the units of the FloatParameter (%s)" % (units, self.units))
243
244 try:
245 value = float(value)
246 except ValueError:
247 raise ValueError("FloatParameter given non-float value of "
248 "type '%s'" % type(value))
249 if value < self.minimum:
250 raise ValueError("FloatParameter value is below the minimum")
251 elif value > self.maximum:
252 raise ValueError("FloatParameter value is above the maximum")
253
254 return value
255
256 def __str__(self):
257 if not self.is_set():
258 return ''
259 result = "%g" % self._value
260 if self.units:
261 result += " %s" % self.units
262 return result
263
264 def __repr__(self):
265 return "<{}(name={},value={},units={},default={})>".format(
266 self.__class__.__name__, self.name, self._value, self.units, self.default)
267
268
269 class VectorParameter(Parameter):
270 """ :class:`.Parameter` sub-class that stores the value in a
271 vector format.
272
273 :var value: The value of the parameter as a list of floating point numbers
274
275 :param name: The parameter name
276 :param length: The integer dimensions of the vector
277 :param units: The units of measure for the parameter
278 :param default: The default value
279 :param ui_class: A Qt class to use for the UI of this parameter
280 """
281
282 def __init__(self, name, length=3, units=None, **kwargs):
283 self._length = length
284 self.units = units
285 super().__init__(name, **kwargs)
286 self._help_fields.append('_length')
287
288 def convert(self, value):
289 if isinstance(value, str):
290 # strip units if included
291 if self.units is not None and value.endswith(" " + self.units):
292 value = value[:-len(self.units)].strip()
293
294 # Strip initial and final brackets
295 if (value[0] != '[') or (value[-1] != ']'):
296 raise ValueError("VectorParameter must be passed a vector"
297 " denoted by square brackets if initializing"
298 " by string.")
299 raw_list = value[1:-1].split(",")
300 elif isinstance(value, (list, tuple)):
301 raw_list = value
302 else:
303 raise ValueError("VectorParameter given undesired value of "
304 "type '%s'" % type(value))
305 if len(raw_list) != self._length:
306 raise ValueError("VectorParameter given value of length "
307 "%d instead of %d" % (len(raw_list), self._length))
308 try:
309 value = [float(ve) for ve in raw_list]
310
311 except ValueError:
312 raise ValueError("VectorParameter given input '%s' that could "
313 "not be converted to floats." % str(value))
314
315 return value
316
317 def __str__(self):
318 """If we eliminate spaces within the list __repr__ then the
319 csv parser will interpret it as a single value."""
320 if not self.is_set():
321 return ''
322 result = "".join(repr(self.value).split())
323 if self.units:
324 result += " %s" % self.units
325 return result
326
327 def __repr__(self):
328 return "<{}(name={},value={},units={},length={})>".format(
329 self.__class__.__name__, self.name, self._value, self.units, self._length)
330
331
332 class ListParameter(Parameter):
333 """ :class:`.Parameter` sub-class that stores the value as a list.
334 String representation of choices must be unique.
335
336 :param name: The parameter name
337 :param choices: An explicit list of choices, which is disregarded if None
338 :param units: The units of measure for the parameter
339 :param default: The default value
340 :param ui_class: A Qt class to use for the UI of this parameter
341 """
342
343 def __init__(self, name, choices=None, units=None, **kwargs):
344 self.units = units
345 if choices is not None:
346 keys = [str(c) for c in choices]
347 # check that string representation is unique
348 if not len(keys) == len(set(keys)):
349 raise ValueError(
350 "String representation of choices is not unique!")
351 self._choices = {k: c for k, c in zip(keys, choices)}
352 else:
353 self._choices = None
354 super().__init__(name, **kwargs)
355 self._help_fields.append(('choices are', 'choices'))
356
357 def convert(self, value):
358 if self._choices is None:
359 raise ValueError("ListParameter cannot be set since "
360 "allowed choices are set to None.")
361
362 # strip units if included
363 if isinstance(value, str):
364 if self.units is not None and value.endswith(" " + self.units):
365 value = value[:-len(self.units)].strip()
366
367 if str(value) in self._choices.keys():
368 value = self._choices[str(value)]
369 else:
370 raise ValueError("Invalid choice for parameter. "
371 "Must be one of %s" % str(self._choices))
372
373 return value
374
375 @property
376 def choices(self):
377 """ Returns an immutable iterable of choices, or None if not set. """
378 return tuple(self._choices.values())
379
380
381 class PhysicalParameter(VectorParameter):
382 """ :class:`.VectorParameter` sub-class of 2 dimensions to store a value
383 and its uncertainty.
384
385 :var value: The value of the parameter as a list of 2 floating point numbers
386
387 :param name: The parameter name
388 :param uncertainty_type: Type of uncertainty, 'absolute', 'relative' or 'percentage'
389 :param units: The units of measure for the parameter
390 :param default: The default value
391 :param ui_class: A Qt class to use for the UI of this parameter
392 """
393
394 def __init__(self, name, uncertaintyType='absolute', **kwargs):
395 super().__init__(name, length=2, **kwargs)
396 self._utype = ListParameter("uncertainty type",
397 choices=['absolute', 'relative', 'percentage'],
398 default=None)
399 self._utype.value = uncertaintyType
400
401 def convert(self, value):
402 if isinstance(value, str):
403 # strip units if included
404 if self.units is not None and value.endswith(" " + self.units):
405 value = value[:-len(self.units)].strip()
406
407 # Strip initial and final brackets
408 if (value[0] != '[') or (value[-1] != ']'):
409 raise ValueError("VectorParameter must be passed a vector"
410 " denoted by square brackets if initializing"
411 " by string.")
412 raw_list = value[1:-1].split(",")
413 elif isinstance(value, (list, tuple)):
414 raw_list = value
415 else:
416 raise ValueError("VectorParameter given undesired value of "
417 "type '%s'" % type(value))
418 if len(raw_list) != self._length:
419 raise ValueError("VectorParameter given value of length "
420 "%d instead of %d" % (len(raw_list), self._length))
421 try:
422 value = [float(ve) for ve in raw_list]
423 except ValueError:
424 raise ValueError("VectorParameter given input '%s' that could "
425 "not be converted to floats." % str(value))
426 # Uncertainty must be non-negative
427 value[1] = abs(value[1])
428
429 return value
430
431 @property
432 def uncertainty_type(self):
433 return self._utype.value
434
435 @uncertainty_type.setter
436 def uncertainty_type(self, uncertaintyType):
437 oldType = self._utype.value
438 self._utype.value = uncertaintyType
439 newType = self._utype.value
440
441 if self.is_set():
442 # Convert uncertainty value to the new type
443 if (oldType, newType) == ('absolute', 'relative'):
444 self._value[1] = abs(self._value[1] / self._value[0])
445 if (oldType, newType) == ('relative', 'absolute'):
446 self._value[1] = abs(self._value[1] * self._value[0])
447 if (oldType, newType) == ('relative', 'percentage'):
448 self._value[1] = abs(self._value[1] * 100.0)
449 if (oldType, newType) == ('percentage', 'relative'):
450 self._value[1] = abs(self._value[1] * 0.01)
451 if (oldType, newType) == ('percentage', 'absolute'):
452 self._value[1] = abs(self._value[1] * self._value[0] * 0.01)
453 if (oldType, newType) == ('absolute', 'percentage'):
454 self._value[1] = abs(self._value[1] * 100.0 / self._value[0])
455
456 def __str__(self):
457 if not self.is_set():
458 return ''
459 result = f"{self._value[0]:g} +/- {self._value[1]:g}"
460 if self.units:
461 result += " %s" % self.units
462 if self._utype.value is not None:
463 result += " (%s)" % self._utype.value
464 return result
465
466 def __repr__(self):
467 return "<{}(name={},value={},units={},uncertaintyType={})>".format(
468 self.__class__.__name__, self.name, self._value, self.units, self._utype.value)
469
470
471 class Measurable:
472 """ Encapsulates the information for a measurable experiment parameter
473 with information about the name, fget function and units if supplied.
474 The value property is called when the procedure retrieves a datapoint
475 and calls the fget function. If no fget function is specified, the value
476 property will return the latest set value of the parameter (or default
477 if never set).
478
479 :var value: The value of the parameter
480
481 :param name: The parameter name
482 :param fget: The parameter fget function (e.g. an instrument parameter)
483 :param default: The default value
484 """
485 DATA_COLUMNS = []
486
487 def __init__(self, name, fget=None, units=None, measure=True, default=None, **kwargs):
488 self.name = name
489 self.units = units
490 self.measure = measure
491 if fget is not None:
492 self.fget = fget
493 self._value = fget()
494 else:
495 self._value = default
496 Measurable.DATA_COLUMNS.append(name)
497
498 def fget(self):
499 return self._value
500
501 @property
502 def value(self):
503 if hasattr(self, 'fget'):
504 self._value = self.fget()
505 return self._value
506
507 @value.setter
508 def value(self, value):
509 self._value = value
510
511
512 class Metadata(object):
513 """ Encapsulates the information for metadata of the experiment with
514 information about the name, the fget function and the units, if supplied.
515 If no fget function is specified, the value property will return the
516 latest set value of the parameter (or default if never set).
517
518 :var value: The value of the parameter. This returns (if a value is set)
519 the value obtained from the `fget` (after evaluation) or a manually
520 set value. Returns `None` if no value has been set
521
522 :param name: The parameter name
523 :param fget: The parameter fget function; can be provided as a callable,
524 or as a string, in which case it is assumed to be the name of a
525 method or attribute of the `Procedure` class in which the Metadata is
526 defined. Passing a string also allows for nested attributes by separating
527 them with a period (e.g. to access an attribute or method of an
528 instrument) where only the last attribute can be a method.
529 :param units: The parameter units
530 :param default: The default value, in case no value is assigned or if no
531 fget method is provided
532 :param fmt: A string used to format the value upon writing it to a file.
533 Default is "%s"
534
535 """
536 def __init__(self, name, fget=None, units=None, default=None, fmt="%s"):
537 self.name = name
538 self.units = units
539
540 self._value = default
541 self.fget = fget
542 self.fmt = fmt
543
544 self.evaluated = False
545
546 @property
547 def value(self):
548 if self.is_set():
549 return self._value
550 else:
551 raise ValueError("Metadata value is not set")
552
553 def is_set(self):
554 """ Returns True if the Parameter value is set
555 """
556 return self._value is not None
557
558 def evaluate(self, parent=None, new_value=None):
559 if new_value is not None and self.fget is not None:
560 raise ValueError("Metadata with a defined fget method"
561 " cannot be manually assigned a value")
562 elif new_value is not None:
563 self._value = new_value
564 elif self.fget is not None:
565 self._value = self.eval_fget(parent)
566
567 self.evaluated = True
568 return self.value
569
570 def eval_fget(self, parent):
571 fget = self.fget
572 if isinstance(fget, str):
573 obj = parent
574 for obj_name in fget.split('.'):
575 obj = getattr(obj, obj_name)
576 fget = obj
577
578 if callable(fget):
579 return fget()
580 else:
581 return fget
582
583 def __str__(self):
584 result = self.fmt % self.value
585
586 if self.units is not None:
587 result += " %s" % self.units
588
589 return result