use crate::gates;
use crate::rng::Rng;
use crate::state::State;
use num_complex::Complex64;
use std::collections::HashMap;
use std::fmt;
type Gate = [[Complex64; 2]; 2];
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExportError {
SingleGate {
label: &'static str,
},
Noise,
}
impl fmt::Display for ExportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExportError::SingleGate { label } => {
write!(f, "cannot export single-qubit gate `{label}` to OpenQASM 2")
}
ExportError::Noise => f.write_str(
"cannot export a noise channel to OpenQASM 2, which has no syntax for one",
),
}
}
}
impl std::error::Error for ExportError {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DensityError {
TooManyQubits {
qubits: usize,
max: usize,
},
TooManyBranches {
max: usize,
},
}
impl fmt::Display for DensityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DensityError::TooManyQubits { qubits, max } => write!(
f,
"a density matrix for {qubits} qubits is 4^{qubits} entries, over the \
maximum of {max}"
),
DensityError::TooManyBranches { max } => write!(
f,
"classical feed-forward needs one density matrix per reachable register \
value, and this circuit exceeds the limit of {max}; sample it instead"
),
}
}
}
impl std::error::Error for DensityError {}
#[derive(Debug, Clone)]
enum Op {
Single {
gate: Gate,
target: usize,
label: &'static str,
params: Vec<f64>,
},
Controlled {
gate: Gate,
control: usize,
target: usize,
label: &'static str,
params: Vec<f64>,
},
Swap {
a: usize,
b: usize,
},
Measure {
qubit: usize,
clbit: usize,
},
Reset {
qubit: usize,
},
MultiControlled {
gate: Gate,
controls: Vec<usize>,
target: usize,
label: &'static str,
},
Kraus {
ops: Vec<[[Complex64; 2]; 2]>,
qubit: usize,
label: &'static str,
},
Conditional {
value: u64,
ops: Vec<Op>,
},
}
#[derive(Debug, Clone)]
pub struct Circuit {
n_qubits: usize,
ops: Vec<Op>,
}
impl Circuit {
pub fn new(n_qubits: usize) -> Self {
Circuit {
n_qubits,
ops: Vec::new(),
}
}
pub fn n_qubits(&self) -> usize {
self.n_qubits
}
pub(crate) fn extend_from(&mut self, other: &Circuit) {
debug_assert_eq!(self.n_qubits, other.n_qubits);
self.ops.extend(other.ops.iter().cloned());
}
pub fn h(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::h(),
target,
label: "H",
params: Vec::new(),
});
self
}
pub fn x(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::x(),
target,
label: "X",
params: Vec::new(),
});
self
}
pub fn z(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::z(),
target,
label: "Z",
params: Vec::new(),
});
self
}
pub fn id(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::id(),
target,
label: "I",
params: Vec::new(),
});
self
}
pub fn sx(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::sx(),
target,
label: "SX",
params: Vec::new(),
});
self
}
pub fn sxdg(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::sxdg(),
target,
label: "SXDG",
params: Vec::new(),
});
self
}
pub fn y(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::y(),
target,
label: "Y",
params: Vec::new(),
});
self
}
pub fn s(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::s(),
target,
label: "S",
params: Vec::new(),
});
self
}
pub fn t(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::t(),
target,
label: "T",
params: Vec::new(),
});
self
}
pub fn sdg(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::sdg(),
target,
label: "SDG",
params: Vec::new(),
});
self
}
pub fn tdg(&mut self, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::tdg(),
target,
label: "TDG",
params: Vec::new(),
});
self
}
pub fn p(&mut self, lambda: f64, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::p(lambda),
target,
label: "P",
params: vec![lambda],
});
self
}
pub fn u3(&mut self, theta: f64, phi: f64, lambda: f64, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::u3(theta, phi, lambda),
target,
label: "U3",
params: vec![theta, phi, lambda],
});
self
}
pub fn u2(&mut self, phi: f64, lambda: f64, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::u2(phi, lambda),
target,
label: "U2",
params: vec![phi, lambda],
});
self
}
pub fn rx(&mut self, theta: f64, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::rx(theta),
target,
label: "RX",
params: vec![theta],
});
self
}
pub fn ry(&mut self, theta: f64, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::ry(theta),
target,
label: "RY",
params: vec![theta],
});
self
}
pub fn rz(&mut self, theta: f64, target: usize) -> &mut Self {
self.ops.push(Op::Single {
gate: gates::rz(theta),
target,
label: "RZ",
params: vec![theta],
});
self
}
pub fn cnot(&mut self, control: usize, target: usize) -> &mut Self {
self.ops.push(Op::Controlled {
gate: gates::x(),
control,
target,
label: "X",
params: Vec::new(),
});
self
}
pub fn cu(&mut self, gate: Gate, control: usize, target: usize) -> &mut Self {
self.ops.push(Op::Controlled {
gate,
control,
target,
label: "U",
params: Vec::new(),
});
self
}
pub fn crz(&mut self, theta: f64, control: usize, target: usize) -> &mut Self {
self.ops.push(Op::Controlled {
gate: gates::rz(theta),
control,
target,
label: "CRZ",
params: vec![theta],
});
self
}
pub fn cp(&mut self, lambda: f64, control: usize, target: usize) -> &mut Self {
self.ops.push(Op::Controlled {
gate: gates::p(lambda),
control,
target,
label: "CP",
params: vec![lambda],
});
self
}
pub fn cu3(
&mut self,
theta: f64,
phi: f64,
lambda: f64,
control: usize,
target: usize,
) -> &mut Self {
self.ops.push(Op::Controlled {
gate: gates::u3(theta, phi, lambda),
control,
target,
label: "CU3",
params: vec![theta, phi, lambda],
});
self
}
pub fn cz(&mut self, control: usize, target: usize) -> &mut Self {
self.ops.push(Op::Controlled {
gate: gates::z(),
control,
target,
label: "Z",
params: Vec::new(),
});
self
}
pub fn cy(&mut self, control: usize, target: usize) -> &mut Self {
self.ops.push(Op::Controlled {
gate: gates::y(),
control,
target,
label: "Y",
params: Vec::new(),
});
self
}
pub fn ch(&mut self, control: usize, target: usize) -> &mut Self {
self.ops.push(Op::Controlled {
gate: gates::h(),
control,
target,
label: "H",
params: Vec::new(),
});
self
}
pub fn swap(&mut self, a: usize, b: usize) -> &mut Self {
self.ops.push(Op::Swap { a, b });
self
}
pub fn cswap(&mut self, control: usize, a: usize, b: usize) -> &mut Self {
self.cnot(b, a);
self.toffoli(control, a, b);
self.cnot(b, a);
self
}
pub fn mcu(&mut self, gate: Gate, controls: &[usize], target: usize) -> &mut Self {
self.ops.push(Op::MultiControlled {
gate,
controls: controls.to_vec(),
target,
label: "U",
});
self
}
pub fn mcx(&mut self, controls: &[usize], target: usize) -> &mut Self {
self.ops.push(Op::MultiControlled {
gate: gates::x(),
controls: controls.to_vec(),
target,
label: "X",
});
self
}
pub fn toffoli(&mut self, control1: usize, control2: usize, target: usize) -> &mut Self {
self.mcx(&[control1, control2], target)
}
pub fn channel(&mut self, ops: Vec<[[Complex64; 2]; 2]>, qubit: usize) -> &mut Self {
self.named_channel(ops, qubit, "N")
}
fn named_channel(
&mut self,
ops: Vec<[[Complex64; 2]; 2]>,
qubit: usize,
label: &'static str,
) -> &mut Self {
assert!(
!ops.is_empty(),
"a channel needs at least one Kraus operator"
);
assert!(
crate::noise::is_trace_preserving(&ops),
"channel is not trace preserving (sum K^dagger K must be the identity)"
);
self.ops.push(Op::Kraus { ops, qubit, label });
self
}
pub fn depolarizing(&mut self, p: f64, qubit: usize) -> &mut Self {
self.named_channel(crate::noise::depolarizing(p), qubit, "DEP")
}
pub fn bit_flip(&mut self, p: f64, qubit: usize) -> &mut Self {
self.named_channel(crate::noise::bit_flip(p), qubit, "BF")
}
pub fn phase_flip(&mut self, p: f64, qubit: usize) -> &mut Self {
self.named_channel(crate::noise::phase_flip(p), qubit, "PF")
}
pub fn amplitude_damping(&mut self, gamma: f64, qubit: usize) -> &mut Self {
self.named_channel(crate::noise::amplitude_damping(gamma), qubit, "AD")
}
pub fn phase_damping(&mut self, gamma: f64, qubit: usize) -> &mut Self {
self.named_channel(crate::noise::phase_damping(gamma), qubit, "PD")
}
pub fn reset(&mut self, qubit: usize) -> &mut Self {
self.ops.push(Op::Reset { qubit });
self
}
pub fn measure(&mut self, qubit: usize) -> &mut Self {
self.measure_into(qubit, qubit)
}
pub fn measure_into(&mut self, qubit: usize, clbit: usize) -> &mut Self {
assert!(
clbit < self.n_qubits,
"classical bit {clbit} is outside the register, which is {} bits wide",
self.n_qubits
);
self.ops.push(Op::Measure { qubit, clbit });
self
}
pub fn if_classical_eq(&mut self, value: u64, build: impl FnOnce(&mut Circuit)) -> &mut Self {
let mut inner = Circuit::new(self.n_qubits);
build(&mut inner);
for op in &inner.ops {
let kind = match op {
Op::Measure { .. } => "a measurement",
Op::Reset { .. } => "a reset",
Op::Conditional { .. } => "a nested conditional",
_ => continue,
};
panic!("a conditional block may only contain gates, but it contains {kind}");
}
if !inner.ops.is_empty() {
self.ops.push(Op::Conditional {
value,
ops: inner.ops,
});
}
self
}
fn has_measurement(&self) -> bool {
self.ops.iter().any(|op| matches!(op, Op::Measure { .. }))
}
fn has_conditional(&self) -> bool {
self.ops
.iter()
.any(|op| matches!(op, Op::Conditional { .. }))
}
fn has_reset(&self) -> bool {
self.ops
.iter()
.any(|op| matches!(op, Op::Reset { .. } | Op::Kraus { .. }))
}
fn trailing_measurements(&self) -> usize {
self.ops
.iter()
.rev()
.take_while(|op| matches!(op, Op::Measure { .. }))
.count()
}
fn measures_mid_circuit(&self) -> bool {
self.has_reset()
|| self.ops[..self.ops.len() - self.trailing_measurements()]
.iter()
.any(|op| matches!(op, Op::Measure { .. }))
}
pub fn run(&self) -> State {
self.run_seeded(0)
}
pub fn run_seeded(&self, seed: u64) -> State {
let mut rng = Rng::new(seed);
self.run_with(&mut rng)
}
fn run_with(&self, rng: &mut Rng) -> State {
let mut state = State::new(self.n_qubits);
let mut clbits: u64 = 0;
let executable = self.ops.len() - self.trailing_measurements();
for op in &self.ops[..executable] {
apply_op(&mut state, op, rng, &mut clbits);
}
state
}
}
impl Op {
fn primary_qubit(&self) -> Option<usize> {
match self {
Op::Single { target, .. } => Some(*target),
Op::Controlled { target, .. } => Some(*target),
Op::MultiControlled { target, .. } => Some(*target),
Op::Swap { a, .. } => Some(*a),
Op::Measure { qubit, .. } | Op::Reset { qubit } | Op::Kraus { qubit, .. } => {
Some(*qubit)
}
Op::Conditional { .. } => None,
}
}
}
const MAX_DENSITY_BRANCHES: usize = 64;
const MAX_DENSITY_MIXTURE_ENTRIES: usize = 1 << 26;
fn branch_allowance(n_qubits: usize) -> usize {
let entries = 1usize << (2 * n_qubits);
(MAX_DENSITY_MIXTURE_ENTRIES / entries).clamp(1, MAX_DENSITY_BRANCHES)
}
fn apply_density_op(rho: &mut crate::density::DensityMatrix, op: &Op) {
match op {
Op::Single { gate, target, .. } => rho.apply_1q(gate, *target),
Op::Controlled {
gate,
control,
target,
..
} => rho.apply_controlled_1q(gate, *control, *target),
Op::Swap { a, b } => rho.swap_qubits(*a, *b),
Op::MultiControlled {
gate,
controls,
target,
..
} => rho.apply_multi_controlled_1q(gate, controls, *target),
Op::Reset { qubit } => rho.reset(*qubit),
Op::Kraus { ops, qubit, .. } => rho.apply_kraus(ops, *qubit),
Op::Measure { .. } => unreachable!("measurements are handled by the caller"),
Op::Conditional { .. } => unreachable!("conditionals are handled by the caller"),
}
}
fn apply_op(state: &mut State, op: &Op, rng: &mut Rng, clbits: &mut u64) {
match op {
Op::Measure { qubit, clbit } => {
assert!(
*clbit < state.n_qubits(),
"classical bit {clbit} out of range"
);
let outcome = state.measure_qubit(*qubit, rng);
let mask = 1u64 << clbit;
if outcome {
*clbits |= mask;
} else {
*clbits &= !mask;
}
}
Op::Reset { qubit } => {
if state.measure_qubit(*qubit, rng) {
state.apply_1q(&gates::x(), *qubit);
}
}
Op::Kraus { ops, qubit, .. } => {
state.apply_kraus(ops, *qubit, rng);
}
Op::Conditional { value, ops } => {
if *clbits == *value {
for inner in ops {
apply_op(state, inner, rng, clbits);
}
}
}
Op::Single { gate, target, .. } => state.apply_1q(gate, *target),
Op::Controlled {
gate,
control,
target,
..
} => state.apply_controlled_1q(gate, *control, *target),
Op::Swap { a, b } => state.swap_qubits(*a, *b),
Op::MultiControlled {
gate,
controls,
target,
..
} => state.apply_multi_controlled_1q(gate, controls, *target),
}
}
impl Circuit {
pub fn run_density(&self) -> Result<crate::density::DensityMatrix, DensityError> {
if self.n_qubits > crate::density::MAX_DENSITY_QUBITS {
return Err(DensityError::TooManyQubits {
qubits: self.n_qubits,
max: crate::density::MAX_DENSITY_QUBITS,
});
}
let mut branches: HashMap<u64, crate::density::DensityMatrix> = HashMap::new();
branches.insert(0, crate::density::DensityMatrix::new(self.n_qubits));
let tracks_outcomes = self.has_conditional();
for op in &self.ops {
match op {
Op::Conditional { value, ops } => {
if let Some(rho) = branches.get_mut(value) {
for inner in ops {
apply_density_op(rho, inner);
}
}
}
Op::Measure { qubit, clbit } => {
if !tracks_outcomes {
for rho in branches.values_mut() {
rho.measure_dephase(*qubit);
}
continue;
}
let allowed = branch_allowance(self.n_qubits);
let mut split: HashMap<u64, crate::density::DensityMatrix> = HashMap::new();
for (value, rho) in branches.drain() {
for outcome in [false, true] {
let mut branch = rho.clone();
branch.project(*qubit, outcome);
if branch.trace() < 1e-15 {
continue;
}
let mut key = value & !(1u64 << clbit);
if outcome {
key |= 1u64 << clbit;
}
split
.entry(key)
.and_modify(|existing| existing.add_assign(&branch))
.or_insert(branch);
if split.len() > allowed {
return Err(DensityError::TooManyBranches { max: allowed });
}
}
}
branches = split;
}
other => {
for rho in branches.values_mut() {
apply_density_op(rho, other);
}
}
}
}
let mut remaining = branches.into_values();
let mut total = remaining
.next()
.unwrap_or_else(|| crate::density::DensityMatrix::zeros(self.n_qubits));
for rest in remaining {
total.add_assign(&rest);
}
Ok(total)
}
pub fn sample(&self, shots: usize, seed: u64) -> HashMap<usize, usize> {
let mut rng = Rng::new(seed);
let mut histogram = HashMap::new();
if self.measures_mid_circuit() {
for _ in 0..shots {
let outcome = self.run_with(&mut rng).measure_all(&mut rng);
*histogram.entry(outcome).or_insert(0) += 1;
}
} else {
let final_state = self.run();
for _ in 0..shots {
let outcome = final_state.clone().measure_all(&mut rng);
*histogram.entry(outcome).or_insert(0) += 1;
}
}
histogram
}
pub fn to_qasm(&self) -> Result<String, ExportError> {
let mut out = String::from("OPENQASM 2.0;\ninclude \"qelib1.inc\";\n");
out.push_str(&format!("qreg q[{}];\n", self.n_qubits));
if self.has_measurement() || self.has_conditional() {
out.push_str(&format!("creg c[{}];\n", self.n_qubits));
}
for op in &self.ops {
emit_op(&mut out, self.n_qubits, op)?;
}
Ok(out)
}
}
fn emit_op(out: &mut String, n_qubits: usize, op: &Op) -> Result<(), ExportError> {
{
match op {
Op::Single {
target,
label,
params,
..
} => {
let name = match *label {
"I" => "id",
"H" => "h",
"X" => "x",
"Y" => "y",
"Z" => "z",
"S" => "s",
"T" => "t",
"SDG" => "sdg",
"SX" => "sx",
"SXDG" => "sxdg",
"TDG" => "tdg",
"P" => "u1",
"U2" => "u2",
"U3" => "u3",
"RX" => "rx",
"RY" => "ry",
"RZ" => "rz",
other => return Err(ExportError::SingleGate { label: other }),
};
out.push_str(&format!("{name}{} q[{target}];\n", format_params(params)));
}
Op::Controlled {
gate,
control,
target,
label,
params,
} => {
match *label {
"X" => out.push_str(&format!("cx q[{control}],q[{target}];\n")),
"Y" => out.push_str(&format!("cy q[{control}],q[{target}];\n")),
"Z" => out.push_str(&format!("cz q[{control}],q[{target}];\n")),
"H" => out.push_str(&format!("ch q[{control}],q[{target}];\n")),
"CRZ" | "CP" | "CU3" => {
let name = match *label {
"CRZ" => "crz",
"CP" => "cu1",
_ => "cu3",
};
out.push_str(&format!(
"{name}{} q[{control}],q[{target}];\n",
format_params(params)
));
}
_ => emit_controlled_u(out, gate, *control, *target),
}
}
Op::Swap { a, b } => {
out.push_str(&format!("swap q[{a}],q[{b}];\n"));
}
Op::Measure { qubit, clbit } => {
out.push_str(&format!("measure q[{qubit}] -> c[{clbit}];\n"));
}
Op::Reset { qubit } => {
out.push_str(&format!("reset q[{qubit}];\n"));
}
Op::Kraus { .. } => return Err(ExportError::Noise),
Op::MultiControlled {
gate,
controls,
target,
label,
} => {
if *label == "X" {
emit_mcx(out, n_qubits, controls, *target);
} else {
emit_mcu(out, n_qubits, gate, controls, *target);
}
}
Op::Conditional { value, ops } => {
let mut block = String::new();
for inner in ops {
emit_op(&mut block, n_qubits, inner)?;
}
for line in block.lines() {
out.push_str(&format!("if(c=={value}) {line}\n"));
}
}
}
}
Ok(())
}
impl Circuit {
pub fn diagram(&self) -> String {
let n = self.n_qubits;
let mut columns: Vec<Vec<Option<&'static str>>> = Vec::with_capacity(self.ops.len());
for op in &self.ops {
let mut col: Vec<Option<&'static str>> = vec![None; n];
match op {
Op::Single { target, label, .. } => {
col[*target] = Some(label);
}
Op::Controlled {
control,
target,
label,
..
} => {
col[*control] = Some("*");
col[*target] = Some(label);
fill_connector(&mut col, &[*control, *target]);
}
Op::Swap { a, b } => {
col[*a] = Some("x");
col[*b] = Some("x");
fill_connector(&mut col, &[*a, *b]);
}
Op::Measure { qubit, .. } => {
col[*qubit] = Some("M");
}
Op::Conditional { ops, .. } => {
for inner in ops {
if let Some(q) = inner.primary_qubit() {
col[q] = Some("?");
}
}
}
Op::Reset { qubit } => {
col[*qubit] = Some("R");
}
Op::Kraus { qubit, label, .. } => {
col[*qubit] = Some(label);
}
Op::MultiControlled {
controls,
target,
label,
..
} => {
for &c in controls {
col[c] = Some("*");
}
col[*target] = Some(label);
let mut involved = controls.clone();
involved.push(*target);
fill_connector(&mut col, &involved);
}
}
columns.push(col);
}
let cell_w = columns
.iter()
.flatten()
.flatten()
.map(|s| s.len())
.max()
.unwrap_or(1)
.max(1);
let gutter = format!("q{}:", n.saturating_sub(1)).len();
let mut lines = Vec::with_capacity(n);
for r in 0..n {
let mut line = format!("{:<width$} -", format!("q{r}:"), width = gutter);
if columns.is_empty() {
line.push_str(&"-".repeat(cell_w));
}
for col in &columns {
line.push_str(¢er(col[r].unwrap_or(""), cell_w));
line.push('-');
}
lines.push(line);
}
lines.join("\n")
}
}
const ANGLE_EPS: f64 = 1e-12;
fn emit_rotation(out: &mut String, name: &str, angle: f64, target: usize) {
if angle.abs() > ANGLE_EPS {
out.push_str(&format!("{name}({angle}) q[{target}];\n"));
}
}
fn emit_controlled_u(out: &mut String, gate: &Gate, control: usize, target: usize) {
let (gamma, theta, phi, lambda) = gates::u3_decompose(gate);
emit_rotation(out, "u1", gamma, control);
out.push_str(&format!(
"cu3({theta},{phi},{lambda}) q[{control}],q[{target}];\n"
));
}
fn free_qubit(n_qubits: usize, controls: &[usize], target: usize) -> Option<usize> {
(0..n_qubits).find(|q| *q != target && !controls.contains(q))
}
fn emit_mcx(out: &mut String, n_qubits: usize, controls: &[usize], target: usize) {
match controls {
[] => out.push_str(&format!("x q[{target}];\n")),
[c] => out.push_str(&format!("cx q[{c}],q[{target}];\n")),
[a, b] => out.push_str(&format!("ccx q[{a}],q[{b}],q[{target}];\n")),
_ => match free_qubit(n_qubits, controls, target) {
Some(borrowed) => {
let (lo, hi) = controls.split_at(controls.len().div_ceil(2));
let mut hi_borrowed = hi.to_vec();
hi_borrowed.push(borrowed);
for _ in 0..2 {
emit_mcx(out, n_qubits, lo, borrowed);
emit_mcx(out, n_qubits, &hi_borrowed, target);
}
}
None => {
let (&last, rest) = controls.split_last().expect("at least three controls");
emit_controlled_u(out, &gates::sx(), last, target);
emit_mcx(out, n_qubits, rest, last);
emit_controlled_u(out, &gates::sxdg(), last, target);
emit_mcx(out, n_qubits, rest, last);
emit_mcu(out, n_qubits, &gates::sx(), rest, target);
}
},
}
}
fn emit_mcu(out: &mut String, n_qubits: usize, gate: &Gate, controls: &[usize], target: usize) {
let (gamma, theta, phi, lambda) = gates::u3_decompose(gate);
if controls.is_empty() {
out.push_str(&format!("u3({theta},{phi},{lambda}) q[{target}];\n"));
return;
}
if theta.abs() < ANGLE_EPS {
emit_mcphase(out, n_qubits, gamma, controls);
let mut controls_and_target = controls.to_vec();
controls_and_target.push(target);
emit_mcphase(out, n_qubits, lambda, &controls_and_target);
return;
}
if controls.len() == 1 {
emit_controlled_u(out, gate, controls[0], target);
return;
}
emit_rotation(out, "rz", (lambda - phi) / 2.0, target);
emit_mcx(out, n_qubits, controls, target);
emit_rotation(out, "rz", -(lambda + phi) / 2.0, target);
emit_rotation(out, "ry", -theta / 2.0, target);
emit_mcx(out, n_qubits, controls, target);
emit_rotation(out, "ry", theta / 2.0, target);
emit_rotation(out, "rz", phi, target);
emit_mcphase(out, n_qubits, gamma + (phi + lambda) / 2.0, controls);
}
fn emit_mcphase(out: &mut String, n_qubits: usize, lambda: f64, qubits: &[usize]) {
if lambda.abs() < ANGLE_EPS {
return;
}
match qubits {
[] => {}
[q] => out.push_str(&format!("u1({lambda}) q[{q}];\n")),
[a, b] => out.push_str(&format!("cu1({lambda}) q[{a}],q[{b}];\n")),
_ => {
let (&last, rest) = qubits.split_last().expect("at least three qubits");
let half = lambda / 2.0;
emit_mcphase(out, n_qubits, half, rest);
emit_mcx(out, n_qubits, rest, last);
emit_rotation(out, "u1", -half, last);
emit_mcx(out, n_qubits, rest, last);
emit_rotation(out, "u1", half, last);
}
}
}
fn format_params(params: &[f64]) -> String {
if params.is_empty() {
return String::new();
}
let joined = params
.iter()
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join(",");
format!("({joined})")
}
fn fill_connector(col: &mut [Option<&'static str>], involved: &[usize]) {
let min = *involved.iter().min().unwrap();
let max = *involved.iter().max().unwrap();
for (r, cell) in col.iter_mut().enumerate() {
if r > min && r < max && cell.is_none() {
*cell = Some("|");
}
}
}
fn center(token: &str, width: usize) -> String {
if token.len() >= width {
return token.to_string();
}
let pad = width - token.len();
let left = pad / 2;
let right = pad - left;
format!("{}{}{}", "-".repeat(left), token, "-".repeat(right))
}
impl fmt::Display for Circuit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.diagram())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn branch_allowance_shrinks_with_register_size() {
assert_eq!(branch_allowance(1), MAX_DENSITY_BRANCHES);
assert_eq!(branch_allowance(10), MAX_DENSITY_BRANCHES);
let mut previous = branch_allowance(10);
for n in 11..=crate::density::MAX_DENSITY_QUBITS {
let allowance = branch_allowance(n);
assert!(allowance >= 1, "{n} qubits allows no branch at all");
assert!(
allowance <= previous,
"{n} qubits allows more than {}",
n - 1
);
previous = allowance;
}
assert!(
branch_allowance(crate::density::MAX_DENSITY_QUBITS) < MAX_DENSITY_BRANCHES,
"the ceiling must be memory-bound, not count-bound"
);
for n in 1..=crate::density::MAX_DENSITY_QUBITS {
let entries = branch_allowance(n) * (1usize << (2 * n));
assert!(
entries <= MAX_DENSITY_MIXTURE_ENTRIES || branch_allowance(n) == 1,
"{n} qubits budgets {entries} entries"
);
}
}
}