Armor cleans one series of numbers: it finds the readings that are obviously broken (a sudden huge value, a missing reading) and replaces them with sensible values. You get back the cleaned series and the list of places it changed.
A loss curve that suddenly jumps to 10⁶. A sensor channel that drops a reading and
returns NaN. A token-likelihood stream that goes from 0.9 to 0 for one sample. These are
the kinds of single-value glitches that break a downstream pipeline silently: the model
does not complain, it just produces wrong numbers from that point on.
Armor is the shield for a single 1D series. You give it an array; you get back
the same array, with the broken samples replaced by the local baseline, plus the list of
indices that were replaced.
clean has the same shape as x: the two broken samples are replaced by the local baseline
(9999 becomes 0.463). Ordinary samples are kept, except those the engine's trigger classifies
as static, which are replaced by the local median without being listed in anomalies (35 of the
300 here, see Hybrid engine, step 3). anomalies lists the replaced indices,
[100, 200]. K is one flag per sample from the engine's trigger: 1 where the spike rule fired
(sample 100), 0 elsewhere; the NaN is cleaned before the trigger, so sample 200 is in anomalies
with K = 0.
livello_ia = 0 means "actively filter". livello_ia = 1 means "only mark, do not
change the values" — useful when you want to log what the shield would have done
without altering the stream.
Armor looks at a window of samples before the one being scored (never after): its
baseline is the mean of those previous samples (radius min(20, max(3, n // 3))), and a
binary trigger decides whether the sample is an impulse. If it is, it is replaced by the
baseline; otherwise it passes through unchanged. The first two samples are never tested (the
trigger needs two previous points), so a glitch there must be caught by another check.
The consequence, on the running example:
The value 9999 at sample 100 is far above the baseline of the previous samples, so it is
replaced. Index 100 appears in anomalies.
The NaN at sample 200 never enters the window (the shield drops non-finite samples
before the comparison), so the next finite sample is scored against the window ending
at sample 199. Index 200 appears in anomalies, and clean[200] is the baseline.
Armor is a point-level shield. It removes isolated spikes and non-finite values.
It does not remove a slow drift, and it does not classify a regime change: those need a
different tool (see CUSUM and Arbiter).
If your signal is a step change that is genuinely intended, Armor leaves it alone
after the first few samples, because after those samples the step is the new local
baseline.
Armor is built on core.hybrid_engine, the binary-trigger engine that generalises
the logic already verified in Dense-Evolution's own
ia_utils.vector_healing.enhanced_dense_healing_hybrid. See
Hybrid engine for the internals.
livello_ia (0..1): how mature the AI that wears it is.
0.0 -> full clip: the shield FILTERS the data (armor for a newborn AI)
1.0 -> zero clip: the shield does NOT touch the data, it only MARKS (a lens for a mature AI)
FLOOR: the marking of anomalies is NEVER clipped — at no level does the
shield fall silent (the anomaly may BE the answer: never erase it
silently). The level can be measured, not declared:
Armor.livello_da_entropia(entropia, vocab_size).
MEMORY: the shield is a PURE function, with no state (light by design).
The memory belongs to the AI that wears it: to see SLOW DRIFT
pass your historical baseline as riferimento.
static_threshold/initial_damping/alpha — kept for signature compatibility
with earlier versions, not used by the hybrid engine (which has no
state or calibration: it is a pure function, see CHANGELOG 1.1.0).
soglia_anomalia — optional fixed threshold (None = computed from the data);
livello_ia — 0=newborn (filters) .. 1=mature (only marks).
def__init__(self,static_threshold:float=0.15,initial_damping:float=0.85,alpha:float=0.05,soglia_anomalia:float|None=None,livello_ia:float=1.0,)->None:"""static_threshold/initial_damping/alpha — kept for signature compatibility with earlier versions, not used by the hybrid engine (which has no state or calibration: it is a pure function, see CHANGELOG 1.1.0). soglia_anomalia — optional fixed threshold (None = computed from the data); livello_ia — 0=newborn (filters) .. 1=mature (only marks)."""self.soglia=soglia_anomaliaself.livello_ia=float(min(1.0,max(0.0,livello_ia)))
defset_livello(self,livello:float)->None:"""Update the level of the AI (0=weak -> filters; 1=mature -> marks)."""self.livello_ia=float(min(1.0,max(0.0,livello)))
@staticmethoddeflivello_da_entropia(entropia:float,vocab_size:int)->float:"""MEASURED level: 1 - entropy/log(V) (same formula as the dynamic vent)."""importmathreturnmax(0.0,min(1.0,1.0-entropia/(math.log(max(2,vocab_size))+1e-12)))
serie: 1D (list/array). For N-D tensors pass tensor.ravel()
and reshape afterwards (the shield is agnostic: the transposition is enough).
Returns (pulito, K, anomaly indices).
Notes: the first two points and the points found only by the robust
detector are marked but are not replaced in pulito (K is 0 there).
With the default threshold (mean + 2 std of the deviation) a share of
the points of a clean series is marked: about 9% on Gaussian noise.
When more than half of the values are equal the MAD is 0 and every
value different from the median is marked.
defanalizza(self,serie:np.ndarray,riferimento:np.ndarray|None=None)->tuple[np.ndarray,np.ndarray,list[int]]:"""serie: 1D (list/array). For N-D tensors pass tensor.ravel() and reshape afterwards (the shield is agnostic: the transposition is enough). Returns (pulito, K, anomaly indices). Notes: the first two points and the points found only by the robust detector are marked but are not replaced in `pulito` (K is 0 there). With the default threshold (mean + 2 std of the deviation) a share of the points of a clean series is marked: about 9% on Gaussian noise. When more than half of the values are equal the MAD is 0 and every value different from the median is marked."""grezza=np.asarray(serie,dtype=np.float64).ravel()pulito_pieno,trigger,_meta=hybrid_shield(grezza,riferimento)# PERCEPTION at full K (floor: never clipped) — binary by design:# the underlying trigger is strictly 0.0/1.0, not a continuous sigmoid.K=1.0-trigger# raw series sanitized (only NaN/Inf -> local median), the same# sanitization used internally by hybrid_shield (see# _local_nan_fill): it is the real "does not touch the data" at zero# clip, not a signal already pre-filtered by an upstream stage. LOCAL# median, not the mean of the whole series: otherwise a spike elsewhere# in the series distorts the substitute of every NaN, not only the# nearby ones (see CHANGELOG 1.1.1).radius_fill=max(3iflen(grezza)<3elsemin(20,max(3,len(grezza)//3)),3)grezza_pulita=_local_nan_fill(np.where(np.isinf(grezza),np.nan,grezza),radius_fill)# INTERVENTION clipped by the level of the AIclip=1.0-self.livello_iapulito=grezza_pulita-(K*clip)*(grezza_pulita-pulito_pieno)dev=np.abs(grezza_pulita-pulito_pieno)soglia=(self.sogliaifself.sogliaisnotNoneelse(dev.mean()+2.0*dev.std()))anomalie={int(i)foriinnp.where(dev>max(soglia,1e-12))[0]}# robust detector (median/MAD), independent of the hybrid engine —# it also covers the first 2 points of the series, which the trigger# loop never evaluates (see known limit in hybrid_engine.hybrid_shield)finiti=grezza[np.isfinite(grezza)]iffiniti.size>=4:med=float(np.median(finiti))mad=float(np.median(np.abs(finiti-med)))or1e-12z_rob=np.abs((np.nan_to_num(grezza,nan=med)-med)/(1.4826*mad))anomalie|={int(i)foriinnp.where(z_rob>6.0)[0]}anomalie|={int(i)foriinnp.where(~np.isfinite(grezza))[0]}returnpulito,K,sorted(anomalie)
SLOW DRIFT DETECTOR (uses METRO, as suggested by Salvatore).
The boiled frog: infinitesimal increments (e.g. +0.004/step) invisible
to the point-by-point shield. Here we look at the TREND of the
increments: if their mean is systematic with respect to the noise,
there is drift — and METRO (logarithmic scaler) resolves its scale
even when it is below the visible precision. It works WITHOUT a
historical baseline (but the baseline via riferimento in analizza()
remains the stronger method).
Returns (rate_per_step, significant: bool, metro_exponent). The
exponent is 0.0 when the rate is 0. significant compares the shift
with 3 times the noise of the medians; on white noise about 10% of
the series are flagged.
defderiva(self,serie:np.ndarray)->tuple[float,bool,float]:"""SLOW DRIFT DETECTOR (uses METRO, as suggested by Salvatore). The boiled frog: infinitesimal increments (e.g. +0.004/step) invisible to the point-by-point shield. Here we look at the TREND of the increments: if their mean is systematic with respect to the noise, there is drift — and METRO (logarithmic scaler) resolves its scale even when it is below the visible precision. It works WITHOUT a historical baseline (but the baseline via `riferimento` in analizza() remains the stronger method). Returns (rate_per_step, significant: bool, metro_exponent). The exponent is 0.0 when the rate is 0. `significant` compares the shift with 3 times the noise of the medians; on white noise about 10% of the series are flagged. """v=np.asarray(serie,dtype=np.float64).ravel()v=v[np.isfinite(v)]ifv.size<9:return0.0,False,0.0# the signature of drift is the CUMULATIVE SHIFT: median of the first# third vs median of the last third (robust to spikes), compared with# the noise of the series. The single increments stay in the noise —# it is the sum that betrays the frog.terzo=v.size//3med_inizio=float(np.median(v[:terzo]))med_fine=float(np.median(v[-terzo:]))spostamento=med_fine-med_iniziotasso=spostamento/max(1,v.size-terzo)mad_serie=float(np.median(np.abs(v-np.median(v))))or1e-12rumore_mediane=1.4826*mad_serie/np.sqrt(terzo)significativa=abs(spostamento)>3.0*rumore_mediane# METRO: resolves the scale of the infinitesimal (readable even at 1e-12)_v_new,fact=Metro().enc(abs(tasso))esponente=(float(np.log10(fact))-(-4.0)iffact>0andtasso!=0else0.0)# = -log10(|tasso|)returntasso,bool(significativa),esponente
MACHINE-READABLE report (dict ready for json.dumps).
Meant for AIs and other programs: no prose, only data.
Non-finite values become strings ("NaN", "Inf", "-Inf") to give valid JSON.
defreferto_json(self,serie:np.ndarray,nome:str="serie",riferimento:np.ndarray|None=None,)->dict:"""MACHINE-READABLE report (dict ready for json.dumps). Meant for AIs and other programs: no prose, only data. Non-finite values become strings ("NaN", "Inf", "-Inf") to give valid JSON."""pulito,K,anomalie=self.analizza(serie,riferimento)s=np.asarray(serie,dtype=np.float64).ravel()tasso,sig,esp=self.deriva(serie)def_num(v:float)->float|str:"""Convert to float, or to a string ("NaN", "Inf", "-Inf") if not finite, to stay JSON-valid."""ifnp.isfinite(v):returnfloat(v)return"NaN"ifnp.isnan(v)else("Inf"ifv>0else"-Inf")return{"nome":nome,"punti":int(s.size),"livello_ia":self.livello_ia,"anomalie":[{"indice":int(i),"grezzo":_num(s[i]),"pulito":_num(pulito[i]),"K":_num(K[i]),}foriinanomalie],"K_medio":_num(np.mean(K)),"deriva":{"tasso_per_passo":_num(tasso),"significativa":bool(sig),"esponente_metro":_num(esp),},}
defmain()->None:"""CLI entry point: `python -m dense_armor [--json] <file_or_numbers...>`."""importreas_reifhasattr(sys.stdout,"reconfigure"):sys.stdout.reconfigure(encoding="utf-8",errors="replace")argv=sys.argv[1:]come_json="--json"inargvargv=[aforainargvifa!="--json"]ifnotargv:print("USO: python -m dense_armor [--json] <file_con_numeri> oppure python -m dense_armor [--json] n1 n2 n3 ...")sys.exit(0)iflen(argv)==1andos.path.exists(argv[0]):withopen(argv[0],encoding="utf-8",errors="ignore")asfh:token=[tfortin_re.split(r"[\s,;]+",fh.read())ift]nome=os.path.basename(argv[0])origine=f"nel file {nome}"else:token=argvnome="serie da riga di comando"origine="e non e' un file esistente"numeri=[]fortintoken:try:numeri.append(float(t))exceptValueError:print(f"ERRORE: '{t}' non e' un numero ({origine}).")sys.exit(2)serie=np.asarray(numeri,dtype=np.float64)ifcome_json:importjsonas_jsonprint(_json.dumps(Armor().referto_json(serie,nome),ensure_ascii=False))else:Armor().referto(serie,nome)
See also: Hybrid engine — the utility/hybrid_engine.py module
Armor is built on. Orca — the full input + output shield for an entire
model, if you have a model rather than a bare series.