stabilizer_ch_form_rust/form/
measure.rs

1use crate::StabilizerCHForm;
2use crate::error::{Error, Result};
3
4use crate::form::types::QubitState;
5use rand::rngs::StdRng;
6use rand::{Rng, SeedableRng};
7
8impl StabilizerCHForm {
9    /// Measures the specified qubit in the computational basis.
10    ///
11    /// ## Arguments
12    /// * `qarg` - The index of the qubit to measure.
13    ///
14    /// ## Returns
15    /// A [`Result`] containing the measurement outcome: `false` for `|0>`, `true` for `|1>`.
16    pub fn measure(&mut self, qarg: usize, seed: Option<[u8; 32]>) -> Result<bool> {
17        if qarg >= self.n {
18            return Err(Error::QubitIndexOutOfBounds(qarg, self.n));
19        }
20
21        let z_basis_state = self.get_qubit_state(qarg)?;
22        match z_basis_state {
23            QubitState::Determined(state) => Ok(state),
24            QubitState::Superposition => {
25                // Randomly collapse the qubit to |0> or |1>
26                let mut rng = match seed {
27                    Some(s) => StdRng::from_seed(s),
28                    None => StdRng::from_entropy(),
29                };
30                let outcome = rng.r#gen::<bool>();
31                self.project(qarg, outcome)?;
32                Ok(outcome)
33            }
34        }
35    }
36}