Skip to main content

State

Struct State 

Source
pub struct State { /* private fields */ }
Expand description

A pure n-qubit state stored as a length-2^n amplitude vector.

Amplitudes are stored in computational-basis order: amps[i] is the amplitude of |i⟩ where i is the integer whose binary little-endian representation encodes the per-qubit basis states.

Implementations§

Source§

impl State

Source

pub fn apply_unitary(&self, u: &DMatrix<f64>) -> Result<State, StateError>

Apply a real-embedded unitary u (as produced by Circuit::unitary or built directly) to this state, returning the evolved state.

The state’s complex amplitude vector is embedded into a real DVector<f64> (2·2^n long, interleaved real/imaginary parts), multiplied by u, and un-embedded.

§Errors

Returns StateError::UnitarySizeMismatch if u is not 2^(n+1) × 2^(n+1) for this state’s n qubits.

§Examples
use tpt_sci_quantum::State;
use tpt_sci_quantum::tensor::kron;
use tpt_math_linalg::tpt_math_linalg_dense::DMatrix;

// H ⊗ I on two qubits, built from per-qubit factors.
let h = tpt_sci_quantum::embed_gate_2x2(&tpt_sci_quantum::H);
let i2 = DMatrix::from_fn(2, 2, |a, b| if a == b { 1.0 } else { 0.0 });
let u = kron(&h, &i2);
let s = State::new(2).unwrap();
let s2 = s.apply_unitary(&u).unwrap();
assert!((s2.amplitude(0).re - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9);
Source§

impl State

Source

pub fn new(n: usize) -> Result<Self, StateError>

Create the all-zero state |0...0⟩ for n qubits.

§Errors

Returns StateError::TooManyQubits if n == 0 (a zero-qubit state is meaningless) or n > 20 (the 2^20 amplitude vector is the supported upper bound).

§Examples
use tpt_sci_quantum::State;
let s = State::new(3).unwrap();
assert_eq!(s.n_qubits(), 3);
assert_eq!(s.amplitude(0), num_complex::Complex::new(1.0, 0.0));
Source

pub fn zero(n: usize) -> Result<Self, StateError>

Alias for State::new retained for readability in examples.

§Errors

See State::new.

Source

pub fn n_qubits(&self) -> usize

The number of qubits represented by this state.

Source

pub fn amplitudes(&self) -> &[Complex<f64>]

The raw amplitude vector (computational-basis order).

Source

pub fn amplitude(&self, index: usize) -> Complex<f64>

The amplitude of the basis state |index⟩.

§Panics

Panics if index >= 2^n.

Source

pub fn probabilities(&self) -> Vec<f64>

The Born-rule probabilities |amp|^2 for each basis state.

The returned vector sums to 1 up to floating-point rounding.

Source

pub fn norm(&self) -> f64

The Euclidean norm sqrt(Σ |amp|^2) of the state vector.

Source

pub fn normalize(&mut self)

Rescale the state so that its norm becomes 1.

§Panics

Panics if the current norm is zero (a zero vector has no normalization).

Source

pub fn measure(&self, rng: &mut impl Rng) -> usize

Sample a basis index from the Born-rule distribution.

Uses rng to draw a uniform value in [0, 1) and returns the first index whose cumulative probability exceeds it.

This method is non-destructive: it only reads the state and reports a sampled outcome. Repeated calls therefore keep returning outcomes from the same (uncollapsed) distribution. Use State::measure_collapsing when you need the standard post-measurement collapse semantics (as in Qiskit/Cirq), where the state is projected onto the measured basis state.

§Examples
use tpt_sci_quantum::State;
use tpt_math_prob_core::SplitMix64;

let mut state = State::new(1).unwrap();
state.h(0).unwrap();
let mut rng = SplitMix64::seed_from_u64(1);
let idx = state.measure(&mut rng);
assert!(idx == 0 || idx == 1);
Source

pub fn measure_collapsing(&mut self, rng: &mut impl Rng) -> usize

Sample a basis index and collapse the state onto that outcome.

Unlike State::measure, which only samples without disturbing the state, this consumes the measurement: the state is projected onto the measured computational-basis state (all other amplitudes zeroed) and the surviving amplitude is renormalised. This matches the standard simulator semantics (Qiskit/Cirq), where a subsequent measurement of the same register is deterministic.

§Examples
use tpt_sci_quantum::State;
use tpt_math_prob_core::SplitMix64;

let mut state = State::new(1).unwrap();
state.x(0).unwrap(); // |1⟩
let mut rng = SplitMix64::seed_from_u64(7);
let idx = state.measure_collapsing(&mut rng);
assert_eq!(idx, 1);
assert!((state.amplitude(1).norm() - 1.0).abs() < 1e-9);
Source

pub fn expectation_z(&self) -> f64

Expectation value ⟨Z^{⊗n}⟩ of the all-qubit parity operator.

Equal to Σ_i (-1)^{popcount(i)} |amp_i|^2. For the all-zero state this is 1; for a uniform superposition of even/odd parity states it is 0.

Source

pub fn apply_single( &mut self, gate: &[Complex<f64>; 4], qubit: usize, ) -> Result<(), StateError>

Apply a single-qubit 2×2 gate to qubit.

gate is row-major: [g00, g01, g10, g11] for [[g00, g01], [g10, g11]]. For each pair of basis states that differ only in qubit, the two amplitudes are transformed by the matrix.

§Errors

Returns StateError::InvalidQubit if qubit >= n_qubits().

Source

pub fn apply_cnot( &mut self, control: usize, target: usize, ) -> Result<(), StateError>

Apply a controlled-NOT: flip target whenever control is set.

§Errors

Returns StateError::InvalidQubit if either qubit is out of range, or StateError::SameQubits if control == target.

Source

pub fn apply_controlled( &mut self, control: usize, target: usize, gate: &[Complex<f64>; 4], ) -> Result<(), StateError>

Apply a single-qubit gate to target, controlled on control == 1.

§Errors

Returns StateError::InvalidQubit if either qubit is out of range, or StateError::SameQubits if control == target.

Source

pub fn h(&mut self, qubit: usize) -> Result<(), StateError>

Apply the Hadamard gate H to qubit.

§Errors

Returns StateError::InvalidQubit if qubit is out of range.

Source

pub fn x(&mut self, qubit: usize) -> Result<(), StateError>

Apply the Pauli-X (bit-flip) gate to qubit.

§Errors

Returns StateError::InvalidQubit if qubit is out of range.

Source

pub fn y(&mut self, qubit: usize) -> Result<(), StateError>

Apply the Pauli-Y gate to qubit.

§Errors

Returns StateError::InvalidQubit if qubit is out of range.

Source

pub fn z(&mut self, qubit: usize) -> Result<(), StateError>

Apply the Pauli-Z (phase-flip) gate to qubit.

§Errors

Returns StateError::InvalidQubit if qubit is out of range.

Source

pub fn s(&mut self, qubit: usize) -> Result<(), StateError>

Apply the phase gate S to qubit.

§Errors

Returns StateError::InvalidQubit if qubit is out of range.

Source

pub fn t(&mut self, qubit: usize) -> Result<(), StateError>

Apply the π/4 (T) gate to qubit.

§Errors

Returns StateError::InvalidQubit if qubit is out of range.

Source

pub fn cnot(&mut self, control: usize, target: usize) -> Result<(), StateError>

Apply a controlled-NOT gate.

§Errors

Returns StateError::InvalidQubit if either qubit is out of range, or StateError::SameQubits if control == target.

Trait Implementations§

Source§

impl Clone for State

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for State

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for State

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for State

Auto Trait Implementations§

§

impl Freeze for State

§

impl RefUnwindSafe for State

§

impl Send for State

§

impl Sync for State

§

impl Unpin for State

§

impl UnsafeUnpin for State

§

impl UnwindSafe for State

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.