Skip to main content

ket/
lib.rs

1// SPDX-FileCopyrightText: 2026 Evandro Chagas Ribeiro da Rosa <evandro@quantuloop.com>
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Libket: a quantum circuit compiler library.
6//!
7//! Libket translates high-level quantum gate sequences into hardware-native
8//! instruction streams. It provides:
9//!
10//! - A rich intermediate representation ([`ir`]) with algebraic gate
11//!   optimisations and multi-controlled gate decomposition.
12//! - Pluggable execution backends ([`execution`]) for both live (mid-circuit
13//!   feedback) and batch (deferred compilation) execution modes.
14//! - A process abstraction ([`process`]) that drives the full compilation and
15//!   execution pipeline.
16//! - A structured, FFI-friendly error type ([`error::KetError`]).
17
18use crate::{
19    error::KetError,
20    ir::{block::BasicBlock, gate::QuantumGate},
21};
22
23pub mod c_api;
24mod decompose;
25pub mod error;
26pub mod execution;
27pub mod ir;
28mod mapping;
29mod matrix;
30pub mod process;
31
32#[cfg(test)]
33mod tests;
34
35/// Return a block with a controlled gate.
36///
37/// # Errors
38///
39/// Propagates any [`KetError`] that occurs during the `control` operation.
40pub fn controlled_gate(
41    gate: QuantumGate,
42    control: &[usize],
43    target: usize,
44) -> Result<BasicBlock, KetError> {
45    let mut quantum_code = BasicBlock::new();
46    quantum_code.append_gate(gate, target);
47    quantum_code.control(control)
48}
49
50/// Return a block with a SWAP gate.
51///
52/// # Errors
53///
54/// Propagates any [`KetError`] that occurs during the `controlled_gate` operation.
55pub fn swap_gate(a: usize, b: usize) -> Result<BasicBlock, KetError> {
56    let mut quantum_code = BasicBlock::new();
57    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[a], b)?, None);
58    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[b], a)?, None);
59    quantum_code.append_block(controlled_gate(QuantumGate::PauliX, &[a], b)?, None);
60    Ok(quantum_code)
61}
62
63/// Return a block with the compute-action-uncompute.
64///
65/// # Errors
66///
67/// Propagates any [`KetError`] that occurs during `compute` or `action` block generation.
68pub fn compute_action_uncompute_gate<Fc, Fa>(
69    mut compute: Fc,
70    mut action: Fa,
71) -> Result<BasicBlock, KetError>
72where
73    Fc: FnMut(BasicBlock) -> Result<BasicBlock, KetError>,
74    Fa: FnMut(BasicBlock) -> Result<BasicBlock, KetError>,
75{
76    let mut quantum_code = BasicBlock::new();
77
78    let compute = compute(BasicBlock::new())?;
79    let uncompute = compute.inverse();
80
81    let action = action(BasicBlock::new())?;
82
83    quantum_code.append_block(compute, None);
84    quantum_code.append_block(action, None);
85    quantum_code.append_block(uncompute, None);
86
87    Ok(quantum_code)
88}