-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathcircuit.rs
More file actions
1296 lines (1235 loc) · 43.3 KB
/
circuit.rs
File metadata and controls
1296 lines (1235 loc) · 43.3 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 2025
//
// 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::ffi::{CStr, CString, c_char};
use crate::exit_codes::ExitCode;
use crate::pointers::{const_ptr_as_ref, mut_ptr_as_ref};
use nalgebra::{Matrix2, Matrix4};
use ndarray::{Array2, ArrayView2};
use num_complex::{Complex64, ComplexFloat};
use qiskit_circuit::bit::{ClassicalRegister, QuantumRegister};
use qiskit_circuit::bit::{ShareableClbit, ShareableQubit};
use qiskit_circuit::circuit_data::CircuitData;
use qiskit_circuit::circuit_drawer::draw_circuit;
use qiskit_circuit::dag_circuit::DAGCircuit;
use qiskit_circuit::operations::{
ArrayType, DelayUnit, Operation, Param, StandardGate, StandardInstruction, UnitaryGate,
};
use qiskit_circuit::packed_instruction::PackedOperation;
use qiskit_circuit::{Clbit, Qubit};
#[cfg(feature = "python_binding")]
use pyo3::ffi::PyObject;
#[cfg(feature = "python_binding")]
use pyo3::types::PyAnyMethods;
#[cfg(feature = "python_binding")]
use pyo3::{Python, intern};
#[cfg(feature = "python_binding")]
use qiskit_circuit::imports::QUANTUM_CIRCUIT;
/// @ingroup QkCircuit
/// Construct a new circuit with the given number of qubits and clbits.
///
/// @param num_qubits The number of qubits the circuit contains.
/// @param num_clbits The number of clbits the circuit contains.
///
/// @return A pointer to the created circuit.
///
/// # Example
///
/// QkCircuit *empty = qk_circuit_new(100, 100);
///
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub extern "C" fn qk_circuit_new(num_qubits: u32, num_clbits: u32) -> *mut CircuitData {
let qubits = if num_qubits > 0 {
Some(
(0..num_qubits)
.map(|_| ShareableQubit::new_anonymous())
.collect::<Vec<_>>(),
)
} else {
None
};
let clbits = if num_clbits > 0 {
Some(
(0..num_clbits)
.map(|_| ShareableClbit::new_anonymous())
.collect::<Vec<_>>(),
)
} else {
None
};
let circuit = CircuitData::new(qubits, clbits, None, 0, (0.).into()).unwrap();
Box::into_raw(Box::new(circuit))
}
/// @ingroup QkQuantumRegister
/// Construct a new owning quantum register with a given number of qubits and name
///
/// @param num_qubits The number of qubits to create the register for
/// @param name The name string for the created register. The name must be comprised of
/// valid UTF-8 characters.
///
/// @return A pointer to the created register
///
/// # Example
/// ```c
/// QkQuantumRegister *qr = qk_quantum_register_new(5, "five_qubits");
/// ```
///
/// # Safety
///
/// The `name` parameter must be a pointer to memory that contains a valid
/// nul terminator at the end of the string. It also must be valid for reads of
/// bytes up to and including the nul terminator.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_quantum_register_new(
num_qubits: u32,
name: *const c_char,
) -> *mut QuantumRegister {
let name = unsafe {
CStr::from_ptr(name)
.to_str()
.expect("Invalid UTF-8 character")
.to_string()
};
// SAFETY: Per documentation the pointer for name is a valid CStr pointer
let reg = QuantumRegister::new_owning(name, num_qubits);
Box::into_raw(Box::new(reg))
}
/// @ingroup QkQuantumRegister
/// Free a quantum register.
///
/// @param reg A pointer to the register to free.
///
/// # Example
/// ```c
/// QkQuantumRegister *qr = qk_quantum_register_new(1024, "qreg");
/// qk_quantum_register_free(qr);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``reg`` is not either null or a valid pointer to a
/// ``QkQuantumRegister``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_quantum_register_free(reg: *mut QuantumRegister) {
if !reg.is_null() {
if !reg.is_aligned() {
panic!("Attempted to free a non-aligned pointer.")
}
// SAFETY: We have verified the pointer is non-null and aligned, so it should be
// readable by Box.
unsafe {
let _ = Box::from_raw(reg);
}
}
}
/// @ingroup QkClassicalRegister
/// Free a classical register.
///
/// @param reg A pointer to the register to free.
///
/// # Example
/// ```c
/// QkClassicalRegister *cr = qk_classical_register_new(1024, "creg");
/// qk_classical_register_free(cr);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``reg`` is not either null or a valid pointer to a
/// ``QkClassicalRegister``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_classical_register_free(reg: *mut ClassicalRegister) {
if !reg.is_null() {
if !reg.is_aligned() {
panic!("Attempted to free a non-aligned pointer.")
}
// SAFETY: We have verified the pointer is non-null and aligned, so it should be
// readable by Box.
unsafe {
let _ = Box::from_raw(reg);
}
}
}
/// @ingroup QkClassicalRegister
/// Construct a new owning classical register with a given number of clbits and name
///
/// @param num_clbits The number of clbits to create the register for
/// @param name The name string for the created register. The name must be comprised of
/// valid UTF-8 characters.
///
/// @return A pointer to the created register
///
/// # Example
/// ```c
/// QkClassicalRegister *cr = qk_classical_register_new(5, "five_qubits");
/// ```
///
/// # Safety
///
/// The `name` parameter must be a pointer to memory that contains a valid
/// nul terminator at the end of the string. It also must be valid for reads of
/// bytes up to and including the nul terminator.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_classical_register_new(
num_clbits: u32,
name: *const c_char,
) -> *mut ClassicalRegister {
// SAFETY: Per documentation the pointer for name is a valid CStr pointer
let name = unsafe {
CStr::from_ptr(name)
.to_str()
.expect("Invalid UTF-8 character")
.to_string()
};
let reg = ClassicalRegister::new_owning(name, num_clbits);
Box::into_raw(Box::new(reg))
}
/// @ingroup QkCircuit
/// Add a quantum register to a given quantum circuit
///
/// @param circuit A pointer to the circuit.
/// @param reg A pointer to the quantum register
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(0, 0);
/// QkQuantumRegister *qr = qk_quantum_register_new(1024, "my_little_register");
/// qk_circuit_add_quantum_register(qc, qr);
/// qk_quantum_register_free(qr);
/// qk_circuit_free(qc);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit`` and
/// if ``reg`` is not a valid, non-null pointer to a ``QkQuantumRegister``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_add_quantum_register(
circuit: *mut CircuitData,
reg: *const QuantumRegister,
) {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { mut_ptr_as_ref(circuit) };
let qreg = unsafe { const_ptr_as_ref(reg) };
circuit
.add_qreg(qreg.clone(), true)
.expect("Invalid register unable to be added to circuit");
}
/// @ingroup QkCircuit
/// Add a classical register to a given quantum circuit
///
/// @param circuit A pointer to the circuit.
/// @param reg A pointer to the classical register
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(0, 0);
/// QkClassicalRegister *cr = qk_classical_register_new(24, "my_big_register");
/// qk_circuit_add_classical_register(qc, cr);
/// qk_classical_register_free(cr);
/// qk_circuit_free(qc);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit`` and
/// if ``reg`` is not a valid, non-null pointer to a ``QkClassicalRegister``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_add_classical_register(
circuit: *mut CircuitData,
reg: *const ClassicalRegister,
) {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { mut_ptr_as_ref(circuit) };
let creg = unsafe { const_ptr_as_ref(reg) };
circuit
.add_creg(creg.clone(), true)
.expect("Invalid register unable to be added to circuit");
}
/// @ingroup QkCircuit
/// Create a copy of a ``QkCircuit``.
///
/// @param circuit A pointer to the circuit to copy.
///
/// @return A new pointer to a copy of the input ``circuit``.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 100);
/// QkCircuit *copy = qk_circuit_copy(qc);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_copy(circuit: *const CircuitData) -> *mut CircuitData {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { const_ptr_as_ref(circuit) };
Box::into_raw(Box::new(circuit.clone()))
}
/// @ingroup QkCircuit
/// Get the number of qubits the circuit contains.
///
/// @param circuit A pointer to the circuit.
///
/// @return The number of qubits the circuit is defined on.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 100);
/// uint32_t num_qubits = qk_circuit_num_qubits(qc); // num_qubits==100
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_num_qubits(circuit: *const CircuitData) -> u32 {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { const_ptr_as_ref(circuit) };
circuit.num_qubits() as u32
}
/// @ingroup QkCircuit
/// Get the number of clbits the circuit contains.
///
/// @param circuit A pointer to the circuit.
///
/// @return The number of qubits the circuit is defined on.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 50);
/// uint32_t num_clbits = qk_circuit_num_clbits(qc); // num_clbits==50
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_num_clbits(circuit: *const CircuitData) -> u32 {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { const_ptr_as_ref(circuit) };
circuit.num_clbits() as u32
}
/// @ingroup QkCircuit
/// Free the circuit.
///
/// @param circuit A pointer to the circuit to free.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 100);
/// qk_circuit_free(qc);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not either null or a valid pointer to a
/// ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_free(circuit: *mut CircuitData) {
if !circuit.is_null() {
if !circuit.is_aligned() {
panic!("Attempted to free a non-aligned pointer.")
}
// SAFETY: We have verified the pointer is non-null and aligned, so it should be
// readable by Box.
unsafe {
let _ = Box::from_raw(circuit);
}
}
}
/// @ingroup QkCircuit
/// Append a ``QkGate`` to the circuit.
///
/// @param circuit A pointer to the circuit to add the gate to.
/// @param gate The StandardGate to add to the circuit.
/// @param qubits The pointer to the array of ``uint32_t`` qubit indices to add the gate on. This
/// can be a null pointer if there are no qubits for ``gate`` (e.g. ``QkGate_GlobalPhase``).
/// @param params The pointer to the array of ``double`` values to use for the gate parameters.
/// This can be a null pointer if there are no parameters for ``gate`` (e.g. ``QkGate_H``).
///
/// @return An exit code.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 0);
/// uint32_t qubit[1] = {0};
/// qk_circuit_gate(qc, QkGate_H, qubit, NULL);
/// ```
///
/// # Safety
///
/// The ``qubits`` and ``params`` types are expected to be a pointer to an array of ``uint32_t``
/// and ``double`` respectively where the length is matching the expectations for the standard
/// gate. If the array is insufficiently long the behavior of this function is undefined as this
/// will read outside the bounds of the array. It can be a null pointer if there are no qubits
/// or params for a given gate. You can check ``qk_gate_num_qubits`` and ``qk_gate_num_params`` to
/// determine how many qubits and params are required for a given gate.
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_gate(
circuit: *mut CircuitData,
gate: StandardGate,
qubits: *const u32,
params: *const f64,
) -> ExitCode {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { mut_ptr_as_ref(circuit) };
// SAFETY: Per the documentation the qubits and params pointers are arrays of num_qubits()
// and num_params() elements respectively.
unsafe {
let qargs: &[Qubit] = match gate.num_qubits() {
0 => &[],
1 => &[Qubit(*qubits.wrapping_add(0))],
2 => &[
Qubit(*qubits.wrapping_add(0)),
Qubit(*qubits.wrapping_add(1)),
],
3 => &[
Qubit(*qubits.wrapping_add(0)),
Qubit(*qubits.wrapping_add(1)),
Qubit(*qubits.wrapping_add(2)),
],
4 => &[
Qubit(*qubits.wrapping_add(0)),
Qubit(*qubits.wrapping_add(1)),
Qubit(*qubits.wrapping_add(2)),
Qubit(*qubits.wrapping_add(3)),
],
// There are no ``QkGate``s > 4 qubits
_ => unreachable!(),
};
let params: &[Param] = match gate.num_params() {
0 => &[],
1 => &[(*params.wrapping_add(0)).into()],
2 => &[
(*params.wrapping_add(0)).into(),
(*params.wrapping_add(1)).into(),
],
3 => &[
(*params.wrapping_add(0)).into(),
(*params.wrapping_add(1)).into(),
(*params.wrapping_add(2)).into(),
],
4 => &[
(*params.wrapping_add(0)).into(),
(*params.wrapping_add(1)).into(),
(*params.wrapping_add(2)).into(),
(*params.wrapping_add(3)).into(),
],
// There are no ``QkGate``s that take > 4 params
_ => unreachable!(),
};
circuit.push_standard_gate(gate, params, qargs).unwrap()
}
ExitCode::Success
}
/// @ingroup QkCircuit
/// Get the number of qubits for a ``QkGate``.
///
/// @param gate The ``QkGate`` to get the number of qubits for.
///
/// @return The number of qubits the gate acts on.
///
/// # Example
/// ```c
/// uint32_t num_qubits = qk_gate_num_qubits(QkGate_CCX);
/// ```
///
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub extern "C" fn qk_gate_num_qubits(gate: StandardGate) -> u32 {
gate.num_qubits()
}
/// @ingroup QkCircuit
/// Get the number of parameters for a ``QkGate``.
///
/// @param gate The ``QkGate`` to get the number of qubits for.
///
/// @return The number of parameters the gate has.
///
/// # Example
/// ```c
/// uint32_t num_params = qk_gate_num_params(QkGate_R);
/// ```
///
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub extern "C" fn qk_gate_num_params(gate: StandardGate) -> u32 {
gate.num_params()
}
/// @ingroup QkCircuit
/// Append a measurement to the circuit
///
/// @param circuit A pointer to the circuit to add the measurement to
/// @param qubit The ``uint32_t`` for the qubit to measure
/// @param clbit The ``uint32_t`` for the clbit to store the measurement outcome in
///
/// @return An exit code.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 1);
/// qk_circuit_measure(qc, 0, 0);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_measure(
circuit: *mut CircuitData,
qubit: u32,
clbit: u32,
) -> ExitCode {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { mut_ptr_as_ref(circuit) };
circuit
.push_packed_operation(
PackedOperation::from_standard_instruction(StandardInstruction::Measure),
&[],
&[Qubit(qubit)],
&[Clbit(clbit)],
)
.unwrap();
ExitCode::Success
}
/// @ingroup QkCircuit
/// Append a reset to the circuit
///
/// @param circuit A pointer to the circuit to add the reset to
/// @param qubit The ``uint32_t`` for the qubit to reset
///
/// @return An exit code.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 0);
/// qk_circuit_reset(qc, 0);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_reset(circuit: *mut CircuitData, qubit: u32) -> ExitCode {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { mut_ptr_as_ref(circuit) };
circuit
.push_packed_operation(
PackedOperation::from_standard_instruction(StandardInstruction::Reset),
&[],
&[Qubit(qubit)],
&[],
)
.unwrap();
ExitCode::Success
}
/// @ingroup QkCircuit
/// Append a barrier to the circuit.
///
/// @param circuit A pointer to the circuit to add the barrier to.
/// @param num_qubits The number of qubits wide the barrier is.
/// @param qubits The pointer to the array of ``uint32_t`` qubit indices to add the barrier on.
///
/// @return An exit code.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 1);
/// uint32_t qubits[5] = {0, 1, 2, 3, 4};
/// qk_circuit_barrier(qc, qubits, 5);
/// ```
///
/// # Safety
///
/// The length of the array ``qubits`` points to must be ``num_qubits``. If there is
/// a mismatch the behavior is undefined.
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_barrier(
circuit: *mut CircuitData,
qubits: *const u32,
num_qubits: u32,
) -> ExitCode {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { mut_ptr_as_ref(circuit) };
// SAFETY: Per the documentation the qubits pointer is an array of num_qubits elements
let qubits: Vec<Qubit> = unsafe {
(0..num_qubits)
.map(|idx| Qubit(*qubits.wrapping_add(idx as usize)))
.collect()
};
circuit
.push_packed_operation(
PackedOperation::from_standard_instruction(StandardInstruction::Barrier(num_qubits)),
&[],
&qubits,
&[],
)
.unwrap();
ExitCode::Success
}
/// An individual operation count represented by the operation name
/// and the number of instances in the circuit.
#[repr(C)]
pub struct OpCount {
/// A nul terminated string representing the operation name
name: *const c_char,
/// The number of instances of this operation in the circuit
count: usize,
}
/// An array of ``OpCount`` objects representing the total counts of all
/// the operation types in a circuit.
#[repr(C)]
pub struct OpCounts {
/// A array of size ``len`` containing ``OpCount`` objects for each
/// type of operation in the circuit
data: *mut OpCount,
/// The number of elements in ``data``
len: usize,
}
#[inline]
fn conjugate(matrix: ArrayView2<Complex64>) -> Array2<Complex64> {
Array2::from_shape_fn((matrix.nrows(), matrix.ncols()), |(i, j)| {
matrix[(j, i)].conj()
})
}
/// Check an [ArrayType] represents a unitary matrix. Uses an element-wise check; if
/// any element in ``conjugate(matrix) * matrix`` differs from the identity by more than ``tol``
/// (in magnitude), the matrix is not considered unitary.
fn is_unitary(matrix: &ArrayType, tol: f64) -> bool {
let not_unitary = match matrix {
ArrayType::OneQ(mat) => (mat.adjoint() * mat - Matrix2::identity())
.iter()
.any(|val| val.abs() > tol),
ArrayType::TwoQ(mat) => (mat.adjoint() * mat - Matrix4::identity())
.iter()
.any(|val| val.abs() > tol),
ArrayType::NDArray(mat) => {
let product = mat.dot(&conjugate(mat.view()));
product.indexed_iter().any(|((row, col), value)| {
if row == col {
(value - Complex64::ONE).abs() > tol
} else {
value.abs() > tol
}
})
}
};
!not_unitary // using double negation to use ``any`` (faster) instead of ``all``
}
/// Create a unitary matrix `ArrayType` from a pointer to a row-major contiguous matrix of the
/// correct dimensions.
///
/// If `tol` is `Some`, the unitary matrix is checked for tolerance against the given value. If the
/// tolerance check fails, no array is returned.
///
/// The data is copied out of `matrix`.
///
/// # Safety
///
/// `matrix` must be aligned and valid for `4 ** num_qubits` reads.
pub(crate) unsafe fn unitary_from_pointer(
matrix: *const Complex64,
num_qubits: u32,
tol: Option<f64>,
) -> Option<ArrayType> {
let dim = 1 << num_qubits;
// SAFETY: per documentation, `matrix` is aligned and valid for `4**num_qubits` reads.
let raw = unsafe { ::std::slice::from_raw_parts(matrix, dim * dim) };
let mat = match num_qubits {
1 => ArrayType::OneQ(Matrix2::from_fn(|i, j| raw[i * dim + j])),
2 => ArrayType::TwoQ(Matrix4::from_fn(|i, j| raw[i * dim + j])),
_ => ArrayType::NDArray(Array2::from_shape_fn((dim, dim), |(i, j)| raw[i * dim + j])),
};
match tol {
Some(tol) => is_unitary(&mat, tol).then_some(mat),
None => Some(mat),
}
}
/// @ingroup QkCircuit
/// Append an arbitrary unitary matrix to the circuit.
///
/// @param circuit A pointer to the circuit to append the unitary to.
/// @param matrix A pointer to the ``QkComplex64`` array representing the unitary matrix.
/// This must be a row-major, unitary matrix of dimension ``2 ^ num_qubits x 2 ^ num_qubits``.
/// More explicitly: the ``(i, j)``-th element is given by ``matrix[i * 2^n + j]``.
/// The contents of ``matrix`` are copied inside this function before being added to the circuit,
/// so caller keeps ownership of the original memory that ``matrix`` points to and can reuse it
/// after the call and the caller is responsible for freeing it.
/// @param qubits A pointer to array of qubit indices, of length ``num_qubits``.
/// @param num_qubits The number of qubits the unitary acts on.
/// @param check_input When true, the function verifies that the matrix is unitary.
/// If set to False the caller is responsible for ensuring the matrix is unitary, if
/// the matrix is not unitary this is undefined behavior and will result in a corrupt
/// circuit.
///
/// @return An exit code.
///
/// # Example
/// ```c
/// QkComplex64 c0 = {0, 0}; // 0+0i
/// QkComplex64 c1 = {1, 0}; // 1+0i
///
/// const uint32_t num_qubits = 1;
/// QkComplex64 unitary[2*2] = {c0, c1, // row 0
/// c1, c0}; // row 1
///
/// QkCircuit *circuit = qk_circuit_new(1, 0); // 1 qubit circuit
/// uint32_t qubit[1] = {0}; // qubit to apply the unitary on
/// qk_circuit_unitary(circuit, unitary, qubit, num_qubits, true);
/// ```
///
/// # Safety
///
/// Behavior is undefined if any of the following is violated:
///
/// * ``circuit`` is a valid, non-null pointer to a ``QkCircuit``
/// * ``matrix`` is an aligned pointer to ``4**num_qubits`` initialized ``QkComplex64`` values
/// * ``qubits`` is an aligned pointer to ``num_qubits`` initialized ``uint32_t`` values
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_unitary(
circuit: *mut CircuitData,
matrix: *const Complex64,
qubits: *const u32,
num_qubits: u32,
check_input: bool,
) -> ExitCode {
// SAFETY: Caller quarantees pointer validation, alignment
let circuit = unsafe { mut_ptr_as_ref(circuit) };
let mat = unsafe { unitary_from_pointer(matrix, num_qubits, check_input.then_some(1e-12)) };
let Some(mat) = mat else {
return ExitCode::ExpectedUnitary;
};
let qubits = if num_qubits == 0 {
// This handles the case of C passing us a null pointer for the qubits; Rust slices
// can't be backed by the null pointer even when empty.
&[]
} else {
// SAFETY: per documentation, `qubits` is aligned and valid for `num_qubits` reads. Per
// previous check, `num_qubits` is nonzero so `qubits` cannot be null.
unsafe { ::std::slice::from_raw_parts(qubits as *const Qubit, num_qubits as usize) }
};
// Create PackedOperation -> push to circuit_data
let u_gate = Box::new(UnitaryGate { array: mat });
let op = PackedOperation::from_unitary(u_gate);
circuit.push_packed_operation(op, &[], qubits, &[]).unwrap();
// Return success
ExitCode::Success
}
/// @ingroup QkCircuit
/// Return a list of string names for instructions in a circuit and their counts.
///
/// To properly free the memory allocated by the struct, you should call ``qk_opcounts_clear``.
/// Dropping the ``QkOpCounts`` struct without doing so will leave the stored array of ``QkOpCount``
/// allocated and produce a memory leak.
///
/// @param circuit A pointer to the circuit to get the counts for.
///
/// @return An ``QkOpCounts`` struct containing the circuit operation counts.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 0);
/// uint32_t qubits[1] = {0};
/// qk_circuit_gate(qc, QkGate_H, qubits, NULL);
/// QkOpCounts counts = qk_circuit_count_ops(qc);
/// // .. once done
/// qk_opcounts_clear(&counts);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_count_ops(circuit: *const CircuitData) -> OpCounts {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { const_ptr_as_ref(circuit) };
let count_ops = circuit.count_ops();
let output = {
let vec: Vec<OpCount> = count_ops
.into_iter()
.map(|(name, count)| OpCount {
name: CString::new(name).unwrap().into_raw(),
count,
})
.collect();
vec.into_boxed_slice()
};
let len = output.len();
let data = Box::into_raw(output) as *mut OpCount;
OpCounts { data, len }
}
/// @ingroup QkCircuit
/// Return the total number of instructions in the circuit.
///
/// @param circuit A pointer to the circuit to get the total number of instructions for.
///
/// @return The total number of instructions in the circuit.
///
/// # Example
/// ```c
/// QkCircuit *qc = qk_circuit_new(100, 0);
/// uint32_t qubit[1] = {0};
/// qk_circuit_gate(qc, QkGate_H, qubit, NULL);
/// size_t num = qk_circuit_num_instructions(qc); // 1
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_num_instructions(circuit: *const CircuitData) -> usize {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { const_ptr_as_ref(circuit) };
circuit.__len__()
}
/// A circuit instruction representation.
///
/// This struct represents the data contained in an individual instruction in a ``QkCircuit``.
/// It is not a pointer to the underlying object, but contains a copy of the properties of the
/// instruction for inspection.
#[repr(C)]
pub struct CInstruction {
/// The instruction name
name: *mut c_char,
/// A pointer to an array of qubit indices this instruction operates on.
qubits: *mut u32,
/// A pointer to an array of clbit indices this instruction operates on.
clbits: *mut u32,
/// A pointer to an array of parameter values for this instruction.
params: *mut f64,
/// The number of qubits for this instruction.
num_qubits: u32,
/// The number of clbits for this instruction.
num_clbits: u32,
/// The number of parameters for this instruction.
num_params: u32,
}
/// @ingroup QkCircuit
/// Return the instruction details for an instruction in the circuit.
///
/// This function is used to get the instruction details for a given instruction in
/// the circuit.
///
/// This function allocates memory internally for the provided ``QkCircuitInstruction``
/// and thus you are responsible for calling ``qk_circuit_instruction_clear`` to
/// free it.
///
/// @param circuit A pointer to the circuit to get the instruction details for.
/// @param index The instruction index to get the instruction details of.
/// @param instruction A pointer to where to write out the ``QkCircuitInstruction``
///
///
/// # Example
/// ```c
/// QkCircuitInstruction inst;
/// QkCircuit *qc = qk_circuit_new(100, 0);
/// uint32_t qubit[1] = {0};
/// qk_circuit_gate(qc, QkGate_H, qubit, NULL);
/// qk_circuit_get_instruction(qc, 0, &inst);
/// qk_circuit_instruction_clear(&inst);
/// ```
///
/// # Safety
///
/// Behavior is undefined if ``circuit`` is not a valid, non-null pointer to a ``QkCircuit``. The
/// value for ``index`` must be less than the value returned by ``qk_circuit_num_instructions``
/// otherwise this function will panic. Behavior is undefined if ``instruction`` is not a valid,
/// non-null pointer to a memory allocation with sufficient space for a ``QkCircuitInstruction``.
#[unsafe(no_mangle)]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_circuit_get_instruction(
circuit: *const CircuitData,
index: usize,
instruction: *mut CInstruction,
) {
// SAFETY: Per documentation, the pointer is non-null and aligned.
let circuit = unsafe { const_ptr_as_ref(circuit) };
if index >= circuit.__len__() {
panic!("Invalid index")
}
let packed_inst = &circuit.data()[index];
let mut qargs = {
let qargs = circuit.get_qargs(packed_inst.qubits);
let qargs_vec: Vec<u32> = qargs.iter().map(|x| x.0).collect();
qargs_vec.into_boxed_slice()
};
let mut cargs = {
let cargs = circuit.get_cargs(packed_inst.clbits);
let cargs_vec: Vec<u32> = cargs.iter().map(|x| x.0).collect();
cargs_vec.into_boxed_slice()
};
let mut params = {
let params = packed_inst.params_view();
let params_vec: Vec<f64> = params
.iter()
.map(|x| match x {
Param::Float(val) => *val,
_ => panic!("Invalid parameter on instruction"),
})
.collect();
params_vec.into_boxed_slice()
};
// These lists (e.g. 'qargs') are Box<[T]>, so we use .as_mut_ptr()
// to get a mutable pointer to the underlying slice/array on
// the heap and Box::into_raw() to consume the Box without freeing
// it (so the underlying array doesn't get freed when we return)
let out_qargs = qargs.as_mut_ptr();
let out_qargs_len = qargs.len() as u32;
let _ = Box::into_raw(qargs);
let out_cargs = cargs.as_mut_ptr();
let out_cargs_len = cargs.len() as u32;
let _ = Box::into_raw(cargs);
let out_params = params.as_mut_ptr();
let out_params_len = params.len() as u32;
let _ = Box::into_raw(params);
// SAFETY: The pointer must point to a CInstruction size allocation
// per the docstring.
unsafe {
std::ptr::write(
instruction,
CInstruction {
name: CString::new(packed_inst.op.name()).unwrap().into_raw(),
num_qubits: out_qargs_len,
qubits: out_qargs,
num_clbits: out_cargs_len,
clbits: out_cargs,
num_params: out_params_len,
params: out_params,
},
);
}
}
/// @ingroup QkCircuit
/// Clear the data in circuit instruction object.
///
/// This function doesn't free the allocation for the provided ``QkCircuitInstruction`` pointer, it
/// only frees the internal allocations for the data contained in the instruction. You are
/// responsible for allocating and freeing the actual allocation used to store a
/// ``QkCircuitInstruction``.
///
/// @param inst A pointer to the instruction to free.
///
/// # Example
/// ```c
/// QkCircuitInstruction *inst = malloc(sizeof(QkCircuitInstruction));
/// QkCircuit *qc = qk_circuit_new(100, 0);
/// uint32_t q0[1] = {0};
/// qk_circuit_gate(qc, QkGate_H, q0, NULL);
/// qk_circuit_get_instruction(qc, 0, inst);
/// qk_circuit_instruction_clear(inst); // clear internal allocations
/// free(inst); // free struct
/// qk_circuit_free(qc); // free the circuit
/// ```
///
/// # Safety