/
backendconfiguration.py
789 lines (692 loc) · 32.1 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
# -*- coding: utf-8 -*-
# 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 warnings
from types import SimpleNamespace
from typing import Dict, List, Any, Iterable, Union
from collections import defaultdict
from qiskit.exceptions import QiskitError
from qiskit.providers.exceptions import BackendConfigurationError
from qiskit.pulse.channels import (Channel, DriveChannel, MeasureChannel,
ControlChannel, AcquireChannel)
class GateConfig:
"""Class representing a Gate Configuration
Attributes:
name: the gate name as it will be referred to in Qasm.
parameters: variable names for the gate parameters (if any).
qasm_def: definition of this gate in terms of Qasm primitives U
and CX.
"""
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 Qasm.
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 Qasm 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 = "GateConfig(%s, %s, %s" % (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.
"""
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 "UchannelLO(%s, %s)" % (self.q, self.scale)
class QasmBackendConfiguration(SimpleNamespace):
"""Class representing a Qasm 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.
"""
def __init__(self, backend_name, backend_version, n_qubits,
basis_gates, gates, local, simulator,
conditional, open_pulse, memory,
max_shots, coupling_map, 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, **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
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): 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
**kwargs: optional fields
"""
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
# 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 becuase some backends do not
# fit within the Qasm / Pulse backend partitioning in Qiskit
if 'dt' in kwargs.keys():
kwargs['dt'] *= 1e-9
if 'dtm' in kwargs.keys():
kwargs['dtm'] *= 1e-9
if 'qubit_lo_range' in kwargs.keys():
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.keys():
kwargs['meas_lo_range'] = [[min_range * 1e9, max_range * 1e9] for
(min_range, max_range) in kwargs['meas_lo_range']]
if 'rep_times' in kwargs.keys():
kwargs['rep_times'] = [_rt * 1e-6 for _rt in kwargs['rep_times']]
self.__dict__.update(kwargs)
def __getstate__(self):
return self.to_dict()
def __setstate__(self, state):
return self.from_dict(state)
def __reduce__(self):
return (self.__class__, (self.backend_name, self.backend_version,
self.n_qubits, self.basis_gates, self.gates,
self.local, self.simulator, self.conditional,
self.open_pulse, self.memory, self.max_shots,
self.coupling_map))
@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 = copy.copy(self.__dict__)
out_dict['gates'] = [x.to_dict() for x in self.gates]
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 compat shim representing an abstract backend configuration."""
pass
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.
"""
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, str] = 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 for device in microseconds.
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): 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
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
self.rep_times = [_rt * 1e-6 for _rt in rep_times]
self.dt = dt * 1e-9 # pylint: disable=invalid-name
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)
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,
'hamiltonian': self.hamiltonian,
'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')
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
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("Invalid index for {}-qubit system.".format(qubit))
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("Invalid index for {}-qubit system.".format(qubit))
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("Invalid index for {}-qubit systems.".format(qubit))
return AcquireChannel(qubit)
def control(self, qubits: Iterable[int] = None,
channel: 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)`.
channel: Deprecated.
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.
"""
if channel is not None:
warnings.warn('The channel argument has been deprecated in favor of qubits. '
'This method will now return accurate ControlChannels determined '
'by qubit indices.',
DeprecationWarning)
qubits = [channel]
try:
if isinstance(qubits, list):
qubits = tuple(qubits)
return self._control_channels[qubits]
except KeyError:
raise BackendConfigurationError("Couldn't find the ControlChannel operating on qubits "
"{} on {}-qubit system. The ControlChannel information"
" is retrieved from the "
" backend.".format(qubits, self.n_qubits))
except AttributeError:
raise BackendConfigurationError("This backend - '{}' does not provide channel "
"information.".format(self.backend_name))
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:
raise BackendConfigurationError("Couldn't find the Channel - {}".format(channel))
except AttributeError:
raise BackendConfigurationError("This backend - '{}' does not provide channel "
"information.".format(self.backend_name))
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 in self._qubit_channel_map.keys():
if qubit in key:
channels.update(self._qubit_channel_map[key])
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:
raise BackendConfigurationError("Couldn't find the qubit - {}".format(qubit))
except AttributeError:
raise BackendConfigurationError("This backend - '{}' does not provide channel "
"information.".format(self.backend_name))
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
``ControlChannel``\s.
"""
qubit_channel_map = defaultdict(list)
channel_qubit_map = defaultdict(list)
control_channels = defaultdict(list)
channels_dict = {
DriveChannel.prefix: DriveChannel,
ControlChannel.prefix: ControlChannel,
MeasureChannel.prefix: MeasureChannel,
'acquire': AcquireChannel
}
for channel, config in channels.items():
channel_prefix, index = self._get_channel_prefix_index(channel)
channel_type = channels_dict[channel_prefix]
qubits = tuple(config['operates']['qubits'])
if channel_prefix in channels_dict:
qubit_channel_map[qubits].append(channel_type(index))
channel_qubit_map[(channel_type(index))].extend(list(qubits))
if channel_prefix == ControlChannel.prefix:
control_channels[qubits].append(channel_type(index))
return dict(qubit_channel_map), dict(channel_qubit_map), dict(control_channels)
def _get_channel_prefix_index(self, channel: str) -> str:
"""Return channel prefix and index from the given ``channel``.
Args:
channel: Name of channel.
Raises:
BackendConfigurationError: If invalid channel name is found.
Return:
Channel name and index. For example, if ``channel=acquire0``, this method
returns ``acquire`` and ``0``.
"""
channel_prefix = re.match(r"(?P<channel>[a-z]+)(?P<index>[0-9]+)", channel)
try:
return channel_prefix.group('channel'), int(channel_prefix.group('index'))
except AttributeError:
raise BackendConfigurationError("Invalid channel name - '{}' found.".format(channel))