| Crates.io | ruqu-quantum-monitor |
| lib.rs | ruqu-quantum-monitor |
| version | 0.1.32 |
| created_at | 2026-01-18 00:45:37.042205+00 |
| updated_at | 2026-01-18 00:45:37.042205+00 |
| description | Anytime-Valid Quantum Kernel Coherence Monitor (AV-QKCM) - Sequential MMD testing with e-values for quantum syndrome distribution drift detection |
| homepage | https://ruv.io |
| repository | https://github.com/ruvnet/ruvector |
| max_upload_size | |
| id | 2051514 |
| size | 204,341 |
Anytime-Valid Quantum Kernel Coherence Monitor (AV-QKCM) - Sequential hypothesis testing with quantum-inspired kernels
ruvector-quantum-monitor implements anytime-valid statistical monitoring for quantum coherence and distribution drift detection. It combines:
SharedMonitor for multi-agent coordinationAdd to your Cargo.toml:
[dependencies]
ruvector-quantum-monitor = "0.1"
use ruqu_quantum_monitor::{
QuantumCoherenceMonitor, MonitorConfig, QuantumKernelConfig
};
// Create monitor with default config
let config = MonitorConfig::default();
let mut monitor = QuantumCoherenceMonitor::new(config)?;
// Set baseline distribution from calibration data
let baseline_data = /* calibration measurements */;
monitor.set_baseline(&baseline_data)?;
// Monitor incoming observations
for observation in live_stream {
let result = monitor.observe(&observation)?;
if result.drift_detected {
println!("ALERT: Drift detected! P-value: {:.4}", result.p_value);
println!("Confidence interval: [{:.4}, {:.4}]",
result.confidence_interval.lower,
result.confidence_interval.upper);
}
}
┌─────────────────────────────────────────────────────────────────┐
│ AV-QKCM Pipeline │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Baseline ┌──────────────┐ ┌──────────────┐ │
│ Data ───────►│ Quantum │───►│ Baseline │ │
│ │ Feature Map │ │ Kernel Stats │ │
│ └──────────────┘ └──────┬───────┘ │
│ │ │
│ Streaming ┌──────────────┐ ┌──────▼───────┐ │
│ Observation─►│ Quantum │───►│ MMD │ │
│ │ Kernel │ │ Estimator │ │
│ └──────────────┘ └──────┬───────┘ │
│ │ │
│ ┌──────▼───────┐ ┌─────────┐ │
│ │ E-Value │─►│ Decision│ │
│ │ Test │ │ + CI │ │
│ └──────────────┘ └─────────┘ │
└─────────────────────────────────────────────────────────────────┘
| Module | Description |
|---|---|
kernel |
Quantum-inspired feature maps and kernel computation |
evalue |
E-value based sequential hypothesis testing |
confidence |
Time-uniform confidence sequences |
monitor |
Main coherence monitoring interface |
error |
Comprehensive error types |
use ruqu_quantum_monitor::{
MonitorConfig, QuantumKernelConfig, EValueConfig, ConfidenceSequenceConfig
};
let config = MonitorConfig {
kernel: QuantumKernelConfig {
n_qubits: 4, // Feature space dimension 2^4 = 16
n_layers: 2, // Quantum circuit depth
sigma: 1.0, // Bandwidth parameter
use_entanglement: true,
seed: Some(42), // Reproducibility
},
evalue: EValueConfig {
alpha: 0.05, // Significance level
bet_fraction: 0.5, // Kelly criterion fraction
adaptive_betting: true,
min_samples: 10,
..Default::default()
},
confidence: ConfidenceSequenceConfig {
confidence_level: 0.95,
min_samples: 5,
..Default::default()
},
};
let mut monitor = QuantumCoherenceMonitor::new(config)?;
use ndarray::Array2;
// Baseline data: n_samples × n_features
let baseline = Array2::from_shape_fn((100, 3), |(i, j)| {
// Your calibration measurements
calibration_data[i][j]
});
monitor.set_baseline(&baseline)?;
println!("Baseline established with {} samples", baseline.nrows());
let mut drift_count = 0;
for (t, observation) in data_stream.enumerate() {
let result = monitor.observe(&observation)?;
// Always-valid p-value
println!("t={}: p-value={:.4}, E-value={:.2}",
t, result.p_value, result.evalue);
// Check drift at any time
if result.drift_detected {
drift_count += 1;
println!(" → DRIFT DETECTED (total: {})", drift_count);
}
// Confidence interval is valid at every step
let ci = result.confidence_interval;
println!(" → 95% CI: [{:.4}, {:.4}]", ci.lower, ci.upper);
}
The quantum kernel computes similarity via quantum state fidelity:
k(x, y) = |⟨φ(x)|φ(y)⟩|²
where |φ(x)⟩ = U(x)|0⟩ⁿ is the quantum feature map.
use ruqu_quantum_monitor::{QuantumKernel, QuantumKernelConfig};
// High-expressivity kernel for complex distributions
let config = QuantumKernelConfig {
n_qubits: 6, // 2^6 = 64 dimensional feature space
n_layers: 4, // Deeper circuit = more entanglement
sigma: 0.5, // Narrower bandwidth = sharper discrimination
use_entanglement: true, // ZZ gates between adjacent qubits
seed: Some(123),
};
let kernel = QuantumKernel::new(config)?;
use ndarray::array;
let x = array![0.1, 0.2, 0.3];
let y = array![0.15, 0.25, 0.35];
// Single kernel value
let k_xy = kernel.kernel(&x, &y)?;
println!("k(x, y) = {:.4}", k_xy);
// Full kernel matrix
let data = Array2::from_shape_vec((100, 3), measurements)?;
let K = kernel.kernel_matrix(&data)?;
println!("Kernel matrix shape: {:?}", K.shape());
// Cross-kernel between baseline and test
let K_cross = kernel.cross_kernel_matrix(&baseline, &test_data)?;
use ruqu_quantum_monitor::StreamingKernelAccumulator;
let mut accumulator = StreamingKernelAccumulator::new(kernel);
accumulator.set_baseline(&baseline)?;
// O(1) memory updates
for observation in stream {
let mmd_estimate = accumulator.update(&observation)?;
println!("Streaming MMD²: {:.6}", mmd_estimate);
}
E-values are a modern alternative to p-values that allow:
Under the null hypothesis H₀, e-values satisfy:
E[E_t] ≤ 1 for all stopping times t
The anytime-valid p-value is p_t = 1/E_t.
use ruqu_quantum_monitor::{EValueTest, EValueConfig, MMDEstimator};
let config = EValueConfig {
alpha: 0.05,
bet_fraction: 0.5, // Kelly-optimal betting
adaptive_betting: true, // Learn optimal bet over time
min_samples: 10,
initial_wealth: 1.0,
};
let mut test = EValueTest::new(config)?;
// Process MMD estimates sequentially
for mmd_squared in mmd_estimates {
let update = test.update(mmd_squared);
println!("E-value: {:.2}, p-value: {:.4}, samples: {}",
update.evalue, update.p_value, update.n_samples);
if test.is_drift_detected() {
println!("Reject H₀ at level α = 0.05");
break; // Optional: can continue collecting
}
}
// Conservative betting (lower power, higher robustness)
let conservative = EValueConfig {
bet_fraction: 0.2,
adaptive_betting: false,
..Default::default()
};
// Aggressive betting (higher power, more variance)
let aggressive = EValueConfig {
bet_fraction: 0.8,
adaptive_betting: true,
..Default::default()
};
A (1-α) confidence sequence is a sequence of intervals [L_t, U_t] such that:
P(μ ∈ [L_t, U_t] for all t ≥ 1) ≥ 1 - α
Unlike standard confidence intervals, these are simultaneously valid at all sample sizes.
use ruqu_quantum_monitor::{ConfidenceSequence, ConfidenceSequenceConfig};
let config = ConfidenceSequenceConfig {
confidence_level: 0.95,
min_samples: 5,
empirical_variance: true,
variance_proxy: 1.0, // Upper bound on variance
rho: 1.0, // Mixture parameter
};
let mut cs = ConfidenceSequence::new(config)?;
for (t, x) in observations.iter().enumerate() {
if let Some(ci) = cs.update(*x) {
println!("t={}: Mean estimate {:.4}, 95% CI [{:.4}, {:.4}]",
t, ci.center(), ci.lower, ci.upper);
println!(" Width: {:.4} (shrinking as ~1/√t)", ci.width);
}
}
use ruqu_quantum_monitor::ChangeDetectionCS;
let mut detector = ChangeDetectionCS::new(
0.0, // Reference value (e.g., expected MMD under H₀)
0.95, // Confidence level
)?;
for mmd in mmd_estimates {
let result = detector.update(mmd);
if result.change_detected {
println!("Change from reference detected!");
println!("New estimate: {:.4} ± {:.4}", result.estimate, result.radius);
}
}
use ruqu_quantum_monitor::SharedMonitor;
use std::sync::Arc;
// Create shared monitor
let monitor = SharedMonitor::new(config)?;
let monitor = Arc::new(monitor);
// Spawn multiple observer threads
let handles: Vec<_> = (0..4).map(|agent_id| {
let monitor = Arc::clone(&monitor);
std::thread::spawn(move || {
for observation in agent_stream(agent_id) {
let result = monitor.observe(&observation)?;
if result.drift_detected {
report_alert(agent_id, result);
}
}
Ok::<_, Error>(())
})
}).collect();
// Wait for all agents
for h in handles {
h.join().unwrap()?;
}
use cognitum_gate_tilezero::CoherenceGate;
use ruqu_quantum_monitor::SharedMonitor;
let monitor = SharedMonitor::new(config)?;
// Use monitor as coherence backend for gate decisions
let gate = CoherenceGate::new()
.with_coherence_monitor(monitor)
.with_threshold(0.01); // P-value threshold for permit
for action in agent_actions {
let decision = gate.evaluate(&action)?;
match decision {
Permit(token) => execute(action, token),
Defer(reason) => queue_for_review(action, reason),
Deny(witness) => log_denial(action, witness),
}
}
| Operation | Dimension | Samples | Time | Memory |
|---|---|---|---|---|
| Kernel value | d=16 | 1 pair | 850ns | O(1) |
| Kernel matrix | d=16 | 100×100 | 8.5ms | O(n²) |
| Streaming MMD | d=16 | per obs | 1.2μs | O(1) |
| E-value update | - | per obs | 45ns | O(1) |
| Full observation | d=16 | per obs | 2.1μs | O(1) |
| Qubits | Feature Dim | Kernel Time | Memory |
|---|---|---|---|
| 2 | 4 | 120ns | 32B |
| 4 | 16 | 850ns | 128B |
| 6 | 64 | 5.2μs | 512B |
| 8 | 256 | 38μs | 2KB |
cargo bench --package ruvector-quantum-monitor
cargo test -p ruvector-quantum-monitor
| Category | Count | Description |
|---|---|---|
| Unit tests | 48 | Module-level functionality |
| Property tests | 17 | Proptest invariant checks |
k(x, y) = k(y, x)E_t ≥ 0 alwaysMMD² ≥ 0 for valid kernels/// Main monitoring interface
pub struct QuantumCoherenceMonitor {
// ...
}
/// Thread-safe wrapper
pub struct SharedMonitor {
// Uses parking_lot::RwLock internally
}
/// Observation result
pub struct ObservationResult {
pub evalue: f64,
pub p_value: f64,
pub drift_detected: bool,
pub confidence_interval: ConfidenceInterval,
pub n_samples: usize,
}
/// Confidence interval
pub struct ConfidenceInterval {
pub lower: f64,
pub upper: f64,
pub width: f64,
}
Licensed under either of Apache License, Version 2.0 or MIT license at your option.