-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
dagcircuit.py
1779 lines (1485 loc) · 68.3 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 collections import OrderedDict, defaultdict
import copy
import itertools
import math
import numpy as np
import retworkx as rx
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.quantumregister import QuantumRegister, Qubit
from qiskit.circuit.classicalregister import ClassicalRegister, Clbit
from qiskit.circuit.gate import Gate
from qiskit.circuit.parameterexpression import ParameterExpression
from qiskit.dagcircuit.exceptions import DAGCircuitError
from qiskit.dagcircuit.dagnode import DAGNode, DAGOpNode, DAGInNode, DAGOutNode
from qiskit.exceptions import MissingOptionalLibraryError
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 = None
# 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 = []
self.clbits = []
self._global_phase = 0
self._calibrations = defaultdict(dict)
self._op_names = {}
self.duration = None
self.unit = "dt"
def to_networkx(self):
"""Returns a copy of the DAGCircuit in networkx format."""
try:
import networkx as nx
except ImportError as ex:
raise MissingOptionalLibraryError(
libname="Networkx",
name="DAG converter to networkx",
pip_install="pip install networkx",
) from ex
G = nx.MultiDiGraph()
for node in self._multi_graph.nodes():
G.add_node(node)
for node_id in rx.topological_sort(self._multi_graph):
for source_id, dest_id, edge in self._multi_graph.in_edges(node_id):
G.add_edge(self._multi_graph[source_id], self._multi_graph[dest_id], wire=edge)
return G
@classmethod
def from_networkx(cls, graph):
"""Take a networkx MultiDigraph and create a new DAGCircuit.
Args:
graph (networkx.MultiDiGraph): The graph to create a DAGCircuit
object from. The format of this MultiDiGraph format must be
in the same format as returned by to_networkx.
Returns:
DAGCircuit: The dagcircuit object created from the networkx
MultiDiGraph.
Raises:
MissingOptionalLibraryError: If networkx is not installed
DAGCircuitError: If input networkx graph is malformed
"""
try:
import networkx as nx
except ImportError as ex:
raise MissingOptionalLibraryError(
libname="Networkx",
name="DAG converter from networkx",
pip_install="pip install networkx",
) from ex
dag = DAGCircuit()
for node in nx.topological_sort(graph):
if isinstance(node, DAGOutNode):
continue
if isinstance(node, DAGInNode):
if isinstance(node.wire, Qubit):
dag.add_qubits([node.wire])
elif isinstance(node.wire, Clbit):
dag.add_clbits([node.wire])
else:
raise DAGCircuitError(f"unknown node wire type: {node.wire}")
elif isinstance(node, DAGOpNode):
dag.apply_operation_back(node.op.copy(), node.qargs, node.cargs)
return dag
@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):
"""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):
"""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):
"""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.
"""
if isinstance(gate, Gate):
self._calibrations[gate.name][(tuple(qubits), tuple(gate.params))] = schedule
else:
self._calibrations[gate][(tuple(qubits), tuple(params or []))] = 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)
self.qubits.extend(qubits)
for qubit in qubits:
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)
self.clbits.extend(clbits)
for clbit in clbits:
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] not in existing_qubits:
self.qubits.append(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] not in existing_clbits:
self.clbits.append(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 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)
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]
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 not None
and condition[0] not in self.clbits
and condition[0].name not in self.cregs
):
raise DAGCircuitError("invalid creg in condition for %s" % 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}")
def _bits_in_condition(self, cond):
"""Return a list of bits in the given condition.
Args:
cond (tuple or None): optional condition (ClassicalRegister, int) or (Clbit, bool)
Returns:
list[Clbit]: list of classical bits
Raises:
CircuitError: if cond[0] is not ClassicalRegister or Clbit
"""
if cond is None:
return []
elif isinstance(cond[0], ClassicalRegister):
# Returns a list of all the cbits in the given creg cond[0].
return cond[0][:]
elif isinstance(cond[0], Clbit):
# Returns a singleton list of the conditional cbit.
return [cond[0]]
else:
raise CircuitError("Condition must be used with ClassicalRegister or Clbit.")
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 _add_op_node(self, op, qargs, cargs):
"""Add a new operation node to the graph and assign properties.
Args:
op (qiskit.circuit.Instruction): the operation associated with the DAG node
qargs (list[Qubit]): list of quantum wires to attach to.
cargs (list[Clbit]): list of classical wires to attach to.
Returns:
int: The integer node index for the new op node on the DAG
"""
# Add a new operation node to the graph
new_node = DAGOpNode(op=op, qargs=qargs, cargs=cargs)
node_index = self._multi_graph.add_node(new_node)
new_node._node_id = node_index
self._increment_op(op)
return node_index
def _copy_circuit_metadata(self):
"""Return a copy of source_dag with metadata but empty."""
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.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, qargs=None, cargs=None):
"""Apply an operation to the output of the circuit.
Args:
op (qiskit.circuit.Instruction): the operation associated with the DAG node
qargs (list[Qubit]): qubits that op will be applied to
cargs (list[Clbit]): cbits that op will be applied to
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 = qargs or []
cargs = cargs or []
all_cbits = self._bits_in_condition(op.condition)
all_cbits = set(all_cbits).union(cargs)
self._check_condition(op.name, op.condition)
self._check_bits(qargs, self.output_map)
self._check_bits(all_cbits, self.output_map)
node_index = self._add_op_node(op, qargs, cargs)
# 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
al = [qargs, all_cbits]
self._multi_graph.insert_node_on_in_edges_multiple(
node_index, [self.output_map[q]._node_id for q in itertools.chain(*al)]
)
return self._multi_graph[node_index]
def apply_operation_front(self, op, qargs, cargs):
"""Apply an operation to the input of the circuit.
Args:
op (qiskit.circuit.Instruction): the operation associated with the DAG node
qargs (list[Qubit]): qubits that op will be applied to
cargs (list[Clbit]): cbits that op will be applied to
Returns:
DAGOpNode: the node for the op that was added to the dag
Raises:
DAGCircuitError: if initial nodes connected to multiple out edges
"""
all_cbits = self._bits_in_condition(op.condition)
all_cbits.extend(cargs)
self._check_condition(op.name, op.condition)
self._check_bits(qargs, self.input_map)
self._check_bits(all_cbits, self.input_map)
node_index = self._add_op_node(op, qargs, cargs)
# 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
al = [qargs, all_cbits]
self._multi_graph.insert_node_on_out_edges_multiple(
node_index, [self.input_map[q]._node_id for q in itertools.chain(*al)]
)
return self._multi_graph[node_index]
def _check_edgemap_registers(self, inbound_wires, inbound_regs):
"""Check that wiremap neither fragments nor leaves duplicate registers.
1. There are no fragmented registers. A register in keyregs
is fragmented if not all of its (qu)bits are renamed by edge_map.
2. There are no duplicate registers. A register is duplicate if
it appears in both self and keyregs but not in edge_map.
Args:
inbound_wires (list): a list of wires being mapped from the inbound dag
inbound_regs (list): a list from registers from the inbound dag
Returns:
set(Register): the set of regs to add to self
Raises:
DAGCircuitError: if the wiremap fragments, or duplicates exist
"""
add_regs = set()
reg_frag_chk = {}
for inbound_reg in inbound_regs:
reg_frag_chk[inbound_reg] = {reg_bit: False for reg_bit in inbound_reg}
for inbound_bit in inbound_wires:
for inbound_reg in inbound_regs:
if inbound_bit in inbound_reg:
reg_frag_chk[inbound_reg][inbound_bit] = True
break
for inbound_reg, v in reg_frag_chk.items():
s = set(v.values())
if len(s) == 2:
raise DAGCircuitError("inbound_wires fragments reg %s" % inbound_reg)
if s == {False}:
if inbound_reg.name in self.qregs or inbound_reg.name in self.cregs:
raise DAGCircuitError("unmapped duplicate reg %s" % inbound_reg)
# Add registers that appear only in inbound_regs
add_regs.add(inbound_reg)
return add_regs
def _check_wiremap_validity(self, wire_map, keymap, valmap):
"""Check that the wiremap is consistent.
Check that the wiremap refers to valid wires and that
those wires have consistent types.
Args:
wire_map (dict): map from Bit in keymap to Bit in valmap
keymap (list): a list of wire_map keys
valmap (dict): a map whose keys are wire_map values
Raises:
DAGCircuitError: if wire_map not valid
"""
for k, v in wire_map.items():
if k not in keymap:
raise DAGCircuitError("invalid wire mapping key %s" % k)
if v not in valmap:
raise DAGCircuitError("invalid wire mapping value %s" % v)
# TODO Support mapping from AncillaQubit to Qubit, since AncillaQubits are mapped to
# Qubits upon being converted to an Instruction. Until this translation is fixed
# and Instructions have a concept of ancilla qubits, this fix is required.
if not (isinstance(k, type(v)) or isinstance(v, type(k))):
raise DAGCircuitError(f"inconsistent wire_map at ({k},{v})")
@staticmethod
def _map_condition(wire_map, condition, target_cregs):
"""Use the wire_map dict to change the condition tuple's creg name.
Args:
wire_map (dict): a map from source wires to destination wires
condition (tuple or None): (ClassicalRegister,int)
target_cregs (list[ClassicalRegister]): List of all cregs in the
target circuit onto which the condition might possibly be mapped.
Returns:
tuple(ClassicalRegister,int): new condition
Raises:
DAGCircuitError: if condition register not in wire_map, or if
wire_map maps condition onto more than one creg, or if the
specified condition is not present in a classical register.
"""
if condition is None:
new_condition = None
else:
# if there is a condition, map the condition bits to the
# composed cregs based on the wire_map
is_reg = False
if isinstance(condition[0], Clbit):
cond_creg = [condition[0]]
else:
cond_creg = condition[0]
is_reg = True
cond_val = condition[1]
new_cond_val = 0
new_creg = None
bits_in_condcreg = [bit for bit in wire_map if bit in cond_creg]
for bit in bits_in_condcreg:
if is_reg:
try:
candidate_creg = next(
creg for creg in target_cregs if wire_map[bit] in creg
)
except StopIteration as ex:
raise DAGCircuitError(
"Did not find creg containing mapped clbit in conditional."
) from ex
else:
# If cond is on a single Clbit then the candidate_creg is
# the target Clbit to which 'bit' is mapped to.
candidate_creg = wire_map[bit]
if new_creg is None:
new_creg = candidate_creg
elif new_creg != candidate_creg:
# Raise if wire_map maps condition creg on to more than one
# creg in target DAG.
raise DAGCircuitError(
"wire_map maps conditional register onto more than one creg."
)
if not is_reg:
# If the cond is on a single Clbit then the new_cond_val is the
# same as the cond_val since the new_creg is also a single Clbit.
new_cond_val = cond_val
elif 2 ** (cond_creg[:].index(bit)) & cond_val:
# If the conditional values of the Clbit 'bit' is 1 then the new_cond_val
# is updated such that the conditional value of the Clbit to which 'bit'
# is mapped to in new_creg is 1.
new_cond_val += 2 ** (new_creg[:].index(wire_map[bit]))
if new_creg is None:
raise DAGCircuitError("Condition registers not found in wire_map.")
new_condition = (new_creg, new_cond_val)
return new_condition
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[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)
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):
condition = dag._map_condition(edge_map, nd.op.condition, dag.cregs.values())
dag._check_condition(nd.op.name, condition)
m_qargs = list(map(lambda x: edge_map.get(x, x), nd.qargs))
m_cargs = list(map(lambda x: edge_map.get(x, x), nd.cargs))
op = nd.op.copy()
op.condition = condition
dag.apply_operation_back(op, m_qargs, m_cargs)
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):
"""Return the number of operations."""
return len(self._multi_graph) - 2 * len(self._wires)
def depth(self):
"""Return the circuit depth.
Returns:
int: the circuit depth
Raises:
DAGCircuitError: if not a directed acyclic graph
"""
try:
depth = rx.dag_longest_path_length(self._multi_graph) - 1
except rx.DAGHasCycle as ex:
raise DAGCircuitError("not a DAG") from ex
return depth if depth >= 0 else 0
def width(self):
"""Return the total number of qubits + clbits used by the circuit.
This function formerly returned the number of qubits by the calculation
return len(self._wires) - self.num_clbits()
but was changed by issue #2564 to return number of qubits + clbits
with the new function DAGCircuit.num_qubits replacing the former
semantic of DAGCircuit.width().
"""
return len(self._wires)
def num_qubits(self):
"""Return the total number of qubits used by the circuit.
num_qubits() replaces former use of width().
DAGCircuit.width() now returns qubits + clbits for
consistency with Circuit.width() [qiskit-terra #2564].
"""
return len(self.qubits)
def num_clbits(self):
"""Return the total number of classical bits used by the circuit."""
return len(self.clbits)
def num_tensor_factors(self):
"""Compute how many components the circuit can decompose into."""
return rx.number_weakly_connected_components(self._multi_graph)
def _check_wires_list(self, wires, node):
"""Check that a list of wires is compatible with a node to be replaced.
- no duplicate names
- correct length for operation
Raise an exception otherwise.
Args:
wires (list[Bit]): gives an order for (qu)bits
in the input circuit that is replacing the node.
node (DAGOpNode): a node in the dag
Raises:
DAGCircuitError: if check doesn't pass.
"""
if len(set(wires)) != len(wires):
raise DAGCircuitError("duplicate wires")
wire_tot = len(node.qargs) + len(node.cargs)
if node.op.condition is not None:
wire_tot += node.op.condition[0].size
if len(wires) != wire_tot:
raise DAGCircuitError("expected %d wires, got %d" % (wire_tot, len(wires)))
def __eq__(self, other):
# Try to convert to float, but in case of unbound ParameterExpressions
# a TypeError will be raise, fallback to normal equality in those
# cases
try:
self_phase = float(self.global_phase)
other_phase = float(other.global_phase)
if (
abs((self_phase - other_phase + np.pi) % (2 * np.pi) - np.pi) > 1.0e-10
): # TODO: atol?
return False
except TypeError:
if self.global_phase != other.global_phase:
return False
if self.calibrations != other.calibrations:
return False
self_bit_indices = {bit: idx for idx, bit in enumerate(self.qubits + self.clbits)}
other_bit_indices = {bit: idx for idx, bit in enumerate(other.qubits + other.clbits)}
self_qreg_indices = [
(regname, [self_bit_indices[bit] for bit in reg]) for regname, reg in self.qregs.items()
]
self_creg_indices = [
(regname, [self_bit_indices[bit] for bit in reg]) for regname, reg in self.cregs.items()
]
other_qreg_indices = [
(regname, [other_bit_indices[bit] for bit in reg])
for regname, reg in other.qregs.items()
]
other_creg_indices = [
(regname, [other_bit_indices[bit] for bit in reg])
for regname, reg in other.cregs.items()
]
if self_qreg_indices != other_qreg_indices or self_creg_indices != other_creg_indices:
return False
def node_eq(node_self, node_other):
return DAGNode.semantic_eq(node_self, node_other, self_bit_indices, other_bit_indices)
return rx.is_isomorphic_node_match(self._multi_graph, other._multi_graph, node_eq)
def topological_nodes(self, key=None):
"""
Yield nodes in topological order.
Args:
key (Callable): A callable which will take a DAGNode object and
return a string sort key. If not specified the
:attr:`~qiskit.dagcircuit.DAGNode.sort_key` attribute will be
used as the sort key for each node.
Returns:
generator(DAGOpNode, DAGInNode, or DAGOutNode): node in topological order
"""