use ndarray::ArrayView2;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OccupancyThreshold {
FrameIdentifiability { frame_dim: usize },
}
impl OccupancyThreshold {
pub fn min_effective_rows(&self) -> f64 {
match *self {
OccupancyThreshold::FrameIdentifiability { frame_dim } => frame_dim as f64,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct AtomOccupancy {
pub active: Vec<usize>,
pub dormant: Vec<usize>,
pub effective_rows: Vec<f64>,
pub threshold: OccupancyThreshold,
}
impl AtomOccupancy {
pub fn capacity(&self) -> usize {
self.effective_rows.len()
}
pub fn n_active(&self) -> usize {
self.active.len()
}
pub fn n_dormant(&self) -> usize {
self.dormant.len()
}
pub fn is_dormant(&self, slot: usize) -> bool {
self.dormant.binary_search(&slot).is_ok()
}
}
pub fn effective_occupancy(
blocks: ArrayView2<'_, u32>,
gates: ArrayView2<'_, f32>,
capacity: usize,
) -> Result<Vec<f64>, String> {
if blocks.dim() != gates.dim() {
return Err(format!(
"effective_occupancy: blocks {:?} and gates {:?} must have the same N×k shape",
blocks.dim(),
gates.dim()
));
}
let mut sum = vec![0.0_f64; capacity];
let mut sum_sq = vec![0.0_f64; capacity];
for row in 0..blocks.nrows() {
for slot in 0..blocks.ncols() {
let index = blocks[[row, slot]] as usize;
if index >= capacity {
return Err(format!(
"effective_occupancy: routed block {index} exceeds capacity {capacity}"
));
}
let gate = gates[[row, slot]] as f64;
if !gate.is_finite() {
return Err("effective_occupancy: routing gates must be finite".to_string());
}
let gate = gate.abs();
if gate == 0.0 {
continue;
}
sum[index] += gate;
sum_sq[index] += gate * gate;
}
}
Ok((0..capacity)
.map(|k| {
if sum_sq[k] <= 0.0 {
0.0
} else {
sum[k] * sum[k] / sum_sq[k]
}
})
.collect())
}
pub fn classify_occupancy(
effective_rows: &[f64],
threshold: OccupancyThreshold,
) -> Result<AtomOccupancy, String> {
let minimum = threshold.min_effective_rows();
if !(minimum.is_finite() && minimum > 0.0) {
return Err(format!(
"classify_occupancy: threshold must demand a positive effective-row count, got {minimum}"
));
}
let mut active = Vec::new();
let mut dormant = Vec::new();
for (slot, &n_eff) in effective_rows.iter().enumerate() {
if !n_eff.is_finite() || n_eff < 0.0 {
return Err(format!(
"classify_occupancy: slot {slot} has invalid effective occupancy {n_eff}"
));
}
if n_eff >= minimum {
active.push(slot);
} else {
dormant.push(slot);
}
}
Ok(AtomOccupancy {
active,
dormant,
effective_rows: effective_rows.to_vec(),
threshold,
})
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ActiveStateResiduals {
pub criterion: f64,
pub gamma: f64,
pub routing: f64,
}
impl ActiveStateResiduals {
fn worst(&self) -> f64 {
self.criterion.max(self.gamma).max(self.routing)
}
fn validate(&self) -> Result<(), String> {
for (name, value) in [
("criterion", self.criterion),
("gamma", self.gamma),
("routing", self.routing),
] {
if !value.is_finite() || value < 0.0 {
return Err(format!(
"certify_dormant_capacity: active {name} residual must be finite and \
non-negative, got {value}"
));
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub struct DormantCapacityInputs<'a> {
pub frames: ArrayView2<'a, f32>,
pub replayed_frames: ArrayView2<'a, f32>,
pub frame_dim: usize,
pub occupancy: &'a AtomOccupancy,
pub replayed_occupancy: &'a AtomOccupancy,
pub active_residuals: ActiveStateResiduals,
pub birth_margins: &'a [f64],
pub structural_margins: &'a [f64],
pub tolerance: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub enum NotConvergedReason {
ActiveFixedPointOpen { residual: f64, tolerance: f64 },
ProfitableBirth { margin: f64 },
ProfitableStructuralMove { margin: f64 },
LedgerChanged {
entered: Vec<usize>,
left: Vec<usize>,
},
OccupancyNotAPartition { capacity: usize },
}
#[derive(Clone, Debug, PartialEq)]
pub enum CapacityVerdict {
Converged,
NotConverged(NotConvergedReason),
}
impl CapacityVerdict {
pub fn is_converged(&self) -> bool {
matches!(self, CapacityVerdict::Converged)
}
}
#[derive(Clone, Debug)]
pub struct DormantCapacityCertificate {
pub occupancy: AtomOccupancy,
pub active_kkt_ok: bool,
pub dormant_excluded: bool,
pub no_profitable_birth: bool,
pub no_profitable_structural_move: bool,
pub ledger_recurs: bool,
pub active_frame_residual: f64,
pub dormant_frame_residual: f64,
pub active_residual: f64,
pub tolerance: f64,
pub verdict: CapacityVerdict,
}
impl DormantCapacityCertificate {
pub fn n_active(&self) -> usize {
self.occupancy.n_active()
}
pub fn n_dormant(&self) -> usize {
self.occupancy.n_dormant()
}
}
fn slot_projector_residual(
previous: ArrayView2<'_, f32>,
next: ArrayView2<'_, f32>,
slot: usize,
frame_dim: usize,
) -> f64 {
let base = slot * frame_dim;
let mut previous_norm2 = 0.0_f64;
let mut next_norm2 = 0.0_f64;
let mut overlap = 0.0_f64;
for left in 0..frame_dim {
for right in 0..frame_dim {
let mut previous_dot = 0.0_f64;
let mut next_dot = 0.0_f64;
let mut cross_dot = 0.0_f64;
for column in 0..previous.ncols() {
previous_dot += previous[[base + left, column]] as f64
* previous[[base + right, column]] as f64;
next_dot +=
next[[base + left, column]] as f64 * next[[base + right, column]] as f64;
cross_dot +=
previous[[base + left, column]] as f64 * next[[base + right, column]] as f64;
}
previous_norm2 += previous_dot * previous_dot;
next_norm2 += next_dot * next_dot;
overlap += cross_dot * cross_dot;
}
}
let scale = previous_norm2 + next_norm2;
let distance2 = (scale - 2.0 * overlap).max(0.0);
if scale == 0.0 {
if distance2 == 0.0 { 0.0 } else { f64::INFINITY }
} else {
(distance2 / scale).sqrt()
}
}
pub fn certify_dormant_capacity(
inputs: DormantCapacityInputs<'_>,
) -> Result<DormantCapacityCertificate, String> {
let DormantCapacityInputs {
frames,
replayed_frames,
frame_dim,
occupancy,
replayed_occupancy,
active_residuals,
birth_margins,
structural_margins,
tolerance,
} = inputs;
if frame_dim == 0 {
return Err("certify_dormant_capacity: frame_dim (block size b) must be >= 1".to_string());
}
if frames.dim() != replayed_frames.dim() {
return Err(format!(
"certify_dormant_capacity: frames {:?} and replayed frames {:?} must share the K×P shape",
frames.dim(),
replayed_frames.dim()
));
}
if frames.nrows() % frame_dim != 0 {
return Err(format!(
"certify_dormant_capacity: {} decoder rows is not a whole number of {frame_dim}-row slots",
frames.nrows()
));
}
let capacity = frames.nrows() / frame_dim;
if occupancy.capacity() != capacity || replayed_occupancy.capacity() != capacity {
return Err(format!(
"certify_dormant_capacity: ledgers report {} / {} slots but the decoder has {capacity}",
occupancy.capacity(),
replayed_occupancy.capacity()
));
}
if !(tolerance.is_finite() && tolerance > 0.0) {
return Err(format!(
"certify_dormant_capacity: tolerance must be finite and > 0, got {tolerance}"
));
}
active_residuals.validate()?;
for (name, margins) in [("birth", birth_margins), ("structural", structural_margins)] {
if margins.iter().any(|m| !m.is_finite()) {
return Err(format!(
"certify_dormant_capacity: every {name} margin must be finite"
));
}
}
let mut covered = vec![0usize; capacity];
for &slot in occupancy.active.iter().chain(occupancy.dormant.iter()) {
if slot >= capacity {
return Err(format!(
"certify_dormant_capacity: ledger slot {slot} exceeds capacity {capacity}"
));
}
covered[slot] += 1;
}
let dormant_excluded = covered.iter().all(|&count| count == 1)
&& occupancy.dormant.iter().all(|&slot| {
occupancy.active.binary_search(&slot).is_err()
});
let mut active_frame_residual = 0.0_f64;
for &slot in &occupancy.active {
active_frame_residual = active_frame_residual.max(slot_projector_residual(
frames,
replayed_frames,
slot,
frame_dim,
));
}
let mut dormant_frame_residual = 0.0_f64;
for &slot in &occupancy.dormant {
dormant_frame_residual = dormant_frame_residual.max(slot_projector_residual(
frames,
replayed_frames,
slot,
frame_dim,
));
}
let active_residual = active_frame_residual.max(active_residuals.worst());
let active_kkt_ok = active_residual <= tolerance;
let best_birth = birth_margins
.iter()
.cloned()
.fold(f64::NEG_INFINITY, f64::max);
let no_profitable_birth = best_birth <= 0.0;
let best_structural = structural_margins
.iter()
.cloned()
.fold(f64::NEG_INFINITY, f64::max);
let no_profitable_structural_move = best_structural <= 0.0;
let entered: Vec<usize> = replayed_occupancy
.active
.iter()
.filter(|slot| occupancy.active.binary_search(slot).is_err())
.cloned()
.collect();
let left: Vec<usize> = occupancy
.active
.iter()
.filter(|slot| replayed_occupancy.active.binary_search(slot).is_err())
.cloned()
.collect();
let ledger_recurs = entered.is_empty() && left.is_empty();
let verdict = if !dormant_excluded {
CapacityVerdict::NotConverged(NotConvergedReason::OccupancyNotAPartition { capacity })
} else if !active_kkt_ok {
CapacityVerdict::NotConverged(NotConvergedReason::ActiveFixedPointOpen {
residual: active_residual,
tolerance,
})
} else if !no_profitable_birth {
CapacityVerdict::NotConverged(NotConvergedReason::ProfitableBirth { margin: best_birth })
} else if !no_profitable_structural_move {
CapacityVerdict::NotConverged(NotConvergedReason::ProfitableStructuralMove {
margin: best_structural,
})
} else if !ledger_recurs {
CapacityVerdict::NotConverged(NotConvergedReason::LedgerChanged { entered, left })
} else {
CapacityVerdict::Converged
};
Ok(DormantCapacityCertificate {
occupancy: occupancy.clone(),
active_kkt_ok,
dormant_excluded,
no_profitable_birth,
no_profitable_structural_move,
ledger_recurs,
active_frame_residual,
dormant_frame_residual,
active_residual,
tolerance,
verdict,
})
}
#[cfg(test)]
mod tests {
use super::*;
use ndarray::Array2;
const P: usize = 16;
const B: usize = 2;
const CAPACITY: usize = 100; const N_PLANES: usize = 3; const ROWS_PER_PLANE: usize = 80;
fn capacity_decoder() -> Array2<f32> {
let mut decoder = Array2::<f32>::zeros((CAPACITY * B, P));
let free = P - 2 * N_PLANES;
for slot in 0..CAPACITY {
let (first, second) = if slot < N_PLANES {
(2 * slot, 2 * slot + 1)
} else {
let low = (slot * 3) % free;
let high = (low + 1 + slot % (free - 1)) % free;
(2 * N_PLANES + low, 2 * N_PLANES + high)
};
decoder[[slot * B, first]] = 1.0;
decoder[[slot * B + 1, second]] = 1.0;
}
decoder
}
fn corpus() -> Array2<f32> {
let n = N_PLANES * ROWS_PER_PLANE;
let mut x = Array2::<f32>::zeros((n, P));
for plane in 0..N_PLANES {
for i in 0..ROWS_PER_PLANE {
let row = plane * ROWS_PER_PLANE + i;
let theta = i as f32 * 0.7 + plane as f32;
let radius = 1.0 + (i % 5) as f32 * 0.25;
x[[row, 2 * plane]] = radius * theta.cos();
x[[row, 2 * plane + 1]] = radius * theta.sin();
}
}
x
}
fn route_top1(x: &Array2<f32>, decoder: &Array2<f32>) -> (Array2<u32>, Array2<f32>) {
let n = x.nrows();
let mut blocks = Array2::<u32>::zeros((n, 1));
let mut gates = Array2::<f32>::zeros((n, 1));
for row in 0..n {
let mut best_slot = 0usize;
let mut best_gate = -1.0_f32;
for slot in 0..CAPACITY {
let mut energy = 0.0_f32;
for axis in 0..B {
let mut dot = 0.0_f32;
for column in 0..P {
dot += x[[row, column]] * decoder[[slot * B + axis, column]];
}
energy += dot * dot;
}
let gate = energy.sqrt();
if gate > best_gate {
best_gate = gate;
best_slot = slot;
}
}
blocks[[row, 0]] = best_slot as u32;
gates[[row, 0]] = best_gate;
}
(blocks, gates)
}
fn ledger(x: &Array2<f32>, decoder: &Array2<f32>) -> AtomOccupancy {
let (blocks, gates) = route_top1(x, decoder);
let n_eff = effective_occupancy(blocks.view(), gates.view(), CAPACITY)
.expect("routing is well formed");
classify_occupancy(
&n_eff,
OccupancyThreshold::FrameIdentifiability { frame_dim: B },
)
.expect("identifiability threshold is positive")
}
fn inputs<'a>(
frames: &'a Array2<f32>,
replayed: &'a Array2<f32>,
occupancy: &'a AtomOccupancy,
replayed_occupancy: &'a AtomOccupancy,
birth_margins: &'a [f64],
) -> DormantCapacityInputs<'a> {
DormantCapacityInputs {
frames: frames.view(),
replayed_frames: replayed.view(),
frame_dim: B,
occupancy,
replayed_occupancy,
active_residuals: ActiveStateResiduals::default(),
birth_margins,
structural_margins: &[],
tolerance: 1.0e-6,
}
}
#[test]
fn dormant_capacity_certificate_ignores_dormant_frame_motion_at_k_far_above_rank() {
let x = corpus();
let decoder = capacity_decoder();
let occupancy = ledger(&x, &decoder);
assert_eq!(occupancy.capacity(), CAPACITY);
assert_eq!(occupancy.active, vec![0, 1, 2]);
assert_eq!(occupancy.n_dormant(), CAPACITY - N_PLANES);
for &slot in &occupancy.active {
assert!(
occupancy.effective_rows[slot] > B as f64,
"active slot {slot} must clear the frame-identifiability count"
);
}
for &slot in &occupancy.dormant {
assert_eq!(
occupancy.effective_rows[slot], 0.0,
"dormant slot {slot} carries no gate mass on a rank-6 corpus"
);
}
let quiet = certify_dormant_capacity(inputs(
&decoder,
&decoder,
&occupancy,
&occupancy,
&[-3.5, -0.25],
))
.expect("well-formed certificate inputs");
assert_eq!(quiet.verdict, CapacityVerdict::Converged);
assert!(quiet.active_kkt_ok && quiet.dormant_excluded && quiet.ledger_recurs);
assert!(quiet.no_profitable_birth && quiet.no_profitable_structural_move);
assert_eq!(quiet.n_active(), N_PLANES);
assert_eq!(quiet.n_dormant(), CAPACITY - N_PLANES);
assert_eq!(quiet.dormant_frame_residual, 0.0);
let mut revived = decoder.clone();
for &slot in &occupancy.dormant {
for axis in 0..B {
for column in 0..P {
revived[[slot * B + axis, column]] = 0.0;
}
let shifted = 2 * N_PLANES + ((slot + 2 * axis + 4) % (P - 2 * N_PLANES));
revived[[slot * B + axis, shifted]] = 1.0;
}
}
let moved = certify_dormant_capacity(inputs(
&decoder,
&revived,
&occupancy,
&occupancy,
&[-3.5, -0.25],
))
.expect("well-formed certificate inputs");
assert!(
moved.dormant_frame_residual > 0.1,
"the test must actually move the dormant frames (residual {})",
moved.dormant_frame_residual
);
assert_eq!(moved.verdict, CapacityVerdict::Converged);
assert_eq!(moved.active_frame_residual, quiet.active_frame_residual);
assert_eq!(moved.active_residual, quiet.active_residual);
assert_eq!(moved.n_active(), N_PLANES);
let mut active_moved = decoder.clone();
for column in 0..P {
active_moved[[0, column]] = 0.0;
}
active_moved[[0, 7]] = 1.0;
let refused = certify_dormant_capacity(inputs(
&decoder,
&active_moved,
&occupancy,
&occupancy,
&[-3.5, -0.25],
))
.expect("well-formed certificate inputs");
assert!(!refused.active_kkt_ok);
assert!(matches!(
refused.verdict,
CapacityVerdict::NotConverged(NotConvergedReason::ActiveFixedPointOpen { .. })
));
}
#[test]
fn dormant_capacity_certificate_refuses_profitable_moves_and_open_ledger() {
let x = corpus();
let decoder = capacity_decoder();
let occupancy = ledger(&x, &decoder);
let birth = certify_dormant_capacity(inputs(
&decoder,
&decoder,
&occupancy,
&occupancy,
&[-1.0, 4.75],
))
.expect("well-formed certificate inputs");
assert!(!birth.no_profitable_birth);
assert_eq!(
birth.verdict,
CapacityVerdict::NotConverged(NotConvergedReason::ProfitableBirth { margin: 4.75 })
);
let mut structural = inputs(&decoder, &decoder, &occupancy, &occupancy, &[]);
let margins = [0.5_f64];
structural.structural_margins = &margins;
let merged = certify_dormant_capacity(structural).expect("well-formed certificate inputs");
assert!(!merged.no_profitable_structural_move);
assert_eq!(
merged.verdict,
CapacityVerdict::NotConverged(NotConvergedReason::ProfitableStructuralMove {
margin: 0.5
})
);
let mut woken = occupancy.clone();
woken.effective_rows[7] = 32.0;
let woken = classify_occupancy(&woken.effective_rows, woken.threshold)
.expect("identifiability threshold is positive");
let open =
certify_dormant_capacity(inputs(&decoder, &decoder, &occupancy, &woken, &[-1.0]))
.expect("well-formed certificate inputs");
assert!(!open.ledger_recurs);
assert_eq!(
open.verdict,
CapacityVerdict::NotConverged(NotConvergedReason::LedgerChanged {
entered: vec![7],
left: vec![],
})
);
}
}