mirror of
https://github.com/allaunthefox/Research-Stack.git
synced 2026-08-13 14:20:36 +00:00
Create 4-Infrastructure/lib/ with canonical implementations of:
- hashing.py: sha256_bytes, sha256_text, sha256_file
- q16.py: Q16_16 fixed-point constants and arithmetic
- jsonl.py: load_json, load_jsonl, write_jsonl, stable_json, canonical_json_bytes
- fraction_utils.py: Fraction serialization helpers for hardware probes
Refactor 66 files across 4-Infrastructure/{hardware,shim,infra} and
5-Applications/{scripts,tools-scripts,hutter_prize,text-to-cad} to import
from the shared library instead of maintaining local copies.
4-Infrastructure/auto/lib/q16.py now re-exports from lib.q16.
Net: -743 lines (490 added, 1233 removed)
Build: not applicable (Python-only change, py_compile verified on all 71 files)
Co-Authored-By: Allaun Silverfox <bigdataiscoming+9i37y6j2@protonmail.com>
59 lines
1.4 KiB
Python
59 lines
1.4 KiB
Python
"""
|
|
Q16_16 fixed-point arithmetic for deterministic compute across all substrates.
|
|
|
|
All thresholds and metric values are stored as Q16_16 integers.
|
|
One = 0x00010000 = 65536. Float is forbidden in compute paths; the
|
|
converters here are boundary-only (JSON parsing, display).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
Q16_ONE: int = 0x00010000 # 65536
|
|
Q16_HALF: int = 0x00008000
|
|
Q16_SCALE: float = 65536.0
|
|
|
|
|
|
def to_q16(value: float) -> int:
|
|
"""Convert a float to Q16_16. Only allowed at the external boundary."""
|
|
return int(round(value * Q16_ONE))
|
|
|
|
|
|
def from_q16(value: int) -> float:
|
|
"""Convert Q16_16 back to float. Only for display, never in compute."""
|
|
return value / Q16_SCALE
|
|
|
|
|
|
def q16_add(a: int, b: int) -> int:
|
|
return a + b
|
|
|
|
|
|
def q16_sub(a: int, b: int) -> int:
|
|
return a - b
|
|
|
|
|
|
def q16_mul(a: int, b: int) -> int:
|
|
"""Multiply two Q16_16 values with normalization."""
|
|
return (a * b) // Q16_ONE
|
|
|
|
|
|
def q16_div(a: int, b: int) -> int:
|
|
"""Divide two Q16_16 values with normalization."""
|
|
if b == 0:
|
|
return 0
|
|
return (a * Q16_ONE) // b
|
|
|
|
|
|
def q16_gt(a: int, b: int) -> bool:
|
|
return a > b
|
|
|
|
|
|
def q16_ge(a: int, b: int) -> bool:
|
|
return a >= b
|
|
|
|
|
|
def ratio_q16(numerator: float, denominator: float) -> int:
|
|
"""Compute Q16_16 ratio of two floats, clamped to [0, 1]."""
|
|
if denominator == 0:
|
|
return 0
|
|
r = numerator / denominator
|
|
r = max(0.0, min(1.0, r))
|
|
return int(r * Q16_ONE)
|