Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Examples PR 3: Grovers example #43

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions qip/examples/grovers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use qip::builder::Qudit;
use qip::builder_traits::UnitaryBuilder;
use qip::prelude::*;
use std::num::NonZeroUsize;
//-> Result<(), CircuitError>

fn prepare_state<P: Precision>(n: u64) -> Result<(), CircuitError> {
let mut b = LocalBuilder::<f64>::default();

let n = NonZeroUsize::new(n as usize).unwrap();
let r = b.register(n);
let r = b.h(r);

let anc = b.qubit();
let anc = b.not(anc);
let anc = b.h(anc);

let r = b.merge_two_registers(r, anc);

let (_, handle) = b.measure_stochastic(r);

let (state, measures) = b.calculate_state();
println!("{:?}", state);
println!("{:?}", measures.get_stochastic_measurement(handle));
Ok(())
}
#[cfg(feature = "macros")]
fn apply_us<P: Precision>(
b: &mut dyn UnitaryBuilder<P>,
search: Qudit,
ancillary: Qudit,
x0: u64,
) -> Result<(Qudit, Qudit), CircuitError> {
let search = b.h(search);
let (search, ancillary) = program!(b, search, ancillary, |x| {
(0, if x == 0 { std::f64::consts::PI } else { 0.0 })
})?;
let search = b.h(search);
Ok((search, ancillary))
}

#[cfg(feature = "macros")]
fn apply_uw(
b: &mut dyn UnitaryBuilder,
search: Qudit,
ancillary: Qudit,
x0: u64,
) -> Result<(Qudit, Qudit), CircuitError> {
// Need to move the x0 value into the closure.
program!(b, search, ancillary, move |x| ((x == x0) as u64, 0.0))
}

#[cfg(feature = "macros")]
fn apply_grover_iteration<P: Precision>(x: u64) -> Result<(), CircuitError> {
let mut b = LocalBuilder::<f64>::default();

let n = NonZeroUsize::new(b.n() - 1).unwrap();

let r = b.register(n);
let anc = b.qubit();

let (r, anc) = apply_uw(&mut b, r, anc, x).unwrap();
let (r, _) = apply_us(&mut b, r, anc).unwrap();

let (_, measured) = b.calculate_state_with_init([(&r, 0b000), (&anc, 0b001)]);

Ok(())
}

fn main() {}