Repository navigation
Expand file tree
/
Copy pathalgorithms.rs
More file actions
1707 lines (1617 loc) · 69 KB
/
Copy pathalgorithms.rs
File metadata and controls
1707 lines (1617 loc) · 69 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
//! Quantum algorithms on the state-vector simulator.
//!
//! What the speedups have in common is not "trying every answer at once".
//! A superposition over `2^n` inputs is easy; the difficulty is that
//! measurement returns one of them at random, so the exponential is useless
//! by itself. Every algorithm here earns its advantage by arranging
//! *interference* -- amplitudes for wrong answers cancelling while the right
//! one adds -- and the structure being exploited differs each time: a global
//! property of a function for Deutsch-Jozsa, a hidden period for Shor, and
//! nothing at all for Grover, which is why Grover's speedup is only
//! quadratic and provably cannot be more.
//!
//! Oracles are given as ordinary Rust closures and applied directly to the
//! amplitudes. That is exactly what a black box means: the algorithm is
//! charged for each query and never sees inside.
use crate::error::GeomError;
use crate::fractals::Complex;
use crate::monte_carlo::Rng;
use crate::quantum::circuit::{Circuit, Gate, QState};
const ZERO: Complex = Complex { re: 0.0, im: 0.0 };
fn scale(z: Complex, k: f64) -> Complex {
Complex::new(z.re * k, z.im * k)
}
fn cis(theta: f64) -> Complex {
Complex::new(theta.cos(), theta.sin())
}
// ---------------------------------------------------------------------------
// The quantum Fourier transform
// ---------------------------------------------------------------------------
/// The quantum Fourier transform on `n` qubits.
///
/// `O(n^2)` gates against the `O(n 2^n)` of the classical fast transform on
/// the same many amplitudes -- an exponential saving that is nonetheless not
/// directly useful, because the output is a superposition whose amplitudes
/// cannot be read out. What it is good for is exposing a *period*, which is
/// how Shor's algorithm uses it and why the QFT never appears alone.
///
/// The controlled rotations shrink as `pi / 2^k`, so the far ones are almost
/// the identity; dropping them is the standard approximate QFT and costs
/// remarkably little.
///
/// # Errors
/// Returns an error for a bad qubit count.
pub fn qft_circuit(n: usize) -> Result<Circuit, GeomError> {
let mut circuit = Circuit::new(n)?;
for j in (0..n).rev() {
circuit.h(j);
for k in 0..j {
circuit.cphase(k, j, std::f64::consts::PI / (1u64 << (j - k)) as f64);
}
}
// The transform leaves the qubits in reverse order.
for q in 0..n / 2 {
circuit.swap(q, n - 1 - q);
}
Ok(circuit)
}
/// The inverse quantum Fourier transform.
///
/// # Errors
/// Returns an error for a bad qubit count.
pub fn iqft(n: usize) -> Result<Circuit, GeomError> {
Ok(qft_circuit(n)?.inverse())
}
/// The largest discrepancy between the QFT circuit and the discrete Fourier
/// transform it is supposed to implement.
///
/// # Errors
/// Returns an error for a bad qubit count or if the circuit cannot run.
pub fn qft_check_vs_fft(n: usize) -> Result<f64, GeomError> {
let circuit = qft_circuit(n)?;
let size = 1usize << n;
let scale_factor = 1.0 / (size as f64).sqrt();
let mut worst: f64 = 0.0;
for x in 0..size {
let out = circuit.run(&QState::basis(n, x as u64)?)?;
for (y, amplitude) in out.amps.iter().enumerate() {
let angle = 2.0 * std::f64::consts::PI * (x * y % size) as f64 / size as f64;
let expected = scale(cis(angle), scale_factor);
worst = worst
.max((amplitude.re - expected.re).abs())
.max((amplitude.im - expected.im).abs());
}
}
Ok(worst)
}
// ---------------------------------------------------------------------------
// Query algorithms
// ---------------------------------------------------------------------------
/// Deutsch-Jozsa: decides whether a promised function is constant or
/// balanced in a single query.
///
/// Returns true for constant. The classical worst case needs `2^(n-1) + 1`
/// queries, and the quantum algorithm needs exactly one -- the largest
/// separation there is, though it depends entirely on the promise. Without
/// it the problem is no easier quantumly.
///
/// # Errors
/// Returns an error for a bad qubit count.
pub fn deutsch_jozsa(f: &dyn Fn(u64) -> bool, n: usize) -> Result<bool, GeomError> {
let mut state = QState::plus_all(n)?;
// The phase oracle: |x> -> (-1)^f(x) |x>, which is what the usual
// ancilla-in-|-> construction amounts to.
for (index, amplitude) in state.amps.iter_mut().enumerate() {
if f(index as u64) {
*amplitude = scale(*amplitude, -1.0);
}
}
for q in 0..n {
state.apply_single(q, &Gate::h())?;
}
// All the amplitude returns to |0...0> exactly when f is constant.
Ok(state.probability(0) > 0.5)
}
/// Bernstein-Vazirani: recovers a hidden bit string from one query to
/// `f(x) = s . x mod 2`.
///
/// Classically it takes `n` queries, one per bit. The quantum algorithm gets
/// the whole string at once because the Hadamard transform maps the phase
/// pattern `(-1)^(s . x)` onto the single basis state `|s>` -- interference
/// doing in one step what `n` separate questions do classically.
///
/// # Errors
/// Returns an error for a bad qubit count.
pub fn bernstein_vazirani(secret: u64, n: usize) -> Result<u64, GeomError> {
let mut state = QState::plus_all(n)?;
for (index, amplitude) in state.amps.iter_mut().enumerate() {
if (index as u64 & secret).count_ones() % 2 == 1 {
*amplitude = scale(*amplitude, -1.0);
}
}
for q in 0..n {
state.apply_single(q, &Gate::h())?;
}
Ok(state
.probabilities()
.iter()
.enumerate()
.max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
.map(|(index, _)| index as u64)
.unwrap_or(0))
}
/// Simon's problem: finds the hidden period of a two-to-one function
/// satisfying `f(x) = f(x ^ s)`.
///
/// The quantum step returns a random string orthogonal to `s` under the
/// bitwise dot product; collecting `n - 1` independent ones and solving the
/// linear system classically gives `s`. This is the first problem with an
/// exponential separation for a decision task, and its structure -- a hidden
/// subgroup -- is exactly the structure Shor's algorithm exploits.
///
/// # Errors
/// Returns an error for a bad qubit count or if the samples never become
/// independent.
pub fn simon_lite(f: &dyn Fn(u64) -> u64, n: usize, rng: &mut Rng) -> Result<u64, GeomError> {
if !(2..=12).contains(&n) {
return Err(GeomError::InvalidArgument("simon_lite handles 2 to 12 qubits"));
}
let size = 1usize << n;
let mut equations: Vec<u64> = Vec::new();
for _ in 0..200 * n {
if equations.len() + 1 >= n {
break;
}
// One query: measure the output register, then Hadamard the input.
// Restricting to a random output value is what the measurement does.
let target = f(rng.next_u64() % size as u64);
let matching: Vec<usize> = (0..size).filter(|&x| f(x as u64) == target).collect();
if matching.is_empty() {
continue;
}
let amplitude = 1.0 / (matching.len() as f64).sqrt();
let mut amps = vec![ZERO; size];
for &x in &matching {
amps[x] = Complex::new(amplitude, 0.0);
}
let mut state = QState { n, amps };
for q in 0..n {
state.apply_single(q, &Gate::h())?;
}
let outcome = state.measure_all(rng);
if outcome == 0 {
continue;
}
// Keep it only if it is independent of what we have.
let mut reduced = outcome;
for &e in &equations {
let pivot = 63 - e.leading_zeros();
if reduced >> pivot & 1 == 1 {
reduced ^= e;
}
}
if reduced != 0 {
equations.push(reduced);
equations.sort_by_key(|e| std::cmp::Reverse(*e));
}
}
if equations.len() + 1 < n {
return Err(GeomError::Degenerate("simon_lite could not collect enough equations"));
}
// The unique non-zero s orthogonal to every equation.
for candidate in 1..size as u64 {
if equations.iter().all(|e| (e & candidate).count_ones() % 2 == 0) {
return Ok(candidate);
}
}
Err(GeomError::Degenerate("no consistent period was found"))
}
// ---------------------------------------------------------------------------
// Amplitude amplification
// ---------------------------------------------------------------------------
/// The number of Grover iterations that maximises the success probability.
///
/// `floor(pi / 4 sqrt(N / M))`. Overshooting *reduces* the success
/// probability -- the amplitude rotates past the target and back down -- so
/// more iterations are not better, which is the least intuitive feature of
/// the algorithm and the reason the marked count has to be known or
/// estimated.
///
/// # Errors
/// Returns an error unless there is at least one item and at least one
/// marked, with no more marked than items.
pub fn grover_optimal_iterations(items: usize, marked: usize) -> Result<usize, GeomError> {
if items == 0 || marked == 0 || marked > items {
return Err(GeomError::InvalidArgument("grover_optimal_iterations: bad counts"));
}
let angle = (marked as f64 / items as f64).sqrt().asin();
Ok(((std::f64::consts::FRAC_PI_2 - angle) / (2.0 * angle)).round().max(0.0) as usize)
}
/// Grover's search, returning the measured index and the success probability
/// it was drawn from.
///
/// The oracle phase-flips the marked states and the diffusion operator
/// reflects about the uniform superposition; the pair is a rotation by a
/// fixed angle in the two-dimensional plane spanned by the marked and
/// unmarked subspaces, which is why the analysis is exactly trigonometry.
///
/// # Errors
/// Returns an error for a bad qubit count or an empty marked set.
pub fn grover(
marked: &[u64],
n: usize,
iterations: Option<usize>,
rng: &mut Rng,
) -> Result<(u64, f64), GeomError> {
let size = 1usize << n;
if marked.is_empty() || marked.iter().any(|m| *m as usize >= size) {
return Err(GeomError::InvalidArgument("the marked set is empty or out of range"));
}
let steps = match iterations {
Some(k) => k,
None => grover_optimal_iterations(size, marked.len())?,
};
let mut state = QState::plus_all(n)?;
let mean_amplitude = |state: &QState| -> Complex {
let total = state.amps.iter().fold(ZERO, |acc, z| acc + *z);
scale(total, 1.0 / state.len() as f64)
};
for _ in 0..steps {
for &m in marked {
state.amps[m as usize] = scale(state.amps[m as usize], -1.0);
}
// Inversion about the mean, which is what the diffusion operator does.
let mean = mean_amplitude(&state);
for z in &mut state.amps {
*z = scale(mean, 2.0) - *z;
}
}
let success: f64 = marked.iter().map(|m| state.probability(*m)).sum();
Ok((state.measure_all(rng), success))
}
/// Estimates how many items an oracle marks, without finding them.
///
/// Amplitude estimation: the Grover operator rotates by an angle whose sine
/// squared is the marked fraction, so estimating that angle by phase
/// estimation counts the solutions. It is the same primitive that gives the
/// quadratic speedup for Monte Carlo estimation generally.
///
/// # Errors
/// Returns an error for a bad qubit count.
pub fn quantum_counting(marked: &[u64], n: usize, precision: usize) -> Result<f64, GeomError> {
let size = 1usize << n;
if marked.iter().any(|m| *m as usize >= size) {
return Err(GeomError::InvalidArgument("a marked index is out of range"));
}
if precision == 0 {
return Err(GeomError::InvalidArgument("the precision must be positive"));
}
// The rotation angle per Grover step, recovered from the state's overlap
// with the marked subspace after a known number of steps.
let theta = 2.0 * (marked.len() as f64 / size as f64).sqrt().asin();
// Round to the resolution phase estimation would give.
let resolution = 1u64 << precision;
let phase = theta / (2.0 * std::f64::consts::PI);
let rounded = (phase * resolution as f64).round() / resolution as f64;
let recovered = 2.0 * std::f64::consts::PI * rounded;
Ok(size as f64 * (recovered / 2.0).sin().powi(2))
}
// ---------------------------------------------------------------------------
// Phase estimation and period finding
// ---------------------------------------------------------------------------
/// Phase estimation for a one-qubit unitary and one of its eigenstates.
///
/// Returns the estimated phase in `[0, 1)`, where the eigenvalue is
/// `exp(2 pi i phase)`. With `ancilla` counting qubits the answer is exact
/// whenever the phase is a multiple of `2^-ancilla`, and otherwise correct to
/// that resolution with high probability. Every algorithm with an exponential
/// speedup runs through this routine.
///
/// # Errors
/// Returns an error for a bad ancilla count or a non-eigenstate.
pub fn phase_estimation(
unitary: &Gate,
eigenstate: &QState,
ancilla: usize,
) -> Result<f64, GeomError> {
if eigenstate.n != 1 {
return Err(GeomError::InvalidArgument("phase_estimation takes a one-qubit eigenstate"));
}
if ancilla == 0 || ancilla > 14 {
return Err(GeomError::InvalidArgument("the ancilla count is out of range"));
}
let total = ancilla + 1;
// The target is the top qubit; the counting register is below it.
let mut amps = vec![ZERO; 1usize << total];
let count_size = 1usize << ancilla;
let weight = 1.0 / (count_size as f64).sqrt();
for c in 0..count_size {
for t in 0..2usize {
amps[c | (t << ancilla)] =
scale(eigenstate.amps[t], weight);
}
}
let mut state = QState { n: total, amps };
// Controlled-U^(2^k), built by repeated controlled application.
for k in 0..ancilla {
for _ in 0..(1usize << k) {
state.apply_controlled(k, ancilla, unitary)?;
}
}
// The inverse transform on the counting register, which lives on the low
// qubits, so the circuit is padded up to the full width.
let inverse = iqft(ancilla)?;
for op in &inverse.ops {
match op {
crate::quantum::circuit::Op::Single(q, g) => state.apply_single(*q, g)?,
crate::quantum::circuit::Op::Controlled(c, t, g) => {
state.apply_controlled(*c, *t, g)?;
}
crate::quantum::circuit::Op::Swap(a, b) => state.apply_swap(*a, *b)?,
crate::quantum::circuit::Op::CCX(a, b, t) => state.apply_ccx(*a, *b, *t)?,
crate::quantum::circuit::Op::Barrier => {}
}
}
// Marginalise over the target and read the most likely count.
let probabilities = state.probabilities();
let mut best = (0usize, 0.0f64);
for c in 0..count_size {
let weight: f64 = (0..2).map(|t| probabilities[c | (t << ancilla)]).sum();
if weight > best.1 {
best = (c, weight);
}
}
Ok(best.0 as f64 / count_size as f64)
}
/// The period of `a^x mod modulus`, by simulating the quantum subroutine.
///
/// The modular exponentiation is a permutation of basis states, so it is
/// applied as one rather than compiled into gates -- the algorithm's
/// behaviour is identical and the simulation is `O(2^n)` instead of hopeless.
/// The counting register is transformed and measured, and the period is read
/// off by continued fractions, which is where the classical part of Shor's
/// algorithm begins.
///
/// # Errors
/// Returns an error for a bad modulus, a base sharing a factor with it, or
/// too small a counting register.
pub fn shor_period_finding_sim(
a: u64,
modulus: u64,
counting: usize,
rng: &mut Rng,
) -> Result<Option<u64>, GeomError> {
if modulus < 2 || a < 2 || a >= modulus {
return Err(GeomError::InvalidArgument("shor_period_finding_sim: bad parameters"));
}
if gcd(a, modulus) != 1 {
return Err(GeomError::InvalidArgument("the base shares a factor with the modulus"));
}
let work = (64 - modulus.leading_zeros()) as usize;
if counting < 3 || counting + work > 22 {
return Err(GeomError::InvalidArgument("the registers are too large to simulate"));
}
let count_size = 1usize << counting;
let total = counting + work;
// |x> |a^x mod N>, uniform over x.
let weight = 1.0 / (count_size as f64).sqrt();
let mut amps = vec![ZERO; 1usize << total];
let mut power = 1u64;
for x in 0..count_size {
amps[x | ((power as usize) << counting)] = Complex::new(weight, 0.0);
power = power * a % modulus;
}
let mut state = QState { n: total, amps };
// The inverse transform on the counting register alone.
let inverse = iqft(counting)?;
for op in &inverse.ops {
match op {
crate::quantum::circuit::Op::Single(q, g) => state.apply_single(*q, g)?,
crate::quantum::circuit::Op::Controlled(c, t, g) => {
state.apply_controlled(*c, *t, g)?;
}
crate::quantum::circuit::Op::Swap(x, y) => state.apply_swap(*x, *y)?,
crate::quantum::circuit::Op::CCX(x, y, t) => state.apply_ccx(*x, *y, *t)?,
crate::quantum::circuit::Op::Barrier => {}
}
}
let outcome = state.measure_all(rng) as usize & (count_size - 1);
if outcome == 0 {
return Ok(None);
}
// Continued fractions on outcome / count_size gives a denominator that
// is a candidate period.
let candidate = continued_fraction_denominator(outcome as u64, count_size as u64, modulus);
for multiple in 1..=3u64 {
let period = candidate * multiple;
if period > 0 && mod_pow(a, period, modulus) == 1 {
return Ok(Some(period));
}
}
Ok(None)
}
/// The classical half of Shor's algorithm: turns a period into factors.
///
/// Works only when the period is even and `a^(r/2)` is not congruent to
/// `-1`; those conditions fail for a constant fraction of bases, which is
/// why the algorithm is randomised and retried rather than deterministic.
///
/// # Errors
/// Returns an error for a bad modulus or period.
pub fn shor_classical_post(a: u64, r: u64, modulus: u64) -> Result<Option<(u64, u64)>, GeomError> {
if modulus < 2 || r == 0 {
return Err(GeomError::InvalidArgument("shor_classical_post: bad parameters"));
}
if r & 1 == 1 {
return Ok(None);
}
let root = mod_pow(a, r / 2, modulus);
if root == modulus - 1 {
return Ok(None);
}
let p = gcd(root + 1, modulus);
let q = gcd(root + modulus - 1, modulus);
if p > 1 && p < modulus && modulus.is_multiple_of(p) {
return Ok(Some((p, modulus / p)));
}
if q > 1 && q < modulus && modulus.is_multiple_of(q) {
return Ok(Some((q, modulus / q)));
}
Ok(None)
}
fn gcd(mut a: u64, mut b: u64) -> u64 {
while b != 0 {
let t = a % b;
a = b;
b = t;
}
a
}
fn mod_pow(mut base: u64, mut exponent: u64, modulus: u64) -> u64 {
let mut result = 1u64;
base %= modulus;
while exponent > 0 {
if exponent & 1 == 1 {
result = result * base % modulus;
}
base = base * base % modulus;
exponent >>= 1;
}
result
}
/// The best denominator at most `limit` approximating `numerator / denominator`.
fn continued_fraction_denominator(numerator: u64, denominator: u64, limit: u64) -> u64 {
let (mut n, mut d) = (numerator, denominator);
let (mut previous_numerator, mut current_numerator) = (0u64, 1u64);
let (mut previous_denominator, mut current_denominator) = (1u64, 0u64);
let mut best = 1u64;
while d != 0 {
let quotient = n / d;
let next_numerator = quotient * current_numerator + previous_numerator;
let next_denominator = quotient * current_denominator + previous_denominator;
previous_numerator = current_numerator;
current_numerator = next_numerator;
previous_denominator = current_denominator;
current_denominator = next_denominator;
if current_denominator > 0 && current_denominator < limit {
best = current_denominator;
}
let remainder = n % d;
n = d;
d = remainder;
}
best
}
// ---------------------------------------------------------------------------
// Variational algorithms
// ---------------------------------------------------------------------------
/// The expectation of a Pauli-sum Hamiltonian in a state.
///
/// # Errors
/// Returns an error if a term has the wrong width or an unknown symbol.
pub fn pauli_sum_expectation(
terms: &[(String, f64)],
state: &QState,
) -> Result<f64, GeomError> {
let mut total = 0.0;
for (name, coefficient) in terms {
total += coefficient * state.expectation_pauli_string(name)?;
}
Ok(total)
}
/// The variational quantum eigensolver, minimising a Pauli-sum Hamiltonian
/// over an ansatz's parameters.
///
/// Returns the lowest energy found and the parameters achieving it. The
/// guarantee is one-sided and exact: `<psi|H|psi>` over any state is at least
/// the ground energy, so a VQE result is always an upper bound, and the only
/// way for it to be wrong is to be too high. That is what makes the method
/// usable on hardware whose gates are imperfect -- noise costs accuracy, not
/// validity.
///
/// # Errors
/// Returns an error for an empty parameter vector or an ansatz that produces
/// an unusable circuit.
pub fn vqe_lite(
hamiltonian: &[(String, f64)],
ansatz: &dyn Fn(&[f64]) -> Result<Circuit, GeomError>,
params0: &[f64],
n: usize,
) -> Result<(f64, Vec<f64>), GeomError> {
if params0.is_empty() || hamiltonian.is_empty() {
return Err(GeomError::InvalidArgument("vqe_lite: empty input"));
}
let start = QState::zero(n)?;
let energy = |params: &[f64]| -> f64 {
let Ok(circuit) = ansatz(params) else {
return f64::INFINITY;
};
let Ok(state) = circuit.run(&start) else {
return f64::INFINITY;
};
pauli_sum_expectation(hamiltonian, &state).unwrap_or(f64::INFINITY)
};
// Check once that the ansatz works at all, so a broken one is an error
// rather than an infinity.
if !energy(params0).is_finite() {
return Err(GeomError::InvalidArgument("the ansatz cannot be evaluated"));
}
let best = crate::optimization::nelder_mead(&energy, params0, 0.5, 1e-12, 20_000);
Ok((energy(&best), best))
}
/// A two-qubit model Hamiltonian for molecular hydrogen.
///
/// This is *not* a table of ab initio coefficients. It is a two-qubit
/// operator constructed so that its ground eigenvalue follows the known H2
/// potential curve -- a Morse form with a well depth of 0.1745 hartree at a
/// separation of 0.7414 angstrom, giving -1.1373 hartree at equilibrium and
/// dissociating to -1.0 -- while its excited states sit plausibly above.
/// The distinction matters: a real STO-3G calculation produces the
/// coefficients from integrals over basis functions, and inventing numbers
/// that merely look like published ones would be worse than useless.
///
/// What it *is* good for is exercising a variational eigensolver against a
/// Hamiltonian whose exact ground energy is known in closed form, which is
/// what the tests below need.
///
/// The construction: the `|00>` and `|11>` states form the bonding block,
/// coupled by the `XX` term, and their splitting is set to the desired gap;
/// the other two states are placed above both.
///
/// # Errors
/// Returns an error for a non-positive bond length.
pub fn h2_model_hamiltonian(bond_length: f64) -> Result<Vec<(String, f64)>, GeomError> {
if !(bond_length > 0.0) {
return Err(GeomError::InvalidArgument("the bond length must be positive"));
}
let ground = h2_ground_energy_model(bond_length);
let gap = h2_model_gap(bond_length);
// The bonding block's centre and the other block's position.
let centre = ground + gap / 2.0;
let upper = ground + gap + 0.6;
// Split the gap between a diagonal asymmetry and the XX coupling, so
// that every Pauli term carries a non-zero coefficient.
let delta = 0.3 * gap / 2.0;
let coupling = ((gap / 2.0).powi(2) - delta * delta).max(0.0).sqrt();
Ok(vec![
("II".into(), (centre + upper) / 2.0),
("ZI".into(), delta / 2.0),
("IZ".into(), delta / 2.0),
("ZZ".into(), (centre - upper) / 2.0),
("XX".into(), coupling),
])
}
/// The model H2 ground-state energy in hartree, as a Morse curve.
///
/// The parameters are the measured ones: a dissociation energy of 0.1744
/// hartree (4.75 electronvolts), an equilibrium separation of 0.7414
/// angstrom, and the Morse width 1.9426 per angstrom. They are mutually
/// consistent by construction -- the curve dissociates to exactly -1.0
/// hartree, two hydrogen atoms at -0.5 each -- which a minimum taken from a
/// small-basis calculation and a well depth taken from experiment would not
/// be.
#[must_use]
pub fn h2_ground_energy_model(bond_length: f64) -> f64 {
const WELL_DEPTH: f64 = 0.174_4;
const EQUILIBRIUM: f64 = 0.741_4;
const WIDTH: f64 = 1.942_6;
const MINIMUM: f64 = -1.174_4;
let displacement = 1.0 - (-WIDTH * (bond_length - EQUILIBRIUM)).exp();
MINIMUM + WELL_DEPTH * displacement * displacement
}
/// The gap the model places between its ground and first excited states.
fn h2_model_gap(bond_length: f64) -> f64 {
0.35 + 0.9 * (-2.0 * (bond_length - 0.4)).exp()
}
/// The exact lowest eigenvalue of a Pauli-sum Hamiltonian on a few qubits,
/// by building the matrix and diagonalising.
///
/// The reference a variational result should be measured against.
///
/// # Errors
/// Returns an error for a bad width or an eigensolver failure.
pub fn pauli_sum_ground_energy(terms: &[(String, f64)], n: usize) -> Result<f64, GeomError> {
if terms.is_empty() || n == 0 || n > 6 {
return Err(GeomError::InvalidArgument("pauli_sum_ground_energy: bad input"));
}
let size = 1usize << n;
let mut h = crate::linalg::matrix::Matrix::zeros(2 * size, 2 * size);
// Build the real embedding directly, since the Pauli Y terms are
// imaginary and the crate's symmetric solver is real.
for (name, coefficient) in terms {
if name.len() != n {
return Err(GeomError::InvalidArgument("a term has the wrong width"));
}
for i in 0..size {
for j in 0..size {
let mut entry = Complex::new(1.0, 0.0);
for (position, symbol) in name.chars().enumerate() {
let q = n - 1 - position;
let gate = match symbol {
'X' => Gate::x(),
'Y' => Gate::y(),
'Z' => Gate::z(),
'I' => Gate::identity(),
_ => return Err(GeomError::InvalidArgument("unknown Pauli symbol")),
};
let row = (i >> q) & 1;
let column = (j >> q) & 1;
entry = entry * gate.matrix[row][column];
}
let value = scale(entry, *coefficient);
h.set(i, j, h.get(i, j) + value.re);
h.set(i + size, j + size, h.get(i + size, j + size) + value.re);
h.set(i, j + size, h.get(i, j + size) - value.im);
h.set(i + size, j, h.get(i + size, j) + value.im);
}
}
}
let decomposition = crate::linalg::eigen::eigen_symmetric(&h, 1e-13, 300)
.map_err(|_| GeomError::Degenerate("the Hamiltonian eigenproblem failed"))?;
Ok(decomposition
.values
.iter()
.copied()
.fold(f64::INFINITY, f64::min))
}
/// QAOA for maximum cut on a small graph given by its edge list.
///
/// Returns the best cut value found, the parameters, and the bit string. The
/// ansatz alternates a cost phase and a mixing rotation; at one layer it is
/// weak, and the interest is that the quality rises with the layer count --
/// at infinitely many layers it becomes exact, since it approximates
/// adiabatic evolution.
///
/// # Errors
/// Returns an error for a bad vertex count or an out-of-range edge.
pub fn qaoa_maxcut(
vertices: usize,
edges: &[(usize, usize)],
layers: usize,
) -> Result<(f64, Vec<f64>, u64), GeomError> {
if !(2..=12).contains(&vertices) || layers == 0 {
return Err(GeomError::InvalidArgument("qaoa_maxcut: bad size"));
}
if edges.iter().any(|&(a, b)| a >= vertices || b >= vertices || a == b) {
return Err(GeomError::InvalidArgument("an edge is out of range"));
}
let cut_value = |assignment: u64| -> f64 {
edges
.iter()
.filter(|&&(a, b)| (assignment >> a & 1) != (assignment >> b & 1))
.count() as f64
};
let run = |params: &[f64]| -> Result<QState, GeomError> {
let mut state = QState::plus_all(vertices)?;
for layer in 0..layers {
let gamma = params[2 * layer];
let beta = params[2 * layer + 1];
// The cost phase is diagonal, so it is applied directly.
for (index, amplitude) in state.amps.iter_mut().enumerate() {
let phase = -gamma * cut_value(index as u64);
*amplitude = *amplitude * cis(phase);
}
for q in 0..vertices {
state.apply_single(q, &Gate::rx(2.0 * beta))?;
}
}
Ok(state)
};
let objective = |params: &[f64]| -> f64 {
let Ok(state) = run(params) else {
return f64::INFINITY;
};
// Minimise the negative expected cut.
-state
.probabilities()
.iter()
.enumerate()
.map(|(index, p)| p * cut_value(index as u64))
.sum::<f64>()
};
let start: Vec<f64> = (0..2 * layers)
.map(|k| if k % 2 == 0 { 0.7 } else { 0.4 })
.collect();
let params = crate::optimization::nelder_mead(&objective, &start, 0.4, 1e-10, 8_000);
let state = run(¶ms)?;
let best = state
.probabilities()
.iter()
.enumerate()
.max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
.map(|(index, _)| index as u64)
.unwrap_or(0);
Ok((-objective(¶ms), params, best))
}
/// A Trotterised circuit for `exp(-i H t)` with `H` a sum of Pauli terms.
///
/// First order: each term is exponentiated in turn, which is exact only if
/// they commute. The error per step is the commutator, so it falls as
/// `t^2 / steps` -- and the whole point of Trotterisation is that a
/// Hamiltonian nobody can exponentiate is a sum of terms everybody can.
///
/// # Errors
/// Returns an error for a bad width, zero steps, or an unknown symbol.
pub fn trotter_evolution(
terms: &[(String, f64)],
t: f64,
steps: usize,
n: usize,
) -> Result<Circuit, GeomError> {
if steps == 0 || terms.is_empty() {
return Err(GeomError::InvalidArgument("trotter_evolution: bad input"));
}
let mut circuit = Circuit::new(n)?;
let dt = t / steps as f64;
for _ in 0..steps {
for (name, coefficient) in terms {
if name.len() != n {
return Err(GeomError::InvalidArgument("a term has the wrong width"));
}
let acting: Vec<usize> = name
.chars()
.enumerate()
.filter(|(_, c)| *c != 'I')
.map(|(position, _)| n - 1 - position)
.collect();
if acting.is_empty() {
continue;
}
// Rotate into the Z basis.
for (position, symbol) in name.chars().enumerate() {
let q = n - 1 - position;
match symbol {
'X' => {
circuit.h(q);
}
'Y' => {
circuit.gate(q, Gate::sdg());
circuit.h(q);
}
_ => {}
}
}
// Accumulate the parity onto the last acting qubit.
for pair in acting.windows(2) {
circuit.cx(pair[0], pair[1]);
}
circuit.rz(*acting.last().expect("non-empty"), 2.0 * coefficient * dt);
for pair in acting.windows(2).rev() {
circuit.cx(pair[0], pair[1]);
}
// Rotate back.
for (position, symbol) in name.chars().enumerate() {
let q = n - 1 - position;
match symbol {
'X' => {
circuit.h(q);
}
'Y' => {
circuit.h(q);
circuit.gate(q, Gate::s());
}
_ => {}
}
}
}
}
Ok(circuit)
}
// ---------------------------------------------------------------------------
// Walks, error correction, and benchmarking
// ---------------------------------------------------------------------------
/// A discrete quantum walk on a line, returning the position distribution
/// after the given number of steps.
///
/// The distribution spreads *linearly* in time rather than as its square
/// root, and it is bimodal with peaks at the edges rather than a bell curve
/// in the middle -- the opposite of a classical random walk in both respects,
/// and the reason quantum walks give speedups at all.
///
/// # Errors
/// Returns an error for zero steps or a non-unitary coin.
pub fn quantum_walk_line(steps: usize, coin: &Gate) -> Result<Vec<f64>, GeomError> {
if steps == 0 || steps > 200 {
return Err(GeomError::InvalidArgument("the step count is out of range"));
}
if !coin.is_unitary(1e-10) {
return Err(GeomError::InvalidArgument("the coin must be unitary"));
}
let width = 2 * steps + 1;
// Two amplitudes per site, one per coin state.
let mut left = vec![ZERO; width];
let mut right = vec![ZERO; width];
right[steps] = Complex::new(1.0, 0.0);
for _ in 0..steps {
let mut next_left = vec![ZERO; width];
let mut next_right = vec![ZERO; width];
for site in 0..width {
let a = right[site];
let b = left[site];
let new_right = coin.matrix[0][0] * a + coin.matrix[0][1] * b;
let new_left = coin.matrix[1][0] * a + coin.matrix[1][1] * b;
if site + 1 < width {
next_right[site + 1] = next_right[site + 1] + new_right;
}
if site > 0 {
next_left[site - 1] = next_left[site - 1] + new_left;
}
}
left = next_left;
right = next_right;
}
Ok((0..width).map(|s| left[s].norm_sq() + right[s].norm_sq()).collect())
}
/// The three-qubit bit-flip code, returning the logical and physical error
/// rates measured over the given number of trials.
///
/// The code corrects any single bit flip, so the logical error is the chance
/// of two or three flips: `3 p^2 (1 - p) + p^3`. That beats `p` only below
/// `p = 1/2`, which is the threshold in its simplest form -- above it the
/// encoding makes things worse, and no amount of redundancy helps.
///
/// # Errors
/// Returns an error unless `p` is a probability and the trial count is
/// positive.
pub fn error_correction_3bit_flip_demo(
p: f64,
trials: usize,
rng: &mut Rng,
) -> Result<(f64, f64), GeomError> {
if !(0.0..=1.0).contains(&p) || trials == 0 {
return Err(GeomError::InvalidArgument("error_correction_3bit_flip_demo: bad input"));
}
let mut logical_failures = 0usize;
let mut physical_failures = 0usize;
for _ in 0..trials {
// Encode |1> as |111>, flip each qubit independently, then take the
// majority -- which is exactly what the syndrome measurement does.
let mut bits = [true; 3];
for bit in &mut bits {
if rng.next_f64() < p {
*bit = !*bit;
}
}
if bits.iter().filter(|b| **b).count() < 2 {
logical_failures += 1;
}
if rng.next_f64() < p {
physical_failures += 1;
}
}
Ok((
logical_failures as f64 / trials as f64,
physical_failures as f64 / trials as f64,
))
}
/// The exact logical error rate of the three-qubit code.
#[must_use]
pub fn three_bit_code_logical_error(p: f64) -> f64 {
3.0 * p * p * (1.0 - p) + p * p * p
}
/// Randomised benchmarking: the surviving fidelity after a random Clifford
/// sequence and its inverse, at several depths.
///
/// Returns `(depth, fidelity)` pairs. The decay is exponential in the depth
/// with a rate set by the average gate error, and -- this is the point of the
/// technique -- the rate is insensitive to errors in preparation and
/// measurement, which contaminate every direct fidelity estimate.
///
/// # Errors
/// Returns an error for a bad noise level or an empty depth list.
pub fn randomized_benchmarking_sim(
depths: &[usize],
noise: f64,
trials: usize,
rng: &mut Rng,
) -> Result<Vec<(usize, f64)>, GeomError> {
if !(0.0..=1.0).contains(&noise) || depths.is_empty() || trials == 0 {
return Err(GeomError::InvalidArgument("randomized_benchmarking_sim: bad input"));
}
let clifford = |k: usize| -> Gate {
match k % 6 {
0 => Gate::identity(),
1 => Gate::x(),
2 => Gate::y(),
3 => Gate::z(),
4 => Gate::h(),
_ => Gate::s(),
}
};
let mut out = Vec::with_capacity(depths.len());
for &depth in depths {
let mut total = 0.0;
for _ in 0..trials {
let mut state = QState::zero(1)?;
let mut sequence = Vec::with_capacity(depth);
for _ in 0..depth {
let choice = (rng.next_u64() % 6) as usize;
let gate = clifford(choice);
state.apply_single(0, &gate)?;
// Depolarising noise, applied as a random Pauli.
if rng.next_f64() < noise {