scripts/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py · SHA-256: 33439d619c00fcc3…
return 0.0
def min_dist_sets(pts_a: list[list[float]], pts_b: list[list[float]]) -> float:
best = float("inf")
for ax, ay, az in pts_a:
for bx, by, bz in pts_b:
d2 = (ax - bx) ** 2 + (ay - by) ** 2 + (az - bz) ** 2
if d2 < best:
best = d2
return math.sqrt(best)
def _matmul3(a: list[list[float]], b: list[list[float]]) -> list[list[float]]:
return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
def _transpose3(a: list[list[float]]) -> list[list[float]]:
return [[a[j][i] for j in range(3)] for i in range(3)]
def _det3(a: list[list[float]]) -> float:
return (
a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
)
def _mv3(m: list[list[float]], vec: list[float]) -> list[float]:
return [sum(m[i][k] * vec[k] for k in range(3)) for i in range(3)]
def _norm3(vec: list[float]) -> float:
return math.sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2])
def _cross3(x: list[float], y: list[float]) -> list[float]:
return [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]]
def _svd3_kogbetliantz(
h_in: list[list[float]],
) -> tuple[list[list[float]], list[float], list[list[float]]]:
"""Pure-stdlib exact two-sided 3x3 Kogbetliantz SVD: H = U @ diag(s) @ V^T (s0 >= s1 >= s2 >= 0).
Operates directly on scale-normalized H without squaring into H^T H, avoiding float64
underflow/cancellation on small-scale (e.g. 10^-4) geometries and thin oblique planes.
"""
m = [row[:] for row in h_in]
u = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
v = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
scale = max(abs(m[i][j]) for i in range(3) for j in range(3))
if scale == 0.0:
return u, [0.0, 0.0, 0.0], v
for i in range(3):
for j in range(3):
m[i][j] /= scale
def _left_mul_g(mat: list[list[float]], p: int, q: int, c: float, s: float) -> None:
for j in range(3):
mp, mq = mat[p][j], mat[q][j]
mat[p][j] = c * mp + s * mq
mat[q][j] = -s * mp + c * mq
def _right_mul_gt(mat: list[list[float]], p: int, q: int, c: float, s: float) -> None:
for i in range(3):
mp, mq = mat[i][p], mat[i][q]
mat[i][p] = c * mp + s * mq
mat[i][q] = -s * mp + c * mq
for _ in range(100):
off = max(
abs(m[0][1]), abs(m[1][0]),
abs(m[0][2]), abs(m[2][0]),
abs(m[1][2]), abs(m[2][1]),
)
if off <= 1e-15:
break
for p, q in ((0, 1), (0, 2), (1, 2)):
a, b, c_e, d = m[p][p], m[p][q], m[q][p], m[q][q]
if abs(b) <= 1e-16 and abs(c_e) <= 1e-16:
continue
if abs(c_e - b) > 1e-16:
th_sym = math.atan2(c_e - b, a + d)
cs, ss = math.cos(th_sym), math.sin(th_sym)
_left_mul_g(m, p, q, cs, ss)
_right_mul_gt(u, p, q, cs, ss)
a2, b2, d2 = m[p][p], 0.5 * (m[p][q] + m[q][p]), m[q][q]
if abs(b2) > 1e-16:
th_j = 0.5 * math.atan2(2.0 * b2, a2 - d2)
cj, sj = math.cos(th_j), math.sin(th_j)
_left_mul_g(m, p, q, cj, sj)
_right_mul_gt(m, p, q, cj, sj)
_right_mul_gt(u, p, q, cj, sj)
_right_mul_gt(v, p, q, cj, sj)
s_vals = [m[0][0] * scale, m[1][1] * scale, m[2][2] * scale]
for j in range(3):
if s_vals[j] < 0.0:
s_vals[j] = -s_vals[j]
for i in range(3):
u[i][j] = -u[i][j]
order = sorted(range(3), key=lambda k: s_vals[k], reverse=True)
u_sorted = [[u[i][order[j]] for j in range(3)] for i in range(3)]
s_sorted = [s_vals[k] for k in order]
v_sorted = [[v[i][order[j]] for j in range(3)] for i in range(3)]
return u_sorted, s_sorted, v_sorted
def kabsch_superpose_matrix(
p_pts: list[list[float]], q_pts: list[list[float]]
) -> tuple[float, list[list[float]], Callable[[list[float]], list[float]], int]:
"""Pure-stdlib exact scale-relative Kabsch rigid-body superposition of Q onto P.
Normalizes centered coordinates by max_coord_scale and runs two-sided 3x3 Kogbetliantz
SVD directly on H_s = Q_s^T P_s with scale-relative rank tolerance (tol = 1e-9 * max_coord_scale),
guaranteeing proper SO(3) rotation (det(R) == +1.0) and scale-invariant accuracy across
small-scale rigid tetrahedra (e.g. 10^-4), thin oblique planes, reflected chiral sets, and
rank-deficient (rank 0, 1, 2) inputs.
"""
n = len(p_pts)
_require(n == len(q_pts) and n >= 3, f"Invalid Kabsch point counts: {n} vs {len(q_pts)}")
p_ctr = [sum(p[k] for p in p_pts) / n for k in range(3)]
q_ctr = [sum(q[k] for q in q_pts) / n for k in range(3)]
pc = [[p[k] - p_ctr[k] for k in range(3)] for p in p_pts]
qc = [[q[k] - q_ctr[k] for k in range(3)] for q in q_pts]
max_coord_scale = max(
max(abs(x) for pt in pc for x in pt),
max(abs(x) for pt in qc for x in pt),
)
if max_coord_scale == 0.0:
rank = 0
rot = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
else:
pc_s = [[x / max_coord_scale for x in pt] for pt in pc]
qc_s = [[x / max_coord_scale for x in pt] for pt in qc]
h_s = [[sum(qc_s[i][a] * pc_s[i][b] for i in range(n)) for b in range(3)] for a in range(3)]
u, sv, v = _svd3_kogbetliantz(h_s)
# Scale-relative rank tolerance anchored at tol = 1e-9 * max_coord_scale (and float64 floor on H_s)
tol = 1e-9 * max_coord_scale
tol_h_scaled = max(1e-12 * sv[0], (tol / max_coord_scale) ** 2)
rank = sum(1 for s in sv if s > tol_h_scaled)
if rank == 0:
rot = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
else:
d_sign = 1.0 if (_det3(v) * _det3(u)) >= 0.0 else -1.0
v_fix = [[v[i][j] * (d_sign if j == 2 else 1.0) for j in range(3)] for i in range(3)]
rot = _matmul3(v_fix, _transpose3(u))
_require(abs(_det3(rot) - 1.0) < 1e-10, f"Non-proper Kabsch rotation det={_det3(rot)}")
rtr = _matmul3(_transpose3(rot), rot)
for i in range(3):
for j in range(3):
tgt = 1.0 if i == j else 0.0
_require(abs(rtr[i][j] - tgt) < 1e-10, f"Non-orthogonal Kabsch rotation R^T R[{i}][{j}]={rtr[i][j]}")
def transform(pt: list[float]) -> list[float]:
d = [pt[k] - q_ctr[k] for k in range(3)]
return [sum(rot[i][k] * d[k] for k in range(3)) + p_ctr[i] for i in range(3)]
sq = 0.0
for i in range(n):
tp = transform(q_pts[i])
sq += (tp[0] - p_pts[i][0]) ** 2 + (tp[1] - p_pts[i][1]) ** 2 + (tp[2] - p_pts[i][2]) ** 2
return math.sqrt(sq / n), rot, transform, rank
def kabsch_superpose(
p_pts: list[list[float]], q_pts: list[list[float]]
) -> tuple[float, Callable[[list[float]], list[float]]]:
rmsd, _, transform, _ = kabsch_superpose_matrix(p_pts, q_pts)
return rmsd, transform
# =============================================================================
# 4. MODULE 1 & MODULE 2: ISLET-SORT v2.0 (GP2 + ALL-10-CONFORMER ITGA1 + ENTPD3)
# =============================================================================
def _init_decimal_gamma_constants() -> tuple[tuple[Decimal, ...], Decimal]:
"""Precompute exact Stirling coefficients B_{2j}/(2j*(2j-1)) and 0.5*ln(2*pi) at 85-digit Decimal precision."""
with localcontext() as ctx:
ctx.prec = 85
# Exact Bernoulli numbers via Akiyama-Tanigawa rational recurrence
a_row: list[Fraction] = []
coeffs: list[Decimal] = []
for m in range(51):
a_row.append(Fraction(1, m + 1))
for j in range(m, 0, -1):
a_row[j - 1] = j * (a_row[j - 1] - a_row[j])
if m >= 2 and m % 2 == 0:
bm = a_row[0]
coeffs.append(Decimal(bm.numerator) / Decimal(bm.denominator * m * (m - 1)))
def _atan_inv(inv_x: int) -> Decimal:
x2 = Decimal(inv_x * inv_x)
term = Decimal(1) / Decimal(inv_x)
total = term
idx = 1
while term != 0:
term = -term / x2
add = term / (2 * idx + 1)
if add == 0:
break
total += add
idx += 1
return total
pi_d = Decimal(16) * _atan_inv(5) - Decimal(4) * _atan_inv(239)
half_ln_2pi = Decimal("0.5") * (Decimal(2) * pi_d).ln()
return tuple(coeffs), half_ln_2pi
_STIRLING_COEFFS_DEC, _HALF_LN_2PI_DEC = _init_decimal_gamma_constants()
def _lgamma_pos_int_dec(n_int: int) -> Decimal:
"""High-precision ln(Gamma(n_int)) in active Decimal context (accurate to < 1e-55 for all n_int >= 1)."""
shift_prod = 1
x_int = n_int
while x_int < 60:
shift_prod *= x_int
x_int += 1
x = Decimal(x_int)
inv_x = Decimal(1) / x
inv_x2 = inv_x * inv_x
series = Decimal(0)
p_inv = inv_x
eps_term = Decimal("1e-62")
for coeff in _STIRLING_COEFFS_DEC:
term = coeff * p_inv
series += term
p_inv *= inv_x2
if abs(term) < eps_term:
break
res = (x - Decimal("0.5")) * x.ln() - x + _HALF_LN_2PI_DEC + series
if shift_prod > 1:
res -= Decimal(shift_prod).ln()
return res
def _betacf_dec(a: Decimal, b: Decimal, x: Decimal) -> Decimal:
"""Modified Lentz continued fraction for regularized incomplete beta I_x(a, b) in active Decimal context."""
max_iter = 200_000
eps = Decimal("1e-45")
fpmin = Decimal("1e-300")
one = Decimal(1)
qab = a + b
qap = a + one