Skip to content

Toolkit (standalone utilities)

A second part of the package, under core//utility/, independent of Armatura and Orca — none of it participates in the anomaly shield. Generic tools for JAX/NumPy pipelines. Each is tested on its own (test/test_chunk.py, test_compiler.py, test_memory.py, test_preset.py, test_tensor.py, test_noise.py, test_vector.py, test_profiler.py, test_visualizer.py, test_logger.py, test_anwav.py, test_diagnostic.py, test_iodat.py, test_resonance_search.py); every example below was run for real before being written down.

Pipeline & chunking

DynamicAICodegen compiles a list of operation names (relu, sigmoid, tanh, scale, dropout, clip, l2_normalize, identity) into a single JIT-compiled JAX pipeline. Useful when you want to describe a small transformation pipeline declaratively (as data, not as hand-written JAX code) and still get one compiled kernel plus a gradient for free.

from dense_armor.core import DynamicAICodegen

codegen = DynamicAICodegen()
ops = codegen.compile_pipeline(["relu", "l2_normalize"])
out = codegen.run_dynamic_pipeline([-2.0, 3.0, -1.0, 4.0], ops)
# out -> [0. 0.6 0. 0.8]

compiler

core/compiler.py

DynamicAICodegen — compila ricette testuali in pipeline JAX eseguibili.

Le operazioni supportate (relu/sigmoid/tanh/scale/dropout/clip/l2_normalize) sono eseguite con jax.lax.switch dentro un unico kernel JIT, e i tipi sono forzati a float64 lato CPU prima di ogni esecuzione per evitare eccezioni quando la pipeline viene salvata/ricaricata da file binario.

DynamicAICodegen

DynamicAICodegen(seed: int = 42)

Compila ricette testuali in matrici di istruzioni JAX ed esegue pipeline con chunking Anti-OOM e calcolo del gradiente via JAX AD.

seed — seme iniziale della chiave PRNG usata dalle istruzioni stocastiche (es. dropout).

Source code in dense_armor/core/compiler.py
def __init__(self, seed: int = 42) -> None:
    """seed — seme iniziale della chiave PRNG usata dalle istruzioni stocastiche (es. dropout)."""
    self.cmd_map  = CMD_MAP
    self.base_key = jax.random.PRNGKey(seed)

compile_pipeline

compile_pipeline(text_instructions: list) -> np.ndarray

Converte una lista di istruzioni testuali/tuple in matrice float64 di shape (N, 4): [cmd_id, p1, p2, reserved].

Source code in dense_armor/core/compiler.py
def compile_pipeline(self, text_instructions: list) -> np.ndarray:
    """
    Converte una lista di istruzioni testuali/tuple in matrice float64
    di shape (N, 4): [cmd_id, p1, p2, reserved].
    """
    compiled = []
    for cmd in text_instructions:
        if isinstance(cmd, tuple):
            name = str(cmd[0]).lower().strip()
            p1   = float(cmd[1]) if len(cmd) > 1 else 0.0
            p2   = float(cmd[2]) if len(cmd) > 2 else 0.0
        else:
            name = str(cmd).lower().strip()
            if name == 'dropout':
                p1, p2 = 0.8, 0.0
            elif name == 'clip':
                p1, p2 = -1.0, 1.0
            elif name == 'scale':
                p1, p2 = float(_PHI), float(_ALPHA) # <-- Sintonizzazione d'Asse Geometrica
            else:
                p1, p2 = 0.0, 0.0

        cmd_id = self.cmd_map.get(name, 0)
        compiled.append([float(cmd_id), p1, p2, 0.0])

    return np.array(compiled, dtype=np.float64)

run_dynamic_pipeline

run_dynamic_pipeline(input_data: ndarray, compiled_ops: ndarray) -> np.ndarray

Esegue la pipeline compilata in un singolo lax.scan JIT.

Source code in dense_armor/core/compiler.py
def run_dynamic_pipeline(
    self,
    input_data:   np.ndarray,
    compiled_ops: np.ndarray,
) -> np.ndarray:
    """Esegue la pipeline compilata in un singolo lax.scan JIT."""
    res_data, updated_key = _run_pipeline_jit(
        jnp.array(input_data, dtype=jnp.float64),
        jnp.array(compiled_ops, dtype=jnp.float64),
        self.base_key,
    )
    self.base_key = updated_key
    return np.array(res_data)

run_pipeline_with_chunking

run_pipeline_with_chunking(input_data: ndarray, compiled_ops: ndarray, chunk_size: int = 500) -> np.ndarray

[ADVANCED ENGINE]: Suddivide la pipeline in blocchi ed esegue il chunking interamente all'interno dell'acceleratore hardware senza colli di bottiglia CPU.

Source code in dense_armor/core/compiler.py
def run_pipeline_with_chunking(
    self,
    input_data:   np.ndarray,
    compiled_ops: np.ndarray,
    chunk_size:   int = 500,
) -> np.ndarray:
    """
    [ADVANCED ENGINE]: Suddivide la pipeline in blocchi ed esegue il chunking 
    interamente all'interno dell'acceleratore hardware senza colli di bottiglia CPU.
    """
    n_ops = len(compiled_ops)
    # Calcolo dei blocchi necessari preservando la conformazione statica
    n_chunks = (n_ops + chunk_size - 1) // chunk_size
    total_slots = n_chunks * chunk_size

    # Allocazione della matrice di padding condizionata
    padded_ops = np.zeros((total_slots, 4), dtype=np.float64)
    padded_ops[:n_ops] = compiled_ops

    # Riorganizzazione geometrica in tensore 3D (N_Chunks x Chunk_Size x 4)
    structured_chunks = padded_ops.reshape(n_chunks, chunk_size, 4)

    j_data = jnp.array(input_data, dtype=jnp.float64)
    j_chunks = jnp.array(structured_chunks, dtype=jnp.float64)

    res_data = _run_pipeline_chunked_jit(j_data, j_chunks, self.base_key)
    return np.array(res_data)

compute_gradients

compute_gradients(input_data: ndarray, compiled_ops: ndarray) -> np.ndarray

Calcola i gradienti AD della loss, normalizzata da una costante fissa (_PHI_FOUR).

Source code in dense_armor/core/compiler.py
def compute_gradients(
    self,
    input_data:   np.ndarray,
    compiled_ops: np.ndarray,
) -> np.ndarray:
    """Calcola i gradienti AD della loss, normalizzata da una costante fissa (_PHI_FOUR)."""
    j_input     = jnp.array(input_data, dtype=jnp.float64)
    j_ops       = jnp.array(compiled_ops, dtype=jnp.float64)

    grads       = _grad_engine(j_input, j_ops, self.base_key)
    self.base_key = jax.random.split(self.base_key)[0]
    return np.array(grads)

save_compiled_pipeline

save_compiled_pipeline(compiled_ops: ndarray, filename: str = 'compiled_recipe.npy')

Salva la matrice delle operazioni compilate in formato binario compresso .npy.

Source code in dense_armor/core/compiler.py
def save_compiled_pipeline(
    self,
    compiled_ops: np.ndarray,
    filename: str = "compiled_recipe.npy",
):
    """Salva la matrice delle operazioni compilate in formato binario compresso .npy."""
    np.save(filename, compiled_ops)
    logger.info("Advanced Pipeline salvata con successo: '%s'", filename)

load_compiled_pipeline

load_compiled_pipeline(filename: str = 'compiled_recipe.npy') -> np.ndarray

Carica una matrice di operazioni precedentemente salvata.

Source code in dense_armor/core/compiler.py
def load_compiled_pipeline(
    self,
    filename: str = "compiled_recipe.npy",
) -> np.ndarray:
    """Carica una matrice di operazioni precedentemente salvata."""
    if not os.path.exists(filename):
        raise FileNotFoundError(f"File pipeline assente: '{filename}'")
    ops = np.load(filename)
    logger.info("Advanced Pipeline caricata con successo: '%s'  shape=%s", filename, ops.shape)
    return ops

ImageChunker splits a large batch (or a long list of compiled operations) into fixed-size blocks, and merges the results back. Useful when a batch doesn't fit in memory in one shot, or when a long instruction list would otherwise force XLA to recompile every time its length changes.

from dense_armor.core.chunk import ImageChunker
import numpy as np

chunker = ImageChunker(chunk_size=2)
chunks = chunker.split_array(np.arange(5))
# chunks -> [array([0, 1]), array([2, 3]), array([4])]
merged = chunker.merge_chunks(chunks)
# merged -> array([0, 1, 2, 3, 4])

chunk

core/chunk.py.

Segmentazione a blocchi (chunking) per batch di dati e per liste di istruzioni compilate, per evitare ricompilazioni JIT quando cambia il numero di elementi/istruzioni.

ImageChunker

ImageChunker(chunk_size: int = 128)

Divide/ricompone batch di dati e liste di istruzioni in blocchi a dimensione fissa.

Utile quando un batch è troppo grande per stare in memoria in un colpo solo, o quando una lista di istruzioni compilate è troppo lunga per essere eseguita senza far ricompilare XLA ad ogni cambio di lunghezza.

chunk_size — dimensione fissa di ogni blocco (batch o istruzioni).

Source code in dense_armor/core/chunk.py
def __init__(self, chunk_size: int = 128) -> None:
    """chunk_size — dimensione fissa di ogni blocco (batch o istruzioni)."""
    self.chunk_size = int(chunk_size)

split_array

split_array(array: ndarray) -> list

Spezza un array multidimensionale in una lista di sotto-chunk.

Source code in dense_armor/core/chunk.py
def split_array(self, array: np.ndarray) -> list:
    """Spezza un array multidimensionale in una lista di sotto-chunk."""
    total_samples = array.shape[0]
    num_chunks = int(np.ceil(total_samples / self.chunk_size))
    chunks = []
    for b in range(num_chunks):
        start_idx = b * self.chunk_size
        end_idx = min(start_idx + self.chunk_size, total_samples)
        chunks.append(array[start_idx:end_idx])
    return chunks

merge_chunks

merge_chunks(chunks_list: list) -> np.ndarray

Ricombina una lista di sotto-chunk in un unico array compatto.

Source code in dense_armor/core/chunk.py
def merge_chunks(self, chunks_list: list) -> np.ndarray:
    """Ricombina una lista di sotto-chunk in un unico array compatto."""
    if not chunks_list:
        return np.array([], dtype=np.float32)
    # Se l'input è monodimensionale flat, usa concatenate invece di vstack
    if chunks_list[0].ndim == 1:
        return np.concatenate(chunks_list)
    return np.vstack(chunks_list)

execute_pipeline_chunked

execute_pipeline_chunked(codegen_engine, input_vector: ndarray, compiled_ops: list) -> np.ndarray

Esegue le istruzioni del compilatore a blocchi fissi (chunk_size).

Impedisce a XLA di ricompilare la pipeline se cambia il numero di istruzioni, delegando l'esecuzione di ogni blocco a codegen_engine.run_pipeline_with_chunking.

Source code in dense_armor/core/chunk.py
def execute_pipeline_chunked(
    self, codegen_engine, input_vector: np.ndarray, compiled_ops: list
) -> np.ndarray:
    """Esegue le istruzioni del compilatore a blocchi fissi (chunk_size).

    Impedisce a XLA di ricompilare la pipeline se cambia il numero di
    istruzioni, delegando l'esecuzione di ogni blocco a
    ``codegen_engine.run_pipeline_with_chunking``.
    """
    output = jnp.array(input_vector, dtype=jnp.float64)

    # Spezza ed esegue la lista di comandi/operazioni
    for i in range(0, len(compiled_ops), self.chunk_size):
        chunk_ops = compiled_ops[i : i + self.chunk_size]
        output = codegen_engine.run_pipeline_with_chunking(
            output, chunk_ops, chunk_size=self.chunk_size
        )

    return np.array(output, dtype=np.float64)

patch_and_scan_parameters staticmethod

patch_and_scan_parameters(template_ops: ndarray, dynamic_parameters: ndarray) -> jnp.ndarray

Sostituisce i marcatori -1.0 in un template di operazioni con parametri dinamici.

Ogni elemento di template_ops diverso da -1.0 viene ripetuto com'è nelle 4 colonne dell'operazione patchata; ogni marcatore -1.0 viene sostituito, in ordine, col prossimo valore di dynamic_parameters. Implementato con jax.lax.scan per restare compatibile con JIT.

Source code in dense_armor/core/chunk.py
@staticmethod
def patch_and_scan_parameters(
    template_ops: jnp.ndarray, dynamic_parameters: jnp.ndarray
) -> jnp.ndarray:
    """Sostituisce i marcatori -1.0 in un template di operazioni con parametri dinamici.

    Ogni elemento di ``template_ops`` diverso da -1.0 viene ripetuto
    com'è nelle 4 colonne dell'operazione patchata; ogni marcatore -1.0
    viene sostituito, in ordine, col prossimo valore di
    ``dynamic_parameters``. Implementato con ``jax.lax.scan`` per
    restare compatibile con JIT.
    """

    def patch_single_op(carry: jnp.ndarray, op: jnp.ndarray) -> tuple:
        """Un passo di scan: se op e' un marcatore -1.0 lo sostituisce col prossimo parametro dinamico."""
        idx = carry
        # Slot parametrico attivo, da riempire col prossimo valore dinamico
        is_parametric = op == -1.0
        final_param = jnp.where(is_parametric, dynamic_parameters[idx], op)
        next_idx = jnp.where(is_parametric, idx + jnp.int32(1), idx)

        # Restituisce l'operazione patchata a basso livello XLA
        patched_op = jnp.array(
            [op, op, op, final_param], dtype=jnp.float64
        )
        return next_idx, patched_op

    _, patched_compiled_ops = jax.lax.scan(
        patch_single_op, jnp.int32(0), template_ops
    )
    return patched_compiled_ops

Memory guard

UniversalMemoryGuard checks free RAM (and VRAM, if an NVIDIA GPU is present) before a heavy allocation, and computes how many chunks a batch needs to fit safely. Useful as a guard rail right before a large jax/numpy allocation you don't want to OOM on.

from dense_armor.core import UniversalMemoryGuard

guard = UniversalMemoryGuard(min_free_ram_percentage=0.10)
guard.check_memory_safety()  # raises MemoryPressureError if RAM is too low

memory

core/memory.py

UniversalMemoryGuard — controlla RAM e VRAM prima di ogni allocazione pesante. MemoryPressureError — eccezione lanciata quando la memoria è insufficiente.

MemoryPressureError

Bases: Exception

Eccezione lanciata quando la memoria di sistema (RAM/VRAM) è insufficiente.

UniversalMemoryGuard

UniversalMemoryGuard(min_free_ram_percentage: float = 0.15, force_gc: bool = True)

Monitora preventivamente RAM e VRAM prima di ogni allocazione pesante. Calcola il partizionamento ottimale dei dati per prevenire OOM.

min_free_ram_percentage — soglia minima di RAM libera richiesta; force_gc — se True tenta un soft garbage-collect prima di bloccare.

Source code in dense_armor/core/memory.py
def __init__(
    self,
    min_free_ram_percentage: float = 0.15,
    force_gc: bool = True,
) -> None:
    """min_free_ram_percentage — soglia minima di RAM libera richiesta;
    force_gc — se True tenta un soft garbage-collect prima di bloccare."""
    self.min_free_ram = min_free_ram_percentage
    self.force_gc     = force_gc

check_memory_safety

check_memory_safety() -> None

Verifica lo stato della RAM e della VRAM prima di allocazioni critiche.

Source code in dense_armor/core/memory.py
def check_memory_safety(self) -> None:
    """Verifica lo stato della RAM e della VRAM prima di allocazioni critiche."""
    vm             = psutil.virtual_memory()
    free_pct       = vm.available / vm.total

    # Soft GC se vicini alla soglia
    if self.force_gc and free_pct < (self.min_free_ram + 0.10):
        gc.collect()
        if HAS_JAX:
            try:
                jax.clear_caches()
            except Exception:
                # pulizia best-effort e non critica: gli interni di JAX
                # possono fallire in troppi modi diversi per elencarli,
                # ma non deve bloccare il check di sicurezza memoria --
                # loggato (non piu' silenzioso) per restare tracciabile.
                logger.debug("jax.clear_caches() fallito durante il soft GC", exc_info=True)
        vm       = psutil.virtual_memory()
        free_pct = vm.available / vm.total

    if free_pct < self.min_free_ram:
        raise MemoryPressureError(
            f"RAM insufficiente: {free_pct:.1%} disponibile — "
            f"richiesta minima: {self.min_free_ram:.1%}"
        )

    # VRAM check (solo se JAX con backend GPU)
    if HAS_JAX:
        try:
            for dev in jax.devices():
                if dev.platform == "gpu":
                    vram_free = self._get_gpu_free_memory_nvidia()
                    if vram_free < 0.05:
                        raise MemoryPressureError(
                            f"VRAM esaurita su {dev.device_kind}: "
                            f"{vram_free:.1%} libera."
                        )
        except MemoryPressureError:
            raise
        except (RuntimeError, AttributeError):
            # query driver/dispositivo JAX fallita (es. driver GPU non
            # inizializzato correttamente): stesso principio del check
            # RAM, non e' un errore dell'utente -- si prosegue senza
            # bloccare su un dato VRAM che non si riesce a leggere.
            pass

calculate_optimal_chunks

calculate_optimal_chunks(total_items: int, item_size_bytes: int) -> int

Calcola il partizionamento ottimale basato sulla RAM e sul sovraccarico XLA.

Source code in dense_armor/core/memory.py
def calculate_optimal_chunks(self, total_items: int, item_size_bytes: int) -> int:
    """Calcola il partizionamento ottimale basato sulla RAM e sul sovraccarico XLA."""
    self.check_memory_safety()
    vm                     = psutil.virtual_memory()

    # [FIX XLA-PADDING]: Riduciamo la finestra allocabile al 40% per compensare 
    # i buffer temporanei generati durante il tracciamento dei grafi statici
    safe_allocatable_bytes = int(vm.available * 0.40)
    total_size_bytes       = total_items * item_size_bytes

    if total_size_bytes <= safe_allocatable_bytes:
        return 1

    return max(math.ceil(total_size_bytes / safe_allocatable_bytes), 1)

Hardware & profiling

AIHardwareProfiler detects the host's CPU/RAM/JAX backend and computes a safe maximum tensor size for it. Honest caveat: the RAM tiers behind max_tensor_dim (2048/4096/8192, doubled on GPU/TPU) are a rough heuristic, not calibrated against anything specific to this package -- treat it as a starting guess, not a guarantee.

from dense_armor.core import AIHardwareProfiler

profile = AIHardwareProfiler()
print(profile.get_profile_summary())
# Processor: ... | RAM: 7.9 GB | Engine: CPU (JAX Accelerato) | SafeMaxDim: 2048

StochasticAdversarialNoise injects synthetic noise (bitflip, dropout, gaussian blur) into a tensor while preserving its norm. Honest caveat: this is a generic noise injector, not a real adversarial-example generator -- for actually testing the shield's robustness, the attacks in test/test_boundA.pytest_boundE.py (PGD/BIM/MI-FGSM, Carlini-Wagner, DeepFool, Fourier) are the real, calibrated benchmark; this module overlaps with that suite rather than adding to it.

from dense_armor.core import StochasticAdversarialNoise
import numpy as np

out = StochasticAdversarialNoise.inject_noise(
    np.array([1.0, 1.0, 1.0, 1.0]), "bitflip", intensity=1.0, seed=0
)
# out -> [-0.5 -0.5 -0.5 -0.5]  (all flipped + renormalized)

noise

core/noise.py

AIHardwareProfiler — profila l'architettura host per soglie di carico ottimali. StochasticAdversarialNoise — inietta perturbazioni avversariali su CPU e GPU.

AIHardwareProfiler

AIHardwareProfiler()

Profila l'architettura host (CPU/GPU/JAX) per impostare le soglie di carico ottimali.

Profila subito CPU/RAM/backend disponibili sull'host corrente.

Source code in dense_armor/core/noise.py
def __init__(self) -> None:
    """Profila subito CPU/RAM/backend disponibili sull'host corrente."""
    self.processor       = platform.processor()
    self.ram_total_gb    = psutil.virtual_memory().total / (1024 ** 3)
    self.has_jax         = HAS_JAX
    self.backend_device  = self._detect_active_backend()
    self.max_tensor_dim  = self._get_safe_tensor_limit()

get_profile_summary

get_profile_summary() -> str

Riepilogo leggibile su una riga del profilo hardware rilevato.

Source code in dense_armor/core/noise.py
def get_profile_summary(self) -> str:
    """Riepilogo leggibile su una riga del profilo hardware rilevato."""
    return (
        f"Processor: {self.processor} | "
        f"RAM: {self.ram_total_gb:.1f} GB | "
        f"Engine: {self.backend_device} | "
        f"SafeMaxDim: {self.max_tensor_dim}"
    )

StochasticAdversarialNoise

Inietta rumore probabilistico o perturbazioni avversariali nei tensori IA, con dispatch automatico CPU (NumPy) / GPU (JAX).

inject_noise staticmethod

inject_noise(data_vector: ndarray, noise_type: str, intensity: float, seed: int = 42) -> np.ndarray

Applica alterazioni probabilistiche preservando la norma del tensore.

Source code in dense_armor/core/noise.py
@staticmethod
def inject_noise(
    data_vector: np.ndarray,
    noise_type:  str,
    intensity:   float,
    seed:        int = 42,
) -> np.ndarray:
    """Applica alterazioni probabilistiche preservando la norma del tensore."""
    noise_type = noise_type.lower().strip()

    if intensity <= 0.0 or noise_type == "clean":
        return data_vector

    # ── JAX path 
    if HAS_JAX and isinstance(data_vector, (jnp.ndarray, jax.Array)):
        key          = jax.random.PRNGKey(seed)
        key, subkey  = jax.random.split(key)
        trigger_mask = jax.random.uniform(subkey, shape=data_vector.shape) < intensity

        if noise_type == "bitflip":
            output = jnp.where(trigger_mask, -data_vector, data_vector)
        elif noise_type == "dropout_noise":
            output = jnp.where(trigger_mask, 0.0, data_vector)
        elif noise_type == "gaussian_blur":
            key, subkey2 = jax.random.split(key)
            noise  = jax.random.normal(subkey2, shape=data_vector.shape) * intensity
            output = data_vector + noise
        else:
            output = data_vector

        norm = jnp.linalg.norm(output)
        return jnp.where(norm > 0, output / (norm + 1e-15), output)

    # ── NumPy fallback 
    output       = np.array(data_vector, copy=True)
    rng          = np.random.default_rng(seed)
    trigger_mask = rng.random(size=output.shape) < intensity

    if noise_type == "bitflip":
        output = np.where(trigger_mask, -output, output)
    elif noise_type == "dropout_noise":
        output = np.where(trigger_mask, 0.0, output)
    elif noise_type == "gaussian_blur":
        noise  = rng.normal(0.0, intensity, size=output.shape)
        output = output + noise

    norm = np.linalg.norm(output)
    return output / (norm + 1e-15) if norm > 0 else output

PipelineProfiler measures JIT latency in microseconds, with the first (compilation) call timed separately from steady-state calls. This is the module that caught a real bug: DynamicAICodegen's kernels used to be re-defined (and re-jax.jit-wrapped) on every single call, so they never reused XLA's compilation cache -- warm-up and steady-state timed almost identically. Once fixed, the split is real: warm-up is 1700x+ slower than steady-state on a small pipeline.

from dense_armor.core import DynamicAICodegen, PipelineProfiler
import numpy as np

codegen = DynamicAICodegen()
ops = codegen.compile_pipeline(["relu", "tanh"])
stats = PipelineProfiler.measure_microseconds(codegen, np.array([1.0, -2.0, 3.0]), ops, repetitions=5)
# stats -> {"warmup_compilation_us": ..., "mean_execution_us": ..., "repetitions": 5, ...}

profiler

core/profiler.py

PipelineProfiler — misura latenze JIT in microsecondi con warm-up XLA separato.

PipelineProfiler

Profila le prestazioni della pipeline e del filtro in microsecondi.

measure_microseconds staticmethod

measure_microseconds(codegen_instance, input_data: ndarray, compiled_ops: ndarray, repetitions: int = 100) -> dict

Misura latenza JIT della pipeline DynamicAICodegen.

Returns

dict con chiavi: warmup_compilation_us — prima esecuzione (compilazione XLA) mean_execution_us — media a regime repetitions — numero di run

Source code in dense_armor/core/profiler.py
@staticmethod
def measure_microseconds(
    codegen_instance,
    input_data:   np.ndarray,
    compiled_ops: np.ndarray,
    repetitions:  int = 100,
) -> dict:
    """
    Misura latenza JIT della pipeline DynamicAICodegen.

    Returns
    -------
    dict con chiavi:
        warmup_compilation_us  — prima esecuzione (compilazione XLA)
        mean_execution_us      — media a regime
        repetitions            — numero di run
    """
    start_warmup = time.perf_counter_ns()
    warmup_res   = codegen_instance.run_dynamic_pipeline(input_data, compiled_ops)
    _            = jax.block_until_ready(warmup_res)
    warmup_us    = (time.perf_counter_ns() - start_warmup) / 1_000.0

    latencies = []
    for _ in range(repetitions):
        t0  = time.perf_counter_ns()
        res = codegen_instance.run_dynamic_pipeline(input_data, compiled_ops)
        _   = jax.block_until_ready(res)
        latencies.append((time.perf_counter_ns() - t0) / 1_000.0)

    return {
        "warmup_compilation_us": warmup_us,
        "mean_execution_us":     float(np.mean(latencies)),
        "std_execution_us":      float(np.std(latencies)),
        "min_execution_us":      float(np.min(latencies)),
        "repetitions":           repetitions,
    }

measure_stabilizer_microseconds staticmethod

measure_stabilizer_microseconds(stabilizer_instance, raw_batch: ndarray, repetitions: int = 100) -> dict

Misura latenza vmap del filtro AdaptiveSignalStabilizer.

Returns

dict con chiavi: warmup_compilation_us — prima esecuzione (compilazione vmap) mean_execution_us — media a regime repetitions — numero di run

Source code in dense_armor/core/profiler.py
@staticmethod
def measure_stabilizer_microseconds(
    stabilizer_instance,
    raw_batch:   np.ndarray,
    repetitions: int = 100,
) -> dict:
    """
    Misura latenza vmap del filtro AdaptiveSignalStabilizer.

    Returns
    -------
    dict con chiavi:
        warmup_compilation_us  — prima esecuzione (compilazione vmap)
        mean_execution_us      — media a regime
        repetitions            — numero di run
    """
    start_warmup = time.perf_counter_ns()
    warmup_res   = stabilizer_instance.filter_batch_scenarios(raw_batch)
    _            = jax.block_until_ready(warmup_res)
    warmup_us    = (time.perf_counter_ns() - start_warmup) / 1_000.0

    latencies = []
    for _ in range(repetitions):
        t0  = time.perf_counter_ns()
        res = stabilizer_instance.filter_batch_scenarios(raw_batch)
        _   = jax.block_until_ready(res)
        latencies.append((time.perf_counter_ns() - t0) / 1_000.0)

    return {
        "warmup_compilation_us": warmup_us,
        "mean_execution_us":     float(np.mean(latencies)),
        "std_execution_us":      float(np.std(latencies)),
        "min_execution_us":      float(np.min(latencies)),
        "repetitions":           repetitions,
    }

Tensors & configuration

TensorVault is a small library of static (invert, identity, edge_detector, blend) and parametric (scale_project, amplify, bias_shift) transformation matrices, with backend (JAX/NumPy) and precision auto-detected. Honest caveat: these are tiny, fixed matrices (2x2 or a 3-element kernel) -- writing one inline is a single line of code. The real value here is the backend/precision auto-detection, not the matrix catalog itself.

from dense_armor.core import TensorVault

vault = TensorVault()
edge = vault.get_static_transform("edge_detector")
# edge -> [-1. 2. -1.]

tensor

core/tensor.py

TensorVault — custodisce matrici di trasformazione statiche e parametriche. Rileva automaticamente il backend (JAX/NumPy) e la precisione (float32/float64).

TensorVault

TensorVault()

Vault ottimizzato e compatto per matrici statiche e parametriche.

Rileva il backend disponibile (JAX o NumPy) e la precisione attiva.

Source code in dense_armor/core/tensor.py
def __init__(self) -> None:
    """Rileva il backend disponibile (JAX o NumPy) e la precisione attiva."""
    self.xp    = jnp if HAS_JAX else np
    # Lettura sicura di jax_enable_x64 senza usare il vecchio metodo .get()
    is_x64     = getattr(jax.config, "jax_enable_x64", False) if HAS_JAX else False
    self.dtype = self.xp.float64 if (is_x64 or not HAS_JAX) else self.xp.float32

get_static_transform

get_static_transform(name: str) -> np.ndarray

Sintetizza e restituisce la matrice statica richiesta.

Source code in dense_armor/core/tensor.py
def get_static_transform(self, name: str) -> np.ndarray:
    """Sintetizza e restituisce la matrice statica richiesta."""
    xp, dt = self.xp, self.dtype
    transforms = {
        'invert':        lambda: xp.array([[0., 1.], [1., 0.]], dtype=dt),
        'identity':      lambda: xp.eye(2, dtype=dt),
        'edge_detector': lambda: xp.array([-1., 2., -1.], dtype=dt),
        'blend':         lambda: xp.array([[0.5, 0.5], [0.5, 0.5]], dtype=dt),
    }
    key = name.lower()
    if key not in transforms:
        raise KeyError(f"Trasformazione statica '{name}' non disponibile. "
                       f"Disponibili: {list(transforms.keys())}")
    return transforms[key]()

get_parametric_transform

get_parametric_transform(name: str, p: float) -> np.ndarray

Sintetizza dinamicamente la matrice parametrizzata richiesta.

Source code in dense_armor/core/tensor.py
def get_parametric_transform(self, name: str, p: float) -> np.ndarray:
    """Sintetizza dinamicamente la matrice parametrizzata richiesta."""
    xp, dt = self.xp, self.dtype
    transforms = {
        'scale_project': lambda: xp.array(
            [[xp.cos(p), -xp.sin(p)], [xp.sin(p), xp.cos(p)]], dtype=dt),
        'amplify':       lambda: xp.array([[p, 0.], [0., p]], dtype=dt),
        'bias_shift':    lambda: xp.array([p, -p], dtype=dt),
    }
    key = name.lower()
    if key not in transforms:
        raise KeyError(f"Trasformazione parametrica '{name}' non disponibile. "
                       f"Disponibili: {list(transforms.keys())}")
    return transforms[key]()

get_backend_info

get_backend_info() -> str

Descrizione leggibile del backend/precisione attivi (es. 'JAX / GPU Accelerato (32-bit)').

Source code in dense_armor/core/tensor.py
def get_backend_info(self) -> str:
    """Descrizione leggibile del backend/precisione attivi (es. 'JAX / GPU Accelerato (32-bit)')."""
    precision = "64-bit" if self.dtype in (
        np.float64, getattr(jnp, "float64", None)
    ) else "32-bit"
    backend = "JAX / GPU Accelerato" if HAS_JAX else "NumPy / CPU Standard"
    return f"{backend} ({precision})"

ParametricScenarioSimulator runs parallel Monte Carlo simulations over time (via jax.vmap), plus a stochastic decision collapse driven by a probability distribution. Honest caveat: the per-step update (next_state = current_state * 0.95 + param * 0.05) is a fixed exponential-moving-average weighting, not a configurable simulation model -- useful mainly if that specific dynamic matches your scenario, not as a general-purpose simulator.

from dense_armor.core import ParametricScenarioSimulator
import numpy as np

sim = ParametricScenarioSimulator()
result, collapsed = sim.collapse_decision(np.array([0.1, 0.2, 0.3, 0.4]), target_idx=2)
# result -> 0 or 1 (stochastic); collapsed -> the vector renormalized after the choice

BitwisePermutationEngine swaps elements of a combinatorial vector (a 2^n-sized space) based on target/control bit masks. Honest caveat: each call performs exactly one controlled-swap between one pair of indices -- a single primitive, not a general permutation engine. Narrower than the name suggests.

from dense_armor.core import BitwisePermutationEngine
import numpy as np

engine = BitwisePermutationEngine(n_elements=2)  # 2^2 = 4 states
out = engine.apply_bitwise_swap(np.array([0., 1., 2., 3.]), target_bit=1, control_bit=0)
# out -> [0. 1. 3. 2.]

vector

core/vector.py

ParametricScenarioSimulator — simulazioni Monte Carlo massive via JAX vmap. BitwisePermutationEngine — manipolazione vettori combinatori via maschere di bit.

collapse_decision non modifica in-place l'array del chiamante: opera su una copia interna e restituisce (result, collapsed_vector) — il chiamante può ignorare il vettore collassato se non gli serve.

BitwisePermutationEngine

BitwisePermutationEngine(n_elements: int)

Manipolazione di vettori combinatori (spazio 2^n) via maschere di bit. Scambia elementi in array multidimensionali in base a coppie di bit target/control.

n_elements — numero di bit del vettore combinatorio (spazio 2^n_elements).

Source code in dense_armor/core/vector.py
def __init__(self, n_elements: int):
    """n_elements — numero di bit del vettore combinatorio (spazio 2^n_elements)."""
    self.n    = n_elements
    self.size = 1 << n_elements     # 2^N stati possibili

apply_bitwise_swap

apply_bitwise_swap(data: ndarray, target_bit: int, control_bit: int) -> np.ndarray

Permuta gli elementi del vettore in base a maschere binarie.

Source code in dense_armor/core/vector.py
def apply_bitwise_swap(
    self,
    data:         np.ndarray,
    target_bit:   int,
    control_bit:  int,
) -> np.ndarray:
    """Permuta gli elementi del vettore in base a maschere binarie."""
    output   = data.copy()
    t_stride = 1 << (self.n - 1 - target_bit)
    c_stride = 1 << (self.n - 1 - control_bit)

    for i in range(self.size):
        if (i & c_stride) and not (i & t_stride):
            idx_0 = i
            idx_1 = i + t_stride
            output[idx_0], output[idx_1] = data[idx_1], data[idx_0]
    return output

ParametricScenarioSimulator

Simulazioni parallele massive (Monte Carlo) e collasso decisionale stocastico condizionato su distribuzione di probabilità reale.

run_parallel_scenarios

run_parallel_scenarios(base_state: float, parameters_batch: ndarray) -> np.ndarray

Esegue in parallelo (vmap) tutti i batch con jax.lax.scan per l'asse temporale.

Parameters

base_state — stato scalare iniziale per tutti gli scenari parameters_batch — array (N_scenari, T_steps) di parametri temporali

Returns

np.ndarray di shape (N_scenari, T_steps)

Source code in dense_armor/core/vector.py
def run_parallel_scenarios(
    self,
    base_state:        float,
    parameters_batch:  np.ndarray,
) -> np.ndarray:
    """
    Esegue in parallelo (vmap) tutti i batch con jax.lax.scan per l'asse
    temporale.

    Parameters
    ----------
    base_state        — stato scalare iniziale per tutti gli scenari
    parameters_batch  — array (N_scenari, T_steps) di parametri temporali

    Returns
    -------
    np.ndarray di shape (N_scenari, T_steps)
    """
    result = _parallel_engine(jnp.float64(base_state), jnp.asarray(parameters_batch))
    return np.array(result)

collapse_decision

collapse_decision(distribution_vector: ndarray, target_idx: int) -> tuple

Collasso decisionale stocastico condizionato dalla distribuzione.

FIX BUG: non modifica più l'array originale in-place. Opera su una copia interna.

Returns

(result: int, collapsed_vector: np.ndarray) result — 0 o 1 (scelta stocastica) collapsed_vector — vettore normalizzato post-collasso

Source code in dense_armor/core/vector.py
def collapse_decision(
    self,
    distribution_vector: np.ndarray,
    target_idx: int,
) -> tuple:
    """
    Collasso decisionale stocastico condizionato dalla distribuzione.

    FIX BUG: non modifica più l'array originale in-place.
    Opera su una copia interna.

    Returns
    -------
    (result: int, collapsed_vector: np.ndarray)
        result            — 0 o 1 (scelta stocastica)
        collapsed_vector  — vettore normalizzato post-collasso
    """
    vec = np.array(distribution_vector, copy=True, dtype=np.float64)

    prob_0 = np.sum(np.abs(vec[:target_idx]))
    prob_1 = np.sum(np.abs(vec[target_idx:]))
    total  = prob_0 + prob_1

    if total < 1e-12:
        raise RuntimeError(
            "Vettore decisionale a energia zero — impossibile calcolare la scelta."
        )

    prob_0 /= total
    prob_1 /= total

    result    = int(np.random.choice([0, 1], p=[prob_0, prob_1]))
    zero_slot = 1 - result

    if zero_slot == 0:
        vec[:target_idx] = 0.0
    else:
        vec[target_idx:] = 0.0

    new_total = np.sum(np.abs(vec))
    if new_total > 0:
        vec /= new_total

    return result, vec

SIGNAL_STABILIZER_PRESETS are 4 empirically-calibrated parameter sets (balanced_v2, cifar10_best_v1, pure_1d_time_v1, cifar10_hardened_lyapunov) for AdaptiveSignalStabilizer (Orca's Stage 1). Verified, not just declared: on the same noisy series with an outlier, pure_1d_time_v1 (tuned for a more reactive regime) leaves over 2x the residual variance of balanced_v2 -- the presets genuinely configure different filtering behavior, not just different numbers that happen to look distinct.

from dense_armor.core.preset import SIGNAL_STABILIZER_PRESETS
from dense_armor.core.engine import AdaptiveSignalStabilizer

stabilizer = AdaptiveSignalStabilizer(**SIGNAL_STABILIZER_PRESETS["balanced_v2"])

preset

core/preset.py.

Configurazioni calibrate empiricamente per i parametri di AdaptiveSignalStabilizer (Stage 1 di Orca), una per scenario/dominio.

Logging & provenance

MinimalConsoleFormatter / CompactJsonFormatter are two logging.Formatter subclasses — one human-readable for the console, one compact JSON for a log file. Honest caveat: fairly thin wrappers around logging.Formatter -- CompactJsonFormatter's structured fields (module/filename/line number, one JSON object per event) are the main reason to reach for this over writing a one-line formatter yourself.

import logging
from dense_armor.core.logger import MinimalConsoleFormatter

handler = logging.StreamHandler()
handler.setFormatter(MinimalConsoleFormatter())
log = logging.getLogger("demo")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info("esempio")
# [13:07:27] [INFO] esempio

logger

MinimalConsoleFormatter

Bases: Formatter

format

format(record: LogRecord) -> str

Formatta un log record come [HH:MM:SS] [LEVEL] messaggio.

Source code in dense_armor/core/logger.py
def format(self, record: logging.LogRecord) -> str:
    """Formatta un log record come `[HH:MM:SS] [LEVEL] messaggio`."""
    timestamp = datetime.fromtimestamp(record.created).strftime("%H:%M:%S")
    return f"[{timestamp}] [{record.levelname}] {record.getMessage()}"

CompactJsonFormatter

Bases: Formatter

format

format(record: LogRecord) -> str

Formatta un log record come riga JSON compatta (una per evento).

Source code in dense_armor/core/logger.py
def format(self, record: logging.LogRecord) -> str:
    """Formatta un log record come riga JSON compatta (una per evento)."""
    log_payload = {
        "timestamp": datetime.fromtimestamp(record.created).isoformat(),
        "level": record.levelname,
        "module": record.module,
        "filename": record.filename,
        "line_number": record.lineno,
        "message": record.getMessage(),
        "framework": "dense-armor",
    }
    if record.exc_info:
        log_payload["exception"] = self.formatException(record.exc_info)

    return json.dumps(log_payload, ensure_ascii=False)

get_json_file_logger

get_json_file_logger(name: str = 'dense_armor') -> logging.Logger

Logger JSON su file (dense_armor.log), niente output su console (vedi commento sotto). Non usato dal resto della libreria.

Source code in dense_armor/core/logger.py
def get_json_file_logger(name: str = "dense_armor") -> logging.Logger:
    """Logger JSON su file (`dense_armor.log`), niente output su
    console (vedi commento sotto). Non usato dal resto della libreria."""
    logger = logging.getLogger(name)

    if not logger.handlers:
        logger.setLevel(logging.INFO)

        # niente console_handler: le carte girano ad ogni passo del train,
        # duplicare ogni riga anche su stdout inonda il terminale -- il
        # file resta la fonte per il dashboard/i log.
        file_handler = logging.FileHandler("dense_armor.log", encoding="utf-8")
        file_handler.setFormatter(CompactJsonFormatter())
        logger.addHandler(file_handler)

    return logger

AIEngineVisualizer exports a SHA-256-signed provenance archive (parameters, execution environment, integrity hash) and plain-text trend reports comparing raw vs. filtered variance. Useful when you need an auditable record of a run, not just its output.

from dense_armor.core import AIEngineVisualizer

viz = AIEngineVisualizer(output_dir=".")
sha256 = viz.export_provenance_archive([{"step": 1, "value": 0.5}], filename="archive.json")
# sha256 -> "b40db71b3b16d081..." (64 hex chars, matches the hash written into archive.json)

visualizer

core/visualizer.py

AIEngineVisualizer — esportazione provenance con SHA-256 e report testuali.

AIEngineVisualizer

AIEngineVisualizer(output_dir: str = '.')

Strumenti di esportazione per la tracciabilità scientifica. Genera archivi JSON firmati SHA-256 e report testuali del filtro.

output_dir — cartella in cui scrivere archivi/report esportati.

Source code in dense_armor/core/visualizer.py
def __init__(self, output_dir: str = ".") -> None:
    """output_dir — cartella in cui scrivere archivi/report esportati."""
    self.output_dir = output_dir

export_provenance_archive

export_provenance_archive(run_history: list, filename: str = 'ai_provenance_archive.json') -> str

Genera un archivio di tracciabilità scientifica con firma SHA-256.

Returns

sha256_hash : str

Source code in dense_armor/core/visualizer.py
def export_provenance_archive(
    self,
    run_history: list,
    filename:    str = "ai_provenance_archive.json",
) -> str:
    """
    Genera un archivio di tracciabilità scientifica con firma SHA-256.

    Returns
    -------
    sha256_hash : str
    """
    filepath = os.path.join(self.output_dir, filename)

    provenance_payload = {
        "metadata": {
            # FIX BUG: engine_signature non più hardcoded, usa la versione del package
            "engine_signature":    self.ENGINE_SIGNATURE,
            "export_timestamp_utc": time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime()),
            "execution_environment": {
                "os":           platform.system(),
                "architecture": platform.machine(),
                "python":       platform.python_version(),
                "hardware": {
                    "cpu_cores_logical": psutil.cpu_count(logical=True),
                    "total_ram_gb":      round(
                        psutil.virtual_memory().total / (1024 ** 3), 2
                    ),
                },
            },
        },
        "records": run_history,
    }

    raw_bytes  = json.dumps(provenance_payload, sort_keys=True, indent=4).encode('utf-8')
    sha256     = hashlib.sha256(raw_bytes).hexdigest()
    provenance_payload["metadata"]["integrity_sha256"] = sha256

    with open(filepath, "w", encoding="utf-8") as f:
        json.dump(provenance_payload, f, indent=4)

    return sha256

export_trend_report_text staticmethod

export_trend_report_text(raw_signal: ndarray, filtered_signal: ndarray, filename: str = 'ai_trend_report.txt')

Esporta un report testuale compatto delle performance del filtro.

Source code in dense_armor/core/visualizer.py
@staticmethod
def export_trend_report_text(
    raw_signal:      np.ndarray,
    filtered_signal: np.ndarray,
    filename:        str = "ai_trend_report.txt",
):
    """Esporta un report testuale compatto delle performance del filtro."""
    var_raw      = float(np.var(raw_signal))
    var_filtered = float(np.var(filtered_signal))
    damping_pct  = (
        (var_raw - var_filtered) / var_raw * 100.0
        if var_raw > 0 else 0.0
    )
    with open(filename, "w", encoding="utf-8") as f:
        f.write("=== DENSE-ARMOR TELEMETRY REPORT ===\n")
        f.write(f"Engine:                  {AIEngineVisualizer.ENGINE_SIGNATURE}\n")
        f.write(f"Timestamp UTC:           {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())}\n")
        f.write(f"Scenari monitorati:      {raw_signal.shape[0]}\n")
        f.write(f"Passi temporali:         {raw_signal.shape[1]}\n")
        f.write(f"Varianza segnale grezzo: {var_raw:.6f}\n")
        f.write(f"Varianza stabilizzata:   {var_filtered:.6f}\n")
        f.write(f"Smorzamento rumore:      {damping_pct:.2f}%\n")

Audio & data I/O

anwav(fpath) analyzes a WAV file: peak, RMS, estimated loudness (LUFS), crest factor, with a plain-text compliance verdict. Useful as a quick sanity check on an audio file's levels.

from dense_armor.utility.anwav import anwav

anwav("track.wav")
# -> File                      : track.wav
# -> Picco Massimo             : -6.02 dBFS
# ...
# [VERDETTO STANDARD]:
#    CONFORME (Peak): Picco in sicurezza sotto i -1.0 dB.

anwav

anwav

anwav(fpath: str) -> None

Analizza il file wav verificando i parametri di picco e dinamica.

Source code in dense_armor/utility/anwav.py
def anwav(fpath: str) -> None:
    """Analizza il file wav verificando i parametri di picco e dinamica."""
    if not os.path.exists(fpath):
        print(f"[ERR] File {fpath} non trovato!")
        return

    srate, data = wavfile.read(fpath)
    if np.issubdtype(data.dtype, np.floating):
        scala = 1.0
    elif data.dtype == np.int16:
        scala = 32768.0
    elif data.dtype == np.int32:
        scala = 2147483648.0
    else:
        scala = float(np.iinfo(data.dtype).max) + 1.0
    audio = data.astype(np.float32) / scala

    # Calcolo parametri essenziali
    mxval = np.max(np.abs(audio))
    p_db  = 20 * np.log10(mxval) if mxval > 0 else -99.0
    rms   = np.sqrt(np.mean(audio**2))
    r_db  = 20 * np.log10(rms) if rms > 0 else -99.0
    lufs  = r_db + 3.0
    crest = p_db - r_db

    print(f" -> File                      : {fpath}")
    print(f" -> Picco Massimo             : {p_db:.2f} dBFS")
    print(f" -> Volume Medio RMS          : {r_db:.2f} dBFS")
    print(f" -> Loudness (LUFS)           : {lufs:.1f} LUFS")
    print(f" -> Fattore Cresta (Dinamica) : {crest:.2f} dB")
    print("-" * 85)

    print("[VERDETTO STANDARD]:")
    if p_db > -1.0:
        print("   AVVISO: Il picco supera i -1.0 dB. Rischio distorsione.")
    else:
        print("   CONFORME (Peak): Picco in sicurezza sotto i -1.0 dB.")

    if lufs > -7.0:
        print("   AVVISO: Volume molto spinto da Club.")
    elif lufs < -16.0:
        print("   AVVISO: Traccia troppo silenziosa.")
    else:
        print("   CONFORME (Loudness): Rispetta i target standard.")

    if crest < 6.0:
        print("   AVVISO: Traccia troppo schiacciata. Manca impatto.")
    else:
        print("   CONFORME (Dinamica): Mantiene l'impatto analogico.")

diag(iorig, ifilt) compares two audio signals (file paths or NumPy arrays): structural fidelity, removed energy, distortion peak. Useful for checking how much an audio filter/process actually changed a signal, beyond just listening to it.

from dense_armor.utility.diagnostic import diag
import numpy as np

rng = np.random.default_rng(0)
originale = rng.normal(size=2000).astype(np.float32)
filtrato = originale * 0.98
risultato = diag(originale, filtrato)
# risultato["fedelta"] -> 99.96  (percent structural fidelity preserved)

diagnostic

diag

diag(iorig: Union[str, ndarray], ifilt: Union[str, ndarray]) -> Optional[Dict[str, float]]

Esegue un'analisi differenziale profonda accettando sia percorsi file (str) che array NumPy.

Source code in dense_armor/utility/diagnostic.py
def diag(iorig: Union[str, np.ndarray], ifilt: Union[str, np.ndarray]) -> Optional[Dict[str, float]]:
    """Esegue un'analisi differenziale profonda accettando sia percorsi file (str) che array NumPy."""
    if isinstance(iorig, str) and isinstance(ifilt, str):
        if not os.path.exists(iorig) or not os.path.exists(ifilt):
            print("[ERR] Uno dei file audio non è presente.")
            return
        sr1, d_ori = wavfile.read(iorig)
        sr2, d_flt = wavfile.read(ifilt)
        v_ori = d_ori.astype(np.float32) / 32768.0
        v_flt = d_flt.astype(np.float32) / 32768.0
    else:
        v_ori = iorig.astype(np.float32) / 32768.0 if iorig.dtype != np.float32 else iorig.copy()
        v_flt = ifilt.astype(np.float32) / 32768.0 if ifilt.dtype != np.float32 else ifilt.copy()

    if len(v_ori.shape) > 1: v_ori = np.mean(v_ori, axis=1)
    if len(v_flt.shape) > 1: v_flt = np.mean(v_flt, axis=1)

    mlen = min(v_ori.shape[0], v_flt.shape[0])
    v_ori = v_ori[:mlen]
    v_flt = v_flt[:mlen]

    v_dff = v_ori - v_flt
    v_rem = float(np.var(v_dff))
    fdel  = (1.0 - (np.sum(v_dff**2) / np.sum(v_ori**2))) * 100.0 if np.sum(v_ori**2) > 0 else 0.0
    pk_df = float(np.max(np.abs(v_dff))) if len(v_dff) > 0 else 0.0
    pk_db = 20 * np.log10(pk_df) if pk_df > 0 else -99.0
    alter = float(np.mean(np.abs(v_dff) > 0.05) * 100.0) if len(v_dff) > 0 else 0.0

    print("=" * 85)
    print("[DIAGNOSTICA DIFFERENZIALE STEREO] RE-ALLINEAMENTO COMPLETATO")
    print("=" * 85)
    print(f" -> Indice Strutturale di Fedeltà : {fdel:.4f}% (Portante preservata)")
    print(f" -> Energia Totale Rimossa (Var)  : {v_rem:.4e}")
    print(f" -> Picco di Distorsione Segato   : {pk_db:.2f} dBFS (Transiente massimo)")
    print(f" -> Tasso Modulazione Reticolo    : {alter:.2f}% (Campioni modificati)")
    print("-" * 85)

    if fdel > 99.5:
        print("[VERDETTO DIAG] INTERVENTO CHIRURGICO: Solo micro-fruscii rimossi.")
    elif fdel >= 95.0:
        print("[VERDETTO DIAG] RESTAURO EQUILIBRATO: Ottimo bilanciamento inter-canale.")
    else:
        print("[VERDETTO DIAG] MUTAZIONE AGGRESSIVA STEREO: Il Test 2 ha riscritto lo spazio dinamico.")
    print("=" * 85)
    return {"fedelta": fdel, "energia_rimossa": v_rem, "picco_distorsione_db": pk_db, "tasso_modulazione": alter}

lodat(fpath, dname) reads a named tensor out of an HDF5 or NetCDF file. Useful as a thin, uniform loader when a pipeline needs to accept either format without branching on the caller's side.

from dense_armor.utility.iodat import lodat
import h5py, numpy as np

with h5py.File("data.h5", "w") as f:
    f.create_dataset("temperature", data=np.arange(12).reshape(3, 4))

tensore = lodat("data.h5", "temperature")
# tensore.shape -> (3, 4)

iodat

lodat

lodat(fpath: str, dname: str) -> np.ndarray

Rileva l'estensione del file ed estrae il tensore di produzione garantendo la massima compatibilità di I/O.

Source code in dense_armor/utility/iodat.py
def lodat(fpath: str, dname: str) -> np.ndarray:
    """
    Rileva l'estensione del file ed estrae il tensore di produzione
    garantendo la massima compatibilità di I/O.
    """
    if not os.path.exists(fpath):
        raise FileNotFoundError(f"File non trovato: {fpath}")

    exten = os.path.splitext(fpath)[1].lower()

    if exten in ['.h5', '.hdf5']:
        with h5py.File(fpath, 'r') as f:
            data = np.array(f[dname])
        logger.info("Estratto HDF5: %s | Shape: %s", fpath, data.shape)
        return data

    elif exten in ['.nc', '.netcdf']:
        with netCDF4.Dataset(fpath, 'r') as f:
            data = np.array(f.variables[dname][:])
        logger.info("Estratto NetCDF: %s | Shape: %s", fpath, data.shape)
        return data

    else:
        raise ValueError(f"Formato file non supportato: {exten}")

apply_fast_resonance(matrix, query) scores cosine similarity between a query vector and each row of a matrix, modulated by apply_damping_blend (the same operator Orca's gating uses). Verified, not just declared: the modulation is load-bearing, not decorative -- kappa (the damping weight) measurably changes the score (kappa=0 vs. kappa=1 differ well beyond floating-point noise on the same inputs), so this is genuinely different from plain cosine similarity, not a rebrand of it.

from dense_armor.utility.resonance_search import apply_fast_resonance
import numpy as np

rng = np.random.default_rng(0)
db = rng.standard_normal((5, 8)).astype(np.float32)
query = db[2].copy()  # an exact copy of row 2
scores = apply_fast_resonance(db, query)
# int(scores.argmax()) -> 2  (the matching row scores highest)

apply_fast_resonance

apply_fast_resonance(matrix_np: ndarray, query_np: ndarray, kappa: float = 0.8621, delta_eff: float = 0.04341, stress_segnale: float = 0.000942194) -> np.ndarray

Punteggio di risonanza tra ogni riga di matrix_np e query_np, gestendo input vuoti/degeneri.

Source code in dense_armor/utility/resonance_search.py
def apply_fast_resonance(
    matrix_np: np.ndarray, 
    query_np: np.ndarray, 
    kappa: float = 0.86210, 
    delta_eff: float = 0.043410,
    stress_segnale: float = 9.42194e-04
) -> np.ndarray:
    """Punteggio di risonanza tra ogni riga di matrix_np e query_np, gestendo input vuoti/degeneri."""
    if matrix_np is None or query_np is None:
        return np.array([], dtype=np.float32)
    if matrix_np.size == 0 or query_np.size == 0:
        return np.zeros(len(matrix_np), dtype=np.float32)

    q = np.asarray(query_np, dtype=np.float32).squeeze()
    if q.ndim == 0 or q.size == 0:
        return np.zeros(len(matrix_np), dtype=np.float32)
    if q.ndim > 1:
        q = q.flatten()

    qn = np.linalg.norm(q)
    if qn < 1e-8:
        return np.zeros(len(matrix_np), dtype=np.float32)
    q = q / qn

    j_matrix = jnp.array(matrix_np, dtype=jnp.float32)
    j_query = jnp.array(q, dtype=jnp.float32)
    scores = _resonance_scores(j_matrix, j_query, float(kappa), float(delta_eff), float(stress_segnale))
    return np.array(scores, dtype=np.float32)

smoke_test

smoke_test() -> bool

Auto-test rapido: True se apply_fast_resonance produce un risultato sensato su dati sintetici.

Source code in dense_armor/utility/resonance_search.py
def smoke_test() -> bool:
    """Auto-test rapido: True se apply_fast_resonance produce un risultato sensato su dati sintetici."""
    try:
        N, D = 4, 8
        rng = np.random.default_rng(42)
        m = rng.standard_normal((N, D)).astype(np.float32)
        q = rng.standard_normal(D).astype(np.float32)
        s = apply_fast_resonance(m, q)
        assert s.shape == (N,)
        assert not np.all(np.isnan(s))
        assert not np.all(s == 0.0)
        return True
    except Exception:
        # broad by design: uno smoke test deve catturare QUALUNQUE
        # fallimento (import, shape, NaN, assert) e ridurlo a True/False --
        # non sta nascondendo un bug, e' la sua funzione.
        return False