use gresil::nir::{
nir_export, LinearFusedRecord, NirAssemblyReport, NirError, NirGraphEncoder, Thousandths,
EDGE_PULSE_QUANTA,
};
use gresil::{NirImport, NirImportOptions, SpikingNeuralNetwork, VoltageResolution};
const CHAIN: &[u8] = include_bytes!("../tests/nir_fixtures/chain.json");
const BRANCH: &[u8] = include_bytes!("../tests/nir_fixtures/branch.json");
const MERGE: &[u8] = include_bytes!("../tests/nir_fixtures/merge.json");
const RECURRENT: &[u8] = include_bytes!("../tests/nir_fixtures/recurrent.json");
fn fail(msg: &str) -> ! {
eprintln!("NIR ASSEMBLY GATE: FAIL — {msg}");
std::process::exit(1);
}
fn centi() -> NirImportOptions {
NirImportOptions::new(1_000, VoltageResolution::CentiMillivolt)
}
fn raster(
net: &mut SpikingNeuralNetwork,
enc: &NirGraphEncoder,
drive: &[&[Thousandths]],
steps: usize,
) -> Vec<(usize, usize)> {
let mut out = vec![(usize::MAX, 0usize); net.neurons().len()];
for t in 0..steps {
for s in net
.step(&enc.encode(drive))
.unwrap_or_else(|e| fail(&e.to_string()))
{
let e = &mut out[s.neuron_id as usize];
e.0 = e.0.min(t);
e.1 += 1;
}
}
out
}
fn print_report(rep: &NirAssemblyReport<'_>) {
println!(
"report : {} neurons · {} synapses · {} inputs · {} drive Linears · {} stages",
rep.neurons, rep.synapses, rep.inputs, rep.drive_linears, rep.stages
);
for LinearFusedRecord { chain, scales, .. } in &rep.fused {
println!("fused : {} (scales {:e})", chain.join("·"), scales[0]);
}
for n in &rep.undriven {
println!("undriven: {n} (assembles silent — documented, never silently)");
}
if rep.multi_linear_gain {
println!(
"quant : D6 note — >1 drive Linear; per-tensor absmax scales absorb branch gain"
);
}
if !rep.plasticity_frozen {
fail("plasticity must be frozen at assembly");
}
}
fn main() {
println!("=== NIR assembly gate — general four-kind graphs, reference-emitted vectors ===");
println!("ref : neuromorphs/NIR @ {}", gresil::nir::NIR_REF_SHA);
println!("contract: EDGE_PULSE_QUANTA = {EDGE_PULSE_QUANTA} (20 pA pulse @ divisor 10)");
println!();
let g = NirImport::from_json(
BRANCH,
NirImportOptions::new(1_000, VoltageResolution::Millivolt),
)
.unwrap_or_else(|e| fail(&e.to_string()));
let (mut net, enc, rep) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
print_report(&rep);
let pins = raster(&mut net, &enc, &[&[6_000, 0, 0].map(Thousandths)], 100);
println!(
"pins : first-spike per neuron {:?} · counts {:?}",
pins.iter().map(|p| p.0).collect::<Vec<_>>(),
pins.iter().map(|p| p.1).collect::<Vec<_>>()
);
if pins.iter().any(|p| p.0 == usize::MAX) {
fail("every population must fire on the seeded drive");
}
let firsts: Vec<usize> = pins.iter().map(|p| p.0).collect::<Vec<_>>();
if firsts != vec![3, 14, 1, 3] {
fail(&format!(
"branch first-spike steps must be [3, 14, 1, 3], got {firsts:?}"
));
}
println!("gate 1 : PASS — all 4 neurons fire; first-spike steps pinned [3, 14, 1, 3]");
let g = NirImport::from_json(MERGE, centi()).unwrap_or_else(|e| fail(&e.to_string()));
let (mut net, enc, rep) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
if !rep.multi_linear_gain {
fail("merge graph must carry the D6 note");
}
let single = raster(&mut net, &enc, &[&[Thousandths(1_000); 2], &[]], 200);
if single[0].1 != 0 {
fail("a single 81 pA branch must stall below the climb");
}
if single[1].1 == 0 {
fail("the 327 pA control row must fire — the encoder is live");
}
let g2 = NirImport::from_json(MERGE, centi()).unwrap();
let (mut net2, enc2, _) = g2.build_network().unwrap();
let one = [Thousandths(1_000); 2];
let both = raster(&mut net2, &enc2, &[&one, &one], 100);
if both[0].0 != 52 {
fail(&format!(
"summed 162 pA first spike must be step 52 (g: 1620->116 by g/20), got {}",
both[0].0
));
}
println!(
"gate 2 : PASS — single stalls (0/200), summed fires: neuron 0 first at step {}",
both[0].0
);
let g = NirImport::from_json(RECURRENT, centi()).unwrap_or_else(|e| fail(&e.to_string()));
let (mut net, enc, rep) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
if rep.synapses != 4 {
fail("recurrent fixture wires 4 synapses (a<->b, 2 neurons each)");
}
let mut moved_at: Option<usize> = None;
for t in 0..80 {
let fired_a0 = net
.step(&enc.encode(&[&[1_000, 0].map(Thousandths)]))
.unwrap()
.iter()
.any(|s| s.neuron_id == 0);
if fired_a0 && moved_at.is_none() {
if net.neurons()[2].membrane_potential() != -7_000 {
fail("b0 unmoved on the spike step — the one-step delay is the contract");
}
moved_at = Some(t);
} else if moved_at.is_some_and(|m| t == m + 1)
&& net.neurons()[2].membrane_potential() != -6_990
{
fail("b0 must sit at exactly -6990 one step after a0's spike (+10 quanta)");
}
}
if moved_at.is_none() {
fail("a0 must fire within 80 steps");
}
if net.neurons()[3].membrane_potential() != -7_000 {
fail("b1 unmoved — a1 never fires (identity element mapping)");
}
if !net
.synapses()
.iter()
.all(|s| s.weight() == EDGE_PULSE_QUANTA)
{
fail("edge quanta frozen (plasticity off)");
}
println!(
"gate 3 : PASS — pulse moves b0 exactly +10 quanta one step after a0 fires (t={})",
moved_at.unwrap_or(usize::MAX)
);
let g = NirImport::from_json(
BRANCH,
NirImportOptions::new(1_000, VoltageResolution::Millivolt),
)
.unwrap();
let (_, enc, rep) = g.build_network().unwrap();
if rep.fused.len() != 1 || rep.fused[0].chain != vec!["l1", "l2"] {
fail("the l1·l2 chain must fuse exactly once, recorded");
}
let w1 = [[0.5f64, -1.0, 0.25], [-0.25, 1.0, 0.5]];
let w2 = [[1.0f64, 0.0], [0.0, -0.5]];
let mut prod = [[0f64; 3]; 2];
for r in 0..2 {
for k in 0..3 {
prod[r][k] = w2[r][0] * w1[0][k] + w2[r][1] * w1[1][k];
}
}
let flat: Vec<f64> = prod.iter().flat_map(|r| r.iter().copied()).collect();
let mut expect = vec![0i16; 6];
gresil::nir::quantize_linear(&flat, 2, 3, &mut expect, 0).expect("seam quantizes");
let fused_found =
(0..enc.stage_count()).any(|i| enc.stage_quanta(i) == Some(expect.as_slice()));
if !fused_found {
fail("the fused stage must BE the once-quantized f64 product");
}
println!("gate 4 : PASS — W2·W1 composed in f64, quantized ONCE: {expect:?}");
#[allow(clippy::type_complexity)]
let table: Vec<(&str, &[u8], NirImportOptions, fn(&NirError) -> bool)> = vec![
(
"pass-through",
include_bytes!("../tests/nir_fixtures/neg_asm_passthrough.json"),
centi(),
|e| {
matches!(
e,
NirError::UnsupportedTopology("Input->Output pass-through")
)
},
),
(
"direct drive (Input->LIF)",
include_bytes!("../tests/nir_fixtures/neg_asm_direct_drive.json"),
centi(),
|e| {
matches!(
e,
NirError::UnsupportedTopology(
"direct drive (Input->LIF) deferred — drive convention not yet named"
)
)
},
),
(
"readout (LIF->Linear->Output)",
include_bytes!("../tests/nir_fixtures/neg_asm_lif_to_linear.json"),
centi(),
|e| {
matches!(e, NirError::UnsupportedTopology(
"readout (LIF->Linear->Output) deferred — spike-count readout convention not yet named"))
},
),
(
"no LIF (encoder-only)",
include_bytes!("../tests/nir_fixtures/neg_asm_no_lif.json"),
centi(),
|e| {
matches!(
e,
NirError::UnsupportedTopology(
"graph without LIF: nothing to fire — encoder-only assembly deferred"
)
)
},
),
(
"self-loop",
include_bytes!("../tests/nir_fixtures/neg_asm_self_loop.json"),
centi(),
|e| {
matches!(
e,
NirError::UnsupportedTopology(
"LIF self-loop — the substrate forbids self-synapse"
)
)
},
),
(
"empty graph",
include_bytes!("../tests/nir_fixtures/neg_asm_empty.json"),
centi(),
|e| matches!(e, NirError::UnsupportedTopology("empty graph")),
),
(
"shape mismatch",
include_bytes!("../tests/nir_fixtures/neg_asm_shape_mismatch.json"),
centi(),
|e| {
matches!(
e,
NirError::EdgeShapeMismatch { src, dst, .. }
if src == "input" && dst == "l1"
)
},
),
(
"cycle without Output",
include_bytes!("../tests/nir_fixtures/neg_asm_cycle_no_output.json"),
centi(),
|e| matches!(e, NirError::UnsupportedTopology("no Output node")),
),
(
"no Input",
include_bytes!("../tests/nir_fixtures/neg_asm_no_input.json"),
centi(),
|e| matches!(e, NirError::UnsupportedTopology("no Input node")),
),
(
"recurrent on mV",
RECURRENT,
NirImportOptions::new(1_000, VoltageResolution::Millivolt),
|e| {
matches!(e, NirError::UnsupportedTopology(m)
if m.contains("CentiMillivolt") && m.contains("~200 pA dead zone"))
},
),
];
for (label, doc, opts, check) in &table {
let g = NirImport::from_json(doc, *opts)
.unwrap_or_else(|e| fail(&format!("{label}: must import: {e}")));
let err = g
.build_network()
.err()
.unwrap_or_else(|| fail(&format!("{label}: expected a named rejection")));
if !check(&err) {
fail(&format!("{label}: wrong error — {err}"));
}
}
println!(
"gate 5 : PASS — {} named rejections, one negative fixture each",
table.len()
);
let opts = NirImportOptions::new(1_000, VoltageResolution::Millivolt);
let g = NirImport::from_json(CHAIN, opts).unwrap_or_else(|e| fail(&e.to_string()));
let (mut net1, enc1) = g
.build_chain_network()
.unwrap_or_else(|e| fail(&e.to_string()));
let (mut net2, enc2, _) = g.build_network().unwrap_or_else(|e| fail(&e.to_string()));
let mut spikes1 = 0usize;
let mut first1 = usize::MAX;
let mut raster1 = Vec::new();
let mut raster2 = Vec::new();
for t in 0..100 {
let f1 = net1.step(&enc1.encode(&[4, 0, 0])).unwrap();
if !f1.is_empty() && first1 == usize::MAX {
first1 = t;
}
spikes1 += f1.len();
raster1.extend(f1.iter().map(|s| s.neuron_id));
raster2.extend(
net2.step(&enc2.encode(&[&[4_000, 0, 0].map(Thousandths)]))
.unwrap()
.iter()
.map(|s| s.neuron_id),
);
}
if (spikes1, first1) != (9, 6) {
fail(&format!(
"frozen chain pins must hold: 9 spikes/100 first at step 6, got ({spikes1}, {first1})"
));
}
if raster1 != raster2 {
fail("the general builder's raster must be bit-identical to the chain builder's");
}
let mut out = vec![0u8; 4096];
let n = nir_export(&g.nodes, &g.edges, &g.weights, &g.lifs, opts, &mut out).unwrap();
if n != 826 {
fail(&format!("chain export must stay 826 B (banked), got {n}"));
}
println!(
"gate 6 : PASS — frozen pins byte-identical: 9 spikes/100 @ step 6, export {n} B, \
general-builder raster bit-identical"
);
println!();
println!("NIR ASSEMBLY GATE: PASS — 6/6 gates on reference-emitted general graphs");
}