-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathdag_circuit.rs
7416 lines (6926 loc) · 294 KB
/
dag_circuit.rs
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 2024
//
// 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.
use std::hash::Hash;
use ahash::RandomState;
use approx::relative_eq;
use smallvec::SmallVec;
use crate::bit_data::BitData;
use crate::circuit_data::CircuitData;
use crate::circuit_instruction::{
CircuitInstruction, ExtraInstructionAttributes, OperationFromPython,
};
use crate::converters::QuantumCircuitData;
use crate::dag_node::{DAGInNode, DAGNode, DAGOpNode, DAGOutNode};
use crate::dot_utils::build_dot;
use crate::error::DAGCircuitError;
use crate::imports;
use crate::interner::{Interned, InternedMap, Interner};
use crate::operations::{ArrayType, Operation, OperationRef, Param, PyInstruction, StandardGate};
use crate::packed_instruction::{PackedInstruction, PackedOperation};
use crate::rustworkx_core_vnext::isomorphism;
use crate::{BitType, Clbit, Qubit, TupleLikeArg};
use hashbrown::{HashMap, HashSet};
use indexmap::IndexMap;
use itertools::Itertools;
use pyo3::exceptions::{
PyDeprecationWarning, PyIndexError, PyRuntimeError, PyTypeError, PyValueError,
};
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::IntoPyObjectExt;
use pyo3::types::{
IntoPyDict, PyDict, PyInt, PyIterator, PyList, PySequence, PySet, PyString, PyTuple, PyType,
};
use rustworkx_core::dag_algo::layers;
use rustworkx_core::err::ContractError;
use rustworkx_core::graph_ext::ContractNodesDirected;
use rustworkx_core::petgraph;
use rustworkx_core::petgraph::prelude::StableDiGraph;
use rustworkx_core::petgraph::prelude::*;
use rustworkx_core::petgraph::stable_graph::{EdgeReference, NodeIndex};
use rustworkx_core::petgraph::unionfind::UnionFind;
use rustworkx_core::petgraph::visit::{
EdgeIndexable, IntoEdgeReferences, IntoNodeReferences, NodeFiltered, NodeIndexable,
};
use rustworkx_core::petgraph::Incoming;
use rustworkx_core::traversal::{
ancestors as core_ancestors, bfs_predecessors as core_bfs_predecessors,
bfs_successors as core_bfs_successors, descendants as core_descendants,
};
use std::cmp::Ordering;
use std::collections::{BTreeMap, VecDeque};
use std::convert::Infallible;
use std::f64::consts::PI;
#[cfg(feature = "cache_pygates")]
use std::sync::OnceLock;
static CONTROL_FLOW_OP_NAMES: [&str; 4] = ["for_loop", "while_loop", "if_else", "switch_case"];
static SEMANTIC_EQ_SYMMETRIC: [&str; 4] = ["barrier", "swap", "break_loop", "continue_loop"];
/// An opaque key type that identifies a variable within a [DAGCircuit].
///
/// When a new variable is added to the DAG, it is associated internally
/// with one of these keys. When enumerating DAG nodes and edges, you can
/// retrieve the associated variable instance via [DAGCircuit::get_var].
///
/// These keys are [Eq], but this is semantically valid only for keys
/// from the same [DAGCircuit] instance.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Var(BitType);
impl Var {
/// Construct a new [Var] object from a usize. if you have a u32 you can
/// create a [Var] object directly with `Var(0u32)`. This will panic
/// if the `usize` index exceeds `u32::MAX`.
#[inline(always)]
fn new(index: usize) -> Self {
Var(index
.try_into()
.unwrap_or_else(|_| panic!("Index value '{}' exceeds the maximum bit width!", index)))
}
/// Get the index of the [Var]
#[inline(always)]
fn index(&self) -> usize {
self.0 as usize
}
}
impl From<BitType> for Var {
fn from(value: BitType) -> Self {
Var(value)
}
}
impl From<Var> for BitType {
fn from(value: Var) -> Self {
value.0
}
}
#[derive(Clone, Debug)]
pub enum NodeType {
QubitIn(Qubit),
QubitOut(Qubit),
ClbitIn(Clbit),
ClbitOut(Clbit),
VarIn(Var),
VarOut(Var),
Operation(PackedInstruction),
}
impl NodeType {
/// Unwraps this node as an operation and returns a reference to
/// the contained [PackedInstruction].
///
/// Panics if this is not an operation node.
pub fn unwrap_operation(&self) -> &PackedInstruction {
match self {
NodeType::Operation(instr) => instr,
_ => panic!("Node is not an operation!"),
}
}
}
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub enum Wire {
Qubit(Qubit),
Clbit(Clbit),
Var(Var),
}
impl Wire {
fn to_pickle(&self, py: Python) -> PyResult<PyObject> {
match self {
Self::Qubit(bit) => (0, bit.0.into_py_any(py)?),
Self::Clbit(bit) => (1, bit.0.into_py_any(py)?),
Self::Var(var) => (2, var.0.into_py_any(py)?),
}
.into_py_any(py)
}
fn from_pickle(b: &Bound<PyAny>) -> PyResult<Self> {
let tuple: Bound<PyTuple> = b.extract()?;
let wire_type: usize = tuple.get_item(0)?.extract()?;
if wire_type == 0 {
Ok(Self::Qubit(Qubit(tuple.get_item(1)?.extract()?)))
} else if wire_type == 1 {
Ok(Self::Clbit(Clbit(tuple.get_item(1)?.extract()?)))
} else if wire_type == 2 {
Ok(Self::Var(Var(tuple.get_item(1)?.extract()?)))
} else {
Err(PyTypeError::new_err("Invalid wire type"))
}
}
}
/// 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.
#[pyclass(module = "qiskit._accelerate.circuit")]
#[derive(Clone, Debug)]
pub struct DAGCircuit {
/// Circuit name. Generally, this corresponds to the name
/// of the QuantumCircuit from which the DAG was generated.
#[pyo3(get, set)]
name: Option<PyObject>,
/// Circuit metadata
#[pyo3(get, set)]
metadata: Option<PyObject>,
calibrations: HashMap<String, Py<PyDict>>,
dag: StableDiGraph<NodeType, Wire>,
#[pyo3(get)]
qregs: Py<PyDict>,
#[pyo3(get)]
cregs: Py<PyDict>,
/// The cache used to intern instruction qargs.
pub qargs_interner: Interner<[Qubit]>,
/// The cache used to intern instruction cargs.
pub cargs_interner: Interner<[Clbit]>,
/// Qubits registered in the circuit.
qubits: BitData<Qubit>,
/// Clbits registered in the circuit.
clbits: BitData<Clbit>,
/// Variables registered in the circuit.
vars: BitData<Var>,
/// Global phase.
global_phase: Param,
/// Duration.
#[pyo3(set)]
duration: Option<PyObject>,
/// Unit of duration.
#[pyo3(set)]
unit: String,
// Note: these are tracked separately from `qubits` and `clbits`
// because it's not yet clear if the Rust concept of a native Qubit
// and Clbit should correspond directly to the numerical Python
// index that users see in the Python API.
/// The index locations of bits, and their positions within
/// registers.
qubit_locations: Py<PyDict>,
clbit_locations: Py<PyDict>,
/// Map from qubit to input and output nodes of the graph.
qubit_io_map: Vec<[NodeIndex; 2]>,
/// Map from clbit to input and output nodes of the graph.
clbit_io_map: Vec<[NodeIndex; 2]>,
/// Map from var to input and output nodes of the graph.
var_io_map: Vec<[NodeIndex; 2]>,
/// Operation kind to count
op_names: IndexMap<String, usize, RandomState>,
// Python modules we need to frequently access (for now).
control_flow_module: PyControlFlowModule,
vars_info: HashMap<String, DAGVarInfo>,
vars_by_type: [Py<PySet>; 3],
}
#[derive(Clone, Debug)]
struct PyControlFlowModule {
condition_resources: Py<PyAny>,
node_resources: Py<PyAny>,
}
#[derive(Clone, Debug)]
struct PyLegacyResources {
clbits: Py<PyTuple>,
cregs: Py<PyTuple>,
}
impl PyControlFlowModule {
fn new(py: Python) -> PyResult<Self> {
let module = PyModule::import(py, "qiskit.circuit.controlflow")?;
Ok(PyControlFlowModule {
condition_resources: module.getattr("condition_resources")?.unbind(),
node_resources: module.getattr("node_resources")?.unbind(),
})
}
fn condition_resources(&self, condition: &Bound<PyAny>) -> PyResult<PyLegacyResources> {
let res = self
.condition_resources
.bind(condition.py())
.call1((condition,))?;
Ok(PyLegacyResources {
clbits: res.getattr("clbits")?.downcast_into_exact()?.unbind(),
cregs: res.getattr("cregs")?.downcast_into_exact()?.unbind(),
})
}
fn node_resources(&self, node: &Bound<PyAny>) -> PyResult<PyLegacyResources> {
let res = self.node_resources.bind(node.py()).call1((node,))?;
Ok(PyLegacyResources {
clbits: res.getattr("clbits")?.downcast_into_exact()?.unbind(),
cregs: res.getattr("cregs")?.downcast_into_exact()?.unbind(),
})
}
}
#[derive(IntoPyObject)]
struct PyVariableMapper {
mapper: Py<PyAny>,
}
impl PyVariableMapper {
fn new(
py: Python,
target_cregs: Bound<PyAny>,
bit_map: Option<Bound<PyDict>>,
var_map: Option<Bound<PyDict>>,
add_register: Option<Py<PyAny>>,
) -> PyResult<Self> {
let kwargs: HashMap<&str, Option<Py<PyAny>>> =
HashMap::from_iter([("add_register", add_register)]);
Ok(PyVariableMapper {
mapper: imports::VARIABLE_MAPPER
.get_bound(py)
.call(
(target_cregs, bit_map, var_map),
Some(&kwargs.into_py_dict(py)?),
)?
.unbind(),
})
}
fn map_condition<'py>(
&self,
condition: &Bound<'py, PyAny>,
allow_reorder: bool,
) -> PyResult<Bound<'py, PyAny>> {
let py = condition.py();
let kwargs: HashMap<&str, bool> = HashMap::from_iter([("allow_reorder", allow_reorder)]);
self.mapper.bind(py).call_method(
intern!(py, "map_condition"),
(condition,),
Some(&kwargs.into_py_dict(py)?),
)
}
fn map_target<'py>(&self, target: &Bound<'py, PyAny>) -> PyResult<Bound<'py, PyAny>> {
let py = target.py();
self.mapper
.bind(py)
.call_method1(intern!(py, "map_target"), (target,))
}
}
#[pyfunction]
fn reject_new_register(reg: &Bound<PyAny>) -> PyResult<()> {
Err(DAGCircuitError::new_err(format!(
"No register with '{:?}' to map this expression onto.",
reg.getattr("bits")?
)))
}
#[pyclass(module = "qiskit._accelerate.circuit")]
#[derive(Clone, Debug)]
struct BitLocations {
#[pyo3(get)]
index: usize,
#[pyo3(get)]
registers: Py<PyList>,
}
#[derive(Copy, Clone, Debug)]
enum DAGVarType {
Input = 0,
Capture = 1,
Declare = 2,
}
#[derive(Clone, Debug)]
struct DAGVarInfo {
var: PyObject,
type_: DAGVarType,
in_node: NodeIndex,
out_node: NodeIndex,
}
#[pymethods]
impl DAGCircuit {
#[new]
pub fn new(py: Python<'_>) -> PyResult<Self> {
Ok(DAGCircuit {
name: None,
metadata: Some(PyDict::new(py).unbind().into()),
calibrations: HashMap::new(),
dag: StableDiGraph::default(),
qregs: PyDict::new(py).unbind(),
cregs: PyDict::new(py).unbind(),
qargs_interner: Interner::new(),
cargs_interner: Interner::new(),
qubits: BitData::new(py, "qubits".to_string()),
clbits: BitData::new(py, "clbits".to_string()),
vars: BitData::new(py, "vars".to_string()),
global_phase: Param::Float(0.),
duration: None,
unit: "dt".to_string(),
qubit_locations: PyDict::new(py).unbind(),
clbit_locations: PyDict::new(py).unbind(),
qubit_io_map: Vec::new(),
clbit_io_map: Vec::new(),
var_io_map: Vec::new(),
op_names: IndexMap::default(),
control_flow_module: PyControlFlowModule::new(py)?,
vars_info: HashMap::new(),
vars_by_type: [
PySet::empty(py)?.unbind(),
PySet::empty(py)?.unbind(),
PySet::empty(py)?.unbind(),
],
})
}
/// The total duration of the circuit, set by a scheduling transpiler pass. Its unit is
/// specified by :attr:`.unit`
///
/// DEPRECATED since Qiskit 1.3.0 and will be removed in Qiskit 2.0.0
#[getter]
fn get_duration(&self, py: Python) -> PyResult<Option<Py<PyAny>>> {
imports::WARNINGS_WARN.get_bound(py).call1((
intern!(
py,
concat!(
"The property ``qiskit.dagcircuit.dagcircuit.DAGCircuit.duration`` is ",
"deprecated as of Qiskit 1.3.0. It will be removed in Qiskit 2.0.0.",
)
),
py.get_type::<PyDeprecationWarning>(),
2,
))?;
Ok(self.duration.as_ref().map(|x| x.clone_ref(py)))
}
/// The unit that duration is specified in.
///
/// DEPRECATED since Qiskit 1.3.0 and will be removed in Qiskit 2.0.0
#[getter]
fn get_unit(&self, py: Python) -> PyResult<String> {
imports::WARNINGS_WARN.get_bound(py).call1((
intern!(
py,
concat!(
"The property ``qiskit.dagcircuit.dagcircuit.DAGCircuit.unit`` is ",
"deprecated as of Qiskit 1.3.0. It will be removed in Qiskit 2.0.0.",
)
),
py.get_type::<PyDeprecationWarning>(),
2,
))?;
Ok(self.unit.clone())
}
#[getter]
fn input_map(&self, py: Python) -> PyResult<Py<PyDict>> {
let out_dict = PyDict::new(py);
for (qubit, indices) in self
.qubit_io_map
.iter()
.enumerate()
.map(|(idx, indices)| (Qubit::new(idx), indices))
{
out_dict.set_item(
self.qubits.get(qubit).unwrap().clone_ref(py),
self.get_node(py, indices[0])?,
)?;
}
for (clbit, indices) in self
.clbit_io_map
.iter()
.enumerate()
.map(|(idx, indices)| (Clbit::new(idx), indices))
{
out_dict.set_item(
self.clbits.get(clbit).unwrap().clone_ref(py),
self.get_node(py, indices[0])?,
)?;
}
for (var, indices) in self
.var_io_map
.iter()
.enumerate()
.map(|(idx, indices)| (Var::new(idx), indices))
{
out_dict.set_item(
self.vars.get(var).unwrap().clone_ref(py),
self.get_node(py, indices[0])?,
)?;
}
Ok(out_dict.unbind())
}
#[getter]
fn output_map(&self, py: Python) -> PyResult<Py<PyDict>> {
let out_dict = PyDict::new(py);
for (qubit, indices) in self
.qubit_io_map
.iter()
.enumerate()
.map(|(idx, indices)| (Qubit::new(idx), indices))
{
out_dict.set_item(
self.qubits.get(qubit).unwrap().clone_ref(py),
self.get_node(py, indices[1])?,
)?;
}
for (clbit, indices) in self
.clbit_io_map
.iter()
.enumerate()
.map(|(idx, indices)| (Clbit::new(idx), indices))
{
out_dict.set_item(
self.clbits.get(clbit).unwrap().clone_ref(py),
self.get_node(py, indices[1])?,
)?;
}
for (var, indices) in self
.var_io_map
.iter()
.enumerate()
.map(|(idx, indices)| (Var::new(idx), indices))
{
out_dict.set_item(
self.vars.get(var).unwrap().clone_ref(py),
self.get_node(py, indices[1])?,
)?;
}
Ok(out_dict.unbind())
}
fn __getstate__(&self, py: Python) -> PyResult<Py<PyDict>> {
let out_dict = PyDict::new(py);
out_dict.set_item("name", self.name.as_ref().map(|x| x.clone_ref(py)))?;
out_dict.set_item("metadata", self.metadata.as_ref().map(|x| x.clone_ref(py)))?;
out_dict.set_item("_calibrations_prop", self.calibrations.clone())?;
out_dict.set_item("qregs", self.qregs.clone_ref(py))?;
out_dict.set_item("cregs", self.cregs.clone_ref(py))?;
out_dict.set_item("global_phase", self.global_phase.clone())?;
out_dict.set_item(
"qubit_io_map",
self.qubit_io_map
.iter()
.enumerate()
.map(|(k, v)| (k, [v[0].index(), v[1].index()]))
.into_py_dict(py)?,
)?;
out_dict.set_item(
"clbit_io_map",
self.clbit_io_map
.iter()
.enumerate()
.map(|(k, v)| (k, [v[0].index(), v[1].index()]))
.into_py_dict(py)?,
)?;
out_dict.set_item(
"var_io_map",
self.var_io_map
.iter()
.enumerate()
.map(|(k, v)| (k, [v[0].index(), v[1].index()]))
.into_py_dict(py)?,
)?;
out_dict.set_item("op_name", self.op_names.clone())?;
out_dict.set_item(
"vars_info",
self.vars_info
.iter()
.map(|(k, v)| {
(
k,
(
v.var.clone_ref(py),
v.type_ as u8,
v.in_node.index(),
v.out_node.index(),
),
)
})
.into_py_dict(py)?,
)?;
out_dict.set_item("vars_by_type", self.vars_by_type.clone())?;
out_dict.set_item("qubits", self.qubits.bits())?;
out_dict.set_item("clbits", self.clbits.bits())?;
out_dict.set_item("vars", self.vars.bits())?;
let mut nodes: Vec<PyObject> = Vec::with_capacity(self.dag.node_count());
for node_idx in self.dag.node_indices() {
let node_data = self.get_node(py, node_idx)?;
nodes.push((node_idx.index(), node_data).into_py_any(py)?);
}
out_dict.set_item("nodes", nodes)?;
out_dict.set_item(
"nodes_removed",
self.dag.node_count() != self.dag.node_bound(),
)?;
let mut edges: Vec<PyObject> = Vec::with_capacity(self.dag.edge_bound());
// edges are saved with none (deleted edges) instead of their index to save space
for i in 0..self.dag.edge_bound() {
let idx = EdgeIndex::new(i);
let edge = match self.dag.edge_weight(idx) {
Some(edge_w) => {
let endpoints = self.dag.edge_endpoints(idx).unwrap();
(
endpoints.0.index(),
endpoints.1.index(),
edge_w.clone().to_pickle(py)?,
)
.into_py_any(py)?
}
None => py.None(),
};
edges.push(edge);
}
out_dict.set_item("edges", edges)?;
Ok(out_dict.unbind())
}
fn __setstate__(&mut self, py: Python, state: PyObject) -> PyResult<()> {
let dict_state = state.downcast_bound::<PyDict>(py)?;
self.name = dict_state.get_item("name")?.unwrap().extract()?;
self.metadata = dict_state.get_item("metadata")?.unwrap().extract()?;
self.calibrations = dict_state
.get_item("_calibrations_prop")?
.unwrap()
.extract()?;
self.qregs = dict_state.get_item("qregs")?.unwrap().extract()?;
self.cregs = dict_state.get_item("cregs")?.unwrap().extract()?;
self.global_phase = dict_state.get_item("global_phase")?.unwrap().extract()?;
self.op_names = dict_state.get_item("op_name")?.unwrap().extract()?;
self.vars_by_type = dict_state.get_item("vars_by_type")?.unwrap().extract()?;
let binding = dict_state.get_item("vars_info")?.unwrap();
let vars_info_raw = binding.downcast::<PyDict>().unwrap();
self.vars_info = HashMap::with_capacity(vars_info_raw.len());
for (key, value) in vars_info_raw.iter() {
let val_tuple = value.downcast::<PyTuple>()?;
let info = DAGVarInfo {
var: val_tuple.get_item(0)?.unbind(),
type_: match val_tuple.get_item(1)?.extract::<u8>()? {
0 => DAGVarType::Input,
1 => DAGVarType::Capture,
2 => DAGVarType::Declare,
_ => return Err(PyValueError::new_err("Invalid var type")),
},
in_node: NodeIndex::new(val_tuple.get_item(2)?.extract()?),
out_node: NodeIndex::new(val_tuple.get_item(3)?.extract()?),
};
self.vars_info.insert(key.extract()?, info);
}
let binding = dict_state.get_item("qubits")?.unwrap();
let qubits_raw = binding.downcast::<PyList>().unwrap();
for bit in qubits_raw.iter() {
self.qubits.add(py, &bit, false)?;
}
let binding = dict_state.get_item("clbits")?.unwrap();
let clbits_raw = binding.downcast::<PyList>().unwrap();
for bit in clbits_raw.iter() {
self.clbits.add(py, &bit, false)?;
}
let binding = dict_state.get_item("vars")?.unwrap();
let vars_raw = binding.downcast::<PyList>().unwrap();
for bit in vars_raw.iter() {
self.vars.add(py, &bit, false)?;
}
let binding = dict_state.get_item("qubit_io_map")?.unwrap();
let qubit_index_map_raw = binding.downcast::<PyDict>().unwrap();
self.qubit_io_map = Vec::with_capacity(qubit_index_map_raw.len());
for (_k, v) in qubit_index_map_raw.iter() {
let indices: [usize; 2] = v.extract()?;
self.qubit_io_map
.push([NodeIndex::new(indices[0]), NodeIndex::new(indices[1])]);
}
let binding = dict_state.get_item("clbit_io_map")?.unwrap();
let clbit_index_map_raw = binding.downcast::<PyDict>().unwrap();
self.clbit_io_map = Vec::with_capacity(clbit_index_map_raw.len());
for (_k, v) in clbit_index_map_raw.iter() {
let indices: [usize; 2] = v.extract()?;
self.clbit_io_map
.push([NodeIndex::new(indices[0]), NodeIndex::new(indices[1])]);
}
let binding = dict_state.get_item("var_io_map")?.unwrap();
let var_index_map_raw = binding.downcast::<PyDict>().unwrap();
self.var_io_map = Vec::with_capacity(var_index_map_raw.len());
for (_k, v) in var_index_map_raw.iter() {
let indices: [usize; 2] = v.extract()?;
self.var_io_map
.push([NodeIndex::new(indices[0]), NodeIndex::new(indices[1])]);
}
// Rebuild Graph preserving index holes:
let binding = dict_state.get_item("nodes")?.unwrap();
let nodes_lst = binding.downcast::<PyList>()?;
let binding = dict_state.get_item("edges")?.unwrap();
let edges_lst = binding.downcast::<PyList>()?;
let node_removed: bool = dict_state.get_item("nodes_removed")?.unwrap().extract()?;
self.dag = StableDiGraph::default();
if !node_removed {
for item in nodes_lst.iter() {
let node_w = item.downcast::<PyTuple>().unwrap().get_item(1).unwrap();
let weight = self.pack_into(py, &node_w)?;
self.dag.add_node(weight);
}
} else if nodes_lst.len() == 1 {
// graph has only one node, handle logic here to save one if in the loop later
let binding = nodes_lst.get_item(0).unwrap();
let item = binding.downcast::<PyTuple>().unwrap();
let node_idx: usize = item.get_item(0).unwrap().extract().unwrap();
let node_w = item.get_item(1).unwrap();
for _i in 0..node_idx {
self.dag.add_node(NodeType::QubitIn(Qubit(u32::MAX)));
}
let weight = self.pack_into(py, &node_w)?;
self.dag.add_node(weight);
for i in 0..node_idx {
self.dag.remove_node(NodeIndex::new(i));
}
} else {
let binding = nodes_lst.get_item(nodes_lst.len() - 1).unwrap();
let last_item = binding.downcast::<PyTuple>().unwrap();
// list of temporary nodes that will be removed later to re-create holes
let node_bound_1: usize = last_item.get_item(0).unwrap().extract().unwrap();
let mut tmp_nodes: Vec<NodeIndex> =
Vec::with_capacity(node_bound_1 + 1 - nodes_lst.len());
for item in nodes_lst {
let item = item.downcast::<PyTuple>().unwrap();
let next_index: usize = item.get_item(0).unwrap().extract().unwrap();
let weight: PyObject = item.get_item(1).unwrap().extract().unwrap();
while next_index > self.dag.node_bound() {
// node does not exist
let tmp_node = self.dag.add_node(NodeType::QubitIn(Qubit(u32::MAX)));
tmp_nodes.push(tmp_node);
}
// add node to the graph, and update the next available node index
let weight = self.pack_into(py, weight.bind(py))?;
self.dag.add_node(weight);
}
// Remove any temporary nodes we added
for tmp_node in tmp_nodes {
self.dag.remove_node(tmp_node);
}
}
// to ensure O(1) on edge deletion, use a temporary node to store missing edges
let tmp_node = self.dag.add_node(NodeType::QubitIn(Qubit(u32::MAX)));
for item in edges_lst {
if item.is_none() {
// add a temporary edge that will be deleted later to re-create the hole
self.dag
.add_edge(tmp_node, tmp_node, Wire::Qubit(Qubit(u32::MAX)));
} else {
let triple = item.downcast::<PyTuple>().unwrap();
let edge_p: usize = triple.get_item(0).unwrap().extract().unwrap();
let edge_c: usize = triple.get_item(1).unwrap().extract().unwrap();
let edge_w = Wire::from_pickle(&triple.get_item(2).unwrap())?;
self.dag
.add_edge(NodeIndex::new(edge_p), NodeIndex::new(edge_c), edge_w);
}
}
self.dag.remove_node(tmp_node);
Ok(())
}
/// Returns the current sequence of registered :class:`.Qubit` instances as a list.
///
/// .. warning::
///
/// Do not modify this list yourself. It will invalidate the :class:`DAGCircuit` data
/// structures.
///
/// Returns:
/// list(:class:`.Qubit`): The current sequence of registered qubits.
#[getter(qubits)]
pub fn py_qubits(&self, py: Python<'_>) -> Py<PyList> {
self.qubits.cached().clone_ref(py)
}
/// Returns the current sequence of registered :class:`.Clbit`
/// instances as a list.
///
/// .. warning::
///
/// Do not modify this list yourself. It will invalidate the :class:`DAGCircuit` data
/// structures.
///
/// Returns:
/// list(:class:`.Clbit`): The current sequence of registered clbits.
#[getter(clbits)]
pub fn py_clbits(&self, py: Python<'_>) -> Py<PyList> {
self.clbits.cached().clone_ref(py)
}
/// Return a list of the wires in order.
#[getter]
fn get_wires(&self, py: Python<'_>) -> PyResult<Py<PyList>> {
let wires: Vec<&PyObject> = self
.qubits
.bits()
.iter()
.chain(self.clbits.bits().iter())
.collect();
let out_list = PyList::new(py, wires)?;
for var_type_set in &self.vars_by_type {
for var in var_type_set.bind(py).iter() {
out_list.append(var)?;
}
}
Ok(out_list.unbind())
}
/// Returns the number of nodes in the dag.
#[getter]
fn get_node_counter(&self) -> usize {
self.dag.node_count()
}
/// Return the global phase of the circuit.
#[getter]
pub fn get_global_phase(&self) -> Param {
self.global_phase.clone()
}
/// Set the global phase of the circuit.
///
/// Args:
/// angle (float, :class:`.ParameterExpression`): The phase angle.
#[setter]
fn set_global_phase(&mut self, angle: Param) -> PyResult<()> {
match angle {
Param::Float(angle) => {
self.global_phase = Param::Float(angle.rem_euclid(2. * PI));
}
Param::ParameterExpression(angle) => {
self.global_phase = Param::ParameterExpression(angle);
}
Param::Obj(_) => return Err(PyTypeError::new_err("Invalid type for global phase")),
}
Ok(())
}
/// Return calibration dictionary.
///
/// The custom pulse definition of a given gate is of the form
/// {'gate_name': {(qubits, params): schedule}}
///
/// DEPRECATED since Qiskit 1.3.0 and will be removed in Qiskit 2.0.0
#[getter]
fn get_calibrations(&self, py: Python) -> HashMap<String, Py<PyDict>> {
emit_pulse_dependency_deprecation(
py,
"property ``qiskit.dagcircuit.dagcircuit.DAGCircuit.calibrations``",
);
self.calibrations.clone()
}
/// 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}}
///
/// DEPRECATED since Qiskit 1.3.0 and will be removed in Qiskit 2.0.0
#[setter]
fn set_calibrations(&mut self, py: Python, calibrations: HashMap<String, Py<PyDict>>) {
emit_pulse_dependency_deprecation(
py,
"property ``qiskit.dagcircuit.dagcircuit.DAGCircuit.calibrations``",
);
self.calibrations = calibrations;
}
// This is an alternative and Python-private path to 'get_calibration' to avoid
// deprecation warnings
#[getter(_calibrations_prop)]
fn get_calibrations_prop(&self) -> HashMap<String, Py<PyDict>> {
self.calibrations.clone()
}
// This is an alternative and Python-private path to 'set_calibration' to avoid
// deprecation warnings
#[setter(_calibrations_prop)]
fn set_calibrations_prop(&mut self, calibrations: HashMap<String, Py<PyDict>>) {
self.calibrations = calibrations;
}
/// 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.
///
/// DEPRECATED since Qiskit 1.3.0 and will be removed in Qiskit 2.0.0
#[pyo3(signature=(gate, qubits, schedule, params=None))]
fn add_calibration<'py>(
&mut self,
py: Python<'py>,
mut gate: Bound<'py, PyAny>,
qubits: Bound<'py, PyAny>,
schedule: Py<PyAny>,
mut params: Option<Bound<'py, PyAny>>,
) -> PyResult<()> {
emit_pulse_dependency_deprecation(
py,
"method ``qiskit.dagcircuit.dagcircuit.DAGCircuit.add_calibration``",
);
if gate.is_instance(imports::GATE.get_bound(py))? {
params = Some(gate.getattr(intern!(py, "params"))?);
gate = gate.getattr(intern!(py, "name"))?;
}
let params_tuple = if let Some(operands) = params {
let add_calibration = PyModule::from_code(
py,
std::ffi::CString::new(
r#"
import numpy as np
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
"#,
)?
.as_c_str(),
std::ffi::CString::new("add_calibration.py")?.as_c_str(),
std::ffi::CString::new("add_calibration")?.as_c_str(),
)?;
let format = add_calibration.getattr("_format")?;
let mapped: PyResult<Vec<_>> =
operands.try_iter()?.map(|p| format.call1((p?,))).collect();
PyTuple::new(py, mapped?)?.into_any()
} else {
PyTuple::empty(py).into_any()
};
let calibrations = self
.calibrations
.entry(gate.extract()?)
.or_insert_with(|| PyDict::new(py).unbind())
.bind(py);
let qubits = if let Ok(qubits) = qubits.downcast::<PySequence>() {
qubits.to_tuple()?.into_any()
} else {
PyTuple::new(py, [qubits])?.into_any()
};
let key = PyTuple::new(py, &[qubits.unbind(), params_tuple.into_any().unbind()])?;
calibrations.set_item(key, schedule)?;
Ok(())
}
/// 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.
///
/// DEPRECATED since Qiskit 1.3.0 and will be removed in Qiskit 2.0.0
pub fn has_calibration_for(&self, py: Python, node: PyRef<DAGOpNode>) -> PyResult<bool> {
emit_pulse_dependency_deprecation(
py,
"method ``qiskit.dagcircuit.dagcircuit.DAGCircuit.has_calibration_for``",
);
self._has_calibration_for(py, node)
}
fn _has_calibration_for(&self, py: Python, node: PyRef<DAGOpNode>) -> PyResult<bool> {
if !self
.calibrations
.contains_key(node.instruction.operation.name())
{
return Ok(false);
}
let mut params = Vec::new();
for p in &node.instruction.params {
if let Param::ParameterExpression(exp) = p {
let exp = exp.bind(py);
if !exp.getattr(intern!(py, "parameters"))?.is_truthy()? {
let as_py_float = exp.call_method0(intern!(py, "__float__"))?;
params.push(as_py_float.unbind());
continue;
}
}
params.push(p.into_py_any(py)?);
}
let qubits: Vec<BitType> = self
.qubits
.map_bits(node.instruction.qubits.bind(py).iter())?
.map(|bit| bit.0)
.collect();
let qubits = PyTuple::new(py, qubits)?;
let params = PyTuple::new(py, params)?;