-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathcircuit_data.rs
More file actions
3485 lines (3253 loc) · 137 KB
/
circuit_data.rs
File metadata and controls
3485 lines (3253 loc) · 137 KB
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 2023, 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 https://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::fmt::Debug;
use std::hash::Hash;
use std::ops::Deref;
#[cfg(feature = "cache_pygates")]
use std::sync::OnceLock;
use crate::bit::{
BitLocations, ClassicalRegister, PyBit, QuantumRegister, Register, ShareableClbit,
ShareableQubit,
};
use crate::bit_locator::BitLocator;
use crate::circuit_instruction::{CircuitInstruction, OperationFromPython};
use crate::classical::expr;
use crate::dag_circuit::{DAGCircuit, add_global_phase};
use crate::imports::{ANNOTATED_OPERATION, QUANTUM_CIRCUIT};
use crate::instruction::Parameters;
use crate::interner::{Interned, InternedMap, Interner};
use crate::object_registry::{self, ObjectRegistry};
use crate::operations::{
ControlFlow, ControlFlowView, Operation, OperationRef, Param, PauliBased, PyOperationTypes,
PythonOperation, StandardGate,
};
use crate::packed_instruction::{PackedInstruction, PackedOperation};
use crate::parameter::parameter_expression::{ParameterError, ParameterExpression};
use crate::parameter::symbol_expr::{Symbol, Value};
use crate::parameter_table::{ParameterTable, ParameterTableError, ParameterUse, ParameterUuid};
use crate::register_data::RegisterData;
use crate::var_stretch_container::{
StretchType, VarStretchContainer, VarStretchContainerError, VarType,
};
use crate::{
Block, BlocksMode, CapacityError, Clbit, ControlFlowBlocks, Qubit, Stretch, Var, VarsMode,
instruction,
};
use qiskit_util::py::{PySequenceIndex, SequenceIndex};
use ndarray::ArrayView1;
use num_complex::Complex64;
use numpy::PyReadonlyArray1;
use pyo3::IntoPyObjectExt;
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyDict, PyList, PySet, PyTuple, PyType};
use pyo3::{PyTraverseError, PyVisit, import_exception, intern};
use hashbrown::{HashMap, HashSet};
use indexmap::IndexMap;
use smallvec::SmallVec;
use thiserror::Error;
import_exception!(qiskit.circuit.exceptions, CircuitError);
/// This struct models the error conditions that can be raised from the
/// rust methods of the [CircuitData] struct. The goal is to explicitly
/// enumerate all the error types that are returned by these functions and
/// make it clear that the return type is part of the interface.
///
/// In the the future it is expected this single enum will be replaced by per
/// method error types to make it even more obvious, but this is a step
/// towards that as we migrate from Python -> Rust.
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum CircuitDataError {
#[error(transparent)]
Capacity(#[from] CapacityError),
#[error("invalid type for global phase")]
InvalidGlobalPhaseType,
#[error(transparent)]
AbsentObject(object_registry::AbsentObject),
#[error(transparent)]
AddObjectRegistry(object_registry::AddError),
// Explicitly an error returned from calling Python
#[error(transparent)]
ErrorFromPython(#[from] PyErr),
#[error(transparent)]
ParameterTableError(#[from] ParameterTableError),
#[error(transparent)]
VarStretchContainerError(#[from] VarStretchContainerError),
#[error(
"Mismatching number of values and parameters. For partial binding please pass a mapping of parameter to value pairs."
)]
ParameterSliceLenMismatch,
#[error(transparent)]
ParameterError(#[from] ParameterError),
#[error("Invalid Parameter")]
InvalidParameter,
#[error("bad type after binding for gate '{0}': '{1}'")]
StandardGateParameterIsComplex(String, String),
}
impl<T: Debug> From<object_registry::AbsentObject<T>> for CircuitDataError {
fn from(val: object_registry::AbsentObject<T>) -> Self {
Self::AbsentObject(val.erase_type())
}
}
impl<T: Debug, B: Debug> From<object_registry::AddError<T, B>> for CircuitDataError {
fn from(val: object_registry::AddError<T, B>) -> Self {
Self::AddObjectRegistry(val.erase_type())
}
}
impl From<CircuitDataError> for PyErr {
fn from(error: CircuitDataError) -> Self {
match error {
CircuitDataError::Capacity(c) => c.into(),
CircuitDataError::InvalidGlobalPhaseType => {
PyTypeError::new_err("invalid type for global phase")
}
CircuitDataError::AbsentObject(e) => e.into(),
CircuitDataError::AddObjectRegistry(e) => e.into(),
CircuitDataError::ErrorFromPython(e) => e,
CircuitDataError::ParameterTableError(e) => e.into(),
CircuitDataError::VarStretchContainerError(e) => CircuitError::new_err(e.to_string()),
CircuitDataError::ParameterSliceLenMismatch => PyValueError::new_err(
"Mismatching number of values and parameters. For partial binding please pass a mapping of {parameter: value} pairs.",
),
CircuitDataError::ParameterError(e) => e.into(),
CircuitDataError::InvalidParameter => {
PyValueError::new_err("An invalid parameter was provided.")
}
CircuitDataError::StandardGateParameterIsComplex(gate_name, expr) => {
CircuitError::new_err(format!(
"bad type after binding for gate '{gate_name}': '{expr}'"
))
}
}
}
}
/// A tuple of a `CircuitData`'s internal state used for pickle's `__setstate__()` method.
type CircuitDataState<'py> = (
Vec<QuantumRegister>,
Vec<ClassicalRegister>,
Bound<'py, PyDict>, // qubit location data
Bound<'py, PyDict>, // clbit location data
Vec<(String, Py<PyAny>)>, // vector of (variable name, var_stretch_container::IdentifierInfo object) pairs
Vec<expr::Var>,
Vec<expr::Stretch>,
);
/// The core data structure representing a quantum circuit's instruction sequence and metadata.
///
/// `CircuitData` is the internal Rust representation of a quantum circuit, storing the complete
/// state including instructions, quantum and classical bits, registers, variables, and parameters.
/// This struct is designed for efficient manipulation and traversal of circuit data from Rust code.
///
/// The data is stored in a packed format for memory efficiency, with interned bit arguments to
/// reduce duplication. Instructions are stored as [`PackedInstruction`] objects in a vector,
/// allowing for fast sequential access and modification.
///
/// # Fields
///
/// The struct contains:
/// - Instruction data and interned bit caches
/// - Quantum and classical bit registries
/// - Quantum and classical registers
/// - Control flow blocks for nested circuit structures
/// - Variable and stretch registries for dynamic circuits
/// - Parameter table for parameterized gates
/// - Global phase information
///
/// # Usage
///
/// This struct is primarily used internally by the circuit implementation and is wrapped by
/// [`PyCircuitData`] for Python interoperability. Direct manipulation should be done carefully
/// to maintain invariants around bit indices, parameter tracking, and register consistency.
#[derive(Clone, Debug)]
pub struct CircuitData {
/// The packed instruction listing.
data: Vec<PackedInstruction>,
/// The cache used to intern instruction bits.
qargs_interner: Interner<[Qubit]>,
/// The cache used to intern instruction bits.
cargs_interner: Interner<[Clbit]>,
/// Qubits registered in the circuit.
qubits: ObjectRegistry<Qubit, ShareableQubit>,
/// Clbits registered in the circuit.
clbits: ObjectRegistry<Clbit, ShareableClbit>,
/// Basic blocks registered in the circuit.
blocks: ControlFlowBlocks<CircuitData>,
/// QuantumRegisters stored in the circuit
qregs: RegisterData<QuantumRegister>,
/// ClassicalRegisters stored in the circuit
cregs: RegisterData<ClassicalRegister>,
/// Mapping between [ShareableQubit] and its locations in
/// the circuit
qubit_indices: BitLocator<ShareableQubit, QuantumRegister>,
/// Mapping between [ShareableClbit] and its locations in
/// the circuit
clbit_indices: BitLocator<ShareableClbit, ClassicalRegister>,
/// Variables and stretches registered in the circuit
vars_stretches: VarStretchContainer,
param_table: ParameterTable,
global_phase: Param,
}
/// A container for :class:`.QuantumCircuit` instruction listings that stores
/// :class:`.CircuitInstruction` instances in a packed form by interning
/// their :attr:`~.CircuitInstruction.qubits` and
/// :attr:`~.CircuitInstruction.clbits` to native vectors of indices.
///
/// Before adding a :class:`.CircuitInstruction` to this container, its
/// :class:`.Qubit` and :class:`.Clbit` instances MUST be registered via the
/// constructor or via :meth:`.CircuitData.add_qubit` and
/// :meth:`.CircuitData.add_clbit`. This is because the order in which
/// bits of the same type are added to the container determines their
/// associated indices used for storage and retrieval.
///
/// Once constructed, this container behaves like a Python list of
/// :class:`.CircuitInstruction` instances. However, these instances are
/// created and destroyed on the fly, and thus should be treated as ephemeral.
///
/// For example,
///
/// .. plot::
/// :include-source:
/// :no-figs:
///
/// qubits = [Qubit()]
/// data = CircuitData(qubits)
/// data.append(CircuitInstruction(XGate(), (qubits[0],), ()))
/// assert(data[0] == data[0]) # => Ok.
/// assert(data[0] is data[0]) # => PANICS!
///
/// .. warning::
///
/// This is an internal interface and no part of it should be relied upon
/// outside of Qiskit.
///
/// Args:
/// qubits (Iterable[:class:`.Qubit`] | None): The initial sequence of
/// qubits, used to map :class:`.Qubit` instances to and from its
/// indices.
/// clbits (Iterable[:class:`.Clbit`] | None): The initial sequence of
/// clbits, used to map :class:`.Clbit` instances to and from its
/// indices.
/// data (Iterable[:class:`.CircuitInstruction`]): An initial instruction
/// listing to add to this container. All bits appearing in the
/// instructions in this iterable must also exist in ``qubits`` and
/// ``clbits``.
/// reserve (int): The container's initial capacity. This is reserved
/// before copying instructions into the container when ``data``
/// is provided, so the initialized container's unused capacity will
/// be ``max(0, reserve - len(data))``.
///
/// Raises:
/// KeyError: if ``data`` contains a reference to a bit that is not present
/// in ``qubits`` or ``clbits``.
#[pyclass(
name = "CircuitData",
sequence,
module = "qiskit._accelerate.circuit",
skip_from_py_object
)]
#[derive(Clone, Debug)]
pub struct PyCircuitData {
pub inner: CircuitData,
}
impl From<CircuitData> for PyCircuitData {
fn from(data: CircuitData) -> Self {
PyCircuitData { inner: data }
}
}
impl From<PyCircuitData> for CircuitData {
fn from(data: PyCircuitData) -> Self {
data.inner
}
}
impl Deref for PyCircuitData {
type Target = CircuitData;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl CircuitData {
pub fn new(
qubits: Option<Vec<ShareableQubit>>,
clbits: Option<Vec<ShareableClbit>>,
global_phase: Param,
) -> Result<Self, CircuitDataError> {
let qubit_size = qubits.as_ref().map_or(0, |bits| bits.len());
let clbit_size = clbits.as_ref().map_or(0, |bits| bits.len());
let qubits_registry = ObjectRegistry::with_capacity(qubit_size);
let clbits_registry = ObjectRegistry::with_capacity(clbit_size);
let qubit_indices = BitLocator::with_capacity(qubit_size);
let clbit_indices = BitLocator::with_capacity(clbit_size);
let mut self_ = CircuitData {
data: Vec::new(),
qargs_interner: Interner::new(),
cargs_interner: Interner::new(),
qubits: qubits_registry,
clbits: clbits_registry,
blocks: ControlFlowBlocks::new(),
param_table: ParameterTable::new(),
global_phase: Param::Float(0.),
qregs: RegisterData::new(),
cregs: RegisterData::new(),
qubit_indices,
clbit_indices,
vars_stretches: VarStretchContainer::new(),
};
self_.set_global_phase_param(global_phase)?;
if let Some(qubits) = qubits {
for bit in qubits.into_iter() {
self_.add_qubit(bit, true)?;
}
}
if let Some(clbits) = clbits {
for bit in clbits.into_iter() {
self_.add_clbit(bit, true)?;
}
}
Ok(self_)
}
pub fn add_qubit(
&mut self,
bit: ShareableQubit,
strict: bool,
) -> Result<Qubit, CircuitDataError> {
let index = if strict {
self.qubits.add(bit.clone())?
} else {
self.qubits.add_allow_existing(bit.clone())?
};
self.qubit_indices
.insert(bit, BitLocations::new(index.0, []));
Ok(index)
}
pub fn add_clbit(
&mut self,
bit: ShareableClbit,
strict: bool,
) -> Result<Clbit, CircuitDataError> {
let index = if strict {
self.clbits.add(bit.clone())?
} else {
self.clbits.add_allow_existing(bit.clone())?
};
self.clbit_indices
.insert(bit, BitLocations::new(index.0, []));
Ok(index)
}
#[inline]
pub fn blocks(&self) -> &ControlFlowBlocks<CircuitData> {
&self.blocks
}
/// Return the number of qubits. This is equivalent to the length of the list returned by
/// :meth:`.CircuitData.qubits`
///
/// Returns:
/// int: The number of qubits.
pub fn num_qubits(&self) -> usize {
self.qubits.len()
}
/// Return the number of clbits. This is equivalent to the length of the list returned by
/// :meth:`.CircuitData.clbits`.
///
/// Returns:
/// int: The number of clbits.
pub fn num_clbits(&self) -> usize {
self.clbits.len()
}
/// Return the number of unbound compile-time symbolic parameters tracked by the circuit.
pub fn num_parameters(&self) -> usize {
self.param_table.num_parameters()
}
/// Return the width of the circuit. This is the number of qubits plus the
/// number of clbits.
///
/// Returns:
/// int: The width of the circuit.
pub fn width(&self) -> usize {
self.num_qubits() + self.num_clbits()
}
/// Registers a :class:`.QuantumRegister` instance.
///
/// Args:
/// bit (:class:`.QuantumRegister`): The register to add.
pub fn add_qreg(&mut self, register: QuantumRegister, strict: bool) -> PyResult<()> {
self.qregs.add_register(register.clone(), strict)?;
for (index, bit) in register.bits().enumerate() {
if let Some(entry) = self.qubit_indices.get_mut(&bit) {
entry.add_register(register.clone(), index);
} else if let Some(bit_idx) = self.qubits.find(&bit) {
self.qubit_indices.insert(
bit,
BitLocations::new(bit_idx.0, [(register.clone(), index)]),
);
} else {
let bit_idx = self.qubits.len();
self.add_qubit(bit.clone(), true)?;
self.qubit_indices.insert(
bit,
BitLocations::new(
bit_idx.try_into().map_err(|_| {
CircuitError::new_err(format!(
"Qubit at index {bit_idx} exceeds circuit capacity."
))
})?,
[(register.clone(), index)],
),
);
}
}
Ok(())
}
/// Registers a :class:`.ClassicalRegister` instance.
///
/// Args:
/// bit (:class:`.ClassicalRegister`): The register to add.
pub fn add_creg(&mut self, register: ClassicalRegister, strict: bool) -> PyResult<()> {
self.cregs.add_register(register.clone(), strict)?;
for (index, bit) in register.bits().enumerate() {
if let Some(entry) = self.clbit_indices.get_mut(&bit) {
entry.add_register(register.clone(), index);
} else if let Some(bit_idx) = self.clbits.find(&bit) {
self.clbit_indices.insert(
bit,
BitLocations::new(bit_idx.0, [(register.clone(), index)]),
);
} else {
let bit_idx = self.clbits.len();
self.add_clbit(bit.clone(), true)?;
self.clbit_indices.insert(
bit,
BitLocations::new(
bit_idx.try_into().map_err(|_| {
CircuitError::new_err(format!(
"Clbit at index {bit_idx} exceeds circuit capacity."
))
})?,
[(register.clone(), index)],
),
);
}
}
Ok(())
}
/// Reserves capacity for at least ``additional`` more
/// :class:`.CircuitInstruction` instances to be added to this container.
///
/// Args:
/// additional (int): The additional capacity to reserve. If the
/// capacity is already sufficient, does nothing.
pub fn reserve(&mut self, additional: usize) {
self.data.reserve(additional);
}
/// Move this [CircuitData] into a complete Python `QuantumCircuit` object.
pub fn into_py_quantum_circuit(self, py: Python) -> PyResult<Bound<PyAny>> {
let py_circuit_data: PyCircuitData = self.into();
py_circuit_data.into_py_quantum_circuit(py)
}
/// Gives the circuit ownership of the provided basic block and returns a
/// unique identifier that can be used to retrieve a reference to it
/// later.
///
/// No attempt is made to deduplicate the given block.
/// No validation is performed to ensure that the given block is valid
/// within the circuit.
pub fn add_block(&mut self, block: CircuitData) -> Block {
self.blocks.push(block)
}
/// Take the blocks from an extraction from an `OperationFromPython<CircuitData>` and add them
/// to this circuit.
///
/// Returns the parameters in terms of block references.
fn take_parameter_blocks(
&mut self,
params: Option<Parameters<CircuitData>>,
) -> Option<Box<Parameters<Block>>> {
params.map(|params| Box::new(params.map_blocks(|block| self.add_block(block))))
}
/// Extract the blocks from a Python-space `CircuitInstruction` and add them to this circuit.
///
/// The inverse of this is [unpack_blocks_to_circuit_parameters]. The version for when you can
/// take the blocks directly is [take_parameter_blocks].
pub fn extract_blocks_from_circuit_parameters(
&mut self,
params: Option<&Parameters<CircuitData>>,
) -> Option<Box<Parameters<Block>>> {
params.map(|params| Box::new(params.map_blocks_ref(|block| self.add_block(block.clone()))))
}
/// Given a `params` object from an instruction packed into this circuit, extract any relevant
/// blocks into the owned-object `CircuitData` block type, suitable for passing back to Python
/// space.
///
/// The inverse of this method is [extract_blocks_from_circuit_parameters].
pub fn unpack_blocks_to_circuit_parameters(
&self,
params: Option<&Parameters<Block>>,
) -> Option<Parameters<CircuitData>> {
params.map(|params| params.map_blocks_ref(|block| self.blocks[*block].clone()))
}
/// Gets an immutable view of a control flow operation.
///
/// Panics or produces incorrect results if `instr` is not from this circuit (or compatible with
/// it, e.g. from a mapped [ControlFlowBlocks]).
pub fn try_view_control_flow<'a>(
&'a self,
instr: &'a PackedInstruction,
) -> Option<ControlFlowView<'a, CircuitData>> {
ControlFlowView::try_from_instruction(instr, &self.blocks)
}
pub fn copy_empty_like(
&self,
vars_mode: VarsMode,
blocks_mode: BlocksMode,
) -> Result<Self, CircuitDataError> {
let mut res = CircuitData::new(
Some(self.qubits.objects().clone()),
Some(self.clbits.objects().clone()),
self.global_phase.clone(),
)?;
res.qargs_interner = self.qargs_interner.clone();
res.cargs_interner = self.cargs_interner.clone();
if blocks_mode == BlocksMode::Keep && !self.blocks.is_empty() {
res.blocks = self.blocks.map_without_references(|block| block.clone());
}
// After initialization, copy register info.
res.qregs = self.qregs.clone();
res.cregs = self.cregs.clone();
res.qubit_indices = self.qubit_indices.clone();
res.clbit_indices = self.clbit_indices.clone();
match vars_mode {
VarsMode::Alike => {
res.vars_stretches = self.vars_stretches.clone();
}
VarsMode::Captures => {
res.vars_stretches = self.vars_stretches.clone_as_captures();
}
VarsMode::Drop => {}
};
Ok(res)
}
/// An alternate constructor to build a new `CircuitData` from an iterator
/// of packed operations. This can be used to build a circuit from a sequence
/// of `PackedOperation` without needing to involve Python.
///
/// This can be connected with the Python space
/// QuantumCircuit.from_circuit_data() constructor to build a full
/// QuantumCircuit from Rust.
///
/// This constructor does not support control flow operations and will panic
/// if they are provided. If you need this, you should construct an empty
/// circuit, register any basic blocks explicitly, and then append control flow
/// operations.
///
/// # Arguments
///
/// * num_qubits: The number of qubits in the circuit.
/// * num_clbits: The number of classical bits in the circuit.
/// * instructions: An iterator of the (packed operation, params, qubits, clbits) to
/// add to the circuit
/// * global_phase: The global phase to use for the circuit
pub fn from_packed_operations<I>(
num_qubits: u32,
num_clbits: u32,
instructions: I,
global_phase: Param,
) -> Result<Self, CircuitDataError>
where
I: IntoIterator<
Item = Result<
(
PackedOperation,
SmallVec<[Param; 3]>,
Vec<Qubit>,
Vec<Clbit>,
),
CircuitDataError,
>,
>,
{
let instruction_iter = instructions.into_iter();
let mut res = Self::with_capacity(
num_qubits,
num_clbits,
instruction_iter.size_hint().0,
global_phase,
)?;
for item in instruction_iter {
let (operation, params, qargs, cargs) = item?;
let qubits = res.qargs_interner.insert_owned(qargs);
let clbits = res.cargs_interner.insert_owned(cargs);
let params = (!params.is_empty()).then(|| Box::new(Parameters::Params(params)));
res.push(PackedInstruction {
op: operation,
qubits,
clbits,
params,
label: None,
#[cfg(feature = "cache_pygates")]
py_op: OnceLock::new(),
})?;
}
Ok(res)
}
/// Clone a new [CircuitData] from a [DAGCircuit].
///
/// This is the logical equivalent of Python's `dag_to_circuit`.
pub fn from_dag_ref(dag: &DAGCircuit) -> Result<Self, CircuitDataError> {
let mut out = Self::empty_like_from_dag(dag)?;
out.data.reserve(dag.num_ops());
for node in dag.topological_op_nodes(false) {
out.push(dag[node].unwrap_operation().clone())?;
}
Ok(out)
}
fn empty_like_from_dag(dag: &DAGCircuit) -> Result<Self, CircuitDataError> {
let mut out = Self {
data: Vec::new(),
qargs_interner: dag.qargs_interner().clone(),
cargs_interner: dag.cargs_interner().clone(),
qubits: dag.qubits().clone(),
clbits: dag.clbits().clone(),
blocks: dag
.blocks()
.try_map_without_references(Self::from_dag_ref)?,
qregs: dag.qregs_data().clone(),
cregs: dag.cregs_data().clone(),
qubit_indices: dag.qubit_locations().clone(),
clbit_indices: dag.clbit_locations().clone(),
vars_stretches: dag.vars_stretches_view().clone(),
param_table: ParameterTable::new(),
global_phase: Param::Float(0.0),
};
out.set_global_phase_param(dag.global_phase().clone())?;
Ok(out)
}
/// An alternate constructor to build a new `CircuitData` from an iterator
/// of standard gates. This can be used to build a circuit from a sequence
/// of standard gates, such as for a `StandardGate` definition or circuit
/// synthesis without needing to involve Python.
///
/// This can be connected with the Python space
/// QuantumCircuit.from_circuit_data() constructor to build a full
/// QuantumCircuit from Rust.
///
/// # Arguments
///
/// * num_qubits: The number of qubits in the circuit. These will be created
/// in Python as loose bits without a register.
/// * instructions: An iterator of the standard gate params and qubits to
/// add to the circuit
/// * global_phase: The global phase to use for the circuit
pub fn from_standard_gates<I>(
num_qubits: u32,
instructions: I,
global_phase: Param,
) -> Result<Self, CircuitDataError>
where
I: IntoIterator<Item = (StandardGate, SmallVec<[Param; 3]>, SmallVec<[Qubit; 2]>)>,
{
let instruction_iter = instructions.into_iter();
let mut res =
Self::with_capacity(num_qubits, 0, instruction_iter.size_hint().0, global_phase)?;
for (operation, params, qargs) in instruction_iter {
let qubits = res.qargs_interner.insert(&qargs);
let params = (!params.is_empty()).then(|| Box::new(params));
res.push(PackedInstruction::from_standard_gate(
operation, params, qubits,
))?;
}
Ok(res)
}
/// Build an empty CircuitData object with an initially allocated instruction capacity
pub fn with_capacity(
num_qubits: u32,
num_clbits: u32,
instruction_capacity: usize,
global_phase: Param,
) -> Result<Self, CircuitDataError> {
let mut res = CircuitData {
data: Vec::with_capacity(instruction_capacity),
qargs_interner: Interner::new(),
cargs_interner: Interner::new(),
qubits: ObjectRegistry::with_capacity(num_qubits as usize),
clbits: ObjectRegistry::with_capacity(num_clbits as usize),
blocks: ControlFlowBlocks::new(),
param_table: ParameterTable::new(),
global_phase: Param::Float(0.0),
qregs: RegisterData::new(),
cregs: RegisterData::new(),
qubit_indices: BitLocator::with_capacity(num_qubits as usize),
clbit_indices: BitLocator::with_capacity(num_clbits as usize),
vars_stretches: VarStretchContainer::new(),
};
// use the global phase setter to ensure parameters are registered
// in the parameter table
res.set_global_phase_param(global_phase)?;
if num_qubits > 0 {
for _i in 0..num_qubits {
let bit = ShareableQubit::new_anonymous();
res.add_qubit(bit, true)?;
}
}
if num_clbits > 0 {
for _i in 0..num_clbits {
let bit = ShareableClbit::new_anonymous();
res.add_clbit(bit, true)?;
}
}
Ok(res)
}
/// Modify `self` to mark its qubits as physical.
///
/// This deletes the information about the virtual registers, and replaces it with the single
/// (implicitly) physical register. This method does not need to traverse the circuit.
///
/// The qubit indices all stay the same; effectively, this is the application of the "trivial"
/// layout. If the incoming circuit is supposed to be considered physical, this method can be
/// used to ensure it is in the canonical physical form.
///
/// # Panics
///
/// If `num_qubits` is less than the number of qubits in the circuit already.
pub fn make_physical(&mut self, num_qubits: u32) {
// If this method needs updating, `DAGCircuit::make_physical` probably does too.
assert!(
num_qubits as usize >= self.num_qubits(),
"number of qubits {num_qubits} too small for circuit"
);
// The strategy here is just to modify the qubit and quantum register objects entirely
// inplace; we maintain all relative indices, so we don't need to modify any interner keys.
let register = QuantumRegister::new_owning("q", num_qubits);
let mut registry = ObjectRegistry::with_capacity(num_qubits as usize);
let mut locator = BitLocator::with_capacity(num_qubits as usize);
for (index, bit) in register.iter().enumerate() {
registry.add_unique_within_capacity(bit.clone());
locator.insert(
bit,
BitLocations::new(index as u32, [(register.clone(), index)]),
);
}
let mut register_data = RegisterData::with_capacity(1);
register_data
.add_register(register, false)
.expect("infallible when 'strict=false'");
self.qubits = registry;
self.qregs = register_data;
self.qubit_indices = locator;
}
/// Append a standard gate to this CircuitData
pub fn push_standard_gate(
&mut self,
operation: StandardGate,
params: &[Param],
qargs: &[Qubit],
) -> Result<(), CircuitDataError> {
let params = (!params.is_empty()).then(|| Box::new(params.iter().cloned().collect()));
let qubits = self.qargs_interner.insert(qargs);
self.push(PackedInstruction::from_standard_gate(
operation, params, qubits,
))
}
/// Append a packed operation to this CircuitData.
///
/// If a [ControlFlow] operation is provided, the blocks given in
/// `params` must already be registered with the circuit.
pub fn push_packed_operation(
&mut self,
operation: PackedOperation,
params: Option<Parameters<Block>>,
qargs: &[Qubit],
cargs: &[Clbit],
) -> Result<(), CircuitDataError> {
let qubits = self.qargs_interner.insert(qargs);
let clbits = self.cargs_interner.insert(cargs);
self.push(PackedInstruction {
op: operation,
qubits,
clbits,
params: params.map(Box::new),
label: None,
#[cfg(feature = "cache_pygates")]
py_op: OnceLock::new(),
})
}
pub fn set_global_phase_f64(&mut self, phase: f64) {
self.clear_global_phase();
self.global_phase = Param::Float(phase.rem_euclid(::std::f64::consts::TAU));
}
/// Reset the global phase of the circuit to zero, updating any parameter tracking.
fn clear_global_phase(&mut self) {
let old = ::std::mem::replace(&mut self.global_phase, Param::Float(0.0));
let Param::ParameterExpression(expr) = old else {
return;
};
for symbol in expr.iter_symbols() {
match self.param_table.remove_use(
ParameterUuid::from_symbol(symbol),
ParameterUse::GlobalPhase,
) {
Ok(_)
| Err(ParameterTableError::ParameterNotTracked(_))
| Err(ParameterTableError::UsageNotTracked(_))
| Err(ParameterTableError::NameConflict(_)) => (),
// Any errors added later might want propagating.
}
}
}
#[inline]
fn track_instruction_blocks(&mut self, index: usize) {
self.data[index]
.blocks_view()
.iter()
.for_each(|block| self.blocks.increment(*block))
}
#[inline]
fn untrack_instruction_blocks(&mut self, index: usize) {
self.data[index]
.blocks_view()
.iter()
.for_each(|block| _ = self.blocks.decrement(*block))
}
/// Add the entries from the `PackedInstruction` at the given index to the internal parameter
/// table.
fn track_instruction_parameters(
&mut self,
instruction_index: usize,
) -> Result<(), CircuitDataError> {
let instr = &self.data[instruction_index];
let Some(parameters) = self.data[instruction_index].params.as_deref() else {
return Ok(());
};
match parameters {
Parameters::Params(params) => {
for (index, param) in params.iter().enumerate() {
if matches!(param, Param::Float(_)) {
continue;
}
let usage = ParameterUse::Index {
instruction: instruction_index,
parameter: index as u32,
};
for symbol in param.iter_parameters()? {
self.param_table.track(&symbol, Some(usage))?;
}
}
}
Parameters::Blocks(_) => {
let view = ControlFlowView::try_from_instruction(instr, &self.blocks)
.expect("all instructions with blocks should be control flow");
for_each_symbol_use_in_control_flow(instruction_index, view, |symbol, usage| {
self.param_table.track(symbol, Some(usage))?;
Ok(())
})?
}
}
Ok(())
}
/// Remove the entries from the `PackedInstruction` at the given index from the internal
/// parameter table.
fn untrack_instruction_parameters(
&mut self,
instruction_index: usize,
) -> Result<(), CircuitDataError> {
let instr = &self.data[instruction_index];
let Some(parameters) = self.data[instruction_index].params.as_deref() else {
return Ok(());
};
match parameters {
Parameters::Params(params) => {
for (index, param) in params.iter().enumerate() {
if matches!(param, Param::Float(_)) {
continue;
}
let usage = ParameterUse::Index {
instruction: instruction_index,
parameter: index as u32,
};
for symbol in param.iter_parameters()? {
self.param_table.untrack(&symbol, usage)?;
}
}
}
Parameters::Blocks(_) => {
let view = ControlFlowView::try_from_instruction(instr, &self.blocks)
.expect("all instructions with blocks should be control flow");
for_each_symbol_use_in_control_flow(instruction_index, view, |symbol, usage| {
self.param_table.untrack(symbol, usage)?;
Ok(())
})?
}
}
Ok(())
}
/// Retrack the entire `ParameterTable`.
///
/// This is necessary each time an insertion or removal occurs on `self.data` other than in the
/// last position.
fn reindex_parameter_table(&mut self) -> Result<(), CircuitDataError> {
self.param_table.clear();
for inst_index in 0..self.len() {
self.track_instruction_parameters(inst_index)?;
}
if matches!(self.global_phase, Param::Float(_)) {
return Ok(());
}
for symbol in self.global_phase.iter_parameters()? {
self.param_table
.track(&symbol, Some(ParameterUse::GlobalPhase))?;
}
Ok(())
}
/// Native internal driver of `__delitem__` that uses a Rust-space version of the
/// `SequenceIndex`. This assumes that the `SequenceIndex` contains only in-bounds indices, and
/// panics if not.
fn delitem(&mut self, indices: SequenceIndex) -> Result<(), CircuitDataError> {
// We need to delete in reverse order so we don't invalidate higher indices with a deletion.
for index in indices.descending() {
self.untrack_instruction_blocks(index);
self.data.remove(index);
}
if !indices.is_empty() {
self.reindex_parameter_table()?;
}
Ok(())
}
pub fn pack(&mut self, py: Python, inst: &CircuitInstruction) -> PyResult<PackedInstruction> {
let qubits = self.qargs_interner.insert_owned(
self.qubits
.map_objects(inst.qubits.extract::<Vec<ShareableQubit>>(py)?)?
.collect(),
);
let clbits = self.cargs_interner.insert_owned(
self.clbits
.map_objects(inst.clbits.extract::<Vec<ShareableClbit>>(py)?)?
.collect(),
);
let params = self.extract_blocks_from_circuit_parameters(inst.params.as_ref());
Ok(PackedInstruction {
op: inst.operation.clone(),
qubits,
clbits,
params,