/
dagcircuit.py
2125 lines (1798 loc) · 87.2 KB
/
dagcircuit.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, 2021.
#
# 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.
"""
Object to represent a quantum circuit as a directed acyclic graph (DAG).
The nodes in the graph are either input/output nodes or operation nodes.
The edges correspond to qubits or bits in the circuit. A directed edge
from node A to node B means that the (qu)bit passes from the output of A
to the input of B. The object's methods allow circuits to be constructed,
composed, and modified. Some natural properties like depth can be computed
directly from the graph.
"""
from __future__ import annotations
from collections import OrderedDict, defaultdict, deque, namedtuple
from collections.abc import Callable, Sequence, Generator, Iterable
import copy
import math
from typing import Any
import numpy as np
import rustworkx as rx
from qiskit.circuit import (
ControlFlowOp,
ForLoopOp,
IfElseOp,
WhileLoopOp,
SwitchCaseOp,
_classical_resource_map,
Operation,
)
from qiskit.circuit.controlflow import condition_resources, node_resources, CONTROL_FLOW_OP_NAMES
from qiskit.circuit.quantumregister import QuantumRegister, Qubit
from qiskit.circuit.classicalregister import ClassicalRegister, Clbit
from qiskit.circuit.gate import Gate
from qiskit.circuit.instruction import Instruction
from qiskit.circuit.parameterexpression import ParameterExpression
from qiskit.dagcircuit.exceptions import DAGCircuitError
from qiskit.dagcircuit.dagnode import DAGNode, DAGOpNode, DAGInNode, DAGOutNode
from qiskit.circuit.bit import Bit
from qiskit.pulse import Schedule
BitLocations = namedtuple("BitLocations", ("index", "registers"))
class DAGCircuit:
"""
Quantum circuit as a directed acyclic graph.
There are 3 types of nodes in the graph: inputs, outputs, and operations.
The nodes are connected by directed edges that correspond to qubits and
bits.
"""
# pylint: disable=invalid-name
def __init__(self):
"""Create an empty circuit."""
# Circuit name. Generally, this corresponds to the name
# of the QuantumCircuit from which the DAG was generated.
self.name = None
# Circuit metadata
self.metadata = {}
# Cache of dag op node sort keys
self._key_cache = {}
# Set of wires (Register,idx) in the dag
self._wires = set()
# Map from wire (Register,idx) to input nodes of the graph
self.input_map = OrderedDict()
# Map from wire (Register,idx) to output nodes of the graph
self.output_map = OrderedDict()
# Directed multigraph whose nodes are inputs, outputs, or operations.
# Operation nodes have equal in- and out-degrees and carry
# additional data about the operation, including the argument order
# and parameter values.
# Input nodes have out-degree 1 and output nodes have in-degree 1.
# Edges carry wire labels (reg,idx) and each operation has
# corresponding in- and out-edges with the same wire labels.
self._multi_graph = rx.PyDAG()
# Map of qreg/creg name to Register object.
self.qregs = OrderedDict()
self.cregs = OrderedDict()
# List of Qubit/Clbit wires that the DAG acts on.
self.qubits: list[Qubit] = []
self.clbits: list[Clbit] = []
# Dictionary mapping of Qubit and Clbit instances to a tuple comprised of
# 0) corresponding index in dag.{qubits,clbits} and
# 1) a list of Register-int pairs for each Register containing the Bit and
# its index within that register.
self._qubit_indices: dict[Qubit, BitLocations] = {}
self._clbit_indices: dict[Clbit, BitLocations] = {}
self._global_phase: float | ParameterExpression = 0.0
self._calibrations: dict[str, dict[tuple, Schedule]] = defaultdict(dict)
self._op_names = {}
self.duration = None
self.unit = "dt"
@property
def wires(self):
"""Return a list of the wires in order."""
return self.qubits + self.clbits
@property
def node_counter(self):
"""
Returns the number of nodes in the dag.
"""
return len(self._multi_graph)
@property
def global_phase(self):
"""Return the global phase of the circuit."""
return self._global_phase
@global_phase.setter
def global_phase(self, angle: float | ParameterExpression):
"""Set the global phase of the circuit.
Args:
angle (float, ParameterExpression)
"""
if isinstance(angle, ParameterExpression):
self._global_phase = angle
else:
# Set the phase to the [0, 2π) interval
angle = float(angle)
if not angle:
self._global_phase = 0
else:
self._global_phase = angle % (2 * math.pi)
@property
def calibrations(self) -> dict[str, dict[tuple, Schedule]]:
"""Return calibration dictionary.
The custom pulse definition of a given gate is of the form
{'gate_name': {(qubits, params): schedule}}
"""
return dict(self._calibrations)
@calibrations.setter
def calibrations(self, calibrations: dict[str, dict[tuple, Schedule]]):
"""Set the circuit calibration data from a dictionary of calibration definition.
Args:
calibrations (dict): A dictionary of input in the format
{'gate_name': {(qubits, gate_params): schedule}}
"""
self._calibrations = defaultdict(dict, calibrations)
def add_calibration(self, gate, qubits, schedule, params=None):
"""Register a low-level, custom pulse definition for the given gate.
Args:
gate (Union[Gate, str]): Gate information.
qubits (Union[int, Tuple[int]]): List of qubits to be measured.
schedule (Schedule): Schedule information.
params (Optional[List[Union[float, Parameter]]]): A list of parameters.
Raises:
Exception: if the gate is of type string and params is None.
"""
def _format(operand):
try:
# Using float/complex value as a dict key is not good idea.
# This makes the mapping quite sensitive to the rounding error.
# However, the mechanism is already tied to the execution model (i.e. pulse gate)
# and we cannot easily update this rule.
# The same logic exists in QuantumCircuit.add_calibration.
evaluated = complex(operand)
if np.isreal(evaluated):
evaluated = float(evaluated.real)
if evaluated.is_integer():
evaluated = int(evaluated)
return evaluated
except TypeError:
# Unassigned parameter
return operand
if isinstance(gate, Gate):
params = gate.params
gate = gate.name
if params is not None:
params = tuple(map(_format, params))
else:
params = ()
self._calibrations[gate][(tuple(qubits), params)] = schedule
def has_calibration_for(self, node):
"""Return True if the dag has a calibration defined for the node operation. In this
case, the operation does not need to be translated to the device basis.
"""
if not self.calibrations or node.op.name not in self.calibrations:
return False
qubits = tuple(self.qubits.index(qubit) for qubit in node.qargs)
params = []
for p in node.op.params:
if isinstance(p, ParameterExpression) and not p.parameters:
params.append(float(p))
else:
params.append(p)
params = tuple(params)
return (qubits, params) in self.calibrations[node.op.name]
def remove_all_ops_named(self, opname):
"""Remove all operation nodes with the given name."""
for n in self.named_nodes(opname):
self.remove_op_node(n)
def add_qubits(self, qubits):
"""Add individual qubit wires."""
if any(not isinstance(qubit, Qubit) for qubit in qubits):
raise DAGCircuitError("not a Qubit instance.")
duplicate_qubits = set(self.qubits).intersection(qubits)
if duplicate_qubits:
raise DAGCircuitError("duplicate qubits %s" % duplicate_qubits)
for qubit in qubits:
self.qubits.append(qubit)
self._qubit_indices[qubit] = BitLocations(len(self.qubits) - 1, [])
self._add_wire(qubit)
def add_clbits(self, clbits):
"""Add individual clbit wires."""
if any(not isinstance(clbit, Clbit) for clbit in clbits):
raise DAGCircuitError("not a Clbit instance.")
duplicate_clbits = set(self.clbits).intersection(clbits)
if duplicate_clbits:
raise DAGCircuitError("duplicate clbits %s" % duplicate_clbits)
for clbit in clbits:
self.clbits.append(clbit)
self._clbit_indices[clbit] = BitLocations(len(self.clbits) - 1, [])
self._add_wire(clbit)
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qregs[qreg.name] = qreg
existing_qubits = set(self.qubits)
for j in range(qreg.size):
if qreg[j] in self._qubit_indices:
self._qubit_indices[qreg[j]].registers.append((qreg, j))
if qreg[j] not in existing_qubits:
self.qubits.append(qreg[j])
self._qubit_indices[qreg[j]] = BitLocations(
len(self.qubits) - 1, registers=[(qreg, j)]
)
self._add_wire(qreg[j])
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
self.cregs[creg.name] = creg
existing_clbits = set(self.clbits)
for j in range(creg.size):
if creg[j] in self._clbit_indices:
self._clbit_indices[creg[j]].registers.append((creg, j))
if creg[j] not in existing_clbits:
self.clbits.append(creg[j])
self._clbit_indices[creg[j]] = BitLocations(
len(self.clbits) - 1, registers=[(creg, j)]
)
self._add_wire(creg[j])
def _add_wire(self, wire):
"""Add a qubit or bit to the circuit.
Args:
wire (Bit): the wire to be added
This adds a pair of in and out nodes connected by an edge.
Raises:
DAGCircuitError: if trying to add duplicate wire
"""
if wire not in self._wires:
self._wires.add(wire)
inp_node = DAGInNode(wire=wire)
outp_node = DAGOutNode(wire=wire)
input_map_id, output_map_id = self._multi_graph.add_nodes_from([inp_node, outp_node])
inp_node._node_id = input_map_id
outp_node._node_id = output_map_id
self.input_map[wire] = inp_node
self.output_map[wire] = outp_node
self._multi_graph.add_edge(inp_node._node_id, outp_node._node_id, wire)
else:
raise DAGCircuitError(f"duplicate wire {wire}")
def find_bit(self, bit: Bit) -> BitLocations:
"""
Finds locations in the circuit, by mapping the Qubit and Clbit to positional index
BitLocations is defined as: BitLocations = namedtuple("BitLocations", ("index", "registers"))
Args:
bit (Bit): The bit to locate.
Returns:
namedtuple(int, List[Tuple(Register, int)]): A 2-tuple. The first element (``index``)
contains the index at which the ``Bit`` can be found (in either
:obj:`~DAGCircuit.qubits`, :obj:`~DAGCircuit.clbits`, depending on its
type). The second element (``registers``) is a list of ``(register, index)``
pairs with an entry for each :obj:`~Register` in the circuit which contains the
:obj:`~Bit` (and the index in the :obj:`~Register` at which it can be found).
Raises:
DAGCircuitError: If the supplied :obj:`~Bit` was of an unknown type.
DAGCircuitError: If the supplied :obj:`~Bit` could not be found on the circuit.
"""
try:
if isinstance(bit, Qubit):
return self._qubit_indices[bit]
elif isinstance(bit, Clbit):
return self._clbit_indices[bit]
else:
raise DAGCircuitError(f"Could not locate bit of unknown type: {type(bit)}")
except KeyError as err:
raise DAGCircuitError(
f"Could not locate provided bit: {bit}. Has it been added to the DAGCircuit?"
) from err
def remove_clbits(self, *clbits):
"""
Remove classical bits from the circuit. All bits MUST be idle.
Any registers with references to at least one of the specified bits will
also be removed.
Args:
clbits (List[Clbit]): The bits to remove.
Raises:
DAGCircuitError: a clbit is not a :obj:`.Clbit`, is not in the circuit,
or is not idle.
"""
if any(not isinstance(clbit, Clbit) for clbit in clbits):
raise DAGCircuitError(
"clbits not of type Clbit: %s" % [b for b in clbits if not isinstance(b, Clbit)]
)
clbits = set(clbits)
unknown_clbits = clbits.difference(self.clbits)
if unknown_clbits:
raise DAGCircuitError("clbits not in circuit: %s" % unknown_clbits)
busy_clbits = {bit for bit in clbits if not self._is_wire_idle(bit)}
if busy_clbits:
raise DAGCircuitError("clbits not idle: %s" % busy_clbits)
# remove any references to bits
cregs_to_remove = {creg for creg in self.cregs.values() if not clbits.isdisjoint(creg)}
self.remove_cregs(*cregs_to_remove)
for clbit in clbits:
self._remove_idle_wire(clbit)
self.clbits.remove(clbit)
del self._clbit_indices[clbit]
# Update the indices of remaining clbits
for i, clbit in enumerate(self.clbits):
self._clbit_indices[clbit] = self._clbit_indices[clbit]._replace(index=i)
def remove_cregs(self, *cregs):
"""
Remove classical registers from the circuit, leaving underlying bits
in place.
Raises:
DAGCircuitError: a creg is not a ClassicalRegister, or is not in
the circuit.
"""
if any(not isinstance(creg, ClassicalRegister) for creg in cregs):
raise DAGCircuitError(
"cregs not of type ClassicalRegister: %s"
% [r for r in cregs if not isinstance(r, ClassicalRegister)]
)
unknown_cregs = set(cregs).difference(self.cregs.values())
if unknown_cregs:
raise DAGCircuitError("cregs not in circuit: %s" % unknown_cregs)
for creg in cregs:
del self.cregs[creg.name]
for j in range(creg.size):
bit = creg[j]
bit_position = self._clbit_indices[bit]
bit_position.registers.remove((creg, j))
def remove_qubits(self, *qubits):
"""
Remove quantum bits from the circuit. All bits MUST be idle.
Any registers with references to at least one of the specified bits will
also be removed.
Args:
qubits (List[~qiskit.circuit.Qubit]): The bits to remove.
Raises:
DAGCircuitError: a qubit is not a :obj:`~.circuit.Qubit`, is not in the circuit,
or is not idle.
"""
if any(not isinstance(qubit, Qubit) for qubit in qubits):
raise DAGCircuitError(
"qubits not of type Qubit: %s" % [b for b in qubits if not isinstance(b, Qubit)]
)
qubits = set(qubits)
unknown_qubits = qubits.difference(self.qubits)
if unknown_qubits:
raise DAGCircuitError("qubits not in circuit: %s" % unknown_qubits)
busy_qubits = {bit for bit in qubits if not self._is_wire_idle(bit)}
if busy_qubits:
raise DAGCircuitError("qubits not idle: %s" % busy_qubits)
# remove any references to bits
qregs_to_remove = {qreg for qreg in self.qregs.values() if not qubits.isdisjoint(qreg)}
self.remove_qregs(*qregs_to_remove)
for qubit in qubits:
self._remove_idle_wire(qubit)
self.qubits.remove(qubit)
del self._qubit_indices[qubit]
# Update the indices of remaining qubits
for i, qubit in enumerate(self.qubits):
self._qubit_indices[qubit] = self._qubit_indices[qubit]._replace(index=i)
def remove_qregs(self, *qregs):
"""
Remove classical registers from the circuit, leaving underlying bits
in place.
Raises:
DAGCircuitError: a qreg is not a QuantumRegister, or is not in
the circuit.
"""
if any(not isinstance(qreg, QuantumRegister) for qreg in qregs):
raise DAGCircuitError(
"qregs not of type QuantumRegister: %s"
% [r for r in qregs if not isinstance(r, QuantumRegister)]
)
unknown_qregs = set(qregs).difference(self.qregs.values())
if unknown_qregs:
raise DAGCircuitError("qregs not in circuit: %s" % unknown_qregs)
for qreg in qregs:
del self.qregs[qreg.name]
for j in range(qreg.size):
bit = qreg[j]
bit_position = self._qubit_indices[bit]
bit_position.registers.remove((qreg, j))
def _is_wire_idle(self, wire):
"""Check if a wire is idle.
Args:
wire (Bit): a wire in the circuit.
Returns:
bool: true if the wire is idle, false otherwise.
Raises:
DAGCircuitError: the wire is not in the circuit.
"""
if wire not in self._wires:
raise DAGCircuitError("wire %s not in circuit" % wire)
try:
child = next(self.successors(self.input_map[wire]))
except StopIteration as e:
raise DAGCircuitError(
"Invalid dagcircuit input node %s has no output" % self.input_map[wire]
) from e
return child is self.output_map[wire]
def _remove_idle_wire(self, wire):
"""Remove an idle qubit or bit from the circuit.
Args:
wire (Bit): the wire to be removed, which MUST be idle.
"""
inp_node = self.input_map[wire]
oup_node = self.output_map[wire]
self._multi_graph.remove_node(inp_node._node_id)
self._multi_graph.remove_node(oup_node._node_id)
self._wires.remove(wire)
del self.input_map[wire]
del self.output_map[wire]
def _check_condition(self, name, condition):
"""Verify that the condition is valid.
Args:
name (string): used for error reporting
condition (tuple or None): a condition tuple (ClassicalRegister, int) or (Clbit, bool)
Raises:
DAGCircuitError: if conditioning on an invalid register
"""
if condition is None:
return
resources = condition_resources(condition)
for creg in resources.cregs:
if creg.name not in self.cregs:
raise DAGCircuitError(f"invalid creg in condition for {name}")
if not set(resources.clbits).issubset(self.clbits):
raise DAGCircuitError(f"invalid clbits in condition for {name}")
def _check_bits(self, args, amap):
"""Check the values of a list of (qu)bit arguments.
For each element of args, check that amap contains it.
Args:
args (list[Bit]): the elements to be checked
amap (dict): a dictionary keyed on Qubits/Clbits
Raises:
DAGCircuitError: if a qubit is not contained in amap
"""
# Check for each wire
for wire in args:
if wire not in amap:
raise DAGCircuitError(f"(qu)bit {wire} not found in {amap}")
@staticmethod
def _bits_in_operation(operation):
"""Return an iterable over the classical bits that are inherent to an instruction. This
includes a `condition`, or the `target` of a :class:`.ControlFlowOp`.
Args:
instruction: the :class:`~.circuit.Instruction` instance for a node.
Returns:
Iterable[Clbit]: the :class:`.Clbit`\\ s involved.
"""
# If updating this, also update the fast-path checker `DAGCirucit._operation_may_have_bits`.
if (condition := getattr(operation, "condition", None)) is not None:
yield from condition_resources(condition).clbits
if isinstance(operation, SwitchCaseOp):
target = operation.target
if isinstance(target, Clbit):
yield target
elif isinstance(target, ClassicalRegister):
yield from target
else:
yield from node_resources(target).clbits
@staticmethod
def _operation_may_have_bits(operation) -> bool:
"""Return whether a given :class:`.Operation` may contain any :class:`.Clbit` instances
in itself (e.g. a control-flow operation).
Args:
operation (qiskit.circuit.Operation): the operation to check.
"""
# This is separate to `_bits_in_operation` because most of the time there won't be any bits,
# so we want a fast path to be able to skip creating and testing a generator for emptiness.
#
# If updating this, also update `DAGCirucit._bits_in_operation`.
return getattr(operation, "condition", None) is not None or isinstance(
operation, SwitchCaseOp
)
def _increment_op(self, op):
if op.name in self._op_names:
self._op_names[op.name] += 1
else:
self._op_names[op.name] = 1
def _decrement_op(self, op):
if self._op_names[op.name] == 1:
del self._op_names[op.name]
else:
self._op_names[op.name] -= 1
def copy_empty_like(self):
"""Return a copy of self with the same structure but empty.
That structure includes:
* name and other metadata
* global phase
* duration
* all the qubits and clbits, including the registers.
Returns:
DAGCircuit: An empty copy of self.
"""
target_dag = DAGCircuit()
target_dag.name = self.name
target_dag._global_phase = self._global_phase
target_dag.duration = self.duration
target_dag.unit = self.unit
target_dag.metadata = self.metadata
target_dag._key_cache = self._key_cache
target_dag.add_qubits(self.qubits)
target_dag.add_clbits(self.clbits)
for qreg in self.qregs.values():
target_dag.add_qreg(qreg)
for creg in self.cregs.values():
target_dag.add_creg(creg)
return target_dag
def apply_operation_back(
self,
op: Operation,
qargs: Iterable[Qubit] = (),
cargs: Iterable[Clbit] = (),
*,
check: bool = True,
) -> DAGOpNode:
"""Apply an operation to the output of the circuit.
Args:
op (qiskit.circuit.Operation): the operation associated with the DAG node
qargs (tuple[~qiskit.circuit.Qubit]): qubits that op will be applied to
cargs (tuple[Clbit]): cbits that op will be applied to
check (bool): If ``True`` (default), this function will enforce that the
:class:`.DAGCircuit` data-structure invariants are maintained (all ``qargs`` are
:class:`~.circuit.Qubit`\\ s, all are in the DAG, etc). If ``False``, the caller *must*
uphold these invariants itself, but the cost of several checks will be skipped.
This is most useful when building a new DAG from a source of known-good nodes.
Returns:
DAGOpNode: the node for the op that was added to the dag
Raises:
DAGCircuitError: if a leaf node is connected to multiple outputs
"""
qargs = tuple(qargs)
cargs = tuple(cargs)
if self._operation_may_have_bits(op):
# This is the slow path; most of the time, this won't happen.
all_cbits = set(self._bits_in_operation(op)).union(cargs)
else:
all_cbits = cargs
if check:
self._check_condition(op.name, getattr(op, "condition", None))
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
node = DAGOpNode(op=op, qargs=qargs, cargs=cargs, dag=self)
node._node_id = self._multi_graph.add_node(node)
self._increment_op(op)
# Add new in-edges from predecessors of the output nodes to the
# operation node while deleting the old in-edges of the output nodes
# and adding new edges from the operation node to each output node
self._multi_graph.insert_node_on_in_edges_multiple(
node._node_id,
[self.output_map[bit]._node_id for bits in (qargs, all_cbits) for bit in bits],
)
return node
def apply_operation_front(
self,
op: Operation,
qargs: Sequence[Qubit] = (),
cargs: Sequence[Clbit] = (),
*,
check: bool = True,
) -> DAGOpNode:
"""Apply an operation to the input of the circuit.
Args:
op (qiskit.circuit.Operation): the operation associated with the DAG node
qargs (tuple[~qiskit.circuit.Qubit]): qubits that op will be applied to
cargs (tuple[Clbit]): cbits that op will be applied to
check (bool): If ``True`` (default), this function will enforce that the
:class:`.DAGCircuit` data-structure invariants are maintained (all ``qargs`` are
:class:`~.circuit.Qubit`\\ s, all are in the DAG, etc). If ``False``, the caller *must*
uphold these invariants itself, but the cost of several checks will be skipped.
This is most useful when building a new DAG from a source of known-good nodes.
Returns:
DAGOpNode: the node for the op that was added to the dag
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
qargs = tuple(qargs)
cargs = tuple(cargs)
if self._operation_may_have_bits(op):
# This is the slow path; most of the time, this won't happen.
all_cbits = set(self._bits_in_operation(op)).union(cargs)
else:
all_cbits = cargs
if check:
self._check_condition(op.name, getattr(op, "condition", None))
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
node = DAGOpNode(op=op, qargs=qargs, cargs=cargs, dag=self)
node._node_id = self._multi_graph.add_node(node)
self._increment_op(op)
# Add new out-edges to successors of the input nodes from the
# operation node while deleting the old out-edges of the input nodes
# and adding new edges to the operation node from each input node
self._multi_graph.insert_node_on_out_edges_multiple(
node._node_id,
[self.input_map[bit]._node_id for bits in (qargs, all_cbits) for bit in bits],
)
return node
def compose(self, other, qubits=None, clbits=None, front=False, inplace=True):
"""Compose the ``other`` circuit onto the output of this circuit.
A subset of input wires of ``other`` are mapped
to a subset of output wires of this circuit.
``other`` can be narrower or of equal width to ``self``.
Args:
other (DAGCircuit): circuit to compose with self
qubits (list[~qiskit.circuit.Qubit|int]): qubits of self to compose onto.
clbits (list[Clbit|int]): clbits of self to compose onto.
front (bool): If True, front composition will be performed (not implemented yet)
inplace (bool): If True, modify the object. Otherwise return composed circuit.
Returns:
DAGCircuit: the composed dag (returns None if inplace==True).
Raises:
DAGCircuitError: if ``other`` is wider or there are duplicate edge mappings.
"""
if front:
raise DAGCircuitError("Front composition not supported yet.")
if len(other.qubits) > len(self.qubits) or len(other.clbits) > len(self.clbits):
raise DAGCircuitError(
"Trying to compose with another DAGCircuit which has more 'in' edges."
)
# number of qubits and clbits must match number in circuit or None
identity_qubit_map = dict(zip(other.qubits, self.qubits))
identity_clbit_map = dict(zip(other.clbits, self.clbits))
if qubits is None:
qubit_map = identity_qubit_map
elif len(qubits) != len(other.qubits):
raise DAGCircuitError(
"Number of items in qubits parameter does not"
" match number of qubits in the circuit."
)
else:
qubit_map = {
other.qubits[i]: (self.qubits[q] if isinstance(q, int) else q)
for i, q in enumerate(qubits)
}
if clbits is None:
clbit_map = identity_clbit_map
elif len(clbits) != len(other.clbits):
raise DAGCircuitError(
"Number of items in clbits parameter does not"
" match number of clbits in the circuit."
)
else:
clbit_map = {
other.clbits[i]: (self.clbits[c] if isinstance(c, int) else c)
for i, c in enumerate(clbits)
}
edge_map = {**qubit_map, **clbit_map} or None
# if no edge_map, try to do a 1-1 mapping in order
if edge_map is None:
edge_map = {**identity_qubit_map, **identity_clbit_map}
# Check the edge_map for duplicate values
if len(set(edge_map.values())) != len(edge_map):
raise DAGCircuitError("duplicates in wire_map")
# Compose
if inplace:
dag = self
else:
dag = copy.deepcopy(self)
dag.global_phase += other.global_phase
for gate, cals in other.calibrations.items():
dag._calibrations[gate].update(cals)
# Ensure that the error raised here is a `DAGCircuitError` for backwards compatibility.
def _reject_new_register(reg):
raise DAGCircuitError(f"No register with '{reg.bits}' to map this expression onto.")
variable_mapper = _classical_resource_map.VariableMapper(
dag.cregs.values(), edge_map, _reject_new_register
)
for nd in other.topological_nodes():
if isinstance(nd, DAGInNode):
# if in edge_map, get new name, else use existing name
m_wire = edge_map.get(nd.wire, nd.wire)
# the mapped wire should already exist
if m_wire not in dag.output_map:
raise DAGCircuitError(
"wire %s[%d] not in self" % (m_wire.register.name, m_wire.index)
)
if nd.wire not in other._wires:
raise DAGCircuitError(
"inconsistent wire type for %s[%d] in other"
% (nd.register.name, nd.wire.index)
)
elif isinstance(nd, DAGOutNode):
# ignore output nodes
pass
elif isinstance(nd, DAGOpNode):
m_qargs = [edge_map.get(x, x) for x in nd.qargs]
m_cargs = [edge_map.get(x, x) for x in nd.cargs]
op = nd.op.copy()
if (condition := getattr(op, "condition", None)) is not None:
if not isinstance(op, ControlFlowOp):
op = op.c_if(*variable_mapper.map_condition(condition, allow_reorder=True))
else:
op.condition = variable_mapper.map_condition(condition, allow_reorder=True)
elif isinstance(op, SwitchCaseOp):
op.target = variable_mapper.map_target(op.target)
dag.apply_operation_back(op, m_qargs, m_cargs, check=False)
else:
raise DAGCircuitError("bad node type %s" % type(nd))
if not inplace:
return dag
else:
return None
def reverse_ops(self):
"""Reverse the operations in the ``self`` circuit.
Returns:
DAGCircuit: the reversed dag.
"""
# TODO: speed up
# pylint: disable=cyclic-import
from qiskit.converters import dag_to_circuit, circuit_to_dag
qc = dag_to_circuit(self)
reversed_qc = qc.reverse_ops()
reversed_dag = circuit_to_dag(reversed_qc)
return reversed_dag
def idle_wires(self, ignore=None):
"""Return idle wires.
Args:
ignore (list(str)): List of node names to ignore. Default: []
Yields:
Bit: Bit in idle wire.
Raises:
DAGCircuitError: If the DAG is invalid
"""
if ignore is None:
ignore = set()
ignore_set = set(ignore)
for wire in self._wires:
if not ignore:
if self._is_wire_idle(wire):
yield wire
else:
for node in self.nodes_on_wire(wire, only_ops=True):
if node.op.name not in ignore_set:
# If we found an op node outside of ignore we can stop iterating over the wire
break
else:
yield wire
def size(self, *, recurse: bool = False):
"""Return the number of operations. If there is control flow present, this count may only
be an estimate, as the complete control-flow path cannot be statically known.
Args:
recurse: if ``True``, then recurse into control-flow operations. For loops with
known-length iterators are counted unrolled. If-else blocks sum both of the two
branches. While loops are counted as if the loop body runs once only. Defaults to
``False`` and raises :class:`.DAGCircuitError` if any control flow is present, to
avoid silently returning a mostly meaningless number.
Returns:
int: the circuit size
Raises:
DAGCircuitError: if an unknown :class:`.ControlFlowOp` is present in a call with
``recurse=True``, or any control flow is present in a non-recursive call.
"""
length = len(self._multi_graph) - 2 * len(self._wires)
if not recurse:
if any(x in self._op_names for x in CONTROL_FLOW_OP_NAMES):
raise DAGCircuitError(
"Size with control flow is ambiguous."
" You may use `recurse=True` to get a result,"
" but see this method's documentation for the meaning of this."
)
return length
# pylint: disable=cyclic-import
from qiskit.converters import circuit_to_dag
for node in self.op_nodes(ControlFlowOp):
if isinstance(node.op, ForLoopOp):
indexset = node.op.params[0]
inner = len(indexset) * circuit_to_dag(node.op.blocks[0]).size(recurse=True)
elif isinstance(node.op, WhileLoopOp):
inner = circuit_to_dag(node.op.blocks[0]).size(recurse=True)
elif isinstance(node.op, (IfElseOp, SwitchCaseOp)):
inner = sum(circuit_to_dag(block).size(recurse=True) for block in node.op.blocks)
else:
raise DAGCircuitError(f"unknown control-flow type: '{node.op.name}'")
# Replace the "1" for the node itself with the actual count.
length += inner - 1
return length
def depth(self, *, recurse: bool = False):
"""Return the circuit depth. If there is control flow present, this count may only be an
estimate, as the complete control-flow path cannot be statically known.
Args:
recurse: if ``True``, then recurse into control-flow operations. For loops
with known-length iterators are counted as if the loop had been manually unrolled
(*i.e.* with each iteration of the loop body written out explicitly).
If-else blocks take the longer case of the two branches. While loops are counted as
if the loop body runs once only. Defaults to ``False`` and raises
:class:`.DAGCircuitError` if any control flow is present, to avoid silently
returning a nonsensical number.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
DAGCircuitError: if unknown control flow is present in a recursive call, or any control
flow is present in a non-recursive call.
"""
if recurse:
from qiskit.converters import circuit_to_dag # pylint: disable=cyclic-import
node_lookup = {}
for node in self.op_nodes(ControlFlowOp):
weight = len(node.op.params[0]) if isinstance(node.op, ForLoopOp) else 1
if weight == 0:
node_lookup[node._node_id] = 0
else:
node_lookup[node._node_id] = weight * max(
circuit_to_dag(block).depth(recurse=True) for block in node.op.blocks
)
def weight_fn(_source, target, _edge):
return node_lookup.get(target, 1)
else:
if any(x in self._op_names for x in CONTROL_FLOW_OP_NAMES):
raise DAGCircuitError(
"Depth with control flow is ambiguous."
" You may use `recurse=True` to get a result,"
" but see this method's documentation for the meaning of this."
)
weight_fn = None