-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathchannel.py
More file actions
1257 lines (1042 loc) · 43.8 KB
/
channel.py
File metadata and controls
1257 lines (1042 loc) · 43.8 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Base class for the channel of an instrument"""
from __future__ import annotations
import sys
import warnings
from collections.abc import Callable, Iterable, Iterator, MutableSequence, Sequence
from typing import TYPE_CHECKING, Any, Generic, Self, cast, overload
from typing_extensions import TypeVar
from qcodes.metadatable import MetadatableWithName
from qcodes.parameters import (
ArrayParameter,
MultiChannelInstrumentParameter,
MultiParameter,
Parameter,
)
from qcodes.parameters.multi_channel_instrument_parameter import InstrumentModuleType
from qcodes.utils import QCoDeSDeprecationWarning, full_class
from qcodes.validators import Validator
from .instrument_base import InstrumentBase
if TYPE_CHECKING:
from typing import Self
from typing_extensions import Unpack
from .instrument import Instrument
from .instrument_base import InstrumentBaseKWArgs
_TIB_co = TypeVar(
"_TIB_co", bound="InstrumentBase", default=InstrumentBase, covariant=True
)
class InstrumentModule(InstrumentBase, Generic[_TIB_co]):
"""
Base class for a module in an instrument.
This could be in the form of a channel (e.g. something that
the instrument has multiple instances of) or another logical grouping
of parameters that you wish to group together separate from the rest of the
instrument.
Args:
parent: The instrument to which this module should be
attached.
name: The name of this module.
**kwargs: Forwarded to the base class.
"""
def __init__(
self, parent: _TIB_co, name: str, **kwargs: Unpack[InstrumentBaseKWArgs]
) -> None:
# need to specify parent before `super().__init__` so that the right
# `full_name` is available in that scope. `full_name` is used for
# registering the filter for the log messages. It is composed by
# iteratively concatenating the full names of the parent instruments
# scope of `Base`
self._parent = parent
super().__init__(name=name, **kwargs)
def __repr__(self) -> str:
"""Custom repr to give parent information"""
return (
f"<{type(self).__name__}: {self.name} of "
f"{type(self._parent).__name__}: {self._parent.name}>"
)
# Pass any commands to read or write from the instrument up to the parent
def write(self, cmd: str) -> None:
return self._parent.write(cmd)
def write_raw(self, cmd: str) -> None:
return self._parent.write_raw(cmd)
def ask(self, cmd: str) -> str:
return self._parent.ask(cmd)
def ask_raw(self, cmd: str) -> str:
return self._parent.ask_raw(cmd)
@property
def parent(self) -> _TIB_co:
return self._parent
@property
def root_instrument(self) -> Instrument:
return self.parent.root_instrument
@property
def name_parts(self) -> list[str]:
name_parts = list(self._parent.name_parts)
name_parts.append(self.short_name)
return name_parts
class InstrumentChannel(InstrumentModule[_TIB_co], Generic[_TIB_co]):
pass
T = TypeVar("T", bound="ChannelTuple")
class ChannelTuple(MetadatableWithName, Sequence[InstrumentModuleType]):
"""
Container for channelized parameters that allows for sweeps over
all channels, as well as addressing of individual channels.
This behaves like a python tuple i.e. it implements the
:class:`collections.abc.Sequence` interface.
Args:
parent: The instrument to which this ChannelTuple
should be attached.
name: The name of the ChannelTuple.
chan_type: The type of channel contained
within this tuple.
chan_list: An optional iterable of
channels of type ``chan_type``.
snapshotable: Optionally disables taking of snapshots
for a given ChannelTuple. This is used when objects
stored inside a ChannelTuple are accessible in multiple
ways and should not be repeated in an instrument snapshot.
multichan_paramclass: The class of
the object to be returned by the :meth:`__getattr__`
method of :class:`ChannelTuple`.
Should be a subclass of :class:`.MultiChannelInstrumentParameter`.
Defaults to :class:`.MultiChannelInstrumentParameter` if None.
Raises:
ValueError: If ``chan_type`` is not a subclass of
:class:`InstrumentChannel`
ValueError: If ``multichan_paramclass`` is not a subclass of
:class:`.MultiChannelInstrumentParameter` (note that a class is a
subclass of itself).
"""
def __init__(
self,
parent: InstrumentBase,
name: str,
chan_type: type[InstrumentModuleType],
chan_list: Sequence[InstrumentModuleType] | None = None,
snapshotable: bool = True,
multichan_paramclass: type[MultiChannelInstrumentParameter] | None = None,
):
if multichan_paramclass is None:
multichan_paramclass = MultiChannelInstrumentParameter
super().__init__()
self._parent = parent
self._name = name
if not isinstance(chan_type, type) or not issubclass(
chan_type, InstrumentModule
):
raise ValueError(
"ChannelTuple can only hold instances of type InstrumentModule"
)
if not isinstance(multichan_paramclass, type) or not issubclass(
multichan_paramclass, MultiChannelInstrumentParameter
):
raise ValueError(
"multichan_paramclass must be a (subclass of) "
"MultiChannelInstrumentParameter"
)
self._chan_type: type[InstrumentModuleType] = chan_type
self._snapshotable = snapshotable
self._paramclass = multichan_paramclass
self._channel_mapping: dict[str, InstrumentModuleType] = {}
# provide lookup of channels by name
# If a list of channels is not provided, define a list to store
# channels. This will eventually become a locked tuple.
self._channels: list[InstrumentModuleType]
if chan_list is None:
self._channels = []
else:
self._channels = list(chan_list)
self._channel_mapping = {
channel.short_name: channel for channel in self._channels
}
if not all(isinstance(chan, chan_type) for chan in self._channels):
raise TypeError(
f"All items in this ChannelTuple must be of "
f"type {chan_type.__name__}."
)
@overload
def __getitem__(self, index: int) -> InstrumentModuleType: ...
@overload
def __getitem__(self: Self, index: slice | tuple[int, ...]) -> Self: ...
def __getitem__(
self: Self, index: int | slice | tuple[int, ...]
) -> InstrumentModuleType | Self:
"""
Return either a single channel, or a new :class:`ChannelTuple`
containing only the specified channels
Args:
index: Either a single channel index or a slice of channels
to get
"""
if isinstance(index, slice):
return type(self)(
self._parent,
self._name,
self._chan_type,
self._channels[index],
multichan_paramclass=self._paramclass,
snapshotable=self._snapshotable,
)
elif isinstance(index, tuple):
return type(self)(
self._parent,
self._name,
self._chan_type,
[self._channels[j] for j in index],
multichan_paramclass=self._paramclass,
snapshotable=self._snapshotable,
)
return self._channels[index]
def __iter__(self) -> Iterator[InstrumentModuleType]:
return iter(self._channels)
def __reversed__(self) -> Iterator[InstrumentModuleType]:
return reversed(self._channels)
def __len__(self) -> int:
return len(self._channels)
def __contains__(self, value: object) -> bool:
return value in self._channels
def __repr__(self) -> str:
return (
f"ChannelTuple({self._parent!r}, "
f"{self._chan_type.__name__}, {self._channels!r})"
)
def __add__(self: Self, other: ChannelTuple) -> Self:
"""
Return a new ChannelTuple containing the channels from both
:class:`ChannelTuple` self and r.
Both ChannelTuple must hold the same type and have the same parent.
Args:
other: Right argument to add.
"""
if not isinstance(self, ChannelTuple) or not isinstance(other, ChannelTuple):
raise TypeError(
f"Can't add objects of type"
f" {type(self).__name__} and {type(other).__name__} together"
)
if self._chan_type != other._chan_type:
raise TypeError(
f"Both l and r arguments to add must contain "
f"channels of the same type."
f" Adding channels of type "
f"{self._chan_type.__name__} and {other._chan_type.__name__}."
)
if self._parent != other._parent:
raise ValueError("Can only add channels from the same parent together.")
return type(self)(
self._parent,
self._name,
self._chan_type,
list(self._channels) + list(other._channels),
snapshotable=self._snapshotable,
)
@property
def short_name(self) -> str:
return self._name
@property
def full_name(self) -> str:
return "_".join(self.name_parts)
@property
def name_parts(self) -> list[str]:
"""
List of the parts that make up the full name of this function
"""
if self._parent is not None:
name_parts = getattr(self._parent, "name_parts", [])
if name_parts == []:
# add fallback for the case where someone has bound
# the function to something that is not an instrument
# but perhaps it has a name anyway?
name = getattr(self._parent, "name", None)
if name is not None:
name_parts = [name]
else:
name_parts = []
name_parts.append(self.short_name)
return name_parts
def index(
self,
value: InstrumentModuleType,
start: int = 0,
stop: int = sys.maxsize,
) -> int:
"""
Return the index of the given object
Args:
value: The object to find in the channel list.
start: Index to start searching from.
stop: Index to stop searching at.
"""
return self._channels.index(value, start, stop)
def count(self, value: InstrumentModuleType) -> int:
"""Returns number of instances of the given object in the list
Args:
value: The object to find in the ChannelTuple.
"""
return self._channels.count(value)
def get_channels_by_name(self: Self, *names: str) -> Self:
"""
Get a a ChannelTuple that only contains the selected names.
Args:
*names: channel names
"""
if len(names) == 0:
raise TypeError("one or more names must be given")
selected_channels = tuple(self._channel_mapping[name] for name in names)
return type(self)(
self._parent,
self._name,
self._chan_type,
selected_channels,
self._snapshotable,
self._paramclass,
)
def get_channel_by_name(self: Self, *names: str) -> InstrumentModuleType | Self:
"""
Get a channel by name, or a ChannelTuple if multiple names are given.
Args:
*names: channel names
"""
if len(names) == 0:
raise TypeError("one or more names must be given")
if len(names) == 1:
return self._channel_mapping[names[0]]
warnings.warn(
"Supplying more than one name to get_channel_by_name is deprecated, use get_channels_by_name instead",
category=QCoDeSDeprecationWarning,
)
selected_channels = tuple(self._channel_mapping[name] for name in names)
return type(self)(
self._parent,
self._name,
self._chan_type,
selected_channels,
self._snapshotable,
self._paramclass,
)
def get_validator(self) -> ChannelTupleValidator:
"""
Returns a validator that checks that the returned object is a channel
in this ChannelTuple
"""
return ChannelTupleValidator(self)
def snapshot_base(
self,
update: bool | None = True,
params_to_skip_update: Sequence[str] | None = None,
) -> dict[Any, Any]:
"""
State of the instrument as a JSON-compatible dict (everything that
the custom JSON encoder class
:class:`.NumpyJSONEncoder` supports).
Args:
update: If True, update the state by querying the
instrument. If None only update if the state is known to be
invalid. If False, just use the latest values in memory
and never update.
params_to_skip_update: List of parameter names that will be skipped
in update even if update is True. This is useful if you have
parameters that are slow to update but can be updated in a
different way (as in the qdac). If you want to skip the
update of certain parameters in all snapshots, use the
``snapshot_get`` attribute of those parameters instead.
Returns:
dict: base snapshot
"""
if self._snapshotable:
snap = {
"channels": {
chan.name: chan.snapshot(update=update) for chan in self._channels
},
"snapshotable": self._snapshotable,
"__class__": full_class(self),
}
else:
snap = {
"snapshotable": self._snapshotable,
"__class__": full_class(self),
}
return snap
def multi_parameter(
self: Self, name: str
) -> MultiChannelInstrumentParameter[InstrumentModuleType]:
"""
Look up a parameter by name. If this is the name of a parameter on the
channel type contained in this container return a multi-channel parameter
that controls this parameter on all channels in the Sequence.
Args:
name: The name of the parameter that we want to
operate on.
Returns:
MultiChannelInstrumentParameter: The multi-channel parameter
that can be used to get or set all items in a channel list
simultaneously.
Raises:
AttributeError: If no parameter with the given name exists.
"""
if len(self) > 0:
# Check if this is a valid parameter
if name in self._channels[0].parameters:
param = self._construct_multiparam(name)
return param
raise AttributeError(
f"'{self.__class__.__name__}' object has no parameter '{name}'"
)
def multi_function(self, name: str) -> Callable[..., None]:
"""
Look up a callable or QCoDeS function by name. If this is the name of a callable or function
on the channel type contained in this container return a callable that calls this callable on
all channels in the Sequence
Args:
name: The name of the callable/function that we want to
operate on.
Returns:
Callable that calls the functions/callables on all channels in the Sequence.
Raises:
AttributeError: If no callable with the given name exists.
"""
if len(self) == 0:
raise AttributeError(
f"'{self.__class__.__name__}' object has no callable or function '{name}'"
)
# Check if this is a valid function
if name in self._channels[0].functions:
# We want to return a reference to a function that would call the
# function for each of the channels in turn.
def multi_func(*args: Any) -> None:
for chan in self._channels:
chan.functions[name](*args)
return multi_func
# check if this is a method on the channels in the
# sequence
maybe_callable = getattr(self._channels[0], name, None)
if callable(maybe_callable):
def multi_callable(*args: Any) -> None:
for chan in self._channels:
getattr(chan, name)(*args)
return multi_callable
raise AttributeError(
f"'{self.__class__.__name__}' object has no callable or function '{name}'"
)
def __getattr__(self, name: str) -> Any:
"""
Look up an attribute by name. If this is the name of a parameter or
a function on the channel type contained in this container return a
multi-channel function or parameter that can be used to get or
set all items in a channel list simultaneously. If this is the
name of a channel, return that channel. This interface is not
type safe as it will return any matching attribute. To get a channel
by name use ``get_channels_by_name`` instead. To get a parameter use
``multi_parameter``. To get a a callable or a qcodes function use
``multi_function``
Args:
name: The name of the parameter, function or channel that we want to
operate on.
"""
if len(self) > 0:
# Check if this is a valid parameter
if name in self._channels[0].parameters:
param = self._construct_multiparam(name)
return param
# Check if this is a valid function
if name in self._channels[0].functions:
# We want to return a reference to a function that would call the
# function for each of the channels in turn.
def multi_func(*args: Any) -> None:
for chan in self._channels:
chan.functions[name](*args)
return multi_func
# check if this is a method on the channels in the
# sequence
maybe_callable = getattr(self._channels[0], name, None)
if callable(maybe_callable):
def multi_callable(*args: Any) -> None:
for chan in self._channels:
getattr(chan, name)(*args)
return multi_callable
try:
return self._channel_mapping[name]
except KeyError:
pass
raise AttributeError(
f"'{self.__class__.__name__}' object has no attribute '{name}'"
)
def _construct_multiparam(self, name: str) -> MultiChannelInstrumentParameter:
setpoints = None
setpoint_names = None
setpoint_labels = None
setpoint_units = None
# We need to construct a MultiParameter object to get each of the
# values our of each parameter in our list, we don't currently try
# to construct a multiparameter from a list of multi parameters
if isinstance(self._channels[0].parameters[name], MultiParameter):
raise NotImplementedError(
"Slicing is currently not supported for MultiParameters"
)
parameters = cast(
"list[Parameter | ArrayParameter]",
[chan.parameters[name] for chan in self._channels],
)
names = tuple(f"{chan.name}_{name}" for chan in self._channels)
labels = tuple(parameter.label for parameter in parameters)
units = tuple(parameter.unit for parameter in parameters)
if isinstance(parameters[0], ArrayParameter):
arrayparameters = cast("list[ArrayParameter]", parameters)
shapes = tuple(parameter.shape for parameter in arrayparameters)
if arrayparameters[0].setpoints:
setpoints = tuple(parameter.setpoints for parameter in arrayparameters)
if arrayparameters[0].setpoint_names:
setpoint_names = tuple(
parameter.setpoint_names for parameter in arrayparameters
)
if arrayparameters[0].setpoint_labels:
setpoint_labels = tuple(
parameter.setpoint_labels for parameter in arrayparameters
)
if arrayparameters[0].setpoint_units:
setpoint_units = tuple(
parameter.setpoint_units for parameter in arrayparameters
)
else:
shapes = tuple(() for _ in self._channels)
param = self._paramclass(
self._channels,
param_name=name,
name=f"Multi_{name}",
names=names,
shapes=shapes,
instrument=self._parent,
labels=labels,
units=units,
setpoints=setpoints,
setpoint_names=setpoint_names,
setpoint_units=setpoint_units,
setpoint_labels=setpoint_labels,
bind_to_instrument=False,
)
return param
def __dir__(self) -> list[Any]:
names = list(super().__dir__())
if self._channels:
names += list(self._channels[0].parameters.keys())
names += list(self._channels[0].functions.keys())
names += [channel.short_name for channel in self._channels]
return sorted(set(names))
def print_readable_snapshot(
self, update: bool = False, max_chars: int = 80
) -> None:
if self._snapshotable:
for channel in self._channels:
channel.print_readable_snapshot(update=update, max_chars=max_chars)
def invalidate_cache(self) -> None:
"""
Invalidate the cache of all parameters on the ChannelTuple.
"""
for chan in self._channels:
chan.invalidate_cache()
# in index method the parameter obj should be called value but that would
# be an incompatible change
class ChannelList( # pyright: ignore[reportIncompatibleMethodOverride]
ChannelTuple[InstrumentModuleType], MutableSequence[InstrumentModuleType]
):
"""
Mutable Container for channelized parameters that allows for sweeps over
all channels, as well as addressing of individual channels.
This behaves like a python list i.e. it implements the
:class:`collections.abc.MutableSequence` interface.
Note it may be useful to use the mutable ChannelList while constructing it.
E.g. adding channels as they are created, but in most use cases it is recommended
to convert this to a :class:`ChannelTuple` before adding it to an instrument.
This can be done using the :meth:`to_channel_tuple` method.
Args:
parent: The instrument to which this :class:`ChannelList`
should be attached.
name: The name of the :class:`ChannelList`.
chan_type: The type of channel contained
within this list.
chan_list: An optional iterable of
channels of type ``chan_type``. This will create a list and
immediately lock the :class:`ChannelList`.
snapshotable: Optionally disables taking of snapshots
for a given ChannelList. This is used when objects
stored inside a ChannelList are accessible in multiple
ways and should not be repeated in an instrument snapshot.
multichan_paramclass: The class of
the object to be returned by the :meth:`__getattr__`
method of :class:`ChannelList`.
Should be a subclass of :class:`.MultiChannelInstrumentParameter`.
Defaults to :class:`.MultiChannelInstrumentParameter` if None.
Raises:
ValueError: If ``chan_type`` is not a subclass of
:class:`InstrumentChannel`
ValueError: If ``multichan_paramclass`` is not a subclass of
:class:`.MultiChannelInstrumentParameter` (note that a class is a
subclass of itself).
"""
def __init__(
self,
parent: InstrumentBase,
name: str,
chan_type: type[InstrumentModuleType],
chan_list: Sequence[InstrumentModuleType] | None = None,
snapshotable: bool = True,
multichan_paramclass: type[MultiChannelInstrumentParameter] | None = None,
):
if multichan_paramclass is None:
multichan_paramclass = MultiChannelInstrumentParameter
super().__init__(
parent, name, chan_type, chan_list, snapshotable, multichan_paramclass
)
if len(self._channels) > 0:
self._locked = True
else:
self._locked = False
@overload
def __delitem__(self, index: int) -> None: ...
@overload
def __delitem__(self, index: slice) -> None: ...
def __delitem__(self, index: int | slice) -> None:
if self._locked:
raise AttributeError("Cannot delete from a locked channel list")
self._channels.__delitem__(index)
self._channel_mapping = {
channel.short_name: channel for channel in self._channels
}
@overload
def __setitem__(self, index: int, value: InstrumentModuleType) -> None: ...
@overload
def __setitem__(
self, index: slice, value: Iterable[InstrumentModuleType]
) -> None: ...
def __setitem__(
self,
index: int | slice,
value: InstrumentModuleType | Iterable[InstrumentModuleType],
) -> None:
if self._locked:
raise AttributeError("Cannot set item in a locked channel list")
# update mapping
# asserts added to work around https://github.com/python/mypy/issues/7858
if isinstance(index, int):
assert isinstance(value, InstrumentModule)
self._channels[index] = value # type: ignore[assignment]
# mypy does not know that InstrumentModuleType is a TypeVar bound to
# InstrumentModule so complains here
else:
assert not isinstance(value, InstrumentModule)
self._channels[index] = value
self._channel_mapping = {
channel.short_name: channel for channel in self._channels
}
def append(self, value: InstrumentModuleType) -> None:
"""
Append a Channel to this list. Requires that the ChannelList is not
locked and that the channel is of the same type as the ones in the list.
Args:
value: New channel to add to the list.
"""
if self._locked:
raise AttributeError("Cannot append to a locked channel list")
if not isinstance(value, self._chan_type):
raise TypeError(
f"All items in a channel list must be of the same "
f"type. Adding {type(value).__name__} to a "
f"list of {self._chan_type.__name__}."
)
self._channel_mapping[value.short_name] = value
self._channels.append(value)
def clear(self) -> None:
"""
Clear all items from the ChannelList.
"""
if self._locked:
raise AttributeError("Cannot clear a locked ChannelList")
# when not locked the _channels seq is a list
self._channels.clear()
self._channel_mapping.clear()
def remove(self, value: InstrumentModuleType) -> None:
"""
Removes value from ChannelList if not locked.
Args:
value: Channel to remove from the list.
"""
if self._locked:
raise AttributeError("Cannot remove from a locked channel list")
else:
self._channels.remove(value)
self._channel_mapping.pop(value.short_name)
def extend(self, values: Iterable[InstrumentModuleType]) -> None:
"""
Insert an iterable of InstrumentModules into the list of channels.
Args:
values: A list of InstrumentModules to add into the
:class:`ChannelList`.
"""
# values may be a generator but we need to iterate over it twice
# below so copy it into a tuple just in case.
if self._locked:
raise AttributeError("Cannot extend a locked channel list")
values_tuple = tuple(values)
if not all(isinstance(value, self._chan_type) for value in values_tuple):
raise TypeError("All items in a channel list must be of the same type.")
self._channels.extend(values_tuple)
self._channel_mapping.update(
{value.short_name: value for value in values_tuple}
)
def insert(self, index: int, value: InstrumentModuleType) -> None:
"""
Insert an object into the ChannelList at a specific index.
Args:
index: Index to insert object.
value: Object of type chan_type to insert.
"""
if self._locked:
raise AttributeError("Cannot insert into a locked channel list")
if not isinstance(value, self._chan_type):
raise TypeError(
f"All items in a channel list must be of the same "
f"type. Adding {type(value).__name__} to a list of {self._chan_type.__name__}."
)
self._channels.insert(index, value)
self._channel_mapping[value.short_name] = value
def get_validator(self) -> ChannelTupleValidator:
"""
Returns a validator that checks that the returned object is a channel
in this ChannelList.
Raises:
AttributeError: If the ChannelList is not locked.
"""
if not self._locked:
raise AttributeError(
"Cannot create a validator for an unlocked ChannelList"
)
return super().get_validator()
def lock(self) -> None:
"""
Lock the channel list. Once this is done, the ChannelList is
locked and any future changes to the list are prevented.
Note this is not recommended and may be deprecated in the future.
Use ``to_channel_tuple`` to convert this into a tuple instead.
"""
if self._locked:
return
self._locked = True
def to_channel_tuple(self) -> ChannelTuple[InstrumentModuleType]:
"""
Returns a ChannelTuple build from this ChannelList containing the
same channels but without the ability to be modified.
"""
return ChannelTuple(
self._parent,
self._name,
self._chan_type,
self._channels,
multichan_paramclass=self._paramclass,
snapshotable=self._snapshotable,
)
def __repr__(self) -> str:
return (
f"ChannelList({self._parent!r}, "
f"{self._chan_type.__name__}, {self._channels!r})"
)
class ChannelTupleValidator(Validator[InstrumentChannel]):
"""
A validator that checks that the returned object is a member of the
ChannelTuple with which the validator was constructed.
This class will not normally be created directly, but created from a channel
list using the ``ChannelTuple.get_validator`` method.
Args:
channel_list: the ChannelTuple that should be checked
against. The channel list must be locked and populated before it
can be used to construct a validator.
"""
def __init__(self, channel_list: ChannelTuple) -> None:
# Save the base parameter list
if not isinstance(channel_list, ChannelTuple):
raise ValueError(
"channel_list must be a ChannelTuple "
"object containing the "
"channels that should be validated"
)
if isinstance(channel_list, ChannelList) and not channel_list._locked:
raise AttributeError(
"channel_list must be locked before it can "
"be used to create a validator"
)
self._channel_list = channel_list
def validate(self, value: InstrumentChannel, context: str = "") -> None:
"""
Checks to see that value is a member of the ChannelTuple referenced by
this validator
Args:
value: the value to be checked against the
reference channel list.
context: the context of the call, used as part of the exception
raised.
"""
if value not in self._channel_list:
raise ValueError(
f"{value!r} is not part of the expected channel list; {context}"
)
class ChannelListValidator(ChannelTupleValidator):
"""Alias for backwards compatibility. Do not use"""
pass
class AutoLoadableInstrumentChannel(InstrumentChannel):
"""
This subclass provides extensions to auto-load channels
from instruments and adds methods to create and delete
channels when possible. Please note that `channel` in this
context does not necessarily mean a physical instrument channel,
but rather an instrument sub-module. For some instruments,
these sub-modules can be created and deleted at will.
"""
@classmethod
def load_from_instrument(
cls,
parent: InstrumentBase,
channel_list: AutoLoadableChannelList | None = None,
**kwargs: Any,
) -> list[Self]:
"""
Load channels that already exist on the instrument
Args:
parent: The instrument through which the instrument
channel is accessible
channel_list: The channel list this
channel is a part of
**kwargs: Keyword arguments needed to create the channels
Returns:
List of instrument channel instances created for channels
that already exist on the instrument
"""
obj_list = []
for new_kwargs in cls._discover_from_instrument(parent, **kwargs):
obj = cls(parent, existence=True, channel_list=channel_list, **new_kwargs)
obj_list.append(obj)
return obj_list
@classmethod
def _discover_from_instrument(
cls, parent: InstrumentBase, **kwargs: Any
) -> list[dict[Any, Any]]:
"""
Discover channels on the instrument and return a list kwargs to create
these channels in memory
Args:
parent: The instrument through which the instrument
channel is accessible
**kwargs: Keyword arguments needed to discover the channels
Returns:
List of keyword arguments for channel instance initialization
for each channel that already exists on the physical instrument