Skip to main content

grover/
grover.rs

1// SPDX-FileCopyrightText: 2024 Evandro Chagas Ribeiro da Rosa <evandro@quantuloop.com>
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use std::f64::consts::FRAC_PI_4;
6
7use ket::{
8    compute_action_uncompute_gate,
9    error::KetError,
10    ir::{block::BasicBlock, gate::QuantumGate},
11    process::{Process, QPUConfig},
12};
13
14fn main() -> Result<(), KetError> {
15    let num_qubits = 3;
16
17    let mut process = Process::new(QPUConfig {
18        num_qubits,
19        quantum_execution: None,
20    });
21
22    let qubits: Result<Vec<_>, _> = (0..num_qubits).map(|_| process.alloc()).collect();
23    let qubits = qubits?;
24
25    let mut quantum_code = BasicBlock::new();
26
27    for target in &qubits {
28        quantum_code.append_gate(QuantumGate::Hadamard, *target);
29    }
30
31    process.append_block(quantum_code)?;
32
33    let steps = ((FRAC_PI_4) * f64::sqrt((1 << num_qubits) as f64)) as i64;
34
35    for _ in 0..steps {
36        process.append_block(compute_action_uncompute_gate(
37            |mut compute| {
38                for target in &qubits {
39                    compute.append_gate(QuantumGate::PauliX, *target);
40                }
41                Ok(compute)
42            },
43            |mut action| {
44                action.append_gate(QuantumGate::PauliZ, qubits[0]);
45                Ok(action.control(&qubits[1..])?)
46            },
47        )?)?;
48
49        process.append_block(compute_action_uncompute_gate(
50            |mut compute| {
51                for target in &qubits {
52                    compute.append_gate(QuantumGate::Hadamard, *target);
53                    compute.append_gate(QuantumGate::PauliX, *target);
54                }
55                Ok(compute)
56            },
57            |mut action| {
58                action.append_gate(QuantumGate::PauliZ, qubits[0]);
59                Ok(action.control(&qubits[1..])?)
60            },
61        )?)?;
62    }
63
64    println!("{:#?}", process);
65
66    Ok(())
67}