pub const CAL_FRAC: u32 = 20;
pub const CAL_ONE: i64 = 1 << CAL_FRAC;
const PI_FX: i64 = 3_294_199;
#[inline]
fn fmul(a: i64, b: i64) -> i64 {
((a as i128 * b as i128) >> CAL_FRAC) as i64
}
pub fn sin2_fx(theta: i64) -> i64 {
let pi = PI_FX as i128;
let t = (theta as i128).rem_euclid(pi); let p = t * (pi - t); let num = 16 * p;
let den = 5 * pi * pi - 4 * p;
let s = ((num << CAL_FRAC) / den) as i64; fmul(s, s) }
fn splitmix64(state: &mut u64) -> u64 {
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = *state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
#[derive(Clone, Copy, Debug)]
pub struct Device {
pub a_pi_fx: i64,
pub seed: u64,
}
impl Device {
pub fn excited_prob(&self, a_fx: i64) -> i64 {
let theta = ((PI_FX as i128 * a_fx as i128) / (2 * self.a_pi_fx as i128)) as i64;
sin2_fx(theta)
}
pub fn measure(&self, a_fx: i64, shots: u32) -> i64 {
let p = self.excited_prob(a_fx);
let mut st = self
.seed
.wrapping_mul(0x1000_0001)
.wrapping_add(a_fx as u64);
let mut hits: u64 = 0;
for _ in 0..shots {
let r = (splitmix64(&mut st) >> (64 - CAL_FRAC)) as i64; if r < p {
hits += 1;
}
}
((hits as i128 * CAL_ONE as i128) / shots.max(1) as i128) as i64
}
}
#[derive(Clone, Copy, Debug)]
pub struct TuneConfig {
pub a_max_fx: i64,
pub n_coarse: u32,
pub n_fine: u32,
pub shots: u32,
}
impl Default for TuneConfig {
fn default() -> Self {
TuneConfig { a_max_fx: 2 * CAL_ONE, n_coarse: 41, n_fine: 41, shots: 2000 }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TuneResult {
pub a_pi_est_fx: i64,
pub peak_prob_fx: i64,
pub n_measurements: u32,
pub sweep: Vec<(i64, i64)>,
}
impl TuneResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-rabi\x01");
h.update(&self.a_pi_est_fx.to_le_bytes());
h.update(&self.peak_prob_fx.to_le_bytes());
h.update(&(self.n_measurements as u64).to_le_bytes());
for (a, p) in &self.sweep {
h.update(&a.to_le_bytes());
h.update(&p.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut ev = Vec::with_capacity(self.sweep.len() * 16 + 16);
ev.extend_from_slice(&self.a_pi_est_fx.to_le_bytes());
ev.extend_from_slice(&self.peak_prob_fx.to_le_bytes());
for (a, p) in &self.sweep {
ev.extend_from_slice(&a.to_le_bytes());
ev.extend_from_slice(&p.to_le_bytes());
}
CalArtifacts {
target: "1q_gate_amplitude".into(),
config_bytes: self.a_pi_est_fx.to_le_bytes().to_vec(),
evidence_kind: "rabi_amplitude_sweep".into(),
evidence_bytes: ev,
summary: format!("pi_amp={} peak_prob={} (2^{CAL_FRAC})", self.a_pi_est_fx, self.peak_prob_fx),
}
}
}
pub fn calibrate_rabi(device: &Device, cfg: &TuneConfig) -> TuneResult {
let n = cfg.n_coarse.max(4);
let mut sweep = Vec::with_capacity(n as usize);
for i in 0..n {
let a = ((cfg.a_max_fx as i128 * i as i128) / (n - 1) as i128) as i64;
sweep.push((a, device.measure(a, cfg.shots)));
}
let fit = |lo: i64, hi: i64, steps: u32| -> i64 {
let steps = steps.max(2);
let mut best = lo.max(1);
let mut best_err = i128::MAX;
for g in 1..=steps {
let a_pi = lo + ((hi - lo) as i128 * g as i128 / steps as i128) as i64;
if a_pi <= 0 {
continue;
}
let mut err = 0i128;
for &(a, p) in &sweep {
let theta = ((PI_FX as i128 * a as i128) / (2 * a_pi as i128)) as i64;
err += (p - sin2_fx(theta)).unsigned_abs() as i128;
}
if err < best_err {
best_err = err;
best = a_pi;
}
}
best
};
let coarse_step = cfg.a_max_fx / (n as i64 - 1);
let a_coarse = fit(coarse_step, cfg.a_max_fx, cfg.n_coarse.max(24));
let a_pi = fit((a_coarse - coarse_step).max(1), a_coarse + coarse_step, cfg.n_fine.max(24));
let peak = device.measure(a_pi, cfg.shots);
TuneResult { a_pi_est_fx: a_pi, peak_prob_fx: peak, n_measurements: n + 1, sweep }
}
#[cfg(feature = "quantum_ops")]
mod sealed {
use super::*;
use crate::quantum_ops::{content_hash, CalibrationReceipt, Evidence, GrantRef};
use ed25519_dalek::SigningKey;
pub fn sweep_bytes(r: &TuneResult) -> Vec<u8> {
let mut o = Vec::with_capacity(r.sweep.len() * 16 + 16);
o.extend_from_slice(&r.a_pi_est_fx.to_le_bytes());
o.extend_from_slice(&r.peak_prob_fx.to_le_bytes());
for (a, p) in &r.sweep {
o.extend_from_slice(&a.to_le_bytes());
o.extend_from_slice(&p.to_le_bytes());
}
o
}
#[allow(clippy::too_many_arguments)]
pub fn calibrate_and_seal(
signer: &SigningKey,
signer_id: impl Into<String>,
device_id: impl Into<String>,
target: impl Into<String>,
device: &Device,
cfg: &TuneConfig,
joules_micro: u64,
grant: GrantRef,
parent: Option<[u8; 32]>,
) -> (TuneResult, CalibrationReceipt) {
let r = calibrate_rabi(device, cfg);
let config_hash = content_hash(&r.a_pi_est_fx.to_le_bytes());
let ev = vec![Evidence {
kind: "rabi_amplitude_sweep".into(),
blob_hash: content_hash(&sweep_bytes(&r)),
summary: format!(
"pi_amp={} peak_prob={} (fixed-point 2^{})",
r.a_pi_est_fx, r.peak_prob_fx, CAL_FRAC
),
}];
let receipt = CalibrationReceipt::seal(
signer, signer_id, device_id, target, config_hash, ev, joules_micro, grant,
parent,
);
(r, receipt)
}
}
#[cfg(feature = "quantum_ops")]
pub use sealed::{calibrate_and_seal, sweep_bytes};
const TWO_PI_FX: i64 = 6_588_397; const HALF_PI_FX: i64 = 1_647_099; const LN2_FX: i64 = 726_817;
pub fn sin_fx(theta: i64) -> i64 {
let two_pi = TWO_PI_FX as i128;
let mut t = (theta as i128).rem_euclid(two_pi); let pi = PI_FX as i128;
let sign = if t >= pi {
t -= pi;
-1i64
} else {
1
};
let p = t * (pi - t);
let num = 16 * p;
let den = 5 * pi * pi - 4 * p;
let s = ((num << CAL_FRAC) / den) as i64;
sign * s
}
pub fn cos_fx(theta: i64) -> i64 {
sin_fx(theta + HALF_PI_FX)
}
pub fn exp_neg_fx(x_fx: i64) -> i64 {
if x_fx <= 0 {
return CAL_ONE;
}
let k = x_fx / LN2_FX;
let r = x_fx - k * LN2_FX; let r2 = fmul(r, r);
let r3 = fmul(r2, r);
let er = CAL_ONE - r + r2 / 2 - r3 / 6; if k >= 62 {
return 0;
}
(er >> k).max(0)
}
fn ratio_fx(a: i64, b: i64) -> i64 {
if b == 0 {
return 0;
}
(((a as i128) << CAL_FRAC) / b as i128) as i64
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CalArtifacts {
pub target: String,
pub config_bytes: Vec<u8>,
pub evidence_kind: String,
pub evidence_bytes: Vec<u8>,
pub summary: String,
}
#[derive(Clone, Copy, Debug)]
pub struct RamseyDevice {
pub omega_fx: i64,
pub t2_fx: i64,
pub seed: u64,
}
impl RamseyDevice {
pub fn prob(&self, tau_fx: i64) -> i64 {
let c = cos_fx(fmul(self.omega_fx, tau_fx));
let env = exp_neg_fx(ratio_fx(tau_fx, self.t2_fx));
(CAL_ONE + fmul(c, env)) / 2
}
pub fn measure(&self, tau_fx: i64, shots: u32) -> i64 {
let p = self.prob(tau_fx);
let mut st = self.seed.wrapping_mul(0x2545_F491).wrapping_add(tau_fx as u64);
let mut hits = 0u64;
for _ in 0..shots {
let r = (splitmix64(&mut st) >> (64 - CAL_FRAC)) as i64;
if r < p {
hits += 1;
}
}
((hits as i128 * CAL_ONE as i128) / shots.max(1) as i128) as i64
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RamseyResult {
pub omega_est_fx: i64,
pub t2_est_fx: i64,
pub sweep: Vec<(i64, i64)>,
pub n_measurements: u32,
}
impl RamseyResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-ramsey\x01");
h.update(&self.omega_est_fx.to_le_bytes());
h.update(&self.t2_est_fx.to_le_bytes());
for (a, b) in &self.sweep {
h.update(&a.to_le_bytes());
h.update(&b.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut cfg = Vec::new();
cfg.extend_from_slice(&self.omega_est_fx.to_le_bytes());
cfg.extend_from_slice(&self.t2_est_fx.to_le_bytes());
let mut ev = Vec::new();
for (a, b) in &self.sweep {
ev.extend_from_slice(&a.to_le_bytes());
ev.extend_from_slice(&b.to_le_bytes());
}
CalArtifacts {
target: "dephasing".into(),
config_bytes: cfg,
evidence_kind: "ramsey_fringe".into(),
evidence_bytes: ev,
summary: format!("omega={} t2={} (2^{CAL_FRAC})", self.omega_est_fx, self.t2_est_fx),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct RamseyConfig {
pub tau_max_fx: i64,
pub n_points: u32,
pub shots: u32,
pub omega_max_fx: i64,
pub t2_max_fx: i64,
pub n_grid: u32,
}
pub fn calibrate_ramsey(dev: &RamseyDevice, cfg: &RamseyConfig) -> RamseyResult {
let n = cfg.n_points.max(4);
let mut sweep = Vec::with_capacity(n as usize);
for i in 0..n {
let tau = ((cfg.tau_max_fx as i128 * i as i128) / (n - 1) as i128) as i64;
sweep.push((tau, dev.measure(tau, cfg.shots)));
}
let ng = cfg.n_grid.max(4);
let mut best_omega = 0i64;
let mut best_score = -1i128;
for g in 1..ng {
let omega = ((cfg.omega_max_fx as i128 * g as i128) / ng as i128) as i64;
let mut acc = 0i128;
for &(tau, p) in &sweep {
acc += ((p - CAL_ONE / 2) as i128 * cos_fx(fmul(omega, tau)) as i128) >> CAL_FRAC;
}
let s = acc.abs();
if s > best_score {
best_score = s;
best_omega = omega;
}
}
let mut best_t2 = cfg.t2_max_fx;
let mut best_err = i128::MAX;
for g in 1..=ng {
let t2 = ((cfg.t2_max_fx as i128 * g as i128) / ng as i128) as i64;
let probe = RamseyDevice { omega_fx: best_omega, t2_fx: t2, seed: 0 };
let mut err = 0i128;
for &(tau, p) in &sweep {
err += (p - probe.prob(tau)).unsigned_abs() as i128;
}
if err < best_err {
best_err = err;
best_t2 = t2;
}
}
RamseyResult { omega_est_fx: best_omega, t2_est_fx: best_t2, sweep, n_measurements: n }
}
#[derive(Clone, Copy, Debug)]
pub struct RbDevice {
pub epsilon_fx: i64,
pub seed: u64,
}
impl RbDevice {
pub fn survival(&self, m: u32) -> i64 {
let p = CAL_ONE - 2 * self.epsilon_fx;
let mut pm = CAL_ONE;
for _ in 0..m {
pm = fmul(pm, p);
}
CAL_ONE / 2 + fmul(CAL_ONE / 2, pm)
}
pub fn measure(&self, m: u32, k: u32, shots: u32) -> i64 {
let s = self.survival(m);
let mut st = self.seed.wrapping_mul(0x27D4_EB2F).wrapping_add(m as u64);
let mut hits = 0u64;
let total = (k.max(1) as u64) * shots.max(1) as u64;
for _ in 0..total {
let r = (splitmix64(&mut st) >> (64 - CAL_FRAC)) as i64;
if r < s {
hits += 1;
}
}
((hits as i128 * CAL_ONE as i128) / total as i128) as i64
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RbResult {
pub p_est_fx: i64,
pub fidelity_fx: i64,
pub curve: Vec<(u32, i64)>,
}
impl RbResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-rb\x01");
h.update(&self.p_est_fx.to_le_bytes());
h.update(&self.fidelity_fx.to_le_bytes());
for (m, s) in &self.curve {
h.update(&m.to_le_bytes());
h.update(&s.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut ev = Vec::new();
for (m, s) in &self.curve {
ev.extend_from_slice(&m.to_le_bytes());
ev.extend_from_slice(&s.to_le_bytes());
}
CalArtifacts {
target: "1q_gate".into(),
config_bytes: self.p_est_fx.to_le_bytes().to_vec(),
evidence_kind: "randomized_benchmarking".into(),
evidence_bytes: ev,
summary: format!("p={} fidelity={} (2^{CAL_FRAC})", self.p_est_fx, self.fidelity_fx),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct RbConfig {
pub lengths: [u32; 8],
pub k_sequences: u32,
pub shots: u32,
pub n_grid: u32,
}
pub fn calibrate_rb(dev: &RbDevice, cfg: &RbConfig) -> RbResult {
let curve: Vec<(u32, i64)> =
cfg.lengths.iter().map(|&m| (m, dev.measure(m, cfg.k_sequences, cfg.shots))).collect();
let ng = cfg.n_grid.max(8);
let mut best_p = CAL_ONE;
let mut best_err = i128::MAX;
for g in 1..ng {
let p = ((CAL_ONE as i128 * g as i128) / ng as i128) as i64;
let mut err = 0i128;
for &(m, s) in &curve {
let mut pm = CAL_ONE;
for _ in 0..m {
pm = fmul(pm, p);
}
let pred = CAL_ONE / 2 + fmul(CAL_ONE / 2, pm);
err += (s - pred).unsigned_abs() as i128;
}
if err < best_err {
best_err = err;
best_p = p;
}
}
let fidelity = CAL_ONE - (CAL_ONE - best_p) / 2;
RbResult { p_est_fx: best_p, fidelity_fx: fidelity, curve }
}
#[derive(Clone, Copy, Debug)]
pub struct ReadoutDevice {
pub s0_fx: i64,
pub s1_fx: i64,
pub sigma_fx: i64,
pub seed: u64,
}
impl ReadoutDevice {
fn gaussian(mean: i64, sigma: i64, st: &mut u64) -> i64 {
let mut acc = 0i64;
for _ in 0..12 {
acc += (splitmix64(st) >> (64 - CAL_FRAC)) as i64;
}
let z = acc - 6 * CAL_ONE;
mean + fmul(z, sigma)
}
pub fn dataset(&self, n: u32) -> (Vec<i64>, Vec<i64>) {
let mut st0 = self.seed ^ 0xA5A5;
let mut st1 = self.seed ^ 0x5A5A;
let zeros = (0..n).map(|_| Self::gaussian(self.s0_fx, self.sigma_fx, &mut st0)).collect();
let ones = (0..n).map(|_| Self::gaussian(self.s1_fx, self.sigma_fx, &mut st1)).collect();
(zeros, ones)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReadoutResult {
pub threshold_fx: i64,
pub mean0_fx: i64,
pub mean1_fx: i64,
pub fidelity_fx: i64,
pub n_shots: u32,
}
impl ReadoutResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-readout\x01");
for v in [self.threshold_fx, self.mean0_fx, self.mean1_fx, self.fidelity_fx] {
h.update(&v.to_le_bytes());
}
h.update(&self.n_shots.to_le_bytes());
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut cfg = Vec::new();
cfg.extend_from_slice(&self.threshold_fx.to_le_bytes());
CalArtifacts {
target: "readout".into(),
config_bytes: cfg,
evidence_kind: "readout_gmm".into(),
evidence_bytes: {
let mut e = Vec::new();
for v in [self.mean0_fx, self.mean1_fx, self.fidelity_fx] {
e.extend_from_slice(&v.to_le_bytes());
}
e.extend_from_slice(&self.n_shots.to_le_bytes());
e
},
summary: format!("threshold={} fidelity={} (2^{CAL_FRAC})", self.threshold_fx, self.fidelity_fx),
}
}
}
pub fn calibrate_readout(dev: &ReadoutDevice, n_per_class: u32) -> ReadoutResult {
let (zeros, ones) = dev.dataset(n_per_class);
let mean = |v: &[i64]| (v.iter().map(|&x| x as i128).sum::<i128>() / v.len().max(1) as i128) as i64;
let m0 = mean(&zeros);
let m1 = mean(&ones);
let threshold = (m0 + m1) / 2;
let high1 = m1 >= m0;
let mis0 = zeros.iter().filter(|&&x| (x >= threshold) == high1).count();
let mis1 = ones.iter().filter(|&&x| (x >= threshold) != high1).count();
let n = n_per_class.max(1) as i128;
let err = ((mis0 as i128 * CAL_ONE as i128 / n) + (mis1 as i128 * CAL_ONE as i128 / n)) / 2;
ReadoutResult {
threshold_fx: threshold,
mean0_fx: m0,
mean1_fx: m1,
fidelity_fx: CAL_ONE - err as i64,
n_shots: n_per_class,
}
}
#[derive(Clone, Copy, Debug)]
pub struct ChargeDevice {
pub alpha_l_fx: i64,
pub alpha_r_fx: i64,
pub beta_lr_fx: i64,
pub beta_rl_fx: i64,
pub off_l_fx: i64,
pub off_r_fx: i64,
}
impl ChargeDevice {
pub fn charge_state(&self, v_l: i64, v_r: i64) -> (i32, i32) {
let e_l = fmul(self.alpha_l_fx, v_l) + fmul(self.beta_lr_fx, v_r) + self.off_l_fx;
let e_r = fmul(self.alpha_r_fx, v_r) + fmul(self.beta_rl_fx, v_l) + self.off_r_fx;
((e_l >> CAL_FRAC).max(0) as i32, (e_r >> CAL_FRAC).max(0) as i32)
}
}
#[derive(Clone, Copy, Debug)]
pub struct ChargeScanConfig {
pub v_max_fx: i64,
pub n_grid: u32,
}
impl Default for ChargeScanConfig {
fn default() -> Self {
ChargeScanConfig { v_max_fx: 8 * CAL_ONE, n_grid: 96 }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChargeResult {
pub v_l_op_fx: i64,
pub v_r_op_fx: i64,
pub target: (i32, i32),
pub found: bool,
pub n_grid: u32,
pub v_max_fx: i64,
pub signal: Vec<i32>,
}
impl ChargeResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-chargestab\x01");
h.update(&self.v_l_op_fx.to_le_bytes());
h.update(&self.v_r_op_fx.to_le_bytes());
h.update(&[self.target.0 as u8, self.target.1 as u8, self.found as u8]);
for s in &self.signal {
h.update(&s.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut cfg = Vec::new();
cfg.extend_from_slice(&self.v_l_op_fx.to_le_bytes());
cfg.extend_from_slice(&self.v_r_op_fx.to_le_bytes());
let mut ev = Vec::with_capacity(self.signal.len() * 4);
for s in &self.signal {
ev.extend_from_slice(&s.to_le_bytes());
}
CalArtifacts {
target: format!("charge_state({},{})", self.target.0, self.target.1),
config_bytes: cfg,
evidence_kind: "charge_stability_scan".into(),
evidence_bytes: ev,
summary: format!(
"op=({},{}) target=({},{}) found={} (2^{CAL_FRAC})",
self.v_l_op_fx, self.v_r_op_fx, self.target.0, self.target.1, self.found
),
}
}
}
pub fn tune_charge_state(
dev: &ChargeDevice,
target: (i32, i32),
cfg: &ChargeScanConfig,
) -> ChargeResult {
let n = cfg.n_grid.max(2);
let mut signal = Vec::with_capacity((n * n) as usize);
let (mut sum_l, mut sum_r, mut count) = (0i128, 0i128, 0i128);
for iy in 0..n {
let v_r = ((cfg.v_max_fx as i128 * iy as i128) / (n - 1) as i128) as i64;
for ix in 0..n {
let v_l = ((cfg.v_max_fx as i128 * ix as i128) / (n - 1) as i128) as i64;
let (nl, nr) = dev.charge_state(v_l, v_r);
signal.push(nl + nr);
if (nl, nr) == target {
sum_l += v_l as i128;
sum_r += v_r as i128;
count += 1;
}
}
}
let found = count > 0;
let (v_l_op_fx, v_r_op_fx) =
if found { ((sum_l / count) as i64, (sum_r / count) as i64) } else { (0, 0) };
ChargeResult { v_l_op_fx, v_r_op_fx, target, found, n_grid: n, v_max_fx: cfg.v_max_fx, signal }
}
#[derive(Clone, Copy, Debug)]
pub struct CrDevice {
pub a_pi0_fx: i64,
pub a_pi1_fx: i64,
pub seed: u64,
}
impl CrDevice {
pub fn measure(&self, a_fx: i64, control: bool, shots: u32) -> i64 {
let a_pi = if control { self.a_pi1_fx } else { self.a_pi0_fx };
Device { a_pi_fx: a_pi.max(1), seed: self.seed ^ (control as u64) }.measure(a_fx, shots)
}
}
#[derive(Clone, Copy, Debug)]
pub struct CrConfig {
pub a_max_fx: i64,
pub n_points: u32,
pub shots: u32,
pub n_fit: u32,
}
impl Default for CrConfig {
fn default() -> Self {
CrConfig { a_max_fx: 2 * CAL_ONE, n_points: 41, shots: 2000, n_fit: 41 }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CrResult {
pub a_pi0_est_fx: i64,
pub a_pi1_est_fx: i64,
pub zx_shift_fx: i64,
pub sweep0: Vec<(i64, i64)>,
pub sweep1: Vec<(i64, i64)>,
}
impl CrResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-cr\x01");
for v in [self.a_pi0_est_fx, self.a_pi1_est_fx, self.zx_shift_fx] {
h.update(&v.to_le_bytes());
}
for (a, p) in self.sweep0.iter().chain(self.sweep1.iter()) {
h.update(&a.to_le_bytes());
h.update(&p.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut cfg = Vec::new();
cfg.extend_from_slice(&self.a_pi0_est_fx.to_le_bytes());
cfg.extend_from_slice(&self.a_pi1_est_fx.to_le_bytes());
let mut ev = Vec::new();
for (a, p) in self.sweep0.iter().chain(self.sweep1.iter()) {
ev.extend_from_slice(&a.to_le_bytes());
ev.extend_from_slice(&p.to_le_bytes());
}
CalArtifacts {
target: "cz(control,target)".into(),
config_bytes: cfg,
evidence_kind: "cross_resonance_sweep".into(),
evidence_bytes: ev,
summary: format!(
"a_pi0={} a_pi1={} zx_shift={} (2^{CAL_FRAC})",
self.a_pi0_est_fx, self.a_pi1_est_fx, self.zx_shift_fx
),
}
}
}
fn fit_pi_amplitude(sweep: &[(i64, i64)], a_max: i64, coarse: u32, fine: u32) -> i64 {
let fit = |lo: i64, hi: i64, steps: u32| -> i64 {
let steps = steps.max(2);
let mut best = lo.max(1);
let mut best_err = i128::MAX;
for g in 1..=steps {
let a_pi = lo + ((hi - lo) as i128 * g as i128 / steps as i128) as i64;
if a_pi <= 0 {
continue;
}
let mut err = 0i128;
for &(a, p) in sweep {
let theta = ((PI_FX as i128 * a as i128) / (2 * a_pi as i128)) as i64;
err += (p - sin2_fx(theta)).unsigned_abs() as i128;
}
if err < best_err {
best_err = err;
best = a_pi;
}
}
best
};
let a_coarse = fit(a_max / coarse.max(2) as i64, a_max, coarse.max(24));
let step = a_max / coarse.max(2) as i64;
fit((a_coarse - step).max(1), a_coarse + step, fine.max(24))
}
pub fn calibrate_cr(dev: &CrDevice, cfg: &CrConfig) -> CrResult {
let n = cfg.n_points.max(4);
let (mut sweep0, mut sweep1) = (Vec::with_capacity(n as usize), Vec::with_capacity(n as usize));
for i in 0..n {
let a = ((cfg.a_max_fx as i128 * i as i128) / (n - 1) as i128) as i64;
sweep0.push((a, dev.measure(a, false, cfg.shots)));
sweep1.push((a, dev.measure(a, true, cfg.shots)));
}
let a0 = fit_pi_amplitude(&sweep0, cfg.a_max_fx, cfg.n_points, cfg.n_fit);
let a1 = fit_pi_amplitude(&sweep1, cfg.a_max_fx, cfg.n_points, cfg.n_fit);
CrResult { a_pi0_est_fx: a0, a_pi1_est_fx: a1, zx_shift_fx: (a1 - a0).abs(), sweep0, sweep1 }
}
#[derive(Clone, Debug)]
pub struct CrosstalkDevice {
pub n: usize,
pub matrix_fx: Vec<i64>,
pub seed: u64,
}
impl CrosstalkDevice {
pub fn measure(&self, i: usize, j: usize, a_fx: i64, shots: u32) -> i64 {
let theta = fmul(self.matrix_fx[i * self.n + j], a_fx);
let p = sin2_fx(theta / 2);
let mut st = self.seed.wrapping_mul(0x1000_0001).wrapping_add((i * 97 + j) as u64);
let mut hits = 0u64;
for _ in 0..shots {
if ((splitmix64(&mut st) >> (64 - CAL_FRAC)) as i64) < p {
hits += 1;
}
}
((hits as i128 * CAL_ONE as i128) / shots.max(1) as i128) as i64
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CrosstalkResult {
pub n: usize,
pub matrix_fx: Vec<i64>,
pub worst_offdiag_fx: i64,
}
impl CrosstalkResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-crosstalk\x01");
h.update(&(self.n as u64).to_le_bytes());
for v in &self.matrix_fx {
h.update(&v.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut ev = Vec::new();
for v in &self.matrix_fx {
ev.extend_from_slice(&v.to_le_bytes());
}
CalArtifacts {
target: format!("crosstalk_{}x{}", self.n, self.n),
config_bytes: self.worst_offdiag_fx.to_le_bytes().to_vec(),
evidence_kind: "crosstalk_matrix".into(),
evidence_bytes: ev,
summary: format!("n={} worst_offdiag={} (2^{CAL_FRAC})", self.n, self.worst_offdiag_fx),
}
}
}
pub fn characterize_crosstalk(dev: &CrosstalkDevice, probe_a_fx: i64, shots: u32) -> CrosstalkResult {
let n = dev.n;
let mut matrix = vec![0i64; n * n];
let sweeps = 12u32;
for i in 0..n {
for j in 0..n {
let mut sweep = Vec::with_capacity(sweeps as usize);
for s in 1..=sweeps {
let a = (probe_a_fx as i128 * s as i128 / sweeps as i128) as i64;
sweep.push((a, dev.measure(i, j, a, shots)));
}
let mut best = 0i64;
let mut best_err = i128::MAX;
let c_max = 2 * CAL_ONE;
for g in 0..=200 {
let c = (c_max as i128 * g as i128 / 200) as i64;
let mut err = 0i128;
for &(a, p) in &sweep {
err += (p - sin2_fx(fmul(c, a) / 2)).unsigned_abs() as i128;
}
if err < best_err {
best_err = err;
best = c;
}
}
matrix[i * n + j] = best;
}
}
let worst = (0..n)
.flat_map(|i| (0..n).filter(move |&j| i != j).map(move |j| (i, j)))
.map(|(i, j)| matrix[i * n + j].abs())
.max()
.unwrap_or(0);
CrosstalkResult { n, matrix_fx: matrix, worst_offdiag_fx: worst }
}
#[derive(Clone, Copy, Debug)]
pub struct DragDevice {
pub beta_opt_fx: i64,
pub curvature_fx: i64,
pub seed: u64,
}
impl DragDevice {
pub fn measure_leakage(&self, beta_fx: i64, shots: u32) -> i64 {
let d = beta_fx - self.beta_opt_fx;
let l = fmul(self.curvature_fx, fmul(d, d)).clamp(0, CAL_ONE);
let mut st = self.seed.wrapping_mul(0x9E37).wrapping_add(beta_fx as u64);
let mut hits = 0u64;
for _ in 0..shots {
if ((splitmix64(&mut st) >> (64 - CAL_FRAC)) as i64) < l {
hits += 1;
}
}
((hits as i128 * CAL_ONE as i128) / shots.max(1) as i128) as i64
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DragResult {
pub beta_opt_est_fx: i64,
pub residual_leakage_fx: i64,
pub sweep: Vec<(i64, i64)>,
}
impl DragResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-drag\x01");
h.update(&self.beta_opt_est_fx.to_le_bytes());
h.update(&self.residual_leakage_fx.to_le_bytes());
for (b, l) in &self.sweep {
h.update(&b.to_le_bytes());
h.update(&l.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut ev = Vec::new();
for (b, l) in &self.sweep {
ev.extend_from_slice(&b.to_le_bytes());
ev.extend_from_slice(&l.to_le_bytes());
}
CalArtifacts {
target: "drag_beta".into(),
config_bytes: self.beta_opt_est_fx.to_le_bytes().to_vec(),
evidence_kind: "drag_leakage_sweep".into(),
evidence_bytes: ev,
summary: format!(
"beta_opt={} residual_leakage={} (2^{CAL_FRAC})",
self.beta_opt_est_fx, self.residual_leakage_fx
),
}
}
}
pub fn calibrate_drag(dev: &DragDevice, beta_min_fx: i64, beta_max_fx: i64, n: u32, shots: u32) -> DragResult {
let n = n.max(4);
let mut sweep = Vec::with_capacity(n as usize);
let (mut best_b, mut best_l) = (beta_min_fx, i64::MAX);
for i in 0..n {
let b = beta_min_fx + ((beta_max_fx - beta_min_fx) as i128 * i as i128 / (n - 1) as i128) as i64;
let l = dev.measure_leakage(b, shots);
sweep.push((b, l));
if l < best_l {
best_l = l;
best_b = b;
}
}
let step = (beta_max_fx - beta_min_fx) / (n as i64 - 1);
let refine = |lo: i64, hi: i64| -> (i64, i64) {
let (mut bb, mut bl) = (lo, i64::MAX);
for g in 0..=60 {
let b = lo + ((hi - lo) as i128 * g as i128 / 60) as i64;
let l = dev.measure_leakage(b, shots);
if l < bl {
bl = l;
bb = b;
}
}
(bb, bl)
};
let (beta, res) = refine((best_b - step).max(beta_min_fx), (best_b + step).min(beta_max_fx));
DragResult { beta_opt_est_fx: beta, residual_leakage_fx: res, sweep }
}
fn bloch_rotate(v: [i64; 3], phi: i64, alpha: i64) -> [i64; 3] {
let (n0, n1) = (cos_fx(phi), sin_fx(phi));
let (c, s) = (cos_fx(alpha), sin_fx(alpha));
let ndotv = fmul(n0, v[0]) + fmul(n1, v[1]); let cross = [fmul(n1, v[2]), -fmul(n0, v[2]), fmul(n0, v[1]) - fmul(n1, v[0])];
let n = [n0, n1, 0];
let omc = CAL_ONE - c;
let mut out = [0i64; 3];
for k in 0..3 {
out[k] = fmul(v[k], c) + fmul(cross[k], s) + fmul(n[k], fmul(ndotv, omc));
}
out
}
pub fn apply_composite(segments: &[(i64, i64)], eps_fx: i64) -> i64 {
let mut v = [0i64, 0, CAL_ONE];
for &(phi, alpha) in segments {
let a = alpha + fmul(alpha, eps_fx);
v = bloch_rotate(v, phi, a);
}
((CAL_ONE - v[2]) / 2).clamp(0, CAL_ONE)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RobustResult {
pub a1_fx: i64,
pub a2_fx: i64,
pub phi_fx: i64,
pub eps_axis_fx: Vec<i64>,
pub naive_infid_fx: Vec<i64>,
pub robust_infid_fx: Vec<i64>,
pub worst_naive_fx: i64,
pub worst_robust_fx: i64,
}
impl RobustResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-robust\x01");
for v in [self.a1_fx, self.a2_fx, self.phi_fx, self.worst_naive_fx, self.worst_robust_fx] {
h.update(&v.to_le_bytes());
}
for v in self.naive_infid_fx.iter().chain(self.robust_infid_fx.iter()) {
h.update(&v.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut cfg = Vec::new();
for v in [self.a1_fx, self.a2_fx, self.phi_fx] {
cfg.extend_from_slice(&v.to_le_bytes());
}
let mut ev = Vec::new();
for v in self.naive_infid_fx.iter().chain(self.robust_infid_fx.iter()) {
ev.extend_from_slice(&v.to_le_bytes());
}
CalArtifacts {
target: "x_pi_robust".into(),
config_bytes: cfg,
evidence_kind: "robust_pulse_infidelity".into(),
evidence_bytes: ev,
summary: format!(
"worst_naive={} worst_robust={} (2^{CAL_FRAC})",
self.worst_naive_fx, self.worst_robust_fx
),
}
}
}
pub fn optimize_robust_pulse(err_max_fx: i64, n_eps: u32) -> RobustResult {
let n_eps = n_eps.max(3);
let eps_axis: Vec<i64> = (0..n_eps)
.map(|i| -err_max_fx + (2 * err_max_fx as i128 * i as i128 / (n_eps - 1) as i128) as i64)
.collect();
let worst = |segs: &[(i64, i64)]| -> (Vec<i64>, i64) {
let mut curve = Vec::with_capacity(eps_axis.len());
let mut w = 0i64;
for &e in &eps_axis {
let inf = CAL_ONE - apply_composite(segs, e);
w = w.max(inf);
curve.push(inf);
}
(curve, w)
};
let (naive_curve, worst_naive) = worst(&[(0, PI_FX)]);
let (mut best, mut best_w) = ((PI_FX / 2, PI_FX, 0i64), i64::MAX);
let a1_lo = PI_FX / 4;
let quarter = PI_FX / 2;
for i in 0..=20 {
let a1 = a1_lo + ((PI_FX - a1_lo) as i128 * i as i128 / 20) as i64;
for j in 0..=20 {
let a2 = quarter + ((3 * PI_FX / 2 - quarter) as i128 * j as i128 / 20) as i64;
for k in 0..=24 {
let phi = (TWO_PI_FX as i128 * k as i128 / 24) as i64;
let segs = [(0, a1), (phi, a2), (0, a1)];
if (CAL_ONE - apply_composite(&segs, 0)).abs() > CAL_ONE / 100 {
continue; }
let (_, w) = worst(&segs);
if w < best_w {
best_w = w;
best = (a1, a2, phi);
}
}
}
}
let best_segs = [(0, best.0), (best.2, best.1), (0, best.0)];
let (robust_curve, worst_robust) = worst(&best_segs);
RobustResult {
a1_fx: best.0,
a2_fx: best.1,
phi_fx: best.2,
eps_axis_fx: eps_axis,
naive_infid_fx: naive_curve,
robust_infid_fx: robust_curve,
worst_naive_fx: worst_naive,
worst_robust_fx: worst_robust,
}
}
#[cfg(feature = "quantum_ops")]
mod seal_any {
use super::CalArtifacts;
use crate::quantum_ops::{content_hash, CalibrationReceipt, Evidence, GrantRef};
use ed25519_dalek::SigningKey;
#[allow(clippy::too_many_arguments)]
pub fn seal_artifacts(
signer: &SigningKey,
signer_id: impl Into<String>,
device_id: impl Into<String>,
art: &CalArtifacts,
joules_micro: u64,
grant: GrantRef,
parent: Option<[u8; 32]>,
) -> CalibrationReceipt {
let ev = vec![Evidence {
kind: art.evidence_kind.clone(),
blob_hash: content_hash(&art.evidence_bytes),
summary: art.summary.clone(),
}];
CalibrationReceipt::seal(
signer, signer_id, device_id, art.target.clone(),
content_hash(&art.config_bytes), ev, joules_micro, grant, parent,
)
}
}
#[cfg(feature = "quantum_ops")]
pub use seal_any::seal_artifacts;
#[cfg(feature = "quantum_ops")]
mod campaign {
use super::*;
use crate::quantum_ops::{CalibrationReceipt, GrantRef};
use ed25519_dalek::SigningKey;
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
pub enum CalStep {
Rabi(Device, TuneConfig),
Ramsey(RamseyDevice, RamseyConfig),
Rb(RbDevice, RbConfig),
Readout(ReadoutDevice, u32),
Charge(ChargeDevice, (i32, i32), ChargeScanConfig),
}
impl CalStep {
fn run(&self) -> (CalArtifacts, &'static str) {
match self {
CalStep::Rabi(d, c) => (calibrate_rabi(d, c).artifacts(), "rabi"),
CalStep::Ramsey(d, c) => (calibrate_ramsey(d, c).artifacts(), "ramsey"),
CalStep::Rb(d, c) => (calibrate_rb(d, c).artifacts(), "rb"),
CalStep::Readout(d, n) => (calibrate_readout(d, *n).artifacts(), "readout"),
CalStep::Charge(d, t, c) => (tune_charge_state(d, *t, c).artifacts(), "charge"),
}
}
}
#[derive(Clone, Debug)]
pub struct Campaign {
pub receipts: Vec<CalibrationReceipt>,
pub kinds: Vec<String>,
}
impl Campaign {
pub fn campaign_hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:quantum-cal-campaign\x01");
for r in &self.receipts {
h.update(&r.receipt_hash());
}
*h.finalize().as_bytes()
}
pub fn verify_chain(&self) -> bool {
let mut prev: Option<[u8; 32]> = None;
for r in &self.receipts {
if !r.verify() || r.parent_receipt_hash != prev {
return false;
}
prev = Some(r.receipt_hash());
}
true
}
}
pub fn run_campaign(
signer: &SigningKey,
signer_id: &str,
device_id: &str,
joules_each: u64,
grant: &GrantRef,
steps: &[CalStep],
) -> Campaign {
let mut receipts = Vec::with_capacity(steps.len());
let mut kinds = Vec::with_capacity(steps.len());
let mut parent: Option<[u8; 32]> = None;
for step in steps {
let (art, kind) = step.run();
let r = seal_artifacts(signer, signer_id, device_id, &art, joules_each, grant.clone(), parent);
parent = Some(r.receipt_hash());
kinds.push(kind.to_string());
receipts.push(r);
}
Campaign { receipts, kinds }
}
}
#[cfg(feature = "quantum_ops")]
pub use campaign::{run_campaign, CalStep, Campaign};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sine_is_accurate_enough() {
assert_eq!(sin2_fx(0), 0);
let at_half_pi = sin2_fx(PI_FX / 2);
assert!((at_half_pi - CAL_ONE).abs() < CAL_ONE / 200, "sin²(π/2)≈1, got {at_half_pi}");
let at_quarter = sin2_fx(PI_FX / 4);
assert!((at_quarter - CAL_ONE / 2).abs() < CAL_ONE / 100, "sin²(π/4)≈0.5, got {at_quarter}");
}
#[test]
fn tune_up_finds_the_true_pi_amplitude() {
let a_pi_true = (0.80 * CAL_ONE as f64) as i64;
let device = Device { a_pi_fx: a_pi_true, seed: 0xCAFE };
let cfg = TuneConfig { a_max_fx: (1.6 * CAL_ONE as f64) as i64, ..Default::default() };
let r = calibrate_rabi(&device, &cfg);
let tol = cfg.a_max_fx / (cfg.n_coarse as i64 - 1) / (cfg.n_fine as i64 - 1) + CAL_ONE / 50;
assert!(
(r.a_pi_est_fx - a_pi_true).abs() <= tol,
"estimate {} vs true {} (tol {tol})",
r.a_pi_est_fx, a_pi_true
);
assert!(r.peak_prob_fx > CAL_ONE - CAL_ONE / 20, "peak prob {} not ~1", r.peak_prob_fx);
}
#[test]
fn calibration_is_byte_exact_deterministic() {
let device = Device { a_pi_fx: (0.73 * CAL_ONE as f64) as i64, seed: 7 };
let cfg = TuneConfig::default();
let a = calibrate_rabi(&device, &cfg);
let b = calibrate_rabi(&device, &cfg);
assert_eq!(a, b);
assert_eq!(a.hash(), b.hash(), "same (device,cfg) must give the same tune-up hash");
}
#[test]
fn different_devices_tune_differently() {
let d1 = Device { a_pi_fx: (0.5 * CAL_ONE as f64) as i64, seed: 1 };
let d2 = Device { a_pi_fx: (1.1 * CAL_ONE as f64) as i64, seed: 1 };
let cfg = TuneConfig { a_max_fx: 2 * CAL_ONE, ..Default::default() };
let r1 = calibrate_rabi(&d1, &cfg);
let r2 = calibrate_rabi(&d2, &cfg);
assert!(r1.a_pi_est_fx < r2.a_pi_est_fx);
}
#[cfg(feature = "quantum_ops")]
#[test]
fn calibrate_and_seal_produces_a_verifying_receipt() {
use crate::quantum_ops::GrantRef;
use ed25519_dalek::SigningKey;
let device = Device { a_pi_fx: (0.9 * CAL_ONE as f64) as i64, seed: 0xABCD };
let cfg = TuneConfig::default();
let grant = GrantRef {
grant_hash: [0u8; 32],
capability: "quantum.calibrate".into(),
joule_ceiling_micro: 10_000_000,
funds_ceiling: None,
};
let (r, receipt) = calibrate_and_seal(
&SigningKey::from_bytes(&[9u8; 32]), "did:key:lab", "sim:transmon:q0", "q0",
&device, &cfg, 3_500_000, grant, None,
);
assert!(receipt.verify());
assert!(receipt.evidence_matches(0, &sweep_bytes(&r)));
let r2 = calibrate_rabi(&device, &cfg);
assert!(receipt.evidence_matches(0, &sweep_bytes(&r2)));
}
fn fx(x: f64) -> i64 {
(x * CAL_ONE as f64) as i64
}
#[test]
fn ramsey_recovers_detuning_and_t2_deterministically() {
let dev = RamseyDevice { omega_fx: fx(3.0), t2_fx: fx(3.0), seed: 0x1234 };
let cfg = RamseyConfig {
tau_max_fx: fx(6.0), n_points: 80, shots: 4000,
omega_max_fx: fx(6.0), t2_max_fx: fx(6.0), n_grid: 60,
};
let r = calibrate_ramsey(&dev, &cfg);
assert!((r.omega_est_fx - fx(3.0)).abs() < fx(0.4), "omega {} vs 3.0", r.omega_est_fx);
assert!((r.t2_est_fx - fx(3.0)).abs() < fx(0.8), "t2 {} vs 3.0", r.t2_est_fx);
assert_eq!(r, calibrate_ramsey(&dev, &cfg));
assert_eq!(r.hash(), calibrate_ramsey(&dev, &cfg).hash());
}
#[test]
fn rb_recovers_gate_fidelity_deterministically() {
let dev = RbDevice { epsilon_fx: fx(0.01), seed: 0xBEEF };
let cfg = RbConfig {
lengths: [1, 2, 4, 8, 16, 32, 64, 128], k_sequences: 20, shots: 100, n_grid: 300,
};
let r = calibrate_rb(&dev, &cfg);
assert!((r.p_est_fx - fx(0.98)).abs() < fx(0.02), "p {} vs 0.98", r.p_est_fx);
assert!((r.fidelity_fx - fx(0.99)).abs() < fx(0.01), "F {} vs 0.99", r.fidelity_fx);
assert_eq!(r, calibrate_rb(&dev, &cfg));
}
#[test]
fn readout_discriminates_well_separated_blobs_deterministically() {
let dev = ReadoutDevice { s0_fx: fx(-2.0), s1_fx: fx(2.0), sigma_fx: fx(1.0), seed: 42 };
let r = calibrate_readout(&dev, 500);
assert!(r.fidelity_fx > fx(0.9), "readout fidelity {} not > 0.9", r.fidelity_fx);
assert!(r.mean0_fx < r.threshold_fx && r.threshold_fx < r.mean1_fx);
assert_eq!(r, calibrate_readout(&dev, 500));
assert_eq!(r.hash(), calibrate_readout(&dev, 500).hash());
}
#[cfg(feature = "quantum_ops")]
#[test]
fn every_routine_seals_a_verifying_receipt() {
use crate::quantum_ops::GrantRef;
use ed25519_dalek::SigningKey;
let signer = SigningKey::from_bytes(&[5u8; 32]);
let grant = GrantRef::unbounded("quantum.calibrate");
let ram = calibrate_ramsey(
&RamseyDevice { omega_fx: fx(2.0), t2_fx: fx(4.0), seed: 1 },
&RamseyConfig { tau_max_fx: fx(8.0), n_points: 60, shots: 3000, omega_max_fx: fx(6.0), t2_max_fx: fx(8.0), n_grid: 50 },
);
let rb = calibrate_rb(
&RbDevice { epsilon_fx: fx(0.005), seed: 2 },
&RbConfig { lengths: [1, 2, 4, 8, 16, 32, 64, 128], k_sequences: 10, shots: 100, n_grid: 200 },
);
let ro = calibrate_readout(&ReadoutDevice { s0_fx: fx(-1.5), s1_fx: fx(1.5), sigma_fx: fx(1.0), seed: 3 }, 400);
for art in [ram.artifacts(), rb.artifacts(), ro.artifacts()] {
let r = seal_artifacts(&signer, "did:key:lab", "sim:transmon:q0", &art, 1_000_000, grant.clone(), None);
assert!(r.verify(), "receipt for {} must verify", art.evidence_kind);
assert!(r.evidence_matches(0, &art.evidence_bytes));
}
}
fn dot() -> ChargeDevice {
ChargeDevice {
alpha_l_fx: fx(0.4), alpha_r_fx: fx(0.4),
beta_lr_fx: fx(0.1), beta_rl_fx: fx(0.1),
off_l_fx: 0, off_r_fx: 0,
}
}
#[test]
fn charge_tune_is_byte_exact_deterministic() {
let (d, cfg) = (dot(), ChargeScanConfig::default());
let a = tune_charge_state(&d, (1, 1), &cfg);
let b = tune_charge_state(&d, (1, 1), &cfg);
assert_eq!(a, b);
assert_eq!(a.hash(), b.hash());
}
#[test]
fn charge_tune_operating_point_reads_the_target() {
let (d, cfg) = (dot(), ChargeScanConfig::default());
for target in [(1, 1), (2, 1), (1, 2), (2, 2)] {
let r = tune_charge_state(&d, target, &cfg);
assert!(r.found, "target {target:?} not in the scan window");
assert_eq!(
d.charge_state(r.v_l_op_fx, r.v_r_op_fx),
target,
"operating point for {target:?} reads the wrong charge state"
);
}
}
#[test]
fn charge_tune_higher_target_needs_higher_voltage() {
let (d, cfg) = (dot(), ChargeScanConfig::default());
let r1 = tune_charge_state(&d, (1, 1), &cfg);
let r2 = tune_charge_state(&d, (2, 2), &cfg);
assert!(r2.v_l_op_fx > r1.v_l_op_fx && r2.v_r_op_fx > r1.v_r_op_fx);
}
#[cfg(feature = "quantum_ops")]
#[test]
fn charge_tune_seals_a_verifying_receipt() {
use crate::quantum_ops::GrantRef;
use ed25519_dalek::SigningKey;
let r = tune_charge_state(&dot(), (1, 1), &ChargeScanConfig::default());
let art = r.artifacts();
let rec = seal_artifacts(
&SigningKey::from_bytes(&[6u8; 32]), "did:key:lab", "sim:double-dot:d0",
&art, 2_000_000, GrantRef::unbounded("quantum.calibrate"), None,
);
assert!(rec.verify());
assert!(rec.evidence_matches(0, &art.evidence_bytes));
}
#[cfg(feature = "quantum_ops")]
#[test]
fn campaign_chains_receipts_into_a_signed_lineage() {
use crate::quantum_ops::GrantRef;
use ed25519_dalek::SigningKey;
let signer = SigningKey::from_bytes(&[7u8; 32]);
let grant = GrantRef::unbounded("quantum.calibrate");
let steps = vec![
CalStep::Readout(
ReadoutDevice { s0_fx: fx(-1.5), s1_fx: fx(1.5), sigma_fx: fx(1.0), seed: 1 },
400,
),
CalStep::Rabi(Device { a_pi_fx: fx(0.8), seed: 2 }, TuneConfig::default()),
CalStep::Charge(dot(), (1, 1), ChargeScanConfig::default()),
];
let camp = run_campaign(&signer, "did:key:lab", "sim:q0", 1_000_000, &grant, &steps);
assert_eq!(camp.receipts.len(), 3);
assert_eq!(camp.kinds, ["readout", "rabi", "charge"]);
assert!(camp.verify_chain(), "the campaign lineage must verify");
let camp2 = run_campaign(&signer, "did:key:lab", "sim:q0", 1_000_000, &grant, &steps);
assert_eq!(camp.campaign_hash(), camp2.campaign_hash());
}
#[cfg(feature = "quantum_ops")]
#[test]
fn campaign_tamper_breaks_the_chain() {
use crate::quantum_ops::GrantRef;
use ed25519_dalek::SigningKey;
let steps = vec![
CalStep::Rabi(Device { a_pi_fx: fx(0.8), seed: 2 }, TuneConfig::default()),
CalStep::Rb(
RbDevice { epsilon_fx: fx(0.005), seed: 3 },
RbConfig { lengths: [1, 2, 4, 8, 16, 32, 64, 128], k_sequences: 8, shots: 80, n_grid: 150 },
),
];
let mut camp = run_campaign(
&SigningKey::from_bytes(&[8u8; 32]), "m", "d", 10,
&GrantRef::unbounded("quantum.calibrate"), &steps,
);
camp.receipts[1].parent_receipt_hash = Some([0u8; 32]);
assert!(!camp.verify_chain());
}
#[test]
fn cr_recovers_both_conditional_amplitudes() {
let dev = CrDevice { a_pi0_fx: fx(0.70), a_pi1_fx: fx(0.95), seed: 11 };
let cfg = CrConfig { a_max_fx: fx(1.8), ..Default::default() };
let r = calibrate_cr(&dev, &cfg);
assert!((r.a_pi0_est_fx - fx(0.70)).abs() < CAL_ONE / 20, "a0 {}", r.a_pi0_est_fx);
assert!((r.a_pi1_est_fx - fx(0.95)).abs() < CAL_ONE / 20, "a1 {}", r.a_pi1_est_fx);
assert!(r.zx_shift_fx > 0);
assert_eq!(r, calibrate_cr(&dev, &cfg));
}
#[test]
fn crosstalk_recovers_the_matrix() {
let dev = CrosstalkDevice {
n: 2,
matrix_fx: vec![fx(1.0), fx(0.12), fx(0.15), fx(1.0)],
seed: 5,
};
let r = characterize_crosstalk(&dev, fx(3.0), 4000);
for k in 0..4 {
assert!(
(r.matrix_fx[k] - dev.matrix_fx[k]).abs() < CAL_ONE / 10,
"coeff {k}: got {} want {}",
r.matrix_fx[k], dev.matrix_fx[k]
);
}
assert!(r.worst_offdiag_fx > 0);
assert_eq!(r, characterize_crosstalk(&dev, fx(3.0), 4000));
}
#[test]
fn drag_finds_the_leakage_minimum() {
let dev = DragDevice { beta_opt_fx: fx(0.5), curvature_fx: fx(2.0), seed: 9 };
let r = calibrate_drag(&dev, fx(-1.0), fx(2.0), 41, 3000);
assert!((r.beta_opt_est_fx - fx(0.5)).abs() < CAL_ONE / 12, "beta {}", r.beta_opt_est_fx);
assert!(r.residual_leakage_fx < CAL_ONE / 20, "residual {}", r.residual_leakage_fx);
assert_eq!(r, calibrate_drag(&dev, fx(-1.0), fx(2.0), 41, 3000));
}
#[cfg(feature = "quantum_ops")]
#[test]
fn new_routines_seal_verifying_receipts() {
use crate::quantum_ops::GrantRef;
use ed25519_dalek::SigningKey;
let signer = SigningKey::from_bytes(&[4u8; 32]);
let grant = GrantRef::unbounded("quantum.calibrate");
let cr = calibrate_cr(&CrDevice { a_pi0_fx: fx(0.7), a_pi1_fx: fx(0.95), seed: 1 }, &CrConfig::default());
let xt = characterize_crosstalk(&CrosstalkDevice { n: 2, matrix_fx: vec![fx(1.0), fx(0.12), fx(0.15), fx(1.0)], seed: 2 }, fx(3.0), 2000);
let dg = calibrate_drag(&DragDevice { beta_opt_fx: fx(0.5), curvature_fx: fx(2.0), seed: 3 }, fx(-1.0), fx(2.0), 31, 2000);
for art in [cr.artifacts(), xt.artifacts(), dg.artifacts()] {
let r = seal_artifacts(&signer, "did:key:lab", "sim:q0", &art, 1_000_000, grant.clone(), None);
assert!(r.verify(), "receipt for {} must verify", art.evidence_kind);
assert!(r.evidence_matches(0, &art.evidence_bytes));
}
}
#[test]
fn sin_cos_are_accurate() {
assert!(sin_fx(0).abs() < CAL_ONE / 400);
assert!((sin_fx(PI_FX / 2) - CAL_ONE).abs() < CAL_ONE / 200);
assert!(sin_fx(PI_FX).abs() < CAL_ONE / 200);
assert!((cos_fx(0) - CAL_ONE).abs() < CAL_ONE / 200);
assert!((sin_fx(PI_FX + PI_FX / 2) + CAL_ONE).abs() < CAL_ONE / 200); }
#[test]
fn naive_pi_pulse_transfers_at_nominal() {
let p = apply_composite(&[(0, PI_FX)], 0);
assert!((p - CAL_ONE).abs() < CAL_ONE / 50, "naive P(0) = {p}");
}
#[test]
fn robust_pulse_beats_naive() {
let r = optimize_robust_pulse(fx(0.3), 13);
assert!(r.worst_naive_fx > CAL_ONE / 12, "naive worst {} too low", r.worst_naive_fx);
assert!(
r.worst_robust_fx * 2 < r.worst_naive_fx,
"robust {} not better than naive {}",
r.worst_robust_fx, r.worst_naive_fx
);
assert_eq!(r, optimize_robust_pulse(fx(0.3), 13)); }
#[cfg(feature = "quantum_ops")]
#[test]
fn robust_pulse_seals_a_receipt() {
use crate::quantum_ops::GrantRef;
use ed25519_dalek::SigningKey;
let r = optimize_robust_pulse(fx(0.3), 13);
let art = r.artifacts();
let rec = seal_artifacts(
&SigningKey::from_bytes(&[3u8; 32]), "did:key:lab", "sim:q0", &art,
5_000_000, GrantRef::unbounded("quantum.calibrate"), None,
);
assert!(rec.verify());
assert!(rec.evidence_matches(0, &art.evidence_bytes));
}
}