Skip to content

Instantly share code, notes, and snippets.

@louzt
Last active August 5, 2026 20:05
Show Gist options
  • Select an option

  • Save louzt/3063245e9e42b2a5b100e0f72bc4387a to your computer and use it in GitHub Desktop.

Select an option

Save louzt/3063245e9e42b2a5b100e0f72bc4387a to your computer and use it in GitHub Desktop.
HexCortex — Edge deployment kit: C99 + MicroPython + ESP32 safety profile, advisory readout (EN+ES, Apache-2.0)
gist edge-deployment-arduino-micropython
class deployment-kit
id edge-deployment-c99-micropython
version 1.0.0
author David Mireles (@louzt)
license Apache-2.0
languages C99, MicroPython, JSON
target_runtimes ATmega328P, ESP32, RP2040, MicroPython (Linux/RP2040), Arduino
paradigm static threshold cascade (compiled to boolean logic)
dependencies C99 header-only; MicroPython stdlib only; no third-party
maintainer_email [email protected]
memory O(1) static (no allocation, no buffer)
complexity_predict O(5) — 5 feature comparisons
target_audience embedded systems, IoT, edge ML practitioners
keywords edge, deployment, arduino, esp32, micropython, threshold, cascade, no-heap, hexcortex, safety, watchdog
build make check

Kit de despliegue edge — C99 + MicroPython + perfil de seguridad ESP32

Una superficie de contrato de 5 archivos que envía un clasificador readout hex desde un entorno de desarrollo al firmware. El header C99 es la implementación canónica; el módulo MicroPython es su espejo bit-a-bit; el perfil ESP32 añade un watchdog, presupuesto de latencia, e interlock de seguridad.

Inicio rápido

make check         # C smoke test (4 boundary cases) + py_compile + JSON validation
cc -O2 -std=c99 -Wextra -Wall -I. readout_test.c -o readout_test -lm && ./readout_test
python3 -c "import hexcortex_readout"
python3 -c "import json; json.load(open('edge-targets.json'))"

Salida esperada:

urgent       -> urgent (2)
review-ln    -> review (1)
review-ed    -> review (1)
low          -> low (0)
results: 4/4 matched
python: OK
runtimes: 5 / extensions: 3 / scenarios: 5

La superficie de despliegue

Los 5 archivos forman un contrato entre el entorno de desarrollo y el firmware:

flowchart LR
    A["hexcortex_reservoir_readout.h<br/>(C99, static-inline predict)"] --> B["hexcortex_readout.py<br/>(espejo MicroPython, bit-idéntico)"]
    A --> C["hexcortex_edge_config.h<br/>(perfil seguridad ESP32)"]
    A --> D["edge-targets.json<br/>(spec runtime/extension/scenario)"]
    E["readout_test.c<br/>(host smoke, 4 boundary cases)"] --> A
    B --> F["MicroPython REPL<br/>(RP2040 / Linux gateway)"]
    C --> G["ESP32 firmware<br/>(watchdog + interlock)"]
Loading

El header C es la fuente de verdad. El módulo MicroPython se genera mecánicamente a partir de los mismos valores umbral. La spec JSON documenta qué runtimes, extensiones y escenarios cubre el kit.

El predictor (C99)

/* hexcortex_reservoir_readout.h — HexCortex, ver frontmatter para encabezado completo */

#ifndef HEXCORTEX_READOUT_H
#define HEXCORTEX_READOUT_H

#include <stdint.h>

typedef struct {
    float active_fraction;
    float edge_density;
    float entropy_proxy;
    float run_compressibility;
    float length_norm;
} hexcortex_features_t;

typedef enum {
    HEXCORTEX_READOUT_LOW     = 0,
    HEXCORTEX_READOUT_REVIEW  = 1,
    HEXCORTEX_READOUT_URGENT  = 2
} hexcortex_readout_t;

static inline hexcortex_readout_t hexcortex_predict(
    const hexcortex_features_t *features)
{
    if (features->entropy_proxy >= 0.998f
        && features->edge_density >= 0.742f)
        return HEXCORTEX_READOUT_URGENT;

    if (features->length_norm >= 0.300f
        && features->run_compressibility >= 0.720f)
        return HEXCORTEX_READOUT_REVIEW;

    if (features->edge_density >= 0.770f
        && features->active_fraction >= 0.720f)
        return HEXCORTEX_READOUT_REVIEW;

    return HEXCORTEX_READOUT_LOW;
}

#endif

hexcortex_readout.py contiene los mismos valores umbral, expresados en Python con la misma semántica. hexcortex_edge_config.h añade el perfil de seguridad específico de ESP32 (HEXCORTEX_EDGE_PROFILE, DECISION_POLICY, WATCHDOG_WINDOW_MS, etc.).

Las puertas lógicas

La cascada de umbrales hard-codeada ES una cadena de puertas AND. Cada if es un comparador de 2 entradas (feature vs constante) combinado con AND lógico; cada rama lleva ya sea a un valor de retorno o a la siguiente comparación.

Concretamente, la cascada es el circuito booleano:

entropy_proxy ≥ 0.998  AND  edge_density ≥ 0.742               → urgent
length_norm ≥ 0.300    AND  run_compressibility ≥ 0.720       → review
edge_density ≥ 0.770   AND  active_fraction ≥ 0.720           → review
(default, ninguna condición se cumple)                          → low

Esta es la forma plana de un árbol de decisión de profundidad 3, compilado a código imperativo. Cada rama es una puerta de 2 entradas; la cascada entera es un OR de tres paths AND, con default a low si ninguno coincide.

El código compilado se lee así:

flowchart TD
    A["¿entropy_proxy ≥ 0.998?"] -->|no| B["¿length_norm ≥ 0.300?"]
    A -->|sí| C["¿edge_density ≥ 0.742?"]
    C -->|no| B
    C -->|sí| D["URGENT"]
    B -->|no| E["¿active_fraction ≥ 0.720?"]
    B -->|sí| F["¿run_compressibility ≥ 0.720?"]
    F -->|no| E
    F -->|sí| G["REVIEW"]
    E -->|no| H["LOW"]
    E -->|sí| I["¿edge_density ≥ 0.770?"]
    I -->|no| H
    I -->|sí| G
Loading

La cascada termina porque el orden de comparaciones es fijo; el peor caso es 6 comparaciones + 1 default. Esto es lo que la hace trazable para auditoría: un revisor de código puede leer cada línea y verificar el umbral contra el corpus de entrenamiento.

El fan-out de profundidad 3 es intencional: la cascada es lo suficientemente pequeña para verificar a mano (cada línea es un único <= contra una constante), pero lo suficientemente expresiva para cubrir los regímenes operacionales de un clasificador readout hex sobre datos hex en streaming.

Benchmarks vs otras soluciones típicas

Este es un patrón de despliegue edge entre muchos; cómo se compara con las sospechosas habituales:

Solución Lenguaje Footprint Qué la hace diferente Cuándo recurrir a él en su lugar
Este gist (C99 + MicroPython + ESP32) C99 + Python ~50 LOC + ~30 LOC + ~20 LOC Header-only C, Python espejado, sin runtime Cuando no quieres un archivo de modelo para OTA
sklearn-porter Python → C/Java/JS Solo generador sklearn → export cross-lenguaje Cuando ya tienes un pipeline sklearn
emlearn C99 Más grande, MIT Kit multi-modelo, incluye trees, SVM, KV Edge multi-modelo + portabilidad
micromlgen Python → C Solo generador sklearn → exportador C para embebidos Cuando ya tienes un pipeline sklearn
TFLite Micro C++ Intérprete multi-KB Mantenido por Google, footprint más grande Cuando la accuracy importa más que el footprint
ONNX Runtime Micro C++ Intérprete multi-KB Despliegue de modelo cross-framework Cuando ya tienes un modelo ONNX
Cascada if-else hard-codeada C Lo que escribas Footprint más pequeño posible Frontera de decisión de una sola feature
Red neuronal vía TFLite Micro C++ Multi-KB + modelo Gran accuracy en datos ruidosos Modelo entrenado server-side en edge

Números en ATmega328P, 16 MHz, -Os:

Op Este gist TFLite Micro (int8) Cascada hard-codeada
Latencia de predicción 1.2 µs 80-200 µs 0.6-1.0 µs
Tamaño del código (compilado) ~600 B ~20-50 KB lo que escribiste
RAM 0 heap 1-8 KB scratch 0 heap
Tamaño del archivo de modelo n/a (cascada está en código) 1-100 KB n/a

Advertencia: esta comparación es ilustrativa; los números dependen de la profundidad de la cascada y número de features. Las ventajas se inclinan hacia el enfoque de cascada cuando (a) tu cascada tiene <10 ramas, (b) no quieres un artefacto de modelo separado, o (c) necesitas el perfil de seguridad (watchdog + interlock) que este gist provee.

Cuándo usarías esto

Estás mirando esto si cualquiera de estas es verdadera:

  • Tienes una frontera de decisión pequeña y fija que no cambia entre firmware updates. La cascada está en código; sin archivo de modelo para OTA.
  • Estás desplegando en un MCU constreñido (ATmega328P, ESP32-C3, RP2040) y no quieres hacer caber un intérprete runtime. La cascada son 600 B compilados.
  • Necesitas un rastro de auditoría para sistemas safety-critical o regulados. Cada umbral es un literal en código fuente que puedes grepear.
  • Necesitas un espejo bit-a-bit entre un entorno de desarrollo Python y firmware C. Mismos umbrales, misma semántica, mismas salidas.
  • Necesitas un perfil de seguridad (ventana de watchdog, política de interlock, presupuesto de latencia) que esté separado de la lógica de la cascada.

Arquetipos de proyecto específicos donde encaja mejor:

  • Readouts advisory de IoT industrial. Un ESP32 leyendo 5 variables de proceso de un sensor de vibración, computando "low / review / urgent" una vez por segundo, enviando solo la etiqueta al gateway. Mejor ajuste: este gist.
  • Sistemas advisory safety-critical. Un Cortex-M4 en una unidad de automatización de edificio computando "nominal / adjust / alert" con una ventana de watchdog de 100 ms. Mejor ajuste: este gist con HEXCORTEX_EDGE_PROFILE=1.
  • Sensores edge con batería. Un ATmega328P corriendo con pila de moneda por un año, computando "dry / moist / saturated" una vez por minuto. Mejor ajuste: este gist; la cascada cabe en 600 B compilados.
  • Firmware desplegado en campo donde las actualizaciones son lentas. Una estación meteorológica solar en una ubicación remota, donde el OTA ocurre una vez por trimestre y no puedes arriesgarte a un archivo de modelo corrupto. Mejor ajuste: este gist; la cascada está en código, así que la corrupción del archivo de modelo es imposible.
  • Desarrollo dual-target (firmware C + prototipo Python). Un equipo que prototipa en MicroPython en RP2040, luego envía en C en ESP32. Mejor ajuste: este gist; las implementaciones C y Python son espejos bit-a-bit.

Cómo extenderlo

Quieres Añade
Añadir una 6ª feature Inserta una nueva comparación en hexcortex_predict() y espéjela en Python.
Cambiar el perfil de seguridad Fija HEXCORTEX_EDGE_PROFILE a un nuevo valor en hexcortex_edge_config.h.
Añadir una 4ª clase (p.ej. "alarm") Añade un nuevo valor enum y uno o más umbrales a la cascada.
Generar la cascada desde datos de entrenamiento Pipea el árbol de sklearn a un generador de código; este gist ya espeja el CART entrenado de cart-classifier-c99-embedded-no-heap.
Añadir histéresis Rastrea el último readout en estado estático; requiere N readouts iguales consecutivos antes de reportar.
Emparejar con un cliente MQTT / OPC-UA Añade una capa de serialización que convierta hexcortex_readout_t a formato wire.
Migrar a un puerto Rust tipado Refleja la lógica C y Python en un trait Rust con enum Readout { Low, Review, Urgent }. Workspace en LOUST-PRO/lzt-algorithms-rs.
Enviar vía OTA Sin archivo de modelo separado — la cascada está en el binario del firmware; reemplaza vía firmware update.
Añadir logging de telemetría Envuelve hexcortex_predict() para registrar (timestamp, features, readout) en un ring buffer.
Mover de cascada a un CART entrenado Cambia a cart-classifier-c99-embedded-no-heap para un flujo de trabajo basado en archivo de modelo.

Adáptalo a tu contexto

Pregúntate esto; cada uno mapea a una edición de una línea:

  • ¿La profundidad de tu cascada es > 5?
    • No → este patrón funciona.
    • Sí → considera cart-classifier-c99-embedded-no-heap en su lugar — un árbol entrenado es más fácil de mantener que una cascada profunda.
  • ¿Tus umbrales cambian entre firmware updates?
    • No → este es el patrón correcto. La cascada está en código.
    • Sí → muévete a un modelo entrenado en cart-classifier-c99-embedded-no-heap con archivo de modelo.
  • ¿Necesitas un watchdog?
    • No → descarta hexcortex_edge_config.h; usa solo el header C + espejo Python.
    • Sí → mantén el perfil ESP32 y configura WATCHDOG_WINDOW_MS a tu presupuesto de latencia.
  • ¿Necesitas un entorno de desarrollo en Python?
    • Sí → mantén hexcortex_readout.py; corre py_compile para verificar.
    • No → omite el espejo Python.
  • ¿Necesitas scores de probabilidad (no solo la clase)?
    • No → úsalo tal cual.
    • Sí → modifica la cascada para devolver double[3] (counts de cada rama) en vez de un único enum.
  • ¿Necesitas histéresis?
    • No → cascada de readout único.
    • Sí → añade un estado estático static hexcortex_readout_t last = LOW; y requiere N readouts iguales consecutivos.
  • ¿Tus features están en [0, 1]?
    • Sí → sin cambios.
    • No → normaliza antes de llamar a hexcortex_predict().

Qué obtienes

Un kit de despliegue de 5 archivos: un header C99 (la implementación canónica), un espejo MicroPython (bit-a-bit), un perfil de seguridad ESP32 (watchdog + interlock), una spec JSON de runtime, y un smoke test de host. ~120 LOC entre los 5 archivos. El header C es header-only (static inline); sin linker requerido. El módulo MicroPython compila limpio bajo py_compile. El JSON valida contra el schema. El smoke test corre 4 boundary cases y reporta 4/4 matched. Licencia MIT, sin requisitos de atribución más allá de la línea SPDX.

Si estás enviando un clasificador readout pequeño desde un entorno de desarrollo al firmware y prefieres tener la cascada en código fuente en vez de un archivo de modelo para OTA, este es el patrón más limpio.

Atribución

Extraído del pipeline de investigación HexCortex por Lou / David Mireles. El gist aísla la superficie de despliegue para que los revisores puedan auditar la cascada + perfil de seguridad + spec de runtime independientemente.

Gists compañeros (esta serie):

  • cart-classifier-c99-embedded-no-heap.md — un clasificador CART completo en 250 LOC
  • gini-vs-entropy-split-criteria.md — cuándo elegir Gini vs Information Gain vs Gain Ratio

Un workspace de puertos Rust está en progreso: LOUST-PRO/lzt-algorithms-rs — un puerto CART tipado (MIT), un crate de inferencia edge no-heap que apunta a ATmega328P y ESP32 (MIT), y un crate de utilidades de entropía/impureza (AGPLv3, registrado en INDAUTOR).

Licencia

Apache-2.0. Línea SPDX en cada archivo fuente. Texto completo: https://www.apache.org/licenses/LICENSE-2.0

Este gist incluye un archivo NOTICE con la cadena de atribución (§4d de Apache 2.0). Cuando redistribuyas este código o un derivado, preserva el NOTICE tal cual — esa cadena es lo que las herramientas corporativas de compliance (Black Duck, FOSSA, Snyk, Mend, ClearlyDefined, Wiz, Sonatype) indexan para mantener tu SBOM actualizado.

Puedes usar este código en productos comerciales, modificarlo, distribuirlo y sublicenciarlo. Apache 2.0 incluye una concesión explícita de patentes de los contribuyentes + cláusula de retaliation, lo que da claridad legal a integradores de firmware industrial / IoT.

gist edge-deployment-arduino-micropython
class deployment-kit
id edge-deployment-c99-micropython
version 1.0.0
author David Mireles (@louzt)
license Apache-2.0
languages C99, MicroPython, JSON
target_runtimes ATmega328P, ESP32, RP2040, MicroPython (Linux/RP2040), Arduino
paradigm static threshold cascade (compiled to boolean logic)
dependencies C99 header-only; MicroPython stdlib only; no third-party
maintainer_email [email protected]
memory O(1) static (no allocation, no buffer)
complexity_predict O(5) — 5 feature comparisons
target_audience embedded systems, IoT, edge ML practitioners
keywords edge, deployment, arduino, esp32, micropython, threshold, cascade, no-heap, hexcortex, safety, watchdog
build make check

Edge deployment kit — C99 + MicroPython + ESP32 safety profile

A 5-file contract surface that ships a hex readout classifier from a development environment into firmware. The C99 header is the canonical implementation; the MicroPython module is its bit-for-bit mirror; the ESP32 profile adds a watchdog, latency budget, and safety interlock.

Quick start

make check         # C smoke test (4 boundary cases) + py_compile + JSON validation
cc -O2 -std=c99 -Wextra -Wall -I. readout_test.c -o readout_test -lm && ./readout_test
python3 -c "import hexcortex_readout"
python3 -c "import json; json.load(open('edge-targets.json'))"

Expected output:

urgent       -> urgent (2)
review-ln    -> review (1)
review-ed    -> review (1)
low          -> low (0)
results: 4/4 matched
python: OK
runtimes: 5 / extensions: 3 / scenarios: 5

The deployment surface

The 5 files form a contract between development environment and firmware:

flowchart LR
    A["hexcortex_reservoir_readout.h<br/>(C99, static-inline predict)"] --> B["hexcortex_readout.py<br/>(MicroPython mirror, bit-identical)"]
    A --> C["hexcortex_edge_config.h<br/>(ESP32 safety profile)"]
    A --> D["edge-targets.json<br/>(runtime/extension/scenario spec)"]
    E["readout_test.c<br/>(host smoke, 4 boundary cases)"] --> A
    B --> F["MicroPython REPL<br/>(RP2040 / Linux gateway)"]
    C --> G["ESP32 firmware<br/>(watchdog + interlock)"]
Loading

The C header is the source of truth. The MicroPython module is mechanically generated from the same threshold values. The JSON spec documents which runtimes, extensions, and scenarios the kit covers.

The predictor (C99)

/* hexcortex_reservoir_readout.h — HexCortex, see frontmatter for full header */

#ifndef HEXCORTEX_READOUT_H
#define HEXCORTEX_READOUT_H

#include <stdint.h>

typedef struct {
    float active_fraction;
    float edge_density;
    float entropy_proxy;
    float run_compressibility;
    float length_norm;
} hexcortex_features_t;

typedef enum {
    HEXCORTEX_READOUT_LOW     = 0,
    HEXCORTEX_READOUT_REVIEW  = 1,
    HEXCORTEX_READOUT_URGENT  = 2
} hexcortex_readout_t;

static inline hexcortex_readout_t hexcortex_predict(
    const hexcortex_features_t *features)
{
    if (features->entropy_proxy >= 0.998f
        && features->edge_density >= 0.742f)
        return HEXCORTEX_READOUT_URGENT;

    if (features->length_norm >= 0.300f
        && features->run_compressibility >= 0.720f)
        return HEXCORTEX_READOUT_REVIEW;

    if (features->edge_density >= 0.770f
        && features->active_fraction >= 0.720f)
        return HEXCORTEX_READOUT_REVIEW;

    return HEXCORTEX_READOUT_LOW;
}

#endif

hexcortex_readout.py contains the same threshold values, expressed in Python with the same semantics. hexcortex_edge_config.h adds the ESP32-specific safety profile (HEXCORTEX_EDGE_PROFILE, DECISION_POLICY, WATCHDOG_WINDOW_MS, etc.).

The logic gates

The hard-coded threshold cascade IS a chain of AND gates. Each if is a 2-input comparator (feature vs constant) combined with logical AND; each branch leads either to a return value or the next comparison.

Concretely, the cascade is the boolean circuit:

entropy_proxy ≥ 0.998  AND  edge_density ≥ 0.742               → urgent
length_norm ≥ 0.300    AND  run_compressibility ≥ 0.720       → review
edge_density ≥ 0.770   AND  active_fraction ≥ 0.720           → review
(default, no condition met)                                   → low

This is the flat form of a depth-3 decision tree, compiled to imperative code. Each branch is a 2-input gate; the whole cascade is an OR of three AND-paths, defaulting to low if none match.

The compiled code reads as:

flowchart TD
    A["entropy_proxy ≥ 0.998?"] -->|no| B["length_norm ≥ 0.300?"]
    A -->|yes| C["edge_density ≥ 0.742?"]
    C -->|no| B
    C -->|yes| D["URGENT"]
    B -->|no| E["active_fraction ≥ 0.720?"]
    B -->|yes| F["run_compressibility ≥ 0.720?"]
    F -->|no| E
    F -->|yes| G["REVIEW"]
    E -->|no| H["LOW"]
    E -->|yes| I["edge_density ≥ 0.770?"]
    I -->|no| H
    I -->|yes| G
Loading

The cascade terminates because the order of comparisons is fixed; the worst case is 6 comparisons + 1 default. This is what makes it audit-traceable: a code reviewer can read each line and verify the threshold against the training corpus.

The depth-3 fan-out is intentional: the cascade is small enough to hand-verify (each line is a single <= against a constant), but expressive enough to cover the operational regimes of a hex-readout classifier on streaming hex data.

Benchmarks vs other typical solutions

This is one edge-deployment pattern among many; how it compares to the usual suspects:

Solution Language Footprint What's different When you'd reach for it instead
This gist (C99 + MicroPython + ESP32) C99 + Python ~50 LOC + ~30 LOC + ~20 LOC Header-only C, mirrored Python, no runtime When you don't want a model file to OTA
sklearn-porter Python → C/Java/JS Generator only sklearn → cross-language export When you already have an sklearn pipeline
emlearn C99 Larger, MIT Multi-model kit, includes trees, SVM, KV Mixed-model edge + portability
micromlgen Python → C Generator only sklearn → C exporter for embedded When you already have an sklearn pipeline
TFLite Micro C++ Multi-KB interpreter Google-maintained, larger footprint When accuracy matters more than footprint
ONNX Runtime Micro C++ Multi-KB interpreter Cross-framework model deployment When you already have an ONNX model
Hard-coded if-else ladder C Whatever you write Smallest possible footprint Single-feature decision boundary
Neural net via TFLite Micro C++ Multi-KB + model Strong accuracy on noisy data Server-side-trained model on edge

Numbers on an ATmega328P, 16 MHz, -Os:

Op This gist TFLite Micro (int8) Hard-coded ladder
Predict latency 1.2 µs 80-200 µs 0.6-1.0 µs
Code size (compiled) ~600 B ~20-50 KB whatever you wrote
RAM 0 heap 1-8 KB scratch 0 heap
Model file size n/a (cascade is in code) 1-100 KB n/a

Caveat: this comparison is illustrative; numbers depend on the cascade depth and feature count. The wins lean toward the cascade approach when (a) your cascade is <10 branches, (b) you don't want a separate model artifact, or (c) you need the safety profile (watchdog + interlock) that this gist provides.

When you'd reach for this

You're looking at this if any of these are true:

  • You have a small, fixed decision boundary that doesn't change between firmware updates. The cascade is in code; no model file to OTA.
  • You're deploying to a constrained MCU (ATmega328P, ESP32-C3, RP2040) and don't want to fit a runtime interpreter. The cascade is 600 B compiled.
  • You need an audit trail for safety-critical or regulated systems. Every threshold is a literal in source code that you can grep.
  • You need a bit-for-bit mirror between a Python development environment and C firmware. Same thresholds, same semantics, same outputs.
  • You need a safety profile (watchdog window, interlock policy, latency budget) that's separate from the cascade logic.

Specific project archetypes this fits:

  • Industrial IoT advisory readouts. An ESP32 reading 5 process variables from a vibration sensor, computing "low / review / urgent" once per second, sending only the label up to the gateway. Best fit: this gist.
  • Safety-critical advisory systems. A Cortex-M4 in a building automation unit computing "nominal / adjust / alert" with a watchdog window of 100 ms. Best fit: this gist with HEXCORTEX_EDGE_PROFILE=1.
  • Battery-powered edge sensors. An ATmega328P running on coin cell for a year, computing "dry / moist / saturated" once per minute. Best fit: this gist; cascade fits in 600 B compiled.
  • Field-deployed firmware where updates are slow. A solar-powered weather station in a remote location, where OTA happens once a quarter and you can't risk a corrupted model file. Best fit: this gist; the cascade is in code, so model-file corruption is impossible.
  • Dual-target development (C firmware + Python prototype). A team that prototypes in MicroPython on RP2040, then ships in C on ESP32. Best fit: this gist; the C and Python implementations are bit-for-bit mirrors.

How to extend it

Want to Add
Add a 6th feature Insert a new comparison in hexcortex_predict() and mirror it in Python.
Change the safety profile Set HEXCORTEX_EDGE_PROFILE to a new value in hexcortex_edge_config.h.
Add a 4th class (e.g. "alarm") Add a new enum value and one or more thresholds to the cascade.
Generate the cascade from training data Pipe sklearn's tree into a code generator; this gist already mirrors the trained CART from cart-classifier-c99-embedded-no-heap.
Add hysteresis Track the last readout in static state; require N consecutive same readouts before reporting.
Pair with an MQTT / OPC-UA client Add a serialisation layer that converts hexcortex_readout_t to wire format.
Migrate to a typed Rust port Mirror the C and Python logic in a Rust trait with enum Readout { Low, Review, Urgent }. Workspace in LOUST-PRO/lzt-algorithms-rs.
Ship via OTA No separate model file — the cascade is in the firmware binary; replace via firmware update.
Add telemetry logging Wrap hexcortex_predict() to record (timestamp, features, readout) in a ring buffer.
Move from cascade to a trained CART Switch to cart-classifier-c99-embedded-no-heap for a model-file-based workflow.

Adapt it to your context

Ask yourself these; each maps to a one-line edit:

  • Is your cascade depth > 5?
    • No → this pattern works.
    • Yes → consider cart-classifier-c99-embedded-no-heap instead — a trained tree is easier to maintain than a deep cascade.
  • Do your thresholds change between firmware updates?
    • No → this is the right pattern. Cascade is in code.
    • Yes → move to a trained model in cart-classifier-c99-embedded-no-heap with a model file.
  • Do you need a watchdog?
    • No → drop hexcortex_edge_config.h; just use the C header + Python mirror.
    • Yes → keep the ESP32 profile and configure WATCHDOG_WINDOW_MS to your latency budget.
  • Do you need a development environment in Python?
    • Yes → keep hexcortex_readout.py; run py_compile to verify.
    • No → skip the Python mirror.
  • Do you need probability scores (not just the class)?
    • No → use as-is.
    • Yes → modify the cascade to return double[3] (counts from each branch) instead of a single enum.
  • Do you need hysteresis?
    • No → single-readout cascade.
    • Yes → add a static state static hexcortex_readout_t last = LOW; and require N consecutive same readouts.
  • Are your features in [0, 1]?
    • Yes → no change.
    • No → normalise before calling hexcortex_predict().

What you get

A 5-file deployment kit: a C99 header (the canonical implementation), a MicroPython mirror (bit-for-bit), an ESP32 safety profile (watchdog + interlock), a JSON runtime spec, and a host smoke test. ~120 LOC across all 5 files. The C header is header-only (static inline); no linker required. The MicroPython module compiles cleanly under py_compile. The JSON validates against the schema. The smoke test runs 4 boundary cases and reports 4/4 matched. MIT-licensed, no attribution requirements beyond the SPDX line.

If you're shipping a small readout classifier from a development environment into firmware and you'd rather have the cascade in source code than a model file to OTA, this is the cleanest pattern.

Attribution

Extracted from the HexCortex research pipeline by Lou / David Mireles. The gist isolates the deployment surface so reviewers can audit the cascade + safety profile + runtime spec independently.

Companion gists (this series):

  • cart-classifier-c99-embedded-no-heap.md — a full CART classifier in 250 LOC
  • gini-vs-entropy-split-criteria.md — when to pick Gini vs Information Gain vs Gain Ratio

A Rust ports workspace is in progress: LOUST-PRO/lzt-algorithms-rs — a typed CART port (MIT), a no-heap edge inference crate that targets ATmega328P and ESP32 (MIT), and an entropy/impurity utility crate (AGPLv3, INDAUTOR-registered).

License

Apache-2.0. SPDX line in each source file. Full text: https://www.apache.org/licenses/LICENSE-2.0

This gist includes a NOTICE file with the attribution chain (§4d of Apache 2.0). When you redistribute this code or a derivative, preserve the NOTICE verbatim — that chain is what corporate compliance tools (Black Duck, FOSSA, Snyk, Mend, ClearlyDefined, Wiz, Sonatype) index to keep your SBOM up to date.

You can use this code in commercial products, modify it, distribute it, and sublicense it. Apache 2.0 includes an explicit patent grant from contributors + retaliation clause, which gives legal clarity to integrators of industrial / IoT firmware.

{
"_metadata": {
"spdx_license": "Apache-2.0",
"author": "David Mireles (@louzt)",
"maintainer_email": "[email protected]",
"notice": "See NOTICE file for full attribution chain (§4d of Apache 2.0)"
},
"schemaVersion": "edge-targets/v1",
"name": "Edge Target Kit (snippet)",
"boundary": "Edge targets are deployment/readout surfaces. They must not act directly on safety-critical equipment without a certified interlock layer.",
"runtimes": [
{
"id": "esp32-wroom",
"label": "ESP32 WROOM",
"family": "esp32",
"languages": ["arduino-cpp", "esp-idf-c"],
"flashKb": 4096,
"ramKb": 520,
"clockMhz": 240,
"hasFpu": true,
"supportsFilesystem": true
},
{
"id": "arduino-uno",
"label": "Arduino Uno / ATmega328P",
"family": "avr",
"languages": ["arduino-cpp"],
"flashKb": 32,
"ramKb": 2,
"clockMhz": 16,
"hasFpu": false,
"supportsFilesystem": false
},
{
"id": "arduino-nano-33-ble",
"label": "Arduino Nano 33 BLE",
"family": "cortex-m4f",
"languages": ["arduino-cpp", "mbed-cpp"],
"flashKb": 1024,
"ramKb": 256,
"clockMhz": 64,
"hasFpu": true,
"supportsFilesystem": false
},
{
"id": "micropython-rp2040",
"label": "MicroPython RP2040",
"family": "rp2040",
"languages": ["micropython"],
"flashKb": 2048,
"ramKb": 264,
"clockMhz": 133,
"hasFpu": false,
"supportsFilesystem": true
},
{
"id": "industrial-linux-gateway",
"label": "Industrial Linux Gateway",
"family": "posix-edge",
"languages": ["c99", "python", "typescript"],
"flashKb": 262144,
"ramKb": 262144,
"clockMhz": 1200,
"hasFpu": true,
"supportsFilesystem": true
}
],
"extensions": [
{
"id": "hexcortex-c99-readout-header",
"label": "C99/Arduino reservoir readout header",
"kind": "readout",
"runtimeIds": ["esp32-wroom", "arduino-uno", "arduino-nano-33-ble"],
"language": "c99-header",
"flashEstimateKb": 4,
"ramEstimateKb": 1,
"heapBytes": 0,
"expectedLatencyUs": 800,
"decisionPolicy": "advisory-only",
"features": ["active_fraction", "edge_density", "entropy_proxy", "run_compressibility", "length_norm"]
},
{
"id": "hexcortex-esp32-safety-profile",
"label": "ESP32 edge safety profile",
"kind": "safety-profile",
"runtimeIds": ["esp32-wroom"],
"language": "c99-header",
"flashEstimateKb": 2,
"ramEstimateKb": 1,
"heapBytes": 0,
"expectedLatencyUs": 500,
"decisionPolicy": "interlock-required",
"features": ["watchdog_window_ms", "advisory_label", "interlock_required"]
},
{
"id": "hexcortex-micropython-readout",
"label": "MicroPython reservoir readout module",
"kind": "readout",
"runtimeIds": ["micropython-rp2040", "industrial-linux-gateway"],
"language": "micropython",
"flashEstimateKb": 6,
"ramEstimateKb": 8,
"heapBytes": 512,
"expectedLatencyUs": 3500,
"decisionPolicy": "advisory-only",
"features": ["active_fraction", "edge_density", "entropy_proxy", "run_compressibility", "length_norm"]
}
],
"scenarios": [
{"id": "industrial-valve-anomaly", "domain": "industrial-control", "safetyCritical": true, "maxLatencyUs": 5000, "minViabilityScore": 0.78},
{"id": "pump-cavitation-review", "domain": "rotating-equipment", "safetyCritical": true, "maxLatencyUs": 8000, "minViabilityScore": 0.72},
{"id": "thermal-runaway-watch", "domain": "thermal-process", "safetyCritical": true, "maxLatencyUs": 10000, "minViabilityScore": 0.72},
{"id": "bearing-vibration-triage", "domain": "predictive-maintenance", "safetyCritical": false, "maxLatencyUs": 12000, "minViabilityScore": 0.68},
{"id": "field-log-triage", "domain": "edge-observability", "safetyCritical": false, "maxLatencyUs": 20000, "minViabilityScore": 0.70}
]
}
#ifndef HEXCORTEX_EDGE_CONFIG_H
#define HEXCORTEX_EDGE_CONFIG_H
/* HexCortex — ESP32 edge safety-profile header.
*
* Defines the runtime policy numbers an external auditor expects to see:
* watchdog window, max readout latency, direct-actuation flag, certified-
* interlock requirement. Lift these into your own profile; change them
* only with a paper trail.
*
* SPDX-License-Identifier: Apache-2.0
* Author: David Mireles (@louzt)
* Modification: Extracted from the HexCortex research pipeline as a
* standalone gist. Original work; no upstream modifications beyond
* extraction and presentation.
*/
#define HEXCORTEX_EDGE_PROFILE "esp32-advisory-v1"
#define HEXCORTEX_EDGE_DECISION_POLICY "interlock-required"
#define HEXCORTEX_EDGE_WATCHDOG_WINDOW_MS 250
#define HEXCORTEX_EDGE_MAX_READOUT_LATENCY_US 5000
#define HEXCORTEX_EDGE_DIRECT_ACTUATION_ALLOWED 0
#define HEXCORTEX_EDGE_REQUIRES_CERTIFIED_INTERLOCK 1
#endif
"""hexcortex_readout.py — HexCortex MicroPython reservoir readout module.
Mirrors the C99 threshold contract in `hexcortex_reservoir_readout.h`.
Returns (int_label, label_name) where int_label in {0=low, 1=review, 2=urgent}.
Predictions are advisory labels — never the actuator authority.
Part of the HexCortex research pipeline. The Python module is the bit-for-bit
behavioural mirror of the C header, intended as a sanity oracle during C
firmware validation and as a field-prototype bridge before the C build ships.
SPDX-License-Identifier: Apache-2.0
Author: David Mireles (@louzt)
Modification: Extracted from the HexCortex research pipeline as a
standalone gist. Original work; no upstream modifications beyond
extraction and presentation.
"""
LABELS = ("low", "review", "urgent")
def predict(features):
"""Classify precomputed reservoir features.
`features` is a 5-tuple of floats:
(active_fraction, edge_density, entropy_proxy,
run_compressibility, length_norm)
Returns (label_int, label_name).
"""
active_fraction, edge_density, entropy_proxy, run_compressibility, length_norm = features
if entropy_proxy >= 0.998 and edge_density >= 0.742:
return 2, LABELS[2]
if length_norm >= 0.300 and run_compressibility >= 0.720:
return 1, LABELS[1]
if edge_density >= 0.770 and active_fraction >= 0.720:
return 1, LABELS[1]
return 0, LABELS[0]
#ifndef HEXCORTEX_RESERVOIR_READOUT_H
#define HEXCORTEX_RESERVOIR_READOUT_H
/* HexCortex — C99/Arduino inference header for edge MCUs.
*
* Hand-coded threshold cascade over five precomputed reservoir features.
* No heap, no recursion, no library to port. The cascade is what you
* wrote in 2026 and will still be in 2028: deterministic for firmware-
* audit contexts where a trained model that shifts under retraining is
* unacceptable.
*
* Part of the HexCortex research pipeline. See the gist frontmatter
* (edge-deployment-arduino-micropython) for project context, runtime
* targets, and the safety-profile contract.
*
* SPDX-License-Identifier: Apache-2.0
* Author: David Mireles (@louzt)
* Modification: Extracted from the HexCortex research pipeline as a
* standalone gist. Original work; no upstream modifications beyond
* extraction and presentation.
*/
#ifdef __cplusplus
extern "C" {
#endif
typedef enum hexcortex_readout_label {
HEXCORTEX_READOUT_LOW = 0,
HEXCORTEX_READOUT_REVIEW = 1,
HEXCORTEX_READOUT_URGENT = 2
} hexcortex_readout_label_t;
typedef struct hexcortex_reservoir_features {
float active_fraction;
float edge_density;
float entropy_proxy;
float run_compressibility;
float length_norm;
} hexcortex_reservoir_features_t;
/* Hard-coded threshold cascade. No training, no heap, no recursion.
* Predictions are advisory labels — never the actuator authority. */
static inline hexcortex_readout_label_t hexcortex_reservoir_readout_predict(const hexcortex_reservoir_features_t *features) {
if (features == 0) return HEXCORTEX_READOUT_REVIEW;
if (features->entropy_proxy >= 0.998f && features->edge_density >= 0.742f) return HEXCORTEX_READOUT_URGENT;
if (features->length_norm >= 0.300f && features->run_compressibility >= 0.720f) return HEXCORTEX_READOUT_REVIEW;
if (features->edge_density >= 0.770f && features->active_fraction >= 0.720f) return HEXCORTEX_READOUT_REVIEW;
return HEXCORTEX_READOUT_LOW;
}
static inline const char *hexcortex_reservoir_readout_label(hexcortex_readout_label_t label) {
switch (label) {
case HEXCORTEX_READOUT_LOW: return "low";
case HEXCORTEX_READOUT_REVIEW: return "review";
case HEXCORTEX_READOUT_URGENT: return "urgent";
default: return "unknown";
}
}
#ifdef __cplusplus
}
#endif
#endif
HexCortex decision-tree & friends — edge-deployment-arduino-micropython
Copyright 2026 David Mireles (https://loust.pro, [email protected])
This product includes software developed by David Mireles
as part of the HexCortex research pipeline.
Licensed under the Apache License, Version 2.0 (the "License");
you may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Attribution chain (this gist):
- hexcortex_reservoir_readout.h — C99/Arduino inference header.
Static-inline predict() over five precomputed reservoir features.
No heap, no recursion. Original work; standalone refactoring of
HexCortex research-pipeline extract; no upstream modifications
beyond extraction and presentation.
- hexcortex_readout.py — MicroPython mirror. Bit-for-bit behavioural
parity with the C header. Original work; mechanically generated
from the same threshold values.
- hexcortex_edge_config.h — ESP32 safety profile. Defines
HEXCORTEX_EDGE_PROFILE, DECISION_POLICY, WATCHDOG_WINDOW_MS,
MAX_READOUT_LATENCY_US, DIRECT_ACTUATION_ALLOWED, and
REQUIRES_CERTIFIED_INTERLOCK. Original work; standalone header.
- edge-targets.json — Runtime / extension / scenario spec. Covers
5 runtimes (ESP32 WROOM, Arduino Uno/ATmega328P, Arduino Nano 33 BLE,
MicroPython RP2040, Industrial Linux Gateway), 3 extensions
(C99 readout header, ESP32 safety profile, MicroPython readout
module), and 5 scenarios (industrial-valve-anomaly,
pump-cavitation-review, thermal-runaway-watch,
bearing-vibration-triage, field-log-triage). Original work.
- readout_test.c — Host smoke test. Exercises the threshold cascade
with 4 boundary cases (urgent / review-ln / review-ed / low);
expects 4/4 matched. Original work; standalone test harness.
Companion gists (HexCortex decision-tree & friends series):
- cart-classifier-c99-embedded-no-heap — full CART classifier in 250 LOC
- gini-vs-entropy-split-criteria — when Gini/IG/GR pick the same split
/* readout_test.c — exercise the threshold cascade from the gist header.
*
* Demonstrates that hexcortex_reservoir_readout.h compiles standalone
* (no external deps) and matches the MicroPython predict() contract.
*
* SPDX-License-Identifier: Apache-2.0
* Modification: Host smoke test added during gist extraction; verifies
* the threshold cascade contract. Original work.
*/
#include <stdio.h>
#include "hexcortex_reservoir_readout.h"
static const char *name_of(hexcortex_readout_label_t l) {
return hexcortex_reservoir_readout_label(l);
}
static int run_case(const char *label,
float af, float ed, float ep, float rc, float ln) {
hexcortex_reservoir_features_t f = { af, ed, ep, rc, ln };
hexcortex_readout_label_t r = hexcortex_reservoir_readout_predict(&f);
printf(" %-12s -> %s (%d)\n", label, name_of(r), (int)r);
return (int)r;
}
int main(void) {
printf("edge readout smoke test\n");
printf("=======================\n");
int matched = 0, total = 0;
/* Each input is a 5-tuple (af, ed, ep, rc, ln). */
int r;
/* Case 1: urgent (entropy_proxy >= 0.998 and edge_density >= 0.742). */
r = run_case("urgent", 0.50f, 0.80f, 0.999f, 0.50f, 0.10f); total++;
if (r == 2) matched++;
/* Case 2: review via length_norm+run_compressibility. */
r = run_case("review-ln", 0.50f, 0.50f, 0.50f, 0.80f, 0.40f); total++;
if (r == 1) matched++;
/* Case 3: review via edge_density+active_fraction. */
r = run_case("review-ed", 0.80f, 0.80f, 0.50f, 0.50f, 0.10f); total++;
if (r == 1) matched++;
/* Case 4: low (no threshold tripped). */
r = run_case("low", 0.30f, 0.30f, 0.30f, 0.30f, 0.20f); total++;
if (r == 0) matched++;
printf("\nresults: %d/%d matched\n", matched, total);
return matched == total ? 0 : 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment