#[cfg(feature = "gpu")]
mod gpu;
mod groups;
mod rng;
mod stabilizer;
mod statevector;
mod uncompute;
pub use uncompute::ReversibleCircuit;
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT_CIRCUIT_ID: AtomicUsize = AtomicUsize::new(0);
#[derive(Debug)]
pub struct Qubit {
circuit: usize,
index: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Bit {
circuit: usize,
index: usize,
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Gate {
H,
X,
Z,
S,
T,
Sdg,
Tdg,
Rx(f64),
Ry(f64),
Rz(f64),
}
impl Gate {
fn name(self) -> &'static str {
match self {
Gate::H => "h",
Gate::X => "x",
Gate::Z => "z",
Gate::S => "s",
Gate::T => "t",
Gate::Sdg => "sdg",
Gate::Tdg => "tdg",
Gate::Rx(_) => "rx",
Gate::Ry(_) => "ry",
Gate::Rz(_) => "rz",
}
}
fn qasm(self) -> String {
match self {
Gate::Rx(a) | Gate::Ry(a) | Gate::Rz(a) => format!("{}({a:?})", self.name()),
_ => self.name().into(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Backend {
Auto,
StateVector,
Stabilizer,
#[cfg(feature = "gpu")]
Gpu,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SimError {
NotClifford {
gate: &'static str,
},
OutOfMemory {
qubits: usize,
required_bytes: u128,
limit_bytes: u128,
},
}
pub const DEFAULT_MEMORY_LIMIT: u64 = 1 << 30;
pub fn state_vector_bytes(n_qubits: usize) -> u128 {
if n_qubits <= 123 {
16u128 << n_qubits
} else {
u128::MAX
}
}
fn fmt_bytes(b: u128) -> String {
const UNITS: [&str; 9] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
let mut v = b as f64;
let mut u = 0;
while v >= 1024.0 && u + 1 < UNITS.len() {
v /= 1024.0;
u += 1;
}
format!("{v:.1} {}", UNITS[u])
}
impl std::fmt::Display for SimError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SimError::NotClifford { gate } => write!(
f,
"스태빌라이저 시뮬레이터는 Clifford 게이트만 지원하며 `{gate}` 게이트는 이에 해당하지 않습니다. 상태 벡터 백엔드 사용을 권장합니다"
),
SimError::OutOfMemory {
qubits,
required_bytes,
limit_bytes,
} => {
let (required, limit) = (fmt_bytes(*required_bytes), fmt_bytes(*limit_bytes));
write!(
f,
"{qubits}큐비트 상태 벡터 시뮬레이션에 {required}가 필요해 제한({limit})을 초과합니다. `set_memory_limit`이나 스태빌라이저 백엔드용 Clifford 전용 회로를 권장합니다"
)
}
}
}
}
impl std::error::Error for SimError {}
#[derive(Debug, Clone)]
pub(crate) enum Op {
Gate(Gate, usize),
Cx(usize, usize),
Ccx(usize, usize, usize),
Measure {
qubit: usize,
bit: usize,
},
Reset(usize),
If {
bit: usize,
value: bool,
body: Vec<Op>,
},
}
#[derive(Debug)]
pub struct Circuit {
id: usize,
n_qubits: usize,
n_bits: usize,
ops: Vec<Op>,
free: std::collections::VecDeque<usize>,
depth: usize,
memory_limit: u64,
groups: groups::Groups,
locked: Vec<u32>,
}
impl Default for Circuit {
fn default() -> Self {
Self::new()
}
}
impl Circuit {
pub fn new() -> Self {
Self {
id: NEXT_CIRCUIT_ID.fetch_add(1, Ordering::Relaxed),
n_qubits: 0,
n_bits: 0,
ops: Vec::new(),
free: std::collections::VecDeque::new(),
depth: 0,
memory_limit: DEFAULT_MEMORY_LIMIT,
groups: groups::Groups::default(),
locked: Vec::new(),
}
}
pub fn qubit(&mut self) -> Qubit {
let reuse = if self.depth == 0 {
self.free.pop_front()
} else {
None
};
let index = match reuse {
Some(i) => {
self.ops.push(Op::Reset(i));
i
}
None => {
self.n_qubits += 1;
self.groups.add_slot();
self.locked.push(0);
self.n_qubits - 1
}
};
Qubit {
circuit: self.id,
index,
}
}
fn own(&self, q: &Qubit) -> usize {
assert_eq!(q.circuit, self.id, "다른 회로의 큐비트를 사용했습니다");
q.index
}
fn gate(&mut self, g: Gate, q: &mut Qubit) {
let i = self.own(q);
self.push_gate(g, i);
}
fn push_gate(&mut self, g: Gate, i: usize) {
if !matches!(
g,
Gate::Z | Gate::S | Gate::Sdg | Gate::T | Gate::Tdg | Gate::Rz(_)
) {
self.check_unlocked(i);
}
self.ops.push(Op::Gate(g, i));
}
fn check_unlocked(&self, slot: usize) {
assert!(self.locked[slot] == 0, "with_ancilla의 apply 단계에서는 compute가 사용한 큐비트를 제어 또는 대각 위상 게이트 외의 연산에 사용할 수 없습니다");
}
pub fn h(&mut self, q: &mut Qubit) {
self.gate(Gate::H, q);
}
pub fn x(&mut self, q: &mut Qubit) {
self.gate(Gate::X, q);
}
pub fn z(&mut self, q: &mut Qubit) {
self.gate(Gate::Z, q);
}
pub fn s(&mut self, q: &mut Qubit) {
self.gate(Gate::S, q);
}
pub fn t(&mut self, q: &mut Qubit) {
self.gate(Gate::T, q);
}
pub fn sdg(&mut self, q: &mut Qubit) {
self.gate(Gate::Sdg, q);
}
pub fn tdg(&mut self, q: &mut Qubit) {
self.gate(Gate::Tdg, q);
}
pub fn rx(&mut self, q: &mut Qubit, theta: f64) {
self.gate(Gate::Rx(theta), q);
}
pub fn ry(&mut self, q: &mut Qubit, theta: f64) {
self.gate(Gate::Ry(theta), q);
}
pub fn rz(&mut self, q: &mut Qubit, theta: f64) {
self.gate(Gate::Rz(theta), q);
}
pub fn cx(&mut self, control: &mut Qubit, target: &mut Qubit) {
let (c, t) = (self.own(control), self.own(target));
self.push_cx(c, t);
}
fn push_cx(&mut self, c: usize, t: usize) {
self.check_unlocked(t);
self.groups.union(c, t);
self.ops.push(Op::Cx(c, t));
}
pub fn ccx(&mut self, control1: &mut Qubit, control2: &mut Qubit, target: &mut Qubit) {
let (a, b, t) = (self.own(control1), self.own(control2), self.own(target));
self.push_ccx(a, b, t);
}
pub fn ccx_ctrl(&mut self, control1: &Qubit, control2: &Qubit, target: &mut Qubit) {
let (a, b, t) = (self.own(control1), self.own(control2), self.own(target));
check_distinct_controls(a, b);
self.push_ccx(a, b, t);
}
fn push_ccx(&mut self, a: usize, b: usize, t: usize) {
self.check_unlocked(t);
self.groups.union(a, t);
self.groups.union(b, t);
self.ops.push(Op::Ccx(a, b, t));
}
pub fn may_be_entangled(&self, a: &Qubit, b: &Qubit) -> bool {
self.groups.same(self.own(a), self.own(b))
}
pub fn measure(&mut self, q: Qubit) -> Bit {
let i = self.own(&q);
self.check_unlocked(i);
assert!(
self.depth == 0,
"조건부 분기 내부 측정은 지원되지 않으므로 밖에서 측정해야 합니다"
);
let b = Bit {
circuit: self.id,
index: self.n_bits,
};
self.n_bits += 1;
self.ops.push(Op::Measure {
qubit: i,
bit: b.index,
});
self.release_clean(i);
b
}
fn release_clean(&mut self, slot: usize) {
self.free.push_back(slot);
self.groups.detach(slot);
}
pub fn qreg(&mut self, n: usize) -> QReg {
QReg {
qubits: (0..n).map(|_| self.qubit()).collect(),
}
}
pub fn measure_reg(&mut self, reg: QReg) -> BitReg {
BitReg {
bits: reg.into_iter().map(|q| self.measure(q)).collect(),
}
}
pub fn reset(&mut self, q: &mut Qubit) {
let i = self.own(q);
self.check_unlocked(i);
self.ops.push(Op::Reset(i));
if self.depth == 0 {
self.groups.detach(i);
}
}
pub fn if_one(&mut self, b: Bit, body: impl FnOnce(&mut Circuit)) {
self.branch(b, true, body);
}
pub fn if_zero(&mut self, b: Bit, body: impl FnOnce(&mut Circuit)) {
self.branch(b, false, body);
}
fn branch(&mut self, b: Bit, value: bool, body: impl FnOnce(&mut Circuit)) {
check_bit(self.id, b);
let outer = std::mem::take(&mut self.ops);
self.depth += 1;
body(self);
self.depth -= 1;
let body = std::mem::replace(&mut self.ops, outer);
self.ops.push(Op::If {
bit: b.index,
value,
body,
});
}
pub fn to_qasm(&self) -> String {
let mut s = String::from("OPENQASM 3.0;\ninclude \"stdgates.inc\";\n");
s += &format!("qubit[{}] q;\n", self.n_qubits);
if self.n_bits > 0 {
s += &format!("bit[{}] c;\n", self.n_bits);
}
write_qasm(&self.ops, 0, &mut s);
s
}
fn check_memory(&self) -> Result<(), SimError> {
let required = state_vector_bytes(self.n_qubits);
if required > u128::from(self.memory_limit) {
return Err(SimError::OutOfMemory {
qubits: self.n_qubits,
required_bytes: required,
limit_bytes: self.memory_limit.into(),
});
}
Ok(())
}
pub fn is_clifford(&self) -> bool {
stabilizer::first_non_clifford(&self.ops).is_none()
}
pub fn select_backend(&self) -> Backend {
if self.is_clifford() {
Backend::Stabilizer
} else {
Backend::StateVector
}
}
pub fn set_memory_limit(&mut self, bytes: u64) {
self.memory_limit = bytes;
}
pub fn simulate_with(&self, backend: Backend, seed: u64) -> Result<Shot, SimError> {
let backend = match backend {
Backend::Auto => self.select_backend(),
b => b,
};
let bits = match backend {
Backend::Auto => unreachable!(),
Backend::StateVector => {
self.check_memory()?;
statevector::run(&self.ops, self.n_qubits, self.n_bits, seed)
}
#[cfg(feature = "gpu")]
Backend::Gpu => {
self.check_memory()?;
gpu::run(&self.ops, self.n_qubits, self.n_bits, seed)
}
Backend::Stabilizer => {
if let Some(gate) = stabilizer::first_non_clifford(&self.ops) {
return Err(SimError::NotClifford { gate });
}
stabilizer::run(&self.ops, self.n_qubits, self.n_bits, seed)
}
};
Ok(Shot {
circuit: self.id,
bits,
})
}
pub fn simulate(&self, seed: u64) -> Shot {
self.simulate_with(Backend::StateVector, seed)
.unwrap_or_else(|e| panic!("{e}"))
}
}
fn check_distinct_controls(a: usize, b: usize) {
assert_ne!(a, b, "ccx의 두 제어 큐비트는 서로 달라야 합니다");
}
fn check_bit(circuit: usize, b: Bit) {
assert_eq!(b.circuit, circuit, "다른 회로의 비트입니다");
}
fn write_qasm(ops: &[Op], depth: usize, s: &mut String) {
let pad = " ".repeat(depth);
for op in ops {
s.push_str(&pad);
match op {
Op::Gate(g, i) => *s += &format!("{} q[{i}];\n", g.qasm()),
Op::Cx(a, b) => *s += &format!("cx q[{a}], q[{b}];\n"),
Op::Ccx(a, b, t) => *s += &format!("ccx q[{a}], q[{b}], q[{t}];\n"),
Op::Measure { qubit, bit } => *s += &format!("c[{bit}] = measure q[{qubit}];\n"),
Op::Reset(i) => *s += &format!("reset q[{i}];\n"),
Op::If { bit, value, body } => {
*s += &format!("if (c[{bit}] == {value}) {{\n");
write_qasm(body, depth + 1, s);
*s += &pad;
*s += "}\n";
}
}
}
}
#[derive(Debug, Clone)]
pub struct Shot {
circuit: usize,
bits: Vec<bool>,
}
impl Shot {
pub fn get(&self, b: Bit) -> bool {
check_bit(self.circuit, b);
self.bits[b.index]
}
pub fn value(&self, reg: &BitReg) -> u64 {
assert!(
reg.len() <= 64,
"최대 64비트까지만 정수로 변환할 수 있습니다"
);
reg.iter()
.enumerate()
.fold(0, |v, (i, &b)| v | (u64::from(self.get(b)) << i))
}
}
#[derive(Debug)]
pub struct QReg {
qubits: Vec<Qubit>,
}
impl std::ops::Deref for QReg {
type Target = [Qubit];
fn deref(&self) -> &[Qubit] {
&self.qubits
}
}
impl std::ops::DerefMut for QReg {
fn deref_mut(&mut self) -> &mut [Qubit] {
&mut self.qubits
}
}
impl IntoIterator for QReg {
type Item = Qubit;
type IntoIter = std::vec::IntoIter<Qubit>;
fn into_iter(self) -> Self::IntoIter {
self.qubits.into_iter()
}
}
impl<'a> IntoIterator for &'a mut QReg {
type Item = &'a mut Qubit;
type IntoIter = std::slice::IterMut<'a, Qubit>;
fn into_iter(self) -> Self::IntoIter {
self.qubits.iter_mut()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BitReg {
bits: Vec<Bit>,
}
impl std::ops::Deref for BitReg {
type Target = [Bit];
fn deref(&self) -> &[Bit] {
&self.bits
}
}
impl From<Vec<Bit>> for BitReg {
fn from(bits: Vec<Bit>) -> Self {
Self { bits }
}
}