| 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 |
from inspect import getmembers |
| 26 |
import logging |
| 27 |
from warnings import warn |
| 28 |
|
| 29 |
log = logging.getLogger(__name__) |
| 30 |
log.addHandler(logging.NullHandler()) |
| 31 |
|
| 32 |
|
| 33 |
class DynamicProperty(property): |
| 34 |
""" Class that allows managing python property behaviour in a "dynamic" fashion |
| 35 |
|
| 36 |
The class allows passing, in addition to regular property parameters, a list of |
| 37 |
runtime configurable parameters. |
| 38 |
The effect is that the behaviour of fget/fset not only depends on the obj parameter, but |
| 39 |
also on a set of keyword parameters with a default value. |
| 40 |
These extra parameters are read from instance, if available, or left with the default value. |
| 41 |
Dynamic behaviour is achieved by changing class or instance variables with special names |
| 42 |
defined as `<prefix> + <property name> + <param name>`. |
| 43 |
|
| 44 |
Code has been based on Python equivalent implementation of properties provided in the |
| 45 |
python documentation `here <https://docs.python.org/3/howto/descriptor.html#properties>`_. |
| 46 |
|
| 47 |
:param fget: class property fget parameter whose signature is expanded with a |
| 48 |
set of keyword arguments as in fget_params_list |
| 49 |
:param fset: class property fget parameter whose signature is expanded with a |
| 50 |
set of keyword arguments as in fset_params_list |
| 51 |
:param fdel: class property fdel parameter |
| 52 |
:param doc: class property doc parameter |
| 53 |
:param fget_params_list: List of parameter names that are dynamically configurable |
| 54 |
:param fset_params_list: List of parameter names that are dynamically configurable |
| 55 |
:param prefix: String to be prefixed to get dynamically configurable |
| 56 |
parameters. |
| 57 |
""" |
| 58 |
|
| 59 |
def __init__(self, fget=None, fset=None, fdel=None, doc=None, fget_params_list=None, |
| 60 |
fset_params_list=None, prefix=""): |
| 61 |
super().__init__(fget, fset, fdel, doc) |
| 62 |
self.fget_params_list = () if fget_params_list is None else fget_params_list |
| 63 |
self.fset_params_list = () if fset_params_list is None else fset_params_list |
| 64 |
self.name = "" |
| 65 |
self.prefix = prefix |
| 66 |
|
| 67 |
def __get__(self, obj, objtype=None): |
| 68 |
if obj is None: |
| 69 |
# Property return itself when invoked from a class |
| 70 |
return self |
| 71 |
if self.fget is None: |
| 72 |
raise AttributeError(f"Unreadable attribute {self.name}") |
| 73 |
|
| 74 |
kwargs = {} |
| 75 |
for attr in self.fget_params_list: |
| 76 |
attr_instance_name = self.prefix + "_".join([self.name, attr]) |
| 77 |
if hasattr(obj, attr_instance_name): |
| 78 |
kwargs[attr] = getattr(obj, attr_instance_name) |
| 79 |
return self.fget(obj, **kwargs) |
| 80 |
|
| 81 |
def __set__(self, obj, value): |
| 82 |
if self.fset is None: |
| 83 |
raise AttributeError(f"Can't set attribute {self.name}") |
| 84 |
kwargs = {} |
| 85 |
for attr in self.fset_params_list: |
| 86 |
attr_instance_name = self.prefix + "_".join([self.name, attr]) |
| 87 |
if hasattr(obj, attr_instance_name): |
| 88 |
kwargs[attr] = getattr(obj, attr_instance_name) |
| 89 |
self.fset(obj, value, **kwargs) |
| 90 |
|
| 91 |
def __set_name__(self, owner, name): |
| 92 |
self.name = name |
| 93 |
|
| 94 |
|
| 95 |
class CommonBase: |
| 96 |
"""Base class for instruments and channels. |
| 97 |
|
| 98 |
This class contains everything needed for pymeasure's property creator |
| 99 |
:meth:`control` and its derivatives :meth:`measurement` and :meth:`setting`. |
| 100 |
|
| 101 |
:param preprocess_reply: An optional callable used to preprocess |
| 102 |
strings received from the instrument. The callable returns the |
| 103 |
processed string. |
| 104 |
|
| 105 |
.. deprecated:: 0.11 |
| 106 |
Implement it in the instrument's `read` method instead. |
| 107 |
""" |
| 108 |
|
| 109 |
# Variable holding the list of DynamicProperty parameters that are configurable |
| 110 |
# by users |
| 111 |
_fget_params_list = ('get_command', |
| 112 |
'values', |
| 113 |
'map_values', |
| 114 |
'get_process', |
| 115 |
'command_process', |
| 116 |
'check_get_errors') |
| 117 |
|
| 118 |
_fset_params_list = ('set_command', |
| 119 |
'validator', |
| 120 |
'values', |
| 121 |
'map_values', |
| 122 |
'set_process', |
| 123 |
'command_process', |
| 124 |
'check_set_errors') |
| 125 |
|
| 126 |
# Prefix used to store reserved variables |
| 127 |
__reserved_prefix = "___" |
| 128 |
|
| 129 |
def __init__(self, preprocess_reply=None, **kwargs): |
| 130 |
self._special_names = self._setup_special_names() |
| 131 |
self._create_channels() |
| 132 |
if preprocess_reply is not None: |
| 133 |
warn(("Parameter `preprocess_reply` is deprecated. " |
| 134 |
"Implement it in the instrument, e.g. in `read`, instead."), |
| 135 |
FutureWarning) |
| 136 |
self.preprocess_reply = preprocess_reply |
| 137 |
super().__init__(**kwargs) |
| 138 |
|
| 139 |
class BaseChannelCreator: |
| 140 |
"""Base class for ChannelCreator and MultiChannelCreator. |
| 141 |
|
| 142 |
:param cls: Class for all children or tuple/list of classes, one for each child. |
| 143 |
:param \\**kwargs: Keyword arguments for all children. |
| 144 |
""" |
| 145 |
|
| 146 |
def __init__(self, cls, **kwargs): |
| 147 |
try: |
| 148 |
self.valid_class = issubclass(cls, CommonBase) |
| 149 |
except TypeError: |
| 150 |
self.valid_class = False |
| 151 |
self.pairs = () |
| 152 |
self.kwargs = kwargs |
| 153 |
|
| 154 |
class ChannelCreator(BaseChannelCreator): |
| 155 |
"""Add a single channel to the parent class. |
| 156 |
|
| 157 |
The child will be added to the parent instance at instantiation with |
| 158 |
:func:`CommonBase.add_child`. The attribute name that ChannelCreator was assigned |
| 159 |
to in the `Instrument` class will be the name of the channel interface. |
| 160 |
|
| 161 |
.. code:: |
| 162 |
|
| 163 |
class Extreme5000(Instrument): |
| 164 |
# Two output channels, accessible by their property names |
| 165 |
# and both are accessible through the 'channels' collection |
| 166 |
output_A = Instrument.ChannelCreator(Extreme5000Channel, "A") |
| 167 |
output_B = Instrument.ChannelCreator(Extreme5000Channel, "B") |
| 168 |
# A channel without a channel accessible through the 'motor' collection |
| 169 |
motor = Instrument.ChannelCreator(MotorControl) |
| 170 |
|
| 171 |
inst = SomeInstrument() |
| 172 |
# Set the extreme_temp for channel A of Extreme5000 instrument |
| 173 |
inst.output_A.extreme_temp = 42 |
| 174 |
|
| 175 |
:param cls: Channel class for channel interface |
| 176 |
:param id: The id of the channel on the instrument, integer or string. |
| 177 |
:param \\**kwargs: Keyword arguments for all children. |
| 178 |
""" |
| 179 |
|
| 180 |
def __init__(self, cls, id=None, **kwargs): |
| 181 |
super().__init__(cls=cls, **kwargs) |
| 182 |
if (isinstance(id, (str, int)) or id is None) and self.valid_class: |
| 183 |
self.pairs = ((cls, id),) |
| 184 |
else: |
| 185 |
raise ValueError("Invalid definition of class '{cls}' and id '{id}'.") |
| 186 |
|
| 187 |
class MultiChannelCreator(BaseChannelCreator): |
| 188 |
"""Add channels to the parent class. |
| 189 |
|
| 190 |
The children will be added to the parent instance at instantiation with |
| 191 |
:func:`CommonBase.add_child`. The attribute name (e.g. :code:`channels`) will be |
| 192 |
used as the `collection` of the children. You may define the attribute |
| 193 |
prefix. If there are no other pressing reasons, use :code:`channels` as the attribute name |
| 194 |
and leave the prefix at the default :code:`"ch_"`. |
| 195 |
|
| 196 |
.. code:: |
| 197 |
|
| 198 |
class Extreme5000(Instrument): |
| 199 |
# Three channels of the same type: 'ch_A', 'ch_B', 'ch_C' |
| 200 |
# and add them to the 'channels' collection |
| 201 |
channels = Instrument.MultiChannelCreator(Extreme5000Channel, ["A", "B", "C"]) |
| 202 |
# Two channel interfaces of different types: 'fn_power', 'fn_voltage' |
| 203 |
# and add them to the 'functions' collection |
| 204 |
functions = Instrument.MultiChannelCreator((PowerChannel, VoltageChannel), |
| 205 |
["power", "voltage"], prefix="fn_") |
| 206 |
|
| 207 |
:param cls: Class for all children or tuple/list of classes, one for each child. |
| 208 |
:param id: tuple/list of ids of the channels on the instrument. |
| 209 |
:param prefix: Collection prefix for the attributes, e.g. `"ch_"` |
| 210 |
creates attribute `self.ch_A`. If prefix evaluates False, |
| 211 |
the child will be added directly under the variable name. Required if id is tuple/list. |
| 212 |
:param \\**kwargs: Keyword arguments for all children. |
| 213 |
""" |
| 214 |
|
| 215 |
def __init__(self, cls, id=None, prefix="ch_", **kwargs): |
| 216 |
super().__init__(cls=cls, **kwargs) |
| 217 |
if isinstance(id, (list, tuple)) and isinstance(cls, (list, tuple)): |
| 218 |
assert (len(id) == len(cls)), "Lengths of cls and id do not match." |
| 219 |
self.pairs = list(zip(cls, id)) |
| 220 |
elif isinstance(id, (list, tuple)) and self.valid_class: |
| 221 |
self.pairs = list(zip((cls,) * len(id), id)) |
| 222 |
else: |
| 223 |
raise ValueError("Invalid definition of classes '{cls}' and ids '{id}'.") |
| 224 |
self.kwargs.setdefault("prefix", prefix) |
| 225 |
|
| 226 |
def _setup_special_names(self): |
| 227 |
""" Return list of class/instance special names. |
| 228 |
|
| 229 |
Compute the list of special names based on the list of |
| 230 |
class attributes that are a DynamicProperty. Check also for class variables |
| 231 |
with special name and copy them at instance level |
| 232 |
Internal method, not intended to be accessed at user level.""" |
| 233 |
special_names = [] |
| 234 |
dynamic_params = tuple(set(self._fget_params_list + self._fset_params_list)) |
| 235 |
# Check whether class variables of DynamicProperty type are present |
| 236 |
for attr_name, attr in getmembers(self.__class__): |
| 237 |
if isinstance(attr, DynamicProperty): |
| 238 |
special_names += [attr_name + "_" + key for key in dynamic_params] |
| 239 |
# Check if special variables are defined at class level |
| 240 |
for attr, value in getmembers(self.__class__): |
| 241 |
if attr in special_names: |
| 242 |
# Copy class special variable at instance level, prefixing reserved_prefix |
| 243 |
setattr(self, self.__reserved_prefix + attr, value) |
| 244 |
return special_names |
| 245 |
|
| 246 |
@staticmethod |
| 247 |
def get_channels(cls): |
| 248 |
"""Return a list of all the Instrument's ChannelCreator and MultiChannelCreator instances""" |
| 249 |
class_members = getmembers(cls) |
| 250 |
|
| 251 |
channels = [] |
| 252 |
for name, member in class_members: |
| 253 |
if isinstance(member, CommonBase.BaseChannelCreator): |
| 254 |
channels.append((name, member)) |
| 255 |
return channels |
| 256 |
|
| 257 |
@staticmethod |
| 258 |
def get_channel_pairs(cls): |
| 259 |
"""Return a list of all the Instrument's channel pairs""" |
| 260 |
channel_pairs = [] |
| 261 |
for name, creator in CommonBase.get_channels(cls): |
| 262 |
for pair in creator.pairs: |
| 263 |
channel_pairs.append(pair) |
| 264 |
return channel_pairs |
| 265 |
|
| 266 |
def _create_channels(self): |
| 267 |
"""Create channel interfaces for all the Instrument's channel pairs.""" |
| 268 |
for name, creator in CommonBase.get_channels(self.__class__): |
| 269 |
for cls, id in creator.pairs: |
| 270 |
# If channel pair was created with MultiChannelCreator |
| 271 |
# add channel interface to collection with passed attribute name |
| 272 |
if isinstance(creator, CommonBase.MultiChannelCreator): |
| 273 |
child = self.add_child(cls, id, collection=name, **creator.kwargs) |
| 274 |
# If channel pair was created with ChannelCreator |
| 275 |
# name channel interface with passed attribute name |
| 276 |
elif isinstance(creator, CommonBase.ChannelCreator): |
| 277 |
child = self.add_child(cls, id, attr_name=name, **creator.kwargs) |
| 278 |
else: |
| 279 |
raise ValueError("Invalid class '{creator}' for channel creation.") |
| 280 |
child._protected = True |
| 281 |
|
| 282 |
def __setattr__(self, name, value): |
| 283 |
""" Add reserved_prefix in front of special variables.""" |
| 284 |
if hasattr(self, '_special_names'): |
| 285 |
if name in self._special_names: |
| 286 |
name = self.__reserved_prefix + name |
| 287 |
super().__setattr__(name, value) |
| 288 |
|
| 289 |
def __getattribute__(self, name): |
| 290 |
""" Prevent read access to variables with special names used to |
| 291 |
support dynamic property behaviour.""" |
| 292 |
if name in ('_special_names', '__dict__'): |
| 293 |
return super().__getattribute__(name) |
| 294 |
if hasattr(self, '_special_names'): |
| 295 |
if name in self._special_names: |
| 296 |
raise AttributeError( |
| 297 |
f"{name} is a reserved variable name and it cannot be read") |
| 298 |
return super().__getattribute__(name) |
| 299 |
|
| 300 |
# Channel management |
| 301 |
def add_child(self, cls, id=None, collection="channels", prefix="ch_", attr_name="", **kwargs): |
| 302 |
"""Add a child to this instance and return its index in the children list. |
| 303 |
|
| 304 |
The newly created child may be accessed either by the id in the |
| 305 |
children dictionary or by the created attribute, e.g. the fifth channel of `instrument` |
| 306 |
with id "F" has two access options: |
| 307 |
:code:`instrument.channels["F"] == instrument.ch_F` |
| 308 |
|
| 309 |
.. note:: |
| 310 |
|
| 311 |
Do not change the default `collection` or `prefix` parameter, unless |
| 312 |
you have to distinguish several collections of different children, |
| 313 |
e.g. different channel types (analog and digital). |
| 314 |
|
| 315 |
:param cls: Class of the channel. |
| 316 |
:param id: Child id how it is used in communication, e.g. `"A"`. |
| 317 |
:param collection: Name of the collection of children, used for dictionary access to the |
| 318 |
channel interfaces. |
| 319 |
:param prefix: For creating multiple channel interfaces, the prefix e.g. `"ch_"` |
| 320 |
is prepended to the attribute name of the channel interface `self.ch_A`. |
| 321 |
If prefix evaluates False, the child will be added directly under the collection name. |
| 322 |
:param attr_name: For creating a single channel interface, the attr_name argument is used |
| 323 |
when setting the attribute name of the channel interface. |
| 324 |
:param \\**kwargs: Keyword arguments for the channel creator. |
| 325 |
:returns: Instance of the created child. |
| 326 |
""" |
| 327 |
child = cls(self, id, **kwargs) |
| 328 |
collection_data = getattr(self, collection, {}) |
| 329 |
if isinstance(collection_data, CommonBase.BaseChannelCreator): |
| 330 |
collection_data = {} |
| 331 |
# Create channel interface if prefix or name is present |
| 332 |
if (prefix or attr_name) and id is not None: |
| 333 |
if not collection_data: |
| 334 |
# Add a grouplist to the parent. |
| 335 |
setattr(self, collection, collection_data) |
| 336 |
collection_data[id] = child |
| 337 |
child._collection = collection |
| 338 |
if attr_name: |
| 339 |
setattr(self, attr_name, child) |
| 340 |
child._name = attr_name |
| 341 |
else: |
| 342 |
setattr(self, f"{prefix}{id}", child) |
| 343 |
child._name = f"{prefix}{id}" |
| 344 |
elif attr_name and id is None: |
| 345 |
# If attribute name is passed with no channel id |
| 346 |
# set the child to the attribute name. |
| 347 |
setattr(self, attr_name, child) |
| 348 |
child._name = attr_name |
| 349 |
else: |
| 350 |
if collection_data: |
| 351 |
raise ValueError(f"An attribute '{collection}' already exists.") |
| 352 |
setattr(self, collection, child) |
| 353 |
child._name = collection |
| 354 |
return child |
| 355 |
|
| 356 |
def remove_child(self, child): |
| 357 |
"""Remove the child from the instrument and the corresponding collection. |
| 358 |
|
| 359 |
:param child: Instance of the child to delete. |
| 360 |
""" |
| 361 |
if hasattr(child, "_protected"): |
| 362 |
raise TypeError("You cannot remove channels defined at class level.") |
| 363 |
if hasattr(child, "_collection"): |
| 364 |
collection = getattr(self, child._collection) |
| 365 |
del collection[child.id] |
| 366 |
delattr(self, child._name) |
| 367 |
|
| 368 |
# Communication functions |
| 369 |
def wait_for(self, query_delay=None): |
| 370 |
"""Wait for some time. Used by 'ask' to wait before reading. |
| 371 |
|
| 372 |
Implement in subclass! |
| 373 |
|
| 374 |
:param query_delay: Delay between writing and reading in seconds. None is default delay. |
| 375 |
""" |
| 376 |
raise NotImplementedError("Implement in subclass!") |
| 377 |
|
| 378 |
def ask(self, command, query_delay=None): |
| 379 |
"""Write a command to the instrument and return the read response. |
| 380 |
|
| 381 |
:param command: Command string to be sent to the instrument. |
| 382 |
:param query_delay: Delay between writing and reading in seconds. |
| 383 |
:returns: String returned by the device without read_termination. |
| 384 |
""" |
| 385 |
self.write(command) |
| 386 |
self.wait_for(query_delay) |
| 387 |
return self.read() |
| 388 |
|
| 389 |
def values(self, command, separator=',', cast=float, preprocess_reply=None, maxsplit=-1, |
| 390 |
**kwargs): |
| 391 |
"""Write a command to the instrument and return a list of formatted |
| 392 |
values from the result. |
| 393 |
|
| 394 |
:param command: SCPI command to be sent to the instrument. |
| 395 |
:param preprocess_reply: Optional callable used to preprocess the string |
| 396 |
received from the instrument, before splitting it. |
| 397 |
The callable returns the processed string. |
| 398 |
:param separator: A separator character to split the string returned by |
| 399 |
the device into a list. |
| 400 |
:param maxsplit: The string returned by the device is splitted at most `maxsplit` times. |
| 401 |
-1 (default) indicates no limit. |
| 402 |
:param cast: A type to cast each element of the splitted string. |
| 403 |
:param \\**kwargs: Keyword arguments to be passed to the :meth:`ask` method. |
| 404 |
:returns: A list of the desired type, or strings where the casting fails. |
| 405 |
""" |
| 406 |
results = self.ask(command, **kwargs).strip() |
| 407 |
if callable(preprocess_reply): |
| 408 |
results = preprocess_reply(results) |
| 409 |
elif callable(self.preprocess_reply): |
| 410 |
results = self.preprocess_reply(results) |
| 411 |
results = results.split(separator, maxsplit=maxsplit) |
| 412 |
for i, result in enumerate(results): |
| 413 |
try: |
| 414 |
if cast == bool: |
| 415 |
# Need to cast to float first since results are usually |
| 416 |
# strings and bool of a non-empty string is always True |
| 417 |
results[i] = bool(float(result)) |
| 418 |
else: |
| 419 |
results[i] = cast(result) |
| 420 |
except Exception: |
| 421 |
pass # Keep as string |
| 422 |
return results |
| 423 |
|
| 424 |
def binary_values(self, command, query_delay=None, **kwargs): |
| 425 |
""" Write a command to the instrument and return a numpy array of the binary data. |
| 426 |
|
| 427 |
:param command: Command to be sent to the instrument. |
| 428 |
:param query_delay: Delay between writing and reading in seconds. |
| 429 |
:param kwargs: Arguments for :meth:`~pymeasure.Adapter.read_binary_values`. |
| 430 |
:returns: NumPy array of values. |
| 431 |
""" |
| 432 |
self.write(command) |
| 433 |
self.wait_for(query_delay) |
| 434 |
return self.read_binary_values(**kwargs) |
| 435 |
|
| 436 |
# Property creators |
| 437 |
@staticmethod |
| 438 |
def control( # noqa: C901 accept that this is a complex method |
| 439 |
get_command, |
| 440 |
set_command, |
| 441 |
docs, |
| 442 |
validator=lambda v, vs: v, |
| 443 |
values=(), |
| 444 |
map_values=False, |
| 445 |
get_process=lambda v: v, |
| 446 |
set_process=lambda v: v, |
| 447 |
command_process=None, |
| 448 |
check_set_errors=False, |
| 449 |
check_get_errors=False, |
| 450 |
dynamic=False, |
| 451 |
preprocess_reply=None, |
| 452 |
separator=',', |
| 453 |
maxsplit=-1, |
| 454 |
cast=float, |
| 455 |
values_kwargs=None, |
| 456 |
**kwargs |
| 457 |
): |
| 458 |
"""Return a property for the class based on the supplied |
| 459 |
commands. This property may be set and read from the |
| 460 |
instrument. See also :meth:`measurement` and :meth:`setting`. |
| 461 |
|
| 462 |
:param get_command: A string command that asks for the value, set to `None` |
| 463 |
if get is not supported (see also :meth:`setting`). |
| 464 |
:param set_command: A string command that writes the value, set to `None` |
| 465 |
if set is not supported (see also :meth:`measurement`). |
| 466 |
:param docs: A docstring that will be included in the documentation |
| 467 |
:param validator: A function that takes both a value and a group of valid values |
| 468 |
and returns a valid value, while it otherwise raises an exception |
| 469 |
:param values: A list, tuple, range, or dictionary of valid values, that can be used |
| 470 |
as to map values if :code:`map_values` is True. |
| 471 |
:param map_values: A boolean flag that determines if the values should be |
| 472 |
interpreted as a map |
| 473 |
:param get_process: A function that take a value and allows processing |
| 474 |
before value mapping, returning the processed value |
| 475 |
:param set_process: A function that takes a value and allows processing |
| 476 |
before value mapping, returning the processed value |
| 477 |
:param command_process: A function that takes a command and allows processing |
| 478 |
before executing the command |
| 479 |
|
| 480 |
.. deprecated:: 0.12 |
| 481 |
Use a dynamic property instead. |
| 482 |
|
| 483 |
:param check_set_errors: Toggles checking errors after setting |
| 484 |
:param check_get_errors: Toggles checking errors after getting |
| 485 |
:param dynamic: Specify whether the property parameters are meant to be changed in |
| 486 |
instances or subclasses. |
| 487 |
:param preprocess_reply: Optional callable used to preprocess the string |
| 488 |
received from the instrument, before splitting it. |
| 489 |
The callable returns the processed string. |
| 490 |
:param separator: A separator character to split the string returned by |
| 491 |
the device into a list. |
| 492 |
:param maxsplit: The string returned by the device is splitted at most `maxsplit` times. |
| 493 |
-1 (default) indicates no limit. |
| 494 |
:param cast: A type to cast each element of the splitted string. |
| 495 |
:param dict values_kwargs: Further keyword arguments for :meth:`values`. |
| 496 |
:param \\**kwargs: Keyword arguments for :meth:`values`. |
| 497 |
|
| 498 |
.. deprecated:: 0.12 |
| 499 |
Use `values_kwargs` dictionary parameter instead. |
| 500 |
|
| 501 |
Example of usage of dynamic parameter is as follows: |
| 502 |
|
| 503 |
.. code-block:: python |
| 504 |
|
| 505 |
class GenericInstrument(Instrument): |
| 506 |
center_frequency = Instrument.control( |
| 507 |
":SENS:FREQ:CENT?;", ":SENS:FREQ:CENT %e GHz;", |
| 508 |
" A floating point property that represents the frequency ... ", |
| 509 |
validator=strict_range, |
| 510 |
# Redefine this in subclasses to reflect actual instrument value: |
| 511 |
values=(1, 20), |
| 512 |
dynamic=True # enable changing property parameters on-the-fly |
| 513 |
) |
| 514 |
|
| 515 |
class SpecificInstrument(GenericInstrument): |
| 516 |
# Identical to GenericInstrument, except for frequency range |
| 517 |
# Override the "values" parameter of the "center_frequency" property |
| 518 |
center_frequency_values = (1, 10) # Redefined at subclass level |
| 519 |
|
| 520 |
instrument = SpecificInstrument() |
| 521 |
instrument.center_frequency_values = (1, 6e9) # Redefined at instance level |
| 522 |
|
| 523 |
.. warning:: Unexpected side effects when using dynamic properties |
| 524 |
|
| 525 |
Users must pay attention when using dynamic properties, since definition of class and/or |
| 526 |
instance attributes matching specific patterns could have unwanted side effect. |
| 527 |
The attribute name pattern `property_param`, where `property` is the name of the dynamic |
| 528 |
property (e.g. `center_frequency` in the example) and `param` is any of this method |
| 529 |
parameters name except `dynamic` and `docs` (e.g. `values` in the example) has to be |
| 530 |
considered reserved for dynamic property control. |
| 531 |
""" |
| 532 |
if values_kwargs is None: |
| 533 |
values_kwargs = {} |
| 534 |
if kwargs: |
| 535 |
warn(f"Do not use keyword arguments {kwargs} as `control` parameter " |
| 536 |
f"for the `values` method, use `values_kwargs` parameter instead. docs:\n{docs}", |
| 537 |
FutureWarning) |
| 538 |
values_kwargs.update(kwargs) |
| 539 |
|
| 540 |
if command_process is None: |
| 541 |
command_process = lambda c: c # noqa: E731 |
| 542 |
else: |
| 543 |
warn("Do not use `command_process`, use a dynamic property instead.", FutureWarning) |
| 544 |
|
| 545 |
def fget(self, |
| 546 |
get_command=get_command, |
| 547 |
values=values, |
| 548 |
map_values=map_values, |
| 549 |
get_process=get_process, |
| 550 |
command_process=command_process, |
| 551 |
check_get_errors=check_get_errors, |
| 552 |
): |
| 553 |
if get_command is None: |
| 554 |
raise LookupError("Property can not be read.") |
| 555 |
vals = self.values(command_process(get_command), |
| 556 |
separator=separator, |
| 557 |
cast=cast, |
| 558 |
preprocess_reply=preprocess_reply, |
| 559 |
maxsplit=maxsplit, |
| 560 |
**values_kwargs) |
| 561 |
if check_get_errors: |
| 562 |
try: |
| 563 |
error_list = self.check_get_errors() |
| 564 |
except Exception as exc: |
| 565 |
log.error("Exception raised while getting a property with the command " |
| 566 |
f"""'{command_process(get_command)}': '{str(exc)}'.""") |
| 567 |
raise |
| 568 |
errors = [str(error) for error in error_list] |
| 569 |
if errors: |
| 570 |
log.error("Error received after trying to get a property with the command " |
| 571 |
f"""'{command_process(get_command)}': '{"', '".join(errors)}'.""") |
| 572 |
if len(vals) == 1: |
| 573 |
value = get_process(vals[0]) |
| 574 |
if not map_values: |
| 575 |
return value |
| 576 |
elif isinstance(values, (list, tuple, range)): |
| 577 |
return values[int(value)] |
| 578 |
elif isinstance(values, dict): |
| 579 |
for k, v in values.items(): |
| 580 |
if v == value: |
| 581 |
return k |
| 582 |
raise KeyError(f"Value {value} not found in mapped values") |
| 583 |
else: |
| 584 |
raise ValueError( |
| 585 |
'Values of type `{}` are not allowed ' |
| 586 |
'for Instrument.control'.format(type(values)) |
| 587 |
) |
| 588 |
else: |
| 589 |
vals = get_process(vals) |
| 590 |
return vals |
| 591 |
|
| 592 |
def fset(self, |
| 593 |
value, |
| 594 |
set_command=set_command, |
| 595 |
validator=validator, |
| 596 |
values=values, |
| 597 |
map_values=map_values, |
| 598 |
set_process=set_process, |
| 599 |
command_process=command_process, |
| 600 |
check_set_errors=check_set_errors, |
| 601 |
): |
| 602 |
|
| 603 |
if set_command is None: |
| 604 |
raise LookupError("Property can not be set.") |
| 605 |
|
| 606 |
value = set_process(validator(value, values)) |
| 607 |
if not map_values: |
| 608 |
pass |
| 609 |
elif isinstance(values, (list, tuple, range)): |
| 610 |
value = values.index(value) |
| 611 |
elif isinstance(values, dict): |
| 612 |
value = values[value] |
| 613 |
else: |
| 614 |
raise ValueError( |
| 615 |
'Values of type `{}` are not allowed ' |
| 616 |
'for CommonBase.control'.format(type(values)) |
| 617 |
) |
| 618 |
self.write(command_process(set_command) % value) |
| 619 |
if check_set_errors: |
| 620 |
try: |
| 621 |
error_list = self.check_set_errors() |
| 622 |
except Exception as exc: |
| 623 |
log.error("Exception raised while setting a property with the command " |
| 624 |
f"""'{command_process(set_command) % value}': '{str(exc)}'.""") |
| 625 |
raise |
| 626 |
errors = [str(error) for error in error_list] |
| 627 |
if errors: |
| 628 |
log.error( |
| 629 |
"Error received after trying to set a property with the command " |
| 630 |
f"""'{command_process(set_command) % value}': '{"', '".join(errors)}'.""" |
| 631 |
) |
| 632 |
|
| 633 |
# Add the specified document string to the getter |
| 634 |
fget.__doc__ = docs |
| 635 |
|
| 636 |
if dynamic: |
| 637 |
fget.__doc__ += "(dynamic)" |
| 638 |
return DynamicProperty(fget=fget, fset=fset, |
| 639 |
fget_params_list=CommonBase._fget_params_list, |
| 640 |
fset_params_list=CommonBase._fset_params_list, |
| 641 |
prefix=CommonBase.__reserved_prefix) |
| 642 |
else: |
| 643 |
return property(fget, fset) |
| 644 |
|
| 645 |
@staticmethod |
| 646 |
def measurement(get_command, docs, values=(), map_values=None, |
| 647 |
get_process=lambda v: v, |
| 648 |
command_process=None, |
| 649 |
check_get_errors=False, dynamic=False, |
| 650 |
preprocess_reply=None, |
| 651 |
separator=',', |
| 652 |
maxsplit=-1, |
| 653 |
cast=float, |
| 654 |
values_kwargs=None, |
| 655 |
**kwargs): |
| 656 |
""" Return a property for the class based on the supplied |
| 657 |
commands. This is a measurement quantity that may only be |
| 658 |
read from the instrument, not set. |
| 659 |
|
| 660 |
:param get_command: A string command that asks for the value |
| 661 |
:param docs: A docstring that will be included in the documentation |
| 662 |
:param values: A list, tuple, range, or dictionary of valid values, that can be used |
| 663 |
as to map values if :code:`map_values` is True. |
| 664 |
:param map_values: A boolean flag that determines if the values should be |
| 665 |
interpreted as a map |
| 666 |
:param get_process: A function that take a value and allows processing |
| 667 |
before value mapping, returning the processed value |
| 668 |
:param command_process: A function that take a command and allows processing |
| 669 |
before executing the command, for getting |
| 670 |
|
| 671 |
.. deprecated:: 0.12 |
| 672 |
Use a dynamic property instead. |
| 673 |
|
| 674 |
:param check_get_errors: Toggles checking errors after getting |
| 675 |
:param dynamic: Specify whether the property parameters are meant to be changed in |
| 676 |
instances or subclasses. See :meth:`control` for an usage example. |
| 677 |
:param preprocess_reply: Optional callable used to preprocess the string |
| 678 |
received from the instrument, before splitting it. |
| 679 |
The callable returns the processed string. |
| 680 |
:param separator: A separator character to split the string returned by |
| 681 |
the device into a list. |
| 682 |
:param maxsplit: The string returned by the device is splitted at most `maxsplit` times. |
| 683 |
-1 (default) indicates no limit. |
| 684 |
:param cast: A type to cast each element of the splitted string. |
| 685 |
:param dict values_kwargs: Further keyword arguments for :meth:`values`. |
| 686 |
:param \\**kwargs: Keyword arguments for :meth:`values`. |
| 687 |
|
| 688 |
.. deprecated:: 0.12 |
| 689 |
Use `values_kwargs` dictionary parameter instead. |
| 690 |
""" |
| 691 |
if values_kwargs is None: |
| 692 |
values_kwargs = {} |
| 693 |
if kwargs: |
| 694 |
warn(f"Do not use keyword arguments {kwargs} as `measurement` parameter " |
| 695 |
f"for the `values` method, use `values_kwargs` parameter instead. docs:\n{docs}", |
| 696 |
FutureWarning) |
| 697 |
values_kwargs.update(kwargs) |
| 698 |
|
| 699 |
return CommonBase.control(get_command=get_command, |
| 700 |
set_command=None, |
| 701 |
docs=docs, |
| 702 |
values=values, |
| 703 |
map_values=map_values, |
| 704 |
get_process=get_process, |
| 705 |
command_process=command_process, |
| 706 |
check_get_errors=check_get_errors, |
| 707 |
dynamic=dynamic, |
| 708 |
preprocess_reply=preprocess_reply, |
| 709 |
separator=separator, |
| 710 |
maxsplit=maxsplit, |
| 711 |
cast=cast, |
| 712 |
values_kwargs=values_kwargs, |
| 713 |
) |
| 714 |
|
| 715 |
@staticmethod |
| 716 |
def setting(set_command, docs, |
| 717 |
validator=lambda x, y: x, values=(), map_values=False, |
| 718 |
set_process=lambda v: v, |
| 719 |
check_set_errors=False, dynamic=False, |
| 720 |
): |
| 721 |
"""Return a property for the class based on the supplied |
| 722 |
commands. This property may be set, but raises an exception |
| 723 |
when being read from the instrument. |
| 724 |
|
| 725 |
:param set_command: A string command that writes the value |
| 726 |
:param docs: A docstring that will be included in the documentation |
| 727 |
:param validator: A function that takes both a value and a group of valid values |
| 728 |
and returns a valid value, while it otherwise raises an exception |
| 729 |
:param values: A list, tuple, range, or dictionary of valid values, that can be used |
| 730 |
as to map values if :code:`map_values` is True. |
| 731 |
:param map_values: A boolean flag that determines if the values should be |
| 732 |
interpreted as a map |
| 733 |
:param set_process: A function that takes a value and allows processing |
| 734 |
before value mapping, returning the processed value |
| 735 |
:param check_set_errors: Toggles checking errors after setting |
| 736 |
:param dynamic: Specify whether the property parameters are meant to be changed in |
| 737 |
instances or subclasses. See :meth:`control` for an usage example. |
| 738 |
""" |
| 739 |
|
| 740 |
return CommonBase.control(get_command=None, |
| 741 |
set_command=set_command, |
| 742 |
docs=docs, |
| 743 |
validator=validator, |
| 744 |
values=values, |
| 745 |
map_values=map_values, |
| 746 |
set_process=set_process, |
| 747 |
check_set_errors=check_set_errors, |
| 748 |
dynamic=dynamic, |
| 749 |
) |
| 750 |
|
| 751 |
def check_errors(self): |
| 752 |
"""Read all errors from the instrument and log them. |
| 753 |
|
| 754 |
:return: List of error entries. |
| 755 |
""" |
| 756 |
raise NotImplementedError("Implement it in a subclass.") |
| 757 |
|
| 758 |
def check_get_errors(self): |
| 759 |
"""Check for errors after having gotten a property and log them. |
| 760 |
|
| 761 |
Called if :code:`check_get_errors=True` is set for that property. |
| 762 |
|
| 763 |
If you override this method, you may choose to raise an Exception for certain errors. |
| 764 |
|
| 765 |
:return: List of error entries. |
| 766 |
""" |
| 767 |
raise NotImplementedError("Implement it in a subclass.") |
| 768 |
|
| 769 |
def check_set_errors(self): |
| 770 |
"""Check for errors after having set a property and log them. |
| 771 |
|
| 772 |
Called if :code:`check_set_errors=True` is set for that property. |
| 773 |
|
| 774 |
If you override this method, you may choose to raise an Exception for certain errors. |
| 775 |
|
| 776 |
:return: List of error entries. |
| 777 |
""" |
| 778 |
raise NotImplementedError("Implement it in a subclass.") |