-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
backendconfiguration.py
1040 lines (920 loc) · 39.3 KB
/
backendconfiguration.py
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
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Backend Configuration Classes."""
import re
import copy
import numbers
from typing import Dict, List, Any, Iterable, Tuple, Union
from collections import defaultdict
from qiskit.exceptions import QiskitError
from qiskit.providers.exceptions import BackendConfigurationError
from qiskit.pulse.channels import (
AcquireChannel,
Channel,
ControlChannel,
DriveChannel,
MeasureChannel,
)
from qiskit.utils import deprecate_func
class GateConfig:
"""Class representing a Gate Configuration
Attributes:
name: the gate name as it will be referred to in OpenQASM.
parameters: variable names for the gate parameters (if any).
qasm_def: definition of this gate in terms of OpenQASM 2 primitives U
and CX.
"""
@deprecate_func(
since="1.2",
removal_timeline="in the 2.0 release",
additional_msg="The models in ``qiskit.providers.models`` are part "
"of the deprecated `BackendV1` workflow and no longer necessary for `BackendV2`. If a user "
"workflow requires these representations it likely relies on deprecated functionality and "
"should be updated to use `BackendV2`.",
stacklevel=3,
)
def __init__(
self,
name,
parameters,
qasm_def,
coupling_map=None,
latency_map=None,
conditional=None,
description=None,
):
"""Initialize a GateConfig object
Args:
name (str): the gate name as it will be referred to in OpenQASM.
parameters (list): variable names for the gate parameters (if any)
as a list of strings.
qasm_def (str): definition of this gate in terms of OpenQASM 2 primitives U and CX.
coupling_map (list): An optional coupling map for the gate. In
the form of a list of lists of integers representing the qubit
groupings which are coupled by this gate.
latency_map (list): An optional map of latency for the gate. In the
the form of a list of lists of integers of either 0 or 1
representing an array of dimension
len(coupling_map) X n_registers that specifies the register
latency (1: fast, 0: slow) conditional operations on the gate
conditional (bool): Optionally specify whether this gate supports
conditional operations (true/false). If this is not specified,
then the gate inherits the conditional property of the backend.
description (str): Description of the gate operation
"""
self.name = name
self.parameters = parameters
self.qasm_def = qasm_def
# coupling_map with length 0 is invalid
if coupling_map:
self.coupling_map = coupling_map
# latency_map with length 0 is invalid
if latency_map:
self.latency_map = latency_map
if conditional is not None:
self.conditional = conditional
if description is not None:
self.description = description
@classmethod
def from_dict(cls, data):
"""Create a new GateConfig object from a dictionary.
Args:
data (dict): A dictionary representing the GateConfig to create.
It will be in the same format as output by
:func:`to_dict`.
Returns:
GateConfig: The GateConfig from the input dictionary.
"""
return cls(**data)
def to_dict(self):
"""Return a dictionary format representation of the GateConfig.
Returns:
dict: The dictionary form of the GateConfig.
"""
out_dict = {
"name": self.name,
"parameters": self.parameters,
"qasm_def": self.qasm_def,
}
if hasattr(self, "coupling_map"):
out_dict["coupling_map"] = self.coupling_map
if hasattr(self, "latency_map"):
out_dict["latency_map"] = self.latency_map
if hasattr(self, "conditional"):
out_dict["conditional"] = self.conditional
if hasattr(self, "description"):
out_dict["description"] = self.description
return out_dict
def __eq__(self, other):
if isinstance(other, GateConfig):
if self.to_dict() == other.to_dict():
return True
return False
def __repr__(self):
out_str = f"GateConfig({self.name}, {self.parameters}, {self.qasm_def}"
for i in ["coupling_map", "latency_map", "conditional", "description"]:
if hasattr(self, i):
out_str += ", " + repr(getattr(self, i))
out_str += ")"
return out_str
class UchannelLO:
"""Class representing a U Channel LO
Attributes:
q: Qubit that scale corresponds too.
scale: Scale factor for qubit frequency.
"""
@deprecate_func(
since="1.2",
removal_timeline="in the 2.0 release",
additional_msg="The models in ``qiskit.providers.models`` are part "
"of the deprecated `BackendV1` workflow and no longer necessary for `BackendV2`. If a user "
"workflow requires these representations it likely relies on deprecated functionality and "
"should be updated to use `BackendV2`.",
)
def __init__(self, q, scale):
"""Initialize a UchannelLOSchema object
Args:
q (int): Qubit that scale corresponds too. Must be >= 0.
scale (complex): Scale factor for qubit frequency.
Raises:
QiskitError: If q is < 0
"""
if q < 0:
raise QiskitError("q must be >=0")
self.q = q
self.scale = scale
@classmethod
def from_dict(cls, data):
"""Create a new UchannelLO object from a dictionary.
Args:
data (dict): A dictionary representing the UChannelLO to
create. It will be in the same format as output by
:func:`to_dict`.
Returns:
UchannelLO: The UchannelLO from the input dictionary.
"""
return cls(**data)
def to_dict(self):
"""Return a dictionary format representation of the UChannelLO.
Returns:
dict: The dictionary form of the UChannelLO.
"""
out_dict = {
"q": self.q,
"scale": self.scale,
}
return out_dict
def __eq__(self, other):
if isinstance(other, UchannelLO):
if self.to_dict() == other.to_dict():
return True
return False
def __repr__(self):
return f"UchannelLO({self.q}, {self.scale})"
class QasmBackendConfiguration:
"""Class representing an OpenQASM 2.0 Backend Configuration.
Attributes:
backend_name: backend name.
backend_version: backend version in the form X.Y.Z.
n_qubits: number of qubits.
basis_gates: list of basis gates names on the backend.
gates: list of basis gates on the backend.
local: backend is local or remote.
simulator: backend is a simulator.
conditional: backend supports conditional operations.
open_pulse: backend supports open pulse.
memory: backend supports memory.
max_shots: maximum number of shots supported.
"""
_data = {}
@deprecate_func(
since="1.2",
removal_timeline="in the 2.0 release",
additional_msg="The models in ``qiskit.providers.models`` are part "
"of the deprecated `BackendV1` workflow and no longer necessary for `BackendV2`. If a user "
"workflow requires these representations it likely relies on deprecated functionality and "
"should be updated to use `BackendV2`.",
stacklevel=3,
)
def __init__(
self,
backend_name,
backend_version,
n_qubits,
basis_gates,
gates,
local,
simulator,
conditional,
open_pulse,
memory,
max_shots,
coupling_map,
supported_instructions=None,
dynamic_reprate_enabled=False,
rep_delay_range=None,
default_rep_delay=None,
max_experiments=None,
sample_name=None,
n_registers=None,
register_map=None,
configurable=None,
credits_required=None,
online_date=None,
display_name=None,
description=None,
tags=None,
dt=None,
dtm=None,
processor_type=None,
parametric_pulses=None,
**kwargs,
):
"""Initialize a QasmBackendConfiguration Object
Args:
backend_name (str): The backend name
backend_version (str): The backend version in the form X.Y.Z
n_qubits (int): the number of qubits for the backend
basis_gates (list): The list of strings for the basis gates of the
backends
gates (list): The list of GateConfig objects for the basis gates of
the backend
local (bool): True if the backend is local or False if remote
simulator (bool): True if the backend is a simulator
conditional (bool): True if the backend supports conditional
operations
open_pulse (bool): True if the backend supports OpenPulse
memory (bool): True if the backend supports memory
max_shots (int): The maximum number of shots allowed on the backend
coupling_map (list): The coupling map for the device
supported_instructions (List[str]): Instructions supported by the backend.
dynamic_reprate_enabled (bool): whether delay between programs can be set dynamically
(ie via ``rep_delay``). Defaults to False.
rep_delay_range (List[float]): 2d list defining supported range of repetition
delays for backend in μs. First entry is lower end of the range, second entry is
higher end of the range. Optional, but will be specified when
``dynamic_reprate_enabled=True``.
default_rep_delay (float): Value of ``rep_delay`` if not specified by user and
``dynamic_reprate_enabled=True``.
max_experiments (int): The maximum number of experiments per job
sample_name (str): Sample name for the backend
n_registers (int): Number of register slots available for feedback
(if conditional is True)
register_map (list): An array of dimension n_qubits X
n_registers that specifies whether a qubit can store a
measurement in a certain register slot.
configurable (bool): True if the backend is configurable, if the
backend is a simulator
credits_required (bool): True if backend requires credits to run a
job.
online_date (datetime.datetime): The date that the device went online
display_name (str): Alternate name field for the backend
description (str): A description for the backend
tags (list): A list of string tags to describe the backend
dt (float): Qubit drive channel timestep in nanoseconds.
dtm (float): Measurement drive channel timestep in nanoseconds.
processor_type (dict): Processor type for this backend. A dictionary of the
form ``{"family": <str>, "revision": <str>, segment: <str>}`` such as
``{"family": "Canary", "revision": "1.0", segment: "A"}``.
- family: Processor family of this backend.
- revision: Revision version of this processor.
- segment: Segment this processor belongs to within a larger chip.
parametric_pulses (list): A list of pulse shapes which are supported on the backend.
For example: ``['gaussian', 'constant']``
**kwargs: optional fields
"""
self._data = {}
self.backend_name = backend_name
self.backend_version = backend_version
self.n_qubits = n_qubits
self.basis_gates = basis_gates
self.gates = gates
self.local = local
self.simulator = simulator
self.conditional = conditional
self.open_pulse = open_pulse
self.memory = memory
self.max_shots = max_shots
self.coupling_map = coupling_map
if supported_instructions:
self.supported_instructions = supported_instructions
self.dynamic_reprate_enabled = dynamic_reprate_enabled
if rep_delay_range:
self.rep_delay_range = [_rd * 1e-6 for _rd in rep_delay_range] # convert to sec
if default_rep_delay is not None:
self.default_rep_delay = default_rep_delay * 1e-6 # convert to sec
# max_experiments must be >=1
if max_experiments:
self.max_experiments = max_experiments
if sample_name is not None:
self.sample_name = sample_name
# n_registers must be >=1
if n_registers:
self.n_registers = 1
# register_map must have at least 1 entry
if register_map:
self.register_map = register_map
if configurable is not None:
self.configurable = configurable
if credits_required is not None:
self.credits_required = credits_required
if online_date is not None:
self.online_date = online_date
if display_name is not None:
self.display_name = display_name
if description is not None:
self.description = description
if tags is not None:
self.tags = tags
# Add pulse properties here because some backends do not
# fit within the Qasm / Pulse backend partitioning in Qiskit
if dt is not None:
self.dt = dt * 1e-9
if dtm is not None:
self.dtm = dtm * 1e-9
if processor_type is not None:
self.processor_type = processor_type
if parametric_pulses is not None:
self.parametric_pulses = parametric_pulses
# convert lo range from GHz to Hz
if "qubit_lo_range" in kwargs:
kwargs["qubit_lo_range"] = [
[min_range * 1e9, max_range * 1e9]
for (min_range, max_range) in kwargs["qubit_lo_range"]
]
if "meas_lo_range" in kwargs:
kwargs["meas_lo_range"] = [
[min_range * 1e9, max_range * 1e9]
for (min_range, max_range) in kwargs["meas_lo_range"]
]
# convert rep_times from μs to sec
if "rep_times" in kwargs:
kwargs["rep_times"] = [_rt * 1e-6 for _rt in kwargs["rep_times"]]
self._data.update(kwargs)
def __getattr__(self, name):
try:
return self._data[name]
except KeyError as ex:
raise AttributeError(f"Attribute {name} is not defined") from ex
@classmethod
def from_dict(cls, data):
"""Create a new GateConfig object from a dictionary.
Args:
data (dict): A dictionary representing the GateConfig to create.
It will be in the same format as output by
:func:`to_dict`.
Returns:
GateConfig: The GateConfig from the input dictionary.
"""
in_data = copy.copy(data)
gates = [GateConfig.from_dict(x) for x in in_data.pop("gates")]
in_data["gates"] = gates
return cls(**in_data)
def to_dict(self):
"""Return a dictionary format representation of the GateConfig.
Returns:
dict: The dictionary form of the GateConfig.
"""
out_dict = {
"backend_name": self.backend_name,
"backend_version": self.backend_version,
"n_qubits": self.n_qubits,
"basis_gates": self.basis_gates,
"gates": [x.to_dict() for x in self.gates],
"local": self.local,
"simulator": self.simulator,
"conditional": self.conditional,
"open_pulse": self.open_pulse,
"memory": self.memory,
"max_shots": self.max_shots,
"coupling_map": self.coupling_map,
"dynamic_reprate_enabled": self.dynamic_reprate_enabled,
}
if hasattr(self, "supported_instructions"):
out_dict["supported_instructions"] = self.supported_instructions
if hasattr(self, "rep_delay_range"):
out_dict["rep_delay_range"] = [_rd * 1e6 for _rd in self.rep_delay_range]
if hasattr(self, "default_rep_delay"):
out_dict["default_rep_delay"] = self.default_rep_delay * 1e6
for kwarg in [
"max_experiments",
"sample_name",
"n_registers",
"register_map",
"configurable",
"credits_required",
"online_date",
"display_name",
"description",
"tags",
"dt",
"dtm",
"processor_type",
"parametric_pulses",
]:
if hasattr(self, kwarg):
out_dict[kwarg] = getattr(self, kwarg)
out_dict.update(self._data)
if "dt" in out_dict:
out_dict["dt"] *= 1e9
if "dtm" in out_dict:
out_dict["dtm"] *= 1e9
# Use GHz in dict
if "qubit_lo_range" in out_dict:
out_dict["qubit_lo_range"] = [
[min_range * 1e-9, max_range * 1e-9]
for (min_range, max_range) in out_dict["qubit_lo_range"]
]
if "meas_lo_range" in out_dict:
out_dict["meas_lo_range"] = [
[min_range * 1e-9, max_range * 1e-9]
for (min_range, max_range) in out_dict["meas_lo_range"]
]
return out_dict
@property
def num_qubits(self):
"""Returns the number of qubits.
In future, `n_qubits` should be replaced in favor of `num_qubits` for consistent use
throughout Qiskit. Until this is properly refactored, this property serves as intermediate
solution.
"""
return self.n_qubits
def __eq__(self, other):
if isinstance(other, QasmBackendConfiguration):
if self.to_dict() == other.to_dict():
return True
return False
def __contains__(self, item):
return item in self.__dict__
class BackendConfiguration(QasmBackendConfiguration):
"""Backwards compatibility shim representing an abstract backend configuration."""
@deprecate_func(
since="1.2",
removal_timeline="in the 2.0 release",
additional_msg="The models in ``qiskit.providers.models`` are part "
"of the deprecated `BackendV1` workflow and no longer necessary for `BackendV2`. If a user "
"workflow requires these representations it likely relies on deprecated functionality and "
"should be updated to use `BackendV2`.",
stacklevel=3,
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class PulseBackendConfiguration(QasmBackendConfiguration):
"""Static configuration state for an OpenPulse enabled backend. This contains information
about the set up of the device which can be useful for building Pulse programs.
"""
@deprecate_func(
since="1.2",
removal_timeline="in the 2.0 release",
additional_msg="The models in ``qiskit.providers.models`` are part "
"of the deprecated `BackendV1` workflow and no longer necessary for `BackendV2`. If a user "
"workflow requires these representations it likely relies on deprecated functionality and "
"should be updated to use `BackendV2`.",
stacklevel=3,
)
def __init__(
self,
backend_name: str,
backend_version: str,
n_qubits: int,
basis_gates: List[str],
gates: GateConfig,
local: bool,
simulator: bool,
conditional: bool,
open_pulse: bool,
memory: bool,
max_shots: int,
coupling_map,
n_uchannels: int,
u_channel_lo: List[List[UchannelLO]],
meas_levels: List[int],
qubit_lo_range: List[List[float]],
meas_lo_range: List[List[float]],
dt: float,
dtm: float,
rep_times: List[float],
meas_kernels: List[str],
discriminators: List[str],
hamiltonian: Dict[str, Any] = None,
channel_bandwidth=None,
acquisition_latency=None,
conditional_latency=None,
meas_map=None,
max_experiments=None,
sample_name=None,
n_registers=None,
register_map=None,
configurable=None,
credits_required=None,
online_date=None,
display_name=None,
description=None,
tags=None,
channels: Dict[str, Any] = None,
**kwargs,
):
"""
Initialize a backend configuration that contains all the extra configuration that is made
available for OpenPulse backends.
Args:
backend_name: backend name.
backend_version: backend version in the form X.Y.Z.
n_qubits: number of qubits.
basis_gates: list of basis gates names on the backend.
gates: list of basis gates on the backend.
local: backend is local or remote.
simulator: backend is a simulator.
conditional: backend supports conditional operations.
open_pulse: backend supports open pulse.
memory: backend supports memory.
max_shots: maximum number of shots supported.
coupling_map (list): The coupling map for the device
n_uchannels: Number of u-channels.
u_channel_lo: U-channel relationship on device los.
meas_levels: Supported measurement levels.
qubit_lo_range: Qubit lo ranges for each qubit with form (min, max) in GHz.
meas_lo_range: Measurement lo ranges for each qubit with form (min, max) in GHz.
dt: Qubit drive channel timestep in nanoseconds.
dtm: Measurement drive channel timestep in nanoseconds.
rep_times: Supported repetition times (program execution time) for backend in μs.
meas_kernels: Supported measurement kernels.
discriminators: Supported discriminators.
hamiltonian: An optional dictionary with fields characterizing the system hamiltonian.
channel_bandwidth (list): Bandwidth of all channels
(qubit, measurement, and U)
acquisition_latency (list): Array of dimension
n_qubits x n_registers. Latency (in units of dt) to write a
measurement result from qubit n into register slot m.
conditional_latency (list): Array of dimension n_channels
[d->u->m] x n_registers. Latency (in units of dt) to do a
conditional operation on channel n from register slot m
meas_map (list): Grouping of measurement which are multiplexed
max_experiments (int): The maximum number of experiments per job
sample_name (str): Sample name for the backend
n_registers (int): Number of register slots available for feedback
(if conditional is True)
register_map (list): An array of dimension n_qubits X
n_registers that specifies whether a qubit can store a
measurement in a certain register slot.
configurable (bool): True if the backend is configurable, if the
backend is a simulator
credits_required (bool): True if backend requires credits to run a
job.
online_date (datetime.datetime): The date that the device went online
display_name (str): Alternate name field for the backend
description (str): A description for the backend
tags (list): A list of string tags to describe the backend
channels: An optional dictionary containing information of each channel -- their
purpose, type, and qubits operated on.
**kwargs: Optional fields.
"""
self.n_uchannels = n_uchannels
self.u_channel_lo = u_channel_lo
self.meas_levels = meas_levels
# convert from GHz to Hz
self.qubit_lo_range = [
[min_range * 1e9, max_range * 1e9] for (min_range, max_range) in qubit_lo_range
]
self.meas_lo_range = [
[min_range * 1e9, max_range * 1e9] for (min_range, max_range) in meas_lo_range
]
self.meas_kernels = meas_kernels
self.discriminators = discriminators
self.hamiltonian = hamiltonian
if hamiltonian is not None:
self.hamiltonian = dict(hamiltonian)
self.hamiltonian["vars"] = {
k: v * 1e9 if isinstance(v, numbers.Number) else v
for k, v in self.hamiltonian["vars"].items()
}
self.rep_times = [_rt * 1e-6 for _rt in rep_times] # convert to sec
self.dt = dt * 1e-9
self.dtm = dtm * 1e-9
if channels is not None:
self.channels = channels
(
self._qubit_channel_map,
self._channel_qubit_map,
self._control_channels,
) = self._parse_channels(channels=channels)
else:
self._control_channels = defaultdict(list)
if channel_bandwidth is not None:
self.channel_bandwidth = [
[min_range * 1e9, max_range * 1e9] for (min_range, max_range) in channel_bandwidth
]
if acquisition_latency is not None:
self.acquisition_latency = acquisition_latency
if conditional_latency is not None:
self.conditional_latency = conditional_latency
if meas_map is not None:
self.meas_map = meas_map
super().__init__(
backend_name=backend_name,
backend_version=backend_version,
n_qubits=n_qubits,
basis_gates=basis_gates,
gates=gates,
local=local,
simulator=simulator,
conditional=conditional,
open_pulse=open_pulse,
memory=memory,
max_shots=max_shots,
coupling_map=coupling_map,
max_experiments=max_experiments,
sample_name=sample_name,
n_registers=n_registers,
register_map=register_map,
configurable=configurable,
credits_required=credits_required,
online_date=online_date,
display_name=display_name,
description=description,
tags=tags,
**kwargs,
)
@classmethod
def from_dict(cls, data):
"""Create a new GateConfig object from a dictionary.
Args:
data (dict): A dictionary representing the GateConfig to create.
It will be in the same format as output by :func:`to_dict`.
Returns:
GateConfig: The GateConfig from the input dictionary.
"""
in_data = copy.copy(data)
gates = [GateConfig.from_dict(x) for x in in_data.pop("gates")]
in_data["gates"] = gates
input_uchannels = in_data.pop("u_channel_lo")
u_channels = []
for channel in input_uchannels:
u_channels.append([UchannelLO.from_dict(x) for x in channel])
in_data["u_channel_lo"] = u_channels
return cls(**in_data)
def to_dict(self):
"""Return a dictionary format representation of the GateConfig.
Returns:
dict: The dictionary form of the GateConfig.
"""
out_dict = super().to_dict()
u_channel_lo = []
for x in self.u_channel_lo:
channel = []
for y in x:
channel.append(y.to_dict())
u_channel_lo.append(channel)
out_dict.update(
{
"n_uchannels": self.n_uchannels,
"u_channel_lo": u_channel_lo,
"meas_levels": self.meas_levels,
"qubit_lo_range": self.qubit_lo_range,
"meas_lo_range": self.meas_lo_range,
"meas_kernels": self.meas_kernels,
"discriminators": self.discriminators,
"rep_times": self.rep_times,
"dt": self.dt,
"dtm": self.dtm,
}
)
if hasattr(self, "channel_bandwidth"):
out_dict["channel_bandwidth"] = self.channel_bandwidth
if hasattr(self, "meas_map"):
out_dict["meas_map"] = self.meas_map
if hasattr(self, "acquisition_latency"):
out_dict["acquisition_latency"] = self.acquisition_latency
if hasattr(self, "conditional_latency"):
out_dict["conditional_latency"] = self.conditional_latency
if "channels" in out_dict:
out_dict.pop("_qubit_channel_map")
out_dict.pop("_channel_qubit_map")
out_dict.pop("_control_channels")
# Use GHz in dict
if self.qubit_lo_range:
out_dict["qubit_lo_range"] = [
[min_range * 1e-9, max_range * 1e-9]
for (min_range, max_range) in self.qubit_lo_range
]
if self.meas_lo_range:
out_dict["meas_lo_range"] = [
[min_range * 1e-9, max_range * 1e-9]
for (min_range, max_range) in self.meas_lo_range
]
if self.rep_times:
out_dict["rep_times"] = [_rt * 1e6 for _rt in self.rep_times]
out_dict["dt"] *= 1e9
out_dict["dtm"] *= 1e9
if hasattr(self, "channel_bandwidth"):
out_dict["channel_bandwidth"] = [
[min_range * 1e-9, max_range * 1e-9]
for (min_range, max_range) in self.channel_bandwidth
]
if self.hamiltonian:
hamiltonian = copy.deepcopy(self.hamiltonian)
hamiltonian["vars"] = {
k: v * 1e-9 if isinstance(v, numbers.Number) else v
for k, v in hamiltonian["vars"].items()
}
out_dict["hamiltonian"] = hamiltonian
if hasattr(self, "channels"):
out_dict["channels"] = self.channels
return out_dict
def __eq__(self, other):
if isinstance(other, QasmBackendConfiguration):
if self.to_dict() == other.to_dict():
return True
return False
@property
def sample_rate(self) -> float:
"""Sample rate of the signal channels in Hz (1/dt)."""
return 1.0 / self.dt
@property
def control_channels(self) -> Dict[Tuple[int, ...], List]:
"""Return the control channels"""
return self._control_channels
def drive(self, qubit: int) -> DriveChannel:
"""
Return the drive channel for the given qubit.
Raises:
BackendConfigurationError: If the qubit is not a part of the system.
Returns:
Qubit drive channel.
"""
if not 0 <= qubit < self.n_qubits:
raise BackendConfigurationError(f"Invalid index for {qubit}-qubit system.")
return DriveChannel(qubit)
def measure(self, qubit: int) -> MeasureChannel:
"""
Return the measure stimulus channel for the given qubit.
Raises:
BackendConfigurationError: If the qubit is not a part of the system.
Returns:
Qubit measurement stimulus line.
"""
if not 0 <= qubit < self.n_qubits:
raise BackendConfigurationError(f"Invalid index for {qubit}-qubit system.")
return MeasureChannel(qubit)
def acquire(self, qubit: int) -> AcquireChannel:
"""
Return the acquisition channel for the given qubit.
Raises:
BackendConfigurationError: If the qubit is not a part of the system.
Returns:
Qubit measurement acquisition line.
"""
if not 0 <= qubit < self.n_qubits:
raise BackendConfigurationError(f"Invalid index for {qubit}-qubit systems.")
return AcquireChannel(qubit)
def control(self, qubits: Iterable[int] = None) -> List[ControlChannel]:
"""
Return the secondary drive channel for the given qubit -- typically utilized for
controlling multiqubit interactions. This channel is derived from other channels.
Args:
qubits: Tuple or list of qubits of the form `(control_qubit, target_qubit)`.
Raises:
BackendConfigurationError: If the ``qubits`` is not a part of the system or if
the backend does not provide `channels` information in its configuration.
Returns:
List of control channels.
"""
try:
if isinstance(qubits, list):
qubits = tuple(qubits)
return self._control_channels[qubits]
except KeyError as ex:
raise BackendConfigurationError(
f"Couldn't find the ControlChannel operating on qubits {qubits} on "
f"{self.n_qubits}-qubit system. The ControlChannel information is retrieved "
"from the backend."
) from ex
except AttributeError as ex:
raise BackendConfigurationError(
f"This backend - '{self.backend_name}' does not provide channel information."
) from ex
def get_channel_qubits(self, channel: Channel) -> List[int]:
"""
Return a list of indices for qubits which are operated on directly by the given ``channel``.
Raises:
BackendConfigurationError: If ``channel`` is not a found or if
the backend does not provide `channels` information in its configuration.
Returns:
List of qubits operated on my the given ``channel``.
"""
try:
return self._channel_qubit_map[channel]
except KeyError as ex:
raise BackendConfigurationError(f"Couldn't find the Channel - {channel}") from ex
except AttributeError as ex:
raise BackendConfigurationError(
f"This backend - '{self.backend_name}' does not provide channel information."
) from ex
def get_qubit_channels(self, qubit: Union[int, Iterable[int]]) -> List[Channel]:
r"""Return a list of channels which operate on the given ``qubit``.
Raises:
BackendConfigurationError: If ``qubit`` is not a found or if
the backend does not provide `channels` information in its configuration.
Returns:
List of ``Channel``\s operated on my the given ``qubit``.
"""
channels = set()
try:
if isinstance(qubit, int):
for key, value in self._qubit_channel_map.items():
if qubit in key:
channels.update(value)
if len(channels) == 0:
raise KeyError
elif isinstance(qubit, list):
qubit = tuple(qubit)
channels.update(self._qubit_channel_map[qubit])
elif isinstance(qubit, tuple):
channels.update(self._qubit_channel_map[qubit])
return list(channels)
except KeyError as ex:
raise BackendConfigurationError(f"Couldn't find the qubit - {qubit}") from ex
except AttributeError as ex:
raise BackendConfigurationError(
f"This backend - '{self.backend_name}' does not provide channel information."
) from ex
def describe(self, channel: ControlChannel) -> Dict[DriveChannel, complex]:
"""
Return a basic description of the channel dependency. Derived channels are given weights
which describe how their frames are linked to other frames.
For instance, the backend could be configured with this setting::
u_channel_lo = [
[UchannelLO(q=0, scale=1. + 0.j)],
[UchannelLO(q=0, scale=-1. + 0.j), UchannelLO(q=1, scale=1. + 0.j)]
]
Then, this method can be used as follows::
backend.configuration().describe(ControlChannel(1))
>>> {DriveChannel(0): -1, DriveChannel(1): 1}
Args:
channel: The derived channel to describe.
Raises:
BackendConfigurationError: If channel is not a ControlChannel.
Returns:
Control channel derivations.
"""
if not isinstance(channel, ControlChannel):
raise BackendConfigurationError("Can only describe ControlChannels.")
result = {}
for u_chan_lo in self.u_channel_lo[channel.index]:
result[DriveChannel(u_chan_lo.q)] = u_chan_lo.scale
return result
def _parse_channels(self, channels: Dict[set, Any]) -> Dict[Any, Any]:
r"""
Generates a dictionaries of ``Channel``\s, and tuple of qubit(s) they operate on.
Args:
channels: An optional dictionary containing information of each channel -- their
purpose, type, and qubits operated on.
Returns:
qubit_channel_map: Dictionary mapping tuple of qubit(s) to list of ``Channel``\s.
channel_qubit_map: Dictionary mapping ``Channel`` to list of qubit(s).
control_channels: Dictionary mapping tuple of qubit(s), to list of