qft/
qft.rs

1/*
2* Copyright (c) 2024 Andrew Rowan Barlow. Licensed under the EUPL-1.2
3* or later. You may obtain a copy of the licence at
4* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12. A copy
5* of the EUPL-1.2 licence in English is given in LICENCE.txt which is
6* found in the root directory of this repository.
7*
8* Author: Andrew Rowan Barlow <a.barlow.dev@gmail.com>
9*/
10
11// Uses the custom functions to define a Quantum Fourier Transform that can be applied to any
12// circuit.
13//
14// To define the custom function, a new circuit is initialised and simulated.
15
16use quantr::{
17    states::{ProductState, SuperPosition},
18    Circuit, Gate, Measurement, Printer, QuantrError,
19};
20
21fn main() -> Result<(), QuantrError> {
22    let mut qc: Circuit = Circuit::new(3)?;
23
24    // Apply qft
25    qc.add_repeating_gate(Gate::X, &[1, 2])?
26        .add_gate(Gate::Custom(qft, vec![0, 1], "QFT".to_string()), 2)?; // QFT on bits 0, 1 and 2
27
28    let mut printer = Printer::new(&qc);
29    printer.print_diagram();
30
31    qc.set_print_progress(true);
32
33    let simulated_circuit = qc.simulate();
34
35    if let Measurement::NonObservable(final_sup) = simulated_circuit.get_state() {
36        println!("\nThe final superposition is:");
37        for (state, amplitude) in final_sup.into_iter() {
38            println!("|{}> : {}", state, amplitude);
39        }
40    }
41
42    Ok(())
43}
44
45// A QFT implementation that can be used for other circuits. Note, the output is reveresed compared
46// to usual conventions; swap gates are needed.
47fn qft(input_state: ProductState) -> Option<SuperPosition> {
48    let qubit_num = input_state.num_qubits();
49    let mut mini_circuit: Circuit = Circuit::new(qubit_num).unwrap();
50
51    for pos in 0..qubit_num {
52        mini_circuit.add_gate(Gate::H, pos).unwrap();
53        for k in 2..=(qubit_num - pos) {
54            mini_circuit
55                .add_gate(Gate::CRk(k as i32, pos + k - 1), pos)
56                .unwrap();
57        }
58    }
59
60    mini_circuit
61        .change_register(SuperPosition::from(input_state))
62        .unwrap();
63
64    Some(mini_circuit.simulate().take_state().take())
65}