quantum_planning/phase_oracle.rs
1//! The bridge from a classical [`Oracle`] to a phase oracle on a [`StateVector`].
2
3use core::marker::PhantomData;
4
5use crate::{Oracle, StateVector};
6
7/// A phase oracle built from an [`Oracle`] and a map from basis index to candidate.
8///
9/// It changes the sign of each basis state whose candidate the oracle accepts. The map
10/// returns `None` for an index without a candidate, for example when the candidate count is
11/// not a power of two; such an index is never marked.
12///
13/// # Query count
14///
15/// One [`apply`](Self::apply) is one quantum query, and one [`check`](Self::check) is one
16/// classical query, as in the query model. The simulator calls [`Oracle::accepts`] once per
17/// basis state inside one `apply`; that cost is a property of the simulation, not of the
18/// algorithm, so it does not count.
19#[derive(Clone, Debug)]
20pub struct PhaseOracle<O, F, C> {
21 /// The classical predicate that marks the solutions.
22 oracle: O,
23 /// The map from basis index to candidate.
24 candidate: F,
25 /// The quantum and classical queries since construction.
26 queries: usize,
27 /// Ties the candidate type to the oracle and the map.
28 marker: PhantomData<fn() -> C>,
29}
30
31impl<O, F, C> PhaseOracle<O, F, C>
32where
33 O: Oracle<C>,
34 F: Fn(usize) -> Option<C>,
35{
36 /// Makes a phase oracle from `oracle` and the index map `candidate`.
37 pub fn new(oracle: O, candidate: F) -> Self {
38 Self {
39 oracle,
40 candidate,
41 queries: 0,
42 marker: PhantomData,
43 }
44 }
45
46 /// Returns the quantum and classical queries since construction.
47 #[must_use]
48 pub fn queries(&self) -> usize {
49 self.queries
50 }
51
52 /// Changes the sign of every marked basis state of `state`. This counts as one query.
53 pub fn apply(&mut self, state: &mut StateVector) {
54 self.queries += 1;
55
56 for index in 0..state.states() {
57 if self.marks(index) {
58 state.negate(index);
59 }
60 }
61 }
62
63 /// Checks classically whether basis index `index` is marked. This counts as one query.
64 pub fn check(&mut self, index: usize) -> bool {
65 self.queries += 1;
66
67 self.marks(index)
68 }
69
70 /// Returns whether `index` maps to a candidate that the oracle accepts. No query counts.
71 fn marks(&self, index: usize) -> bool {
72 (self.candidate)(index).is_some_and(|candidate| self.oracle.accepts(&candidate))
73 }
74}