Skip to main content

bell/
bell.rs

1//! The smallest complete thing: build a circuit, simulate it exactly, and get a
2//! hash that is the same on every machine.
3//!
4//!     cargo run --example bell
5
6use wai_quantum::quantum::{circuit_hash, Circuit};
7use wai_quantum::quantum_toolchain as qt;
8
9fn main() {
10    // A new circuit is in the circuit2 gateset, whose phase table is correctly
11    // rounded; `Circuit::with_gateset(2, Gateset::V1)` reproduces circuit/1.
12    let mut c = Circuit::new(2);
13    c.h(0).cx(0, 1); // a Bell pair
14
15    let sv = c.simulate().expect("simulate");
16    // The circuit's identity covers its capability; a circuit that simulates
17    // always has one.
18    let id = circuit_hash(&c).expect("a valid circuit has a hash");
19
20    println!("circuit    {} qubits, {} gates, {}", c.n_qubits, c.ops.len(), c.gateset.capability());
21    print!("circuit-id ");
22    for b in id {
23        print!("{b:02x}");
24    }
25    println!();
26    let (backend, why) = qt::recommend_backend(&c);
27    println!("backend    {backend:?} — {why}");
28
29    println!("outcomes");
30    for (state, p) in qt::top_outcomes(&sv, 4) {
31        if p > 0.0 {
32            println!("  |{state:02b}>  {p:.6}");
33        }
34    }
35
36    // Not "a hash of this run" — the reconstruction is byte-exact, so this is the
37    // same value natively, in a browser, and in a WASI component at the edge.
38    let h = sv.statevector_hash();
39    print!("state-hash ");
40    for b in h {
41        print!("{b:02x}");
42    }
43    println!();
44}