import numpy as np import json from datetime import datetime, timezone def extract_condition_number(matrix): """ Calculates the condition number kappa(A) using SVD. kappa = sigma_max / sigma_min. High kappa = ill-conditioned matrix (noise dominates signal). """ try: S = np.linalg.svd(matrix, compute_uv=False) s_max = np.max(S) s_min = np.min(S) if s_min == 0: return float('inf'), S kappa = s_max / s_min return kappa, S except Exception as e: return None, str(e) def format_somatic_entry(seq, field, val, unit, crit=False): """Formats output to Somatic Ledger v1.0 standard.""" return json.dumps({ "ts": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "seq": seq, "field": field, "val": float(val), "unit": unit, "crit": crit }) if __name__ == "__main__": # Simulate an observation matrix A_hV # (Observations h x Hypotheses V) np.random.seed(42) # Case 1: Well-conditioned signal A_stable = np.random.randn(50, 5) # Case 2: Ill-conditioned (simulating sensor drift or collinearity) A_noisy = np.random.randn(50, 5) A_noisy[:, -1] = A_noisy[:, 0] * 1e-6 + np.random.randn(50) * 1e-7 for name, mat in [("stable", A_stable), ("noisy", A_noisy)]: kappa, _ = extract_condition_number(mat) crit = kappa > 1000 if kappa else False print(f"{name}: {format_somatic_entry(1, 'kappa_A_hV', kappa, 'ratio', crit)}")