use crate::quantum_cal::{cos_fx, exp_neg_fx, seal_artifacts, sin_fx, CalArtifacts, CAL_FRAC, CAL_ONE};
use crate::quantum_ops::{content_hash, CalibrationReceipt, GrantRef};
use ed25519_dalek::SigningKey;
const ONE: i64 = CAL_ONE;
const FRAC: u32 = CAL_FRAC;
const PI_FX: i64 = 3_294_199; const INV_PI_FX: i64 = 333_772;
#[inline]
fn fmul(a: i64, b: i64) -> i64 {
((a as i128 * b as i128) >> FRAC) as i64
}
#[inline]
fn fdiv(a: i64, b: i64) -> i64 {
if b == 0 {
return 0;
}
(((a as i128) << FRAC) / b as i128) as i64
}
fn ln_fx(x: i64) -> i64 {
if x <= 0 {
return -20 * ONE; }
let z = fdiv(x - ONE, x + ONE); let z2 = fmul(z, z);
let mut term = z;
let mut acc = 0i64;
let mut k = 1i64;
for _ in 0..12 {
acc += term / k;
term = fmul(term, z2);
k += 2;
}
2 * acc
}
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, Debug)]
pub struct NoiseGrid {
pub omega: Vec<i64>,
pub dw: i64,
}
impl NoiseGrid {
pub fn linear(w_min: f64, w_max: f64, n: usize) -> NoiseGrid {
let wmin = (w_min * ONE as f64) as i64;
let wmax = (w_max * ONE as f64) as i64;
let dw = (wmax - wmin) / (n as i64 - 1).max(1);
let omega = (0..n).map(|i| wmin + i as i64 * dw).collect();
NoiseGrid { omega, dw }
}
}
pub fn psd_model(g: &NoiseGrid, a_over_f: f64, bump: f64, w0: f64, gamma: f64) -> Vec<i64> {
let a = (a_over_f * ONE as f64) as i64;
let h = (bump * ONE as f64) as i64;
let w0f = (w0 * ONE as f64) as i64;
let gf = (gamma * ONE as f64) as i64;
let g2 = fmul(gf, gf);
g.omega
.iter()
.map(|&w| {
let one_over_f = fdiv(a, w); let dwn = w - w0f;
let lor = fmul(h, fdiv(g2, fmul(dwn, dwn) + g2)); one_over_f + lor
})
.collect()
}
fn hash_psd(psd: &[i64]) -> [u8; 32] {
let mut b = Vec::with_capacity(psd.len() * 8 + 8);
b.extend_from_slice(b"wai:qc-psd\x01");
for &v in psd {
b.extend_from_slice(&v.to_le_bytes());
}
content_hash(&b)
}
pub fn dd_free() -> Vec<i64> {
Vec::new()
}
pub fn dd_hahn() -> Vec<i64> {
vec![ONE / 2]
}
pub fn dd_cpmg(n: usize) -> Vec<i64> {
(1..=n)
.map(|k| ((2 * k as i64 - 1) * ONE) / (2 * n as i64))
.collect()
}
pub fn dd_udd(n: usize) -> Vec<i64> {
(1..=n)
.map(|k| {
let theta = (PI_FX * k as i64) / (2 * n as i64 + 2);
let s = sin_fx(theta);
fmul(s, s)
})
.collect()
}
pub fn filter_kernel(pulses: &[i64], g: &NoiseGrid) -> Vec<i64> {
let mut t = Vec::with_capacity(pulses.len() + 2);
t.push(0i64);
t.extend_from_slice(pulses);
t.push(ONE);
g.omega
.iter()
.map(|&w| {
let (mut re, mut im) = (0i64, 0i64);
for k in 0..t.len() - 1 {
let sign = if k % 2 == 0 { 1i64 } else { -1 };
let p1 = fmul(w, t[k + 1]);
let p0 = fmul(w, t[k]);
re += sign * (cos_fx(p1) - cos_fx(p0));
im += sign * (sin_fx(p1) - sin_fx(p0));
}
let mag2 = re as i128 * re as i128 + im as i128 * im as i128;
let w2 = w as i128 * w as i128;
let yy = if w2 == 0 { 0 } else { ((mag2 * ONE as i128) / w2) as i64 };
fmul(fmul(yy, g.dw), INV_PI_FX)
})
.collect()
}
pub fn overlap(psd: &[i64], kern: &[i64]) -> i64 {
psd.iter().zip(kern).map(|(&s, &k)| fmul(s, k)).sum()
}
pub fn coherence(chi: i64) -> i64 {
exp_neg_fx(chi)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpectroResult {
pub omega: Vec<i64>,
pub psd_true: Vec<i64>,
pub psd_est: Vec<i64>,
pub n_sequences: usize,
pub error_fx: i64,
}
pub fn reconstruct_psd(
g: &NoiseGrid,
psd_true: &[i64],
n_max: usize,
shots: u32,
iters: u32,
seed: u64,
) -> SpectroResult {
let kernels: Vec<Vec<i64>> = (1..=n_max).map(|n| filter_kernel(&dd_cpmg(n), g)).collect();
let mut chi_meas = Vec::with_capacity(n_max);
for (idx, kern) in kernels.iter().enumerate() {
let chi_true = overlap(psd_true, kern);
let c_true = coherence(chi_true);
let mut st = seed.wrapping_mul(0x100_0001).wrapping_add(idx as u64 + 1);
let p_plus = (ONE + c_true) / 2;
let mut hits = 0u64;
for _ in 0..shots {
let r = (splitmix64(&mut st) >> (64 - FRAC)) as i64;
if r < p_plus {
hits += 1;
}
}
let c_hat = (2 * (hits as i128 * ONE as i128) / shots.max(1) as i128 - ONE as i128) as i64;
let c_hat = c_hat.clamp(ONE / 100, ONE);
chi_meas.push(-ln_fx(c_hat));
}
let ng = g.omega.len();
let denom: Vec<i64> = (0..ng).map(|i| kernels.iter().map(|k| k[i]).sum()).collect();
let mut est = vec![ONE / 10; ng]; for _ in 0..iters {
let pred: Vec<i64> = kernels.iter().map(|k| overlap(&est, k)).collect();
let ratio: Vec<i64> = pred
.iter()
.zip(&chi_meas)
.map(|(&p, &m)| if p <= 0 { ONE } else { fdiv(m, p) })
.collect();
for i in 0..ng {
if denom[i] <= 0 {
continue;
}
let num: i64 = kernels.iter().zip(&ratio).map(|(k, &r)| fmul(k[i], r)).sum();
let corr = fdiv(num, denom[i]);
est[i] = fmul(est[i], corr).max(0);
}
}
let error_fx = {
let s: i64 = psd_true
.iter()
.zip(&est)
.map(|(&a, &b)| (a - b).abs())
.sum();
s / ng.max(1) as i64
};
SpectroResult {
omega: g.omega.clone(),
psd_true: psd_true.to_vec(),
psd_est: est,
n_sequences: n_max,
error_fx,
}
}
impl SpectroResult {
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:qc-spectro\x01");
for &v in &self.psd_est {
h.update(&v.to_le_bytes());
}
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut cfg = Vec::new();
for &v in &self.psd_est {
cfg.extend_from_slice(&v.to_le_bytes());
}
let mut ev = Vec::new();
for &v in &self.psd_true {
ev.extend_from_slice(&v.to_le_bytes());
}
CalArtifacts {
target: "noise-psd:q0".into(),
config_bytes: cfg,
evidence_kind: "dd_noise_spectroscopy".into(),
evidence_bytes: ev,
summary: format!("PSD reconstructed from {} CPMG filters", self.n_sequences),
}
}
pub fn seal(&self, signer: &SigningKey, signer_id: &str, joules_micro: u64, grant: GrantRef) -> CalibrationReceipt {
seal_artifacts(signer, signer_id, "sim:transmon:q0", &self.artifacts(), joules_micro, grant, None)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RobustResult {
pub pulses: Vec<i64>,
pub chi_opt: i64,
pub chi_cpmg: i64,
pub coh_opt: i64,
pub coh_cpmg: i64,
pub psd_hash: [u8; 32],
pub kern_opt: Vec<i64>,
pub kern_cpmg: Vec<i64>,
}
pub fn optimize_dd(g: &NoiseGrid, psd: &[i64], n: usize, rounds: u32) -> RobustResult {
let cpmg = dd_cpmg(n);
let kern_cpmg = filter_kernel(&cpmg, g);
let chi_cpmg = overlap(psd, &kern_cpmg);
let mut pos = cpmg.clone();
let chi_of = |p: &[i64]| overlap(psd, &filter_kernel(p, g));
let mut best = chi_of(&pos);
let mut step = ONE / 8;
for _ in 0..rounds {
for i in 0..n {
let lo = if i == 0 { ONE / 200 } else { pos[i - 1] + ONE / 200 };
let hi = if i == n - 1 { ONE - ONE / 200 } else { pos[i + 1] - ONE / 200 };
for &dir in &[-1i64, 1] {
let cand = (pos[i] + dir * step).clamp(lo, hi);
if cand == pos[i] {
continue;
}
let save = pos[i];
pos[i] = cand;
let c = chi_of(&pos);
if c < best {
best = c;
} else {
pos[i] = save;
}
}
}
step = (step * 3) / 5; if step < ONE / 2000 {
break;
}
}
let kern_opt = filter_kernel(&pos, g);
let chi_opt = overlap(psd, &kern_opt);
RobustResult {
pulses: pos,
chi_opt,
chi_cpmg,
coh_opt: coherence(chi_opt),
coh_cpmg: coherence(chi_cpmg),
psd_hash: hash_psd(psd),
kern_opt,
kern_cpmg,
}
}
impl RobustResult {
pub fn improvement_fx(&self) -> i64 {
fdiv(self.chi_cpmg, self.chi_opt.max(1))
}
pub fn hash(&self) -> [u8; 32] {
let mut h = blake3::Hasher::new();
h.update(b"wai:qc-robust-ff\x01");
for &p in &self.pulses {
h.update(&p.to_le_bytes());
}
h.update(&self.chi_opt.to_le_bytes());
*h.finalize().as_bytes()
}
pub fn artifacts(&self) -> CalArtifacts {
let mut cfg = Vec::new();
for &p in &self.pulses {
cfg.extend_from_slice(&p.to_le_bytes());
}
let mut ev = Vec::new();
ev.extend_from_slice(&self.psd_hash);
ev.extend_from_slice(&self.chi_opt.to_le_bytes());
CalArtifacts {
target: "robust-dd:q0".into(),
config_bytes: cfg,
evidence_kind: "filter_function_robust_control".into(),
evidence_bytes: ev,
summary: format!(
"{}-pulse DD, χ {}→{} vs CPMG (filter dodges the pinned PSD)",
self.pulses.len(),
self.chi_cpmg,
self.chi_opt
),
}
}
pub fn seal(&self, signer: &SigningKey, signer_id: &str, joules_micro: u64, grant: GrantRef) -> CalibrationReceipt {
seal_artifacts(signer, signer_id, "sim:transmon:q0", &self.artifacts(), joules_micro, grant, None)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key(s: u8) -> SigningKey {
SigningKey::from_bytes(&[s; 32])
}
fn grid() -> NoiseGrid {
NoiseGrid::linear(0.5, 90.0, 180)
}
fn f(v: i64) -> f64 {
v as f64 / ONE as f64
}
#[test]
fn ln_and_coherence_roundtrip() {
for &chi in &[ONE / 10, ONE / 2, ONE, 2 * ONE] {
let c = coherence(chi);
let back = -ln_fx(c);
assert!((back - chi).abs() < ONE / 20, "χ {} → C {} → {}", f(chi), f(c), f(back));
}
}
#[test]
fn more_pulses_suppress_low_freq_noise() {
let g = grid();
let psd = psd_model(&g, 0.02, 0.0, 0.0, 1.0);
let chi_free = overlap(&psd, &filter_kernel(&dd_free(), &g));
let chi_hahn = overlap(&psd, &filter_kernel(&dd_hahn(), &g));
let chi_cpmg8 = overlap(&psd, &filter_kernel(&dd_cpmg(8), &g));
assert!(chi_hahn < chi_free, "echo beats free: {} vs {}", chi_hahn, chi_free);
assert!(chi_cpmg8 < chi_hahn, "CPMG-8 beats echo: {} vs {}", chi_cpmg8, chi_hahn);
}
#[test]
fn spectroscopy_recovers_hidden_bump() {
let g = grid();
let psd = psd_model(&g, 0.015, 0.5, 40.0, 6.0);
let r = reconstruct_psd(&g, &psd, 20, 40_000, 40, 0xC0FFEE);
let mean_psd: i64 = psd.iter().sum::<i64>() / psd.len() as i64;
assert!(
r.error_fx < mean_psd,
"reconstruction error {} should be below mean PSD {}",
r.error_fx, mean_psd
);
assert!(r.psd_est.iter().all(|&v| v >= 0));
}
#[test]
fn spectroscopy_is_deterministic() {
let g = grid();
let psd = psd_model(&g, 0.02, 0.3, 30.0, 5.0);
let a = reconstruct_psd(&g, &psd, 16, 20_000, 30, 7);
let b = reconstruct_psd(&g, &psd, 16, 20_000, 30, 7);
assert_eq!(a, b);
}
#[test]
fn robust_control_beats_cpmg() {
let g = grid();
let psd = psd_model(&g, 0.04, 0.0, 0.0, 1.0);
let r = optimize_dd(&g, &psd, 6, 30);
assert!(r.chi_opt <= r.chi_cpmg, "optimised {} must not exceed CPMG {}", r.chi_opt, r.chi_cpmg);
assert!(r.coh_opt >= r.coh_cpmg);
}
#[test]
fn results_seal_and_verify() {
let g = grid();
let psd = psd_model(&g, 0.02, 0.4, 35.0, 5.0);
let spec = reconstruct_psd(&g, &psd, 16, 20_000, 30, 1);
let sr = spec.seal(&key(1), "did:key:lab", 1_000_000, GrantRef::unbounded("quantum.calibrate"));
assert!(sr.verify());
let rob = optimize_dd(&g, &psd, 6, 25);
let rr = rob.seal(&key(2), "did:key:lab", 1_000_000, GrantRef::unbounded("quantum.calibrate"));
assert!(rr.verify());
assert!(rob.artifacts().evidence_bytes.starts_with(&hash_psd(&psd)));
}
}