Skip to main content

metatron_qso/quantum/
program.rs

1//! Programs with mid-circuit measurements, resets and classical
2//! conditions — the dynamic part of OpenQASM.
3//!
4//! A [`Program`] is a list of [`Operation`]s on `n_qubits` qubits and
5//! `n_bits` classical bits: gates, measurements into bits, resets to |0⟩,
6//! and blocks executed when a classical condition holds. Registers only
7//! name ranges of qubits and bits; they matter for printing and for
8//! conditions on whole registers.
9//!
10//! [`Program::probabilities`] returns the exact distribution of the
11//! classical bits. A program whose measurements all come after the last
12//! gate on their qubit, without resets or conditions, needs one
13//! simulation; otherwise every measurement splits the computation into
14//! branches, which is exact but grows with the number of branches with
15//! non-zero probability (at most [`MAX_BRANCHES`]). [`Program::sample`]
16//! samples shots from that distribution, or simulates shot by shot when it
17//! has too many branches.
18//!
19//! ```
20//! use metatron_qso::quantum::Program;
21//!
22//! // Teleport RY(0.8)|0⟩ from qubit 0 to qubit 2 and measure it.
23//! let p = Program::from_qasm(
24//!     "OPENQASM 3.0; include \"stdgates.inc\";
25//!      qubit[3] q; bit[3] c;
26//!      ry(0.8) q[0]; h q[1]; cx q[1], q[2];
27//!      cx q[0], q[1]; h q[0];
28//!      c[0] = measure q[0]; c[1] = measure q[1];
29//!      if (c[1] == 1) x q[2];
30//!      if (c[0] == 1) z q[2];
31//!      c[2] = measure q[2];",
32//! ).unwrap();
33//! let dist = p.probabilities().unwrap();
34//! let p1: f64 = dist.iter().filter(|(b, _)| *b >> 2 & 1 == 1).map(|(_, p)| p).sum();
35//! assert!((p1 - (0.4f64).sin().powi(2)).abs() < 1e-12);
36//! ```
37
38use std::collections::BTreeMap;
39
40use serde::{Deserialize, Serialize};
41
42use super::circuit::{Circuit, Instruction};
43use super::state::{MAX_QUBITS, StateVector};
44use crate::error::{QsoError, Result};
45use crate::rng::Rng;
46
47/// A classical record as a bit string of `n_bits` digits, bit 0 on the
48/// right (like [`bitstring`](super::bitstring), but for 64-bit records on
49/// every platform).
50pub fn record_bitstring(record: u64, n_bits: usize) -> String {
51    (0..n_bits)
52        .rev()
53        .map(|k| {
54            if k < 64 && (record >> k) & 1 == 1 {
55                '1'
56            } else {
57                '0'
58            }
59        })
60        .collect()
61}
62
63/// Most measurement branches [`Program::probabilities`] follows.
64pub const MAX_BRANCHES: usize = 1 << 12;
65/// Most amplitudes held over all branches at once.
66pub const MAX_BRANCH_AMPLITUDES: usize = 1 << 26;
67/// Most shots × operations of shot-by-shot simulation.
68pub const MAX_SHOT_WORK: usize = 1 << 30;
69/// Most classical bits (outcomes are 64-bit masks).
70pub const MAX_BITS: usize = 64;
71/// Most qubits a program may declare; simulating it needs at most
72/// [`MAX_QUBITS`].
73pub const MAX_PROGRAM_QUBITS: usize = 1 << 14;
74
75/// A named range of qubits or bits.
76#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
77pub struct Register {
78    pub name: String,
79    pub offset: usize,
80    pub size: usize,
81}
82
83/// Classical condition: the bits `bits` (least significant first) read as
84/// an integer equal (or, with `equal = false`, differ from) `value`.
85#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
86pub struct Condition {
87    pub bits: Vec<usize>,
88    pub value: u64,
89    pub equal: bool,
90}
91
92impl Condition {
93    /// Whether the condition holds for the classical record `record`.
94    pub fn holds(&self, record: u64) -> bool {
95        let v = self
96            .bits
97            .iter()
98            .enumerate()
99            .fold(0u64, |acc, (k, &b)| acc | (((record >> b) & 1) << k));
100        (v == self.value) == self.equal
101    }
102}
103
104/// One step of a [`Program`].
105#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
106pub enum Operation {
107    Gate(Instruction),
108    Measure {
109        qubit: usize,
110        bit: usize,
111    },
112    Reset {
113        qubit: usize,
114    },
115    If {
116        condition: Condition,
117        body: Vec<Operation>,
118    },
119}
120
121/// Qubits, bits, registers and operations of a dynamic circuit.
122#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
123pub struct Program {
124    n_qubits: usize,
125    n_bits: usize,
126    qubit_registers: Vec<Register>,
127    bit_registers: Vec<Register>,
128    operations: Vec<Operation>,
129}
130
131impl Program {
132    /// Empty program with one register `q` of `n_qubits` qubits and one
133    /// register `c` of `n_bits` bits (if any).
134    pub fn new(n_qubits: usize, n_bits: usize) -> Result<Self> {
135        let mut p = Self::with_registers(Vec::new(), Vec::new())?;
136        if n_qubits > 0 {
137            p.add_qubit_register("q", n_qubits)?;
138        }
139        if n_bits > 0 {
140            p.add_bit_register("c", n_bits)?;
141        }
142        Ok(p)
143    }
144
145    pub(crate) fn with_registers(qubits: Vec<Register>, bits: Vec<Register>) -> Result<Self> {
146        let mut p = Self {
147            n_qubits: 0,
148            n_bits: 0,
149            qubit_registers: Vec::new(),
150            bit_registers: Vec::new(),
151            operations: Vec::new(),
152        };
153        for r in qubits {
154            p.add_qubit_register(&r.name, r.size)?;
155        }
156        for r in bits {
157            p.add_bit_register(&r.name, r.size)?;
158        }
159        Ok(p)
160    }
161
162    /// Append a quantum register; its qubits follow the existing ones.
163    pub fn add_qubit_register(&mut self, name: &str, size: usize) -> Result<&Register> {
164        if self
165            .qubit_registers
166            .iter()
167            .chain(&self.bit_registers)
168            .any(|r| r.name == name)
169        {
170            return Err(QsoError::invalid(
171                "register",
172                format!("'{name}' declared twice"),
173            ));
174        }
175        let total = self
176            .n_qubits
177            .checked_add(size)
178            .filter(|&t| t <= MAX_PROGRAM_QUBITS);
179        let Some(total) = total else {
180            return Err(QsoError::TooManyQubits {
181                what: "program",
182                max: MAX_PROGRAM_QUBITS,
183                requested: self.n_qubits.saturating_add(size),
184            });
185        };
186        self.qubit_registers.push(Register {
187            name: name.to_string(),
188            offset: self.n_qubits,
189            size,
190        });
191        self.n_qubits = total;
192        Ok(self.qubit_registers.last().expect("just pushed"))
193    }
194
195    /// Append a classical register; its bits follow the existing ones.
196    pub fn add_bit_register(&mut self, name: &str, size: usize) -> Result<&Register> {
197        if self
198            .qubit_registers
199            .iter()
200            .chain(&self.bit_registers)
201            .any(|r| r.name == name)
202        {
203            return Err(QsoError::invalid(
204                "register",
205                format!("'{name}' declared twice"),
206            ));
207        }
208        let total = self.n_bits.checked_add(size).filter(|&t| t <= MAX_BITS);
209        let Some(total) = total else {
210            return Err(QsoError::invalid(
211                "register",
212                format!("programs may have at most {MAX_BITS} classical bits"),
213            ));
214        };
215        self.bit_registers.push(Register {
216            name: name.to_string(),
217            offset: self.n_bits,
218            size,
219        });
220        self.n_bits = total;
221        Ok(self.bit_registers.last().expect("just pushed"))
222    }
223
224    /// The program of `circuit` (parameters bound to `theta`), with every
225    /// qubit measured into the bit of the same index if `measure_all`.
226    pub fn from_circuit(circuit: &Circuit, theta: &[f64], measure_all: bool) -> Result<Self> {
227        let bound = circuit.bind(theta)?;
228        let n = circuit.n_qubits();
229        let mut p = Self::new(n, if measure_all { n } else { 0 })?;
230        for inst in bound.instructions() {
231            p.push(Operation::Gate(inst.clone()))?;
232        }
233        if measure_all {
234            for q in 0..n {
235                p.push(Operation::Measure { qubit: q, bit: q })?;
236            }
237        }
238        Ok(p)
239    }
240
241    fn validate(&self, op: &Operation) -> Result<()> {
242        match op {
243            Operation::Gate(inst) => {
244                inst.validate(self.n_qubits)?;
245                if inst.is_parametrised() {
246                    return Err(QsoError::invalid(
247                        "program",
248                        "gates in programs must have numeric angles",
249                    ));
250                }
251            }
252            Operation::Measure { qubit, bit } => {
253                self.check_qubit(*qubit)?;
254                self.check_bit(*bit)?;
255            }
256            Operation::Reset { qubit } => self.check_qubit(*qubit)?,
257            Operation::If { condition, body } => {
258                if condition.bits.is_empty() || condition.bits.len() > 64 {
259                    return Err(QsoError::invalid("condition", "needs 1 to 64 bits"));
260                }
261                for &b in &condition.bits {
262                    self.check_bit(b)?;
263                }
264                if condition.bits.len() < 64 && condition.value >> condition.bits.len() != 0 {
265                    return Err(QsoError::invalid(
266                        "condition",
267                        format!(
268                            "value {} does not fit into {} bits",
269                            condition.value,
270                            condition.bits.len()
271                        ),
272                    ));
273                }
274                for o in body {
275                    self.validate(o)?;
276                }
277            }
278        }
279        Ok(())
280    }
281
282    fn check_simulable(&self) -> Result<()> {
283        if self.n_qubits > MAX_QUBITS {
284            return Err(QsoError::TooManyQubits {
285                what: "program simulation",
286                max: MAX_QUBITS,
287                requested: self.n_qubits,
288            });
289        }
290        Ok(())
291    }
292
293    fn check_qubit(&self, q: usize) -> Result<()> {
294        if q >= self.n_qubits {
295            return Err(QsoError::QubitOutOfRange {
296                qubit: q,
297                n_qubits: self.n_qubits,
298            });
299        }
300        Ok(())
301    }
302
303    fn check_bit(&self, b: usize) -> Result<()> {
304        if b >= self.n_bits {
305            return Err(QsoError::invalid(
306                "bit",
307                format!("bit {b} out of range for {} bits", self.n_bits),
308            ));
309        }
310        Ok(())
311    }
312
313    /// Append a validated operation.
314    pub fn push(&mut self, op: Operation) -> Result<&mut Self> {
315        self.validate(&op)?;
316        self.operations.push(op);
317        Ok(self)
318    }
319
320    pub fn n_qubits(&self) -> usize {
321        self.n_qubits
322    }
323
324    pub fn n_bits(&self) -> usize {
325        self.n_bits
326    }
327
328    pub fn qubit_registers(&self) -> &[Register] {
329        &self.qubit_registers
330    }
331
332    pub fn bit_registers(&self) -> &[Register] {
333        &self.bit_registers
334    }
335
336    pub fn operations(&self) -> &[Operation] {
337        &self.operations
338    }
339
340    /// Number of operations, counting the bodies of conditions.
341    pub fn len(&self) -> usize {
342        fn count(ops: &[Operation]) -> usize {
343            ops.iter()
344                .map(|o| match o {
345                    Operation::If { body, .. } => 1 + count(body),
346                    _ => 1,
347                })
348                .sum()
349        }
350        count(&self.operations)
351    }
352
353    pub fn is_empty(&self) -> bool {
354        self.operations.is_empty()
355    }
356
357    /// Whether the program has only gates.
358    pub fn is_unitary(&self) -> bool {
359        self.operations
360            .iter()
361            .all(|o| matches!(o, Operation::Gate(_)))
362    }
363
364    /// The gates as a [`Circuit`]; an error if the program measures,
365    /// resets or branches.
366    pub fn to_circuit(&self) -> Result<Circuit> {
367        if !self.is_unitary() {
368            return Err(QsoError::invalid(
369                "program",
370                "has measurements, resets or conditions; use the unitary part explicitly",
371            ));
372        }
373        self.gates_skipping_measurements()
374    }
375
376    /// The gates, with measurements dropped (resets and conditions are
377    /// errors) — the reading of OpenQASM 2 programs by `from_qasm2`.
378    pub(crate) fn gates_skipping_measurements(&self) -> Result<Circuit> {
379        let mut c = Circuit::new(self.n_qubits);
380        for op in &self.operations {
381            match op {
382                Operation::Gate(inst) => {
383                    c.try_push(inst.clone())?;
384                }
385                Operation::Measure { .. } => {}
386                Operation::Reset { .. } => {
387                    return Err(QsoError::Parse("'reset' is not supported here".into()));
388                }
389                Operation::If { .. } => {
390                    return Err(QsoError::Parse(
391                        "classical conditions are not supported here".into(),
392                    ));
393                }
394            }
395        }
396        Ok(c)
397    }
398
399    /// If the program is gates followed by measurements of qubits no gate
400    /// touches afterwards: the gates and the `(qubit, bit)` pairs.
401    fn terminal_form(&self) -> Option<(Circuit, Vec<(usize, usize)>)> {
402        let mut c = Circuit::new(self.n_qubits);
403        let mut measured: Vec<(usize, usize)> = Vec::new();
404        for op in &self.operations {
405            match op {
406                Operation::Gate(inst) => {
407                    if inst.qubits().any(|q| measured.iter().any(|m| m.0 == q)) {
408                        return None;
409                    }
410                    c.try_push(inst.clone()).ok()?;
411                }
412                Operation::Measure { qubit, bit } => measured.push((*qubit, *bit)),
413                _ => return None,
414            }
415        }
416        Some((c, measured))
417    }
418
419    /// Exact probabilities of the classical records (bit `k` of the key is
420    /// bit `k`; unwritten bits are 0). Probabilities below 10⁻¹⁵ are
421    /// dropped.
422    pub fn probabilities(&self) -> Result<BTreeMap<u64, f64>> {
423        self.check_simulable()?;
424        let mut out: BTreeMap<u64, f64> = BTreeMap::new();
425        if let Some((c, measured)) = self.terminal_form() {
426            let psi = StateVector::from_circuit(&c, &[])?;
427            for (b, p) in psi.probabilities().into_iter().enumerate() {
428                if p <= 0.0 {
429                    continue;
430                }
431                let mut record = 0u64;
432                for &(q, bit) in &measured {
433                    let v = ((b >> q) & 1) as u64;
434                    record = (record & !(1 << bit)) | (v << bit);
435                }
436                *out.entry(record).or_default() += p;
437            }
438        } else {
439            let start = Branch {
440                weight: 1.0,
441                state: StateVector::zero(self.n_qubits),
442                record: 0,
443            };
444            let branches = run_branches(vec![start], &self.operations, self.n_qubits)?;
445            for b in branches {
446                *out.entry(b.record).or_default() += b.weight;
447            }
448        }
449        out.retain(|_, p| *p > 1e-15);
450        Ok(out)
451    }
452
453    /// `shots` records sampled with a seeded generator: from the exact
454    /// distribution when it has at most [`MAX_BRANCHES`] branches,
455    /// otherwise by simulating every shot.
456    pub fn sample(&self, shots: usize, seed: u64) -> Result<BTreeMap<u64, usize>> {
457        self.check_simulable()?;
458        let mut rng = Rng::seed_from_u64(seed);
459        let mut counts: BTreeMap<u64, usize> = BTreeMap::new();
460        match self.probabilities() {
461            Ok(dist) => {
462                let entries: Vec<(u64, f64)> = dist.into_iter().collect();
463                let total: f64 = entries.iter().map(|e| e.1).sum();
464                let mut cumulative = Vec::with_capacity(entries.len());
465                let mut acc = 0.0;
466                for e in &entries {
467                    acc += e.1 / total;
468                    cumulative.push(acc);
469                }
470                for _ in 0..shots {
471                    let u = rng.uniform();
472                    let k = cumulative
473                        .partition_point(|&x| x <= u)
474                        .min(entries.len() - 1);
475                    *counts.entry(entries[k].0).or_default() += 1;
476                }
477            }
478            Err(QsoError::InvalidArgument {
479                name: "branches", ..
480            }) => {
481                if shots.saturating_mul(self.len().max(1)) > MAX_SHOT_WORK {
482                    return Err(QsoError::invalid(
483                        "shots",
484                        format!("shots × operations exceed {MAX_SHOT_WORK}"),
485                    ));
486                }
487                for _ in 0..shots {
488                    let mut psi = StateVector::zero(self.n_qubits);
489                    let mut record = 0u64;
490                    run_shot(&mut psi, &mut record, &self.operations, &mut rng)?;
491                    *counts.entry(record).or_default() += 1;
492                }
493            }
494            Err(e) => return Err(e),
495        }
496        Ok(counts)
497    }
498}
499
500struct Branch {
501    weight: f64,
502    state: StateVector,
503    record: u64,
504}
505
506/// Probability that qubit `q` is |1⟩.
507fn p_one(psi: &StateVector, q: usize) -> f64 {
508    psi.amplitudes()
509        .iter()
510        .enumerate()
511        .filter(|(b, _)| (b >> q) & 1 == 1)
512        .map(|(_, a)| a.norm_sqr())
513        .sum::<f64>()
514        .clamp(0.0, 1.0)
515}
516
517/// Project qubit `q` onto `outcome` and renormalise by `p` (its
518/// probability).
519fn project(psi: &mut StateVector, q: usize, outcome: bool, p: f64) {
520    let s = 1.0 / p.sqrt();
521    for (b, a) in psi.amplitudes_mut().iter_mut().enumerate() {
522        if ((b >> q) & 1 == 1) == outcome {
523            *a *= s;
524        } else {
525            *a = num_complex::Complex64::new(0.0, 0.0);
526        }
527    }
528}
529
530fn flip(psi: &mut StateVector, q: usize) {
531    let amps = psi.amplitudes_mut();
532    let bit = 1usize << q;
533    for b in 0..amps.len() {
534        if b & bit == 0 {
535            amps.swap(b, b | bit);
536        }
537    }
538}
539
540fn run_branches(mut branches: Vec<Branch>, ops: &[Operation], n: usize) -> Result<Vec<Branch>> {
541    let too_many = || {
542        QsoError::invalid(
543            "branches",
544            format!(
545                "more than {MAX_BRANCHES} measurement branches (or {MAX_BRANCH_AMPLITUDES} amplitudes); sample shot by shot instead"
546            ),
547        )
548    };
549    for op in ops {
550        match op {
551            Operation::Gate(inst) => {
552                for b in &mut branches {
553                    b.state.apply_instruction(inst, &[])?;
554                }
555            }
556            Operation::Measure { qubit, bit } => {
557                branches = split(branches, *qubit, Some(*bit), false, n).ok_or_else(too_many)?;
558            }
559            Operation::Reset { qubit } => {
560                branches = split(branches, *qubit, None, true, n).ok_or_else(too_many)?;
561            }
562            Operation::If { condition, body } => {
563                let (hit, miss): (Vec<Branch>, Vec<Branch>) = branches
564                    .into_iter()
565                    .partition(|b| condition.holds(b.record));
566                let mut hit = run_branches(hit, body, n)?;
567                hit.extend(miss);
568                branches = hit;
569            }
570        }
571        if branches.len() > MAX_BRANCHES
572            || branches.len().saturating_mul(1usize << n) > MAX_BRANCH_AMPLITUDES
573        {
574            return Err(too_many());
575        }
576    }
577    Ok(branches)
578}
579
580/// Split every branch on the value of `qubit`: record it in `bit`, and for
581/// a reset flip the |1⟩ branch back to |0⟩.
582/// Split every branch by the outcome of measuring `qubit`; `None` if the
583/// result would exceed [`MAX_BRANCHES`] or [`MAX_BRANCH_AMPLITUDES`] (checked
584/// before any state is copied).
585fn split(
586    branches: Vec<Branch>,
587    qubit: usize,
588    bit: Option<usize>,
589    reset: bool,
590    n: usize,
591) -> Option<Vec<Branch>> {
592    let p_ones: Vec<f64> = branches.iter().map(|b| p_one(&b.state, qubit)).collect();
593    let count: usize = p_ones
594        .iter()
595        .map(|&p1| if p1 > 1e-15 && 1.0 - p1 > 1e-15 { 2 } else { 1 })
596        .sum();
597    if count > MAX_BRANCHES || count.saturating_mul(1usize << n) > MAX_BRANCH_AMPLITUDES {
598        return None;
599    }
600    let mut out = Vec::with_capacity(count);
601    for (b, p1) in branches.into_iter().zip(p_ones) {
602        let p0 = 1.0 - p1;
603        let set = |record: u64, v: bool| match bit {
604            Some(k) => (record & !(1 << k)) | (u64::from(v) << k),
605            None => record,
606        };
607        if p1 > 1e-15 && p0 > 1e-15 {
608            let mut one = b.state.clone();
609            project(&mut one, qubit, true, p1);
610            if reset {
611                flip(&mut one, qubit);
612            }
613            let mut zero = b.state;
614            project(&mut zero, qubit, false, p0);
615            out.push(Branch {
616                weight: b.weight * p0,
617                state: zero,
618                record: set(b.record, false),
619            });
620            out.push(Branch {
621                weight: b.weight * p1,
622                state: one,
623                record: set(b.record, true),
624            });
625        } else {
626            let outcome = p1 > 1e-15;
627            let mut state = b.state;
628            if outcome && reset {
629                flip(&mut state, qubit);
630            }
631            out.push(Branch {
632                weight: b.weight,
633                state,
634                record: set(b.record, outcome),
635            });
636        }
637    }
638    Some(out)
639}
640
641fn run_shot(
642    psi: &mut StateVector,
643    record: &mut u64,
644    ops: &[Operation],
645    rng: &mut Rng,
646) -> Result<()> {
647    for op in ops {
648        match op {
649            Operation::Gate(inst) => psi.apply_instruction(inst, &[])?,
650            Operation::Measure { qubit, bit } => {
651                let v = psi.measure(*qubit, rng)?;
652                *record = (*record & !(1 << bit)) | (u64::from(v) << bit);
653            }
654            Operation::Reset { qubit } => {
655                if psi.measure(*qubit, rng)? {
656                    flip(psi, *qubit);
657                }
658            }
659            Operation::If { condition, body } => {
660                if condition.holds(*record) {
661                    run_shot(psi, record, body, rng)?;
662                }
663            }
664        }
665    }
666    Ok(())
667}