NeckSense (necksense v2.0.0)
Concentration- and load-invariant normalisation, zero-float vibration/acoustic spectrum conditioning, sparse binary hashing, one-shot novelty detection and continual associative classification, modelled on the Drosophila chordotonal organ, antennal lobe and two-compartment mushroom body (BANC v888 / MaleCNS), in Python (NumPy), ANSI C99 (< 6 KB SRAM with -DNS_TINY=1) and Arduino.
Install · Quick start · C99 & Arduino · Benchmarks · When to use it · Changelog
What it is
Multi-channel chemical, IMU vibration, piezo acoustic and telemetry sensors face slow baseline drift, 10×–100× load/concentration swings, sequential class forgetting and tight microcontroller SRAM budgets. NeckSense turns the fly's sensory conditioning and Mushroom Body memory circuits (BANC v888 connectome: 3,006 ORNs, 2,132 frequency-tuned chordotonal mechanoreceptors, 2,057 KCγ short-term + 1,943 KCα/β long-term + 122 KCα'/β' novelty Kenyon cells) into a compact Python + ANSI C99 library:
raw IMU / piezo window w[0..N-1] (optional)
│ [0] Chordotonal VibrationFrontEnd: 16-ch integer stationary Haar + resonator
│ + impulse crest + envelope AM filterbank (strips static 1g tilt on 3-axis IMUs)
▼
raw or spectral vector x(t)
│ [1] ORN dual-timescale adaptation + phasic plume whiff-rate / intermittency tracking
│ [2] Antennal-lobe divisive normalisation: r_i = p_i^n / (sigma^n + (gamma*mean)^n + p_i^n)
│ [3] Mushroom-body projection: each Kenyon cell sums d_proj=6 inputs (additions only),
│ then global APL winner-take-all keeps top k cells -> packed uint64 bit tag
├──► KenyonIndex popcount similarity search over binary tags
├──► MushroomNoveltyDetector KCα'/β' -> MBON-α'3 one-shot habituation & anomaly score
└──► MushroomValenceClassifier KCγ (fast STM) + KCα/β (consolidated anti-forgetting LTM)
- Concentration & motor-load invariance. Channel ratios survive scaling: cosine similarity between
1×and100×inputs exceeds0.99999, andVibrationFrontEnduses homogeneous degree-1 integer features so 1-shot bearing/propeller/spindle fault signatures survive10×+throttle or load swings. - Plume whiff intermittency.
AntennalNormalizer.step_with_whiff()anddiagnostics()track phasic ORN up-crossings (2–20 Hzturbulent odor filaments vs static background clouds) for chemical source proximity. - Two-compartment continual memory (
KCγ+KCα/β). Callingclf.consolidate()(ns_valence_consolidate()in C) protects consolidatedα/β-lobe synapses from cross-class opponent erosion while preserving explicit opposite-sign reward extinction (0%catastrophic forgetting across sequential multi-class updates). - No weight matrix &
< 6 KBTiny MCU SRAM. Deterministicxorshift32projection uses0 Bof weights and zero multiplications; the entire 5-struct C99 suite fits in20,284 Bby default (6.9×smaller thanv1.1.0) and5,804 B(< 6 KB) with-DNS_TINY=1. - Bit-identical Python ↔ C. With
c_parity=True, Python reproduces the C core'sQ16.16/Q14outputs, tags, whiff rates, vibration features and scores bit-for-bit.
Install
pip install necksense
# or from this repository:
pip install "git+https://github.com/indian-aman/necklink.git#subdirectory=packages/necksense"
Quick start
import numpy as np
from necksense import (
AntennalNormalizer,
KenyonIndex,
MushroomNoveltyDetector,
MushroomValenceClassifier,
VibrationFrontEnd,
)
ethanol_1x = np.array([0.90, 0.35, 0.10, 0.02, 0.50, 0.05, 0.01, 0.20])
acetone_1x = np.array([0.45, 0.15, 0.08, 0.80, 0.75, 0.10, 0.30, 0.05])
# 1. Antennal lobe + associative learning + KC-alpha/beta LTM consolidation
ant = AntennalNormalizer(n_channels=8, sigma=0.008, gamma=1.0, hill_n=2.0, tonic_alpha=0.03)
clf = MushroomValenceClassifier(n_inputs=8, antennal=ant, n_kc=1024, d_proj=6, wta_frac=0.05)
clf.learn(ethanol_1x, "ethanol", reward=1.0)
clf.consolidate() # protect in KC-alpha/beta LTM against future multi-class overwriting
clf.learn(acetone_1x, "acetone", reward=1.0)
assert clf.predict(20.0 * acetone_1x) == "acetone"
# 2. One-shot IMU / acoustic bearing-fault classification across a 10x load swing
vib = VibrationFrontEnd(n_samples=128)
vib_clf = MushroomValenceClassifier(n_inputs=16, antennal=AntennalNormalizer(16, sigma=0.004))
t = np.arange(128, dtype=np.float64)
healthy_1x = 0.20 * np.sin(2.0 * np.pi * t / 32.0)
spall_1x = healthy_1x + np.where((t % 16) == 0, 0.55, 0.0)
vib_clf.learn(vib.extract(healthy_1x), "healthy")
vib_clf.learn(vib.extract(spall_1x), "bearing_spall")
assert vib_clf.predict(vib.extract(10.0 * spall_1x)) == "bearing_spall"
# 3. Streaming novelty + turbulent plume whiff rate
nov = MushroomNoveltyDetector(n_inputs=8, antennal=AntennalNormalizer(8, sigma=0.008), lr=0.55)
scores = [nov.update_and_score(ethanol_1x) for _ in range(3)] # 1.00 -> 0.45 -> 0.20
s_anomaly = nov.update_and_score(acetone_1x) # unseen pattern: > 0.75
_, whiff_rate = ant.step_with_whiff(ethanol_1x)
print([round(s, 2) for s in scores], round(s_anomaly, 2), round(whiff_rate, 3))
# 4. Popcount similarity search over 128-byte (1024-bit) Kenyon tags
idx = KenyonIndex(n_inputs=64, n_kc=1024, d_proj=6, wta_frac=0.05)
db = np.random.default_rng(0).standard_normal((5000, 64))
idx.add(db)
assert idx.query(db[42] + 0.05, top_k=5)[0].id == 42
Command line
necksense demo # four-stage circuit + vibration walkthrough
necksense benchmark-quick # short version of the three benchmarks
necksense hash-csv sensors.csv --id-col 0 --n-kc 1024 --antennal-normalize -o tags.csv
Zero-heap, zero-float ANSI C99 core (csrc/) & Arduino library
csrc/necksense.h and csrc/necksense.c use only fixed-width integer types (int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t in Q16.16 / Q14), with zero heap allocation and zero floating-point types. Both the standard profile and -DNS_TINY=1 compile cleanly under -O2 -std=c99 -Wall -Wextra -pedantic -Werror and -fsanitize=address,undefined.
make -C csrc clean all test sanitize
#include "necksense.h"
static ns_vib_fe_t vib;
static ns_antennal_t ant;
static ns_kenyon_t ken;
static ns_novelty_t nov;
void sensor_init(void) {
ns_vib_init(&vib, 128u, 5u);
ns_antennal_init(&ant, NS_VIB_CHANNELS, 256, NS_Q16_ONE, 2u, 655, 1311, 32768, 22938);
ns_kenyon_init(&ken, NS_VIB_CHANNELS, 512u, 6u, 10u, 42u); /* 2% active for novelty */
ns_novelty_init(&nov, 512u, 36045 /* lr = 0.55 */, 16);
}
int32_t imu_window_novelty_q16(const int16_t accel_xyz_mg[128 * 3]) {
int32_t feat_q16[NS_VIB_CHANNELS];
int32_t norm_q16[NS_VIB_CHANNELS];
uint64_t kc_tag[8];
ns_vib_extract_3axis_i16(&vib, accel_xyz_mg, 128u, feat_q16);
ns_antennal_normalize(&ant, feat_q16, norm_q16);
ns_kenyon_hash(&ken, norm_q16, kc_tag);
return ns_novelty_update_and_score(&nov, kc_tag); /* 0 .. 65536 */
}
Static SRAM footprint (verified by necksense_selftest & necksense_selftest_tiny)
| Struct | v1.1.0 Default | v2.0.0 Default (M=1024, C=8) |
v2.0.0 -DNS_TINY=1 (M=512, C=4) |
|---|---|---|---|
ns_antennal_t (drift + divisive + whiff) |
548 B |
576 B |
256 B |
ns_kenyon_t (0-byte weight matrix) |
24 B |
24 B |
24 B |
ns_novelty_t (lossless 17-bit Q16.16) |
8,216 B |
2,200 B |
1,112 B |
ns_valence_t (Q14 + KCα/β LTM mask) |
131,172 B |
17,472 B |
4,400 B |
ns_vib_fe_t (16-ch chordotonal front-end) |
— | 12 B |
12 B |
| Total 5-struct suite | 139,960 B (~140 KB) |
20,284 B (6.9× smaller) |
5,804 B (< 6 KB, 24× smaller) |
Full C99 pipeline (D=16 normalise + hash + novelty): ~14 us/sample (-DNS_TINY=1, M=512) to ~35 us/sample (M=1024) on a single desktop x86-64 core at -O2.
Drop-in Arduino / PlatformIO library (arduino/NeckSense/)
Copy arduino/NeckSense into ~/Documents/Arduino/libraries/NeckSense (or add lib_deps = symlink://.../packages/necksense/arduino/NeckSense in platformio.ini) and #include <NeckSense.h>. AVR and ESP8266 targets automatically enable NS_TINY=1 (5,804 B total SRAM); see ESP32_Vibration_And_Gas_Anomaly.ino for a complete 3-axis IMU vibration + 8-channel MOX gas anomaly sketch.
Benchmarks (5-seed mean)
python scripts/benchmark_necksense.py # ~40 s; writes results/benchmark_summary.json and the chart
1. Nearest-neighbour retrieval (N = 5,000, D = 64, Recall@10)
A. Equal number of active bits k. This is the protocol of Dasgupta, Stevens & Navlakha (Science 2017). FlyHash uses M = 20k Kenyon cells; SimHash uses k Gaussian hyperplanes.
k |
FlyHash | SimHash | FlyHash float multiplications | SimHash float multiplications |
|---|---|---|---|---|
| 16 | 17.85% ± 0.58% |
9.96% ± 0.21% |
0 | 1,024 |
| 32 | 23.21% ± 0.30% |
13.69% ± 0.43% |
0 | 2,048 |
| 64 | 29.93% ± 0.44% |
16.68% ± 0.48% |
0 | 4,096 |
| 128 | 36.19% ± 0.35% |
22.53% ± 0.18% |
0 | 8,192 |
B. Equal stored bits per item. Both are stored as dense bit vectors. SimHash wins clearly, because a 50%-dense bit carries more information than a 5%-sparse one:
| Tag size | FlyHash | SimHash | FlyHash weight RAM | SimHash weight RAM |
|---|---|---|---|---|
| 64 B (512 bits) | 21.67% |
40.64% |
0 KB | 128 KB |
| 128 B (1024 bits) | 27.50% |
50.51% |
0 KB | 256 KB |
| 256 B (2048 bits) | 34.02% |
59.80% |
0 KB | 512 KB |
FlyHash's advantage is that it needs no weight matrix and no multiplications, which matters on an MCU. If you have the RAM and an FPU, SimHash, PQ or HNSW give better recall per byte.
2. Gas classification: 8 sensors, 6 gases, 3 calibration shots per gas
300 test plumes per seed at 0.1×–25× concentration, with sinusoidal + linear baseline drift in the drift regimes. "Baseline-corrected L2 k-NN" is the standard e-nose pipeline: subtract a moving average of the clean-air readings between plumes (the same information NeckSense's drift tracker gets), L2-normalise, then 3-NN.
| Regime | NeckSense (3-shot) | NeckSense (1-shot) | Baseline-corrected L2 k-NN | L2 k-NN (no drift correction) | Z-score centroid |
|---|---|---|---|---|---|
| Clean 1× | 100% |
100% |
100% |
100% |
100% |
0.1×–25×, no drift |
100% |
100% |
100% |
100% |
89.9% |
Weak 0.1×–0.5× + drift |
99.3% ± 0.7% |
99.5% ± 0.6% |
100% |
33.4% |
30.1% |
Full 0.1×–25× + drift |
99.5% ± 0.5% |
99.5% ± 0.5% |
100% |
76.5% |
72.7% |
What this shows:
- Drift correction plus ratio normalisation is what solves this task. Any pipeline with those two steps, NeckSense or the classical one, reaches ≥ 99%.
- NeckSense's version runs in integer C with one-shot learning.
- Without drift correction, k-NN collapses: dividing
0.2·gas + driftby its norm points mostly along the drift.
3. Streaming one-shot anomaly detection (D = 16, 20 recurring normal modes at 0.5×–5×, 5% novel chords)
| Detector | AUROC | State | Python time / sample |
|---|---|---|---|
| NeckSense novelty (2% sparse, 1024 cells) | 0.9942 ± 0.0018 |
4 KB (Q16 weights) |
~100–130 us |
| L2 + nearest-neighbour memory, 512 slots | 0.9993 ± 0.0002 |
32 KB (float32) |
~11 us |
| L2 + nearest-neighbour memory, 64 slots | 0.9403 ± 0.0081 |
4 KB (float32) |
~10 us |
| L2 + online Mahalanobis | 0.9581 ± 0.0098 |
1 KB + O(D²) math |
~20 us |
| Online Mahalanobis (raw) | 0.8453 ± 0.0209 |
~18 us | |
| Rolling z-score (raw) | 0.6349 ± 0.0400 |
~12 us | |
| Half-space, 32 projections (raw) | 0.5902 ± 0.0346 |
~36 us |
What this shows:
- At equal memory (4 KB), NeckSense beats a nearest-neighbour memory (0.994 vs 0.940).
- Given 8× the memory and floating point, plain nearest-neighbour is better (0.999).
- Normalisation matters most: every raw-input detector does poorly.
- The Python implementation is slower than the baselines; use the C core where speed matters.
When to use NeckSense, and when not to
Good fit:
- One-shot novelty or one-shot classification on a microcontroller. Integer-only, no weight matrix, a few KB of state, and bit-identical Python for development.
- Sensors with amplitude swings and slow drift.
AntennalNormalizergives drift tracking and ratio normalisation in one integer-friendly block. - Sparse binary codes that can be ANDed, popcounted and updated online.
Use something else when:
- You have a server with RAM and an FPU. SimHash, PQ or HNSW (
faiss,hnswlib) beat FlyHash on recall per byte, and a plain normalised nearest-neighbour memory beats the novelty detector if you can afford the memory. - You already run baseline correction plus normalisation feeding k-NN. On our gas benchmark it is as accurate (100% vs 99.5%).
- You have thousands of labelled examples. Gradient-boosted trees or a trained network will outperform one-shot associative rules.
- Faults are single-channel amplitude spikes. A per-channel z-score is simpler and faster.
Repository layout
| Path | Contents |
|---|---|
necksense/vibration.py |
VibrationFrontEnd (VibrationAnalyzer): 16-ch zero-float chordotonal spectrum & envelope extractor |
necksense/antennal.py |
AntennalNormalizer: drift tracking, divisive normalisation, plume whiff intermittency, Q16.16 parity |
necksense/kenyon.py |
KenyonHasher (FlyHash) and KenyonIndex (popcount search, .npz save/load) |
necksense/mushroom.py |
MushroomNoveltyDetector and 2-compartment MushroomValenceClassifier (KCγ STM + KCα/β LTM) |
necksense/cli.py |
necksense demo, benchmark-quick, hash-csv |
csrc/ |
ANSI C99 core, Makefile (default, NS_TINY=1, ASan+UBSan), 8 self-tests & --json-parity |
arduino/NeckSense/ |
Drop-in Arduino / PlatformIO library + ESP32_Vibration_And_Gas_Anomaly.ino |
scripts/benchmark_necksense.py |
Reproducible benchmark and chart generator |
tests/ |
24 pytest items, including README execution, zero-heap/zero-float C/Arduino audit & live WSL bit parity |
Changelog
2.0.0
- C99 SRAM reduction (
6.9×–24×) &-DNS_TINY=1MCU profile: lossless 17-bitns_novelty_t(uint16_t+ full-weight bitmask) andQ14int16_t+ consolidatedltm_abbitmask inns_valence_tshrink the default 5-struct suite from139,960 B(~140 KB) to20,284 B, and to5,804 B(< 6 KB) under-DNS_TINY=1while keepingv1.1.0Q16.16golden-vector bit parity. - Zero-float vibration & acoustic front-end: added
VibrationFrontEnd(VibrationAnalyzer) and C99ns_vib_fe_t(ns_vib_extract_q16,ns_vib_extract_i16,ns_vib_extract_3axis_i16) extracting 16 homogeneous degree-1 stationary Haar, quadrature resonator, impulse crest and envelope modulation channels (10×+load-invariant 1-shot bearing/motor fault ID; strips static1gtilt on 3-axis accelerometers). - Plume whiff intermittency: added phasic ORN up-crossing tracking (
step_with_whiff(),diagnostics(),ns_antennal_step_whiff) distinguishing pulsatile turbulent plumes from static background clouds. - Two-compartment
KCγ+KCα/βanti-forgetting memory: addedMushroomValenceClassifier.consolidate()andns_valence_consolidate()protecting consolidated synapses from sequential cross-class opponent erosion (0%catastrophic forgetting across sequential tasks) while preserving active opposite-sign extinction. - Arduino library: added drop-in
arduino/NeckSensepackage (library.properties,NeckSense.h, byte-mirrored C99 core andESP32_Vibration_And_Gas_Anomaly.ino).
1.1.0
- Improvement:
MushroomNoveltyDetectornow defaults to 2% sparse codes (wta_frac=0.02). Streaming anomaly AUROC rose from0.9658to0.9942on the benchmark seeds and from0.961to0.997on held-out seeds. For the C core, passk = 20(of 1024) tons_kenyon_initfor novelty. - Benchmark: added baseline-corrected k-NN, nearest-neighbour memories at equal and 8× memory, and L2 + Mahalanobis. 1.0.0 compared only against baselines without drift correction or normalisation, which overstated the gap: "99.5% where k-NN drops to 33%", and "0.966 vs 0.845 AUROC".
- Docs & packaging: published
necksense1.1.0to PyPI (pip install necksense). The C memory table now includes the classifier struct (131 KB by default). Every Python example runs as written.
Scientific foundations
- Olsen, S. R. & Wilson, R. I. (2008). Lateral presynaptic inhibition mediates gain control in an olfactory circuit. Nature, 452, 956–960.
- Nagel, K. I. & Wilson, R. I. (2011). Biophysical mechanisms underlying olfactory receptor neuron dynamics. Nature Neuroscience, 14, 208–216.
- Dasgupta, S., Stevens, C. F. & Navlakha, S. (2017). A neural algorithm for a fundamental computing problem. Science, 358(6364), 793–796.
- Hattori, D. et al. (2017). Representations of novelty and familiarity in a mushroom body compartment. Cell, 169(5), 956–969.
- Aso, Y. et al. (2014). Mushroom body output neurons encode valence and guide memory-based action selection in Drosophila. eLife, 3, e04580.
License
Released under the MIT License. Copyright (c) 2026 Amandeep Singh Bains.
Metadata
Release files for necksense 2.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| necksense-2.0.0.tar.gz | 73.0 kB | Without provenance | Details for necksense-2.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| necksense-2.0.0-py3-none-any.whl | Python 3 | none | any | Details for necksense-2.0.0-py3-none-any.whl |
Total release size: 110.8 kB
Release files / necksense-2.0.0.tar.gz
| Download URL | necksense-2.0.0.tar.gz |
|---|---|
| Size | 73.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
75f1c218ecfac278f499ecff8ffaf67337048826852cf0c9941e4b3feab840f0
|
|
BLAKE2b-256 checksum How to use checksums |
cd95a2b078db8582d13d91b405c55787145156ecd72ea2d9067cb891a4626cc9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Release files / necksense-2.0.0-py3-none-any.whl
| Download URL | necksense-2.0.0-py3-none-any.whl |
|---|---|
| Size | 37.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c84f1edeab54eab28dbb7013ec70efeeac3828db38b26d6157584f244f0446e3
|
|
BLAKE2b-256 checksum How to use checksums |
2b485cb1bd0af5bfdc62494b54a2c6ee6a56bda00285b06376656342528a5e94
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Security for necksense 2.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.