tonynzh2's picture
Validate restricted all-atom SB reference and publish posterior audit
2723b14 verified
Raw History Blame Contribute Delete
15.2 kB
"""Source-only, one-edit Brownian/ancestral-gap reference (CPU validation).
Coordinates and Gaussian means are in Angstrom; variances/covariance rates are
in Angstrom squared. This deliberately broad reference does not impose bonds.
Every birth/reset mean places its actual named atoms at the source CA (or the
permanent source-gap CA midpoint). No target or evolving neighbor defines it.
"""
from __future__ import annotations
from dataclasses import dataclass, field, replace
import hashlib
import json
from typing import Any
import numpy as np
AA = "ACDEFGHIKLMNPQRSTVWY"
SIDECHAINS = dict(zip(AA, [
"CB", "CB SG", "CB CG OD1 OD2", "CB CG CD OE1 OE2",
"CB CG CD1 CD2 CE1 CE2 CZ", "", "CB CG ND1 CD2 NE2",
"CB CG1 CG2 CD1", "CB CG CD CE NZ", "CB CG CD1 CD2",
"CB CG SD CE", "CB CG OD1 ND2", "CB CG CD", "CB CG CD OE1 NE2",
"CB CG CD NE CZ NH1 NH2", "CB OG", "CB OG1 CG2", "CB CG1 CG2",
"CB CG CD1 CD2 NE1 CE2 CE3 CZ2 CZ3 CH2", "CB CG CD1 CD2 CE1 CE2 CZ OH",
]))
# Histidine includes CE1 as in the deployed real-heavy-atom inventory.
SIDECHAINS["H"] = "CB CG ND1 CD2 CE1 NE2"
NAMES = {a: tuple(["N", "CA", "C", "O"] + SIDECHAINS[a].split()) for a in AA}
BACKBONE_NAMES = ("N", "CA", "C", "O")
def _immutable_array(value, dtype=float):
result = np.array(value, dtype=dtype, copy=True)
result.setflags(write=False)
return result
@dataclass(frozen=True)
class Residue:
aa: str
coords: np.ndarray
def __post_init__(self):
if self.aa not in NAMES:
raise ValueError(f"Noncanonical amino acid: {self.aa!r}")
x = _immutable_array(self.coords)
if x.shape != (len(NAMES[self.aa]), 3) or not np.isfinite(x).all():
raise ValueError(f"{self.aa}: expected finite coordinates for {NAMES[self.aa]}")
object.__setattr__(self, "coords", x)
@property
def names(self):
return NAMES[self.aa]
@dataclass(frozen=True)
class Endpoint:
residues: tuple[Residue, ...]
# Target entry j is -1 or the uniquely mandated protected SOURCE origin.
protected_origins: np.ndarray | None = None
def __post_init__(self):
residues = tuple(self.residues)
if not residues or not all(isinstance(r, Residue) for r in residues):
raise ValueError("An endpoint must contain at least one typed residue")
labels = np.full(len(residues), -1, dtype=np.int64) if self.protected_origins is None else self.protected_origins
labels = _immutable_array(labels, np.int64)
if labels.shape != (len(residues),) or np.any(labels < -1):
raise ValueError("protected_origins must have one -1/source-origin label per residue")
nonnegative = labels[labels >= 0]
if len(np.unique(nonnegative)) != len(nonnegative):
raise ValueError("A protected source origin cannot label two target positions")
object.__setattr__(self, "residues", residues)
object.__setattr__(self, "protected_origins", labels)
@property
def sequence(self):
return "".join(r.aa for r in self.residues)
def fingerprint(self):
h = hashlib.sha256(self.sequence.encode())
h.update(self.protected_origins.tobytes())
for r in self.residues:
h.update(r.coords.tobytes())
return h.hexdigest()
def regularize_target(target, sigma_A, rng):
"""Draw endpoint-coordinate jitter BEFORE computing emissions/posterior.
Labels, AA identities and actual atom inventories are retained. sigma=0 is
allowed for kernel/oracle diagnostics and denotes point conditioning, not a
finite-KL claim for an absolutely continuous endpoint law.
"""
if not np.isfinite(sigma_A) or sigma_A < 0:
raise ValueError("Endpoint jitter standard deviation must be nonnegative")
return Endpoint(tuple(Residue(r.aa, r.coords + sigma_A * rng.normal(size=r.coords.shape))
for r in target.residues), target.protected_origins)
@dataclass(frozen=True)
class ReferenceConfig:
horizon: float = 1.0
deletion_rate: float = 0.35
substitution_rate: float = 0.35 # TOTAL race rate, divided over 19 alternatives
birth_rate: float = 0.1 # per immutable ancestral gap
backbone_diffusion_A2: float = 1.0
sidechain_diffusion_A2: float = 1.0
birth_variance_A2: float = 4.0
reset_variance_A2: float = 4.0
aa_probabilities: tuple[float, ...] = tuple([1.0 / 20] * 20)
def __post_init__(self):
positive = ("horizon", "backbone_diffusion_A2", "sidechain_diffusion_A2",
"birth_variance_A2", "reset_variance_A2")
for key in positive:
value = getattr(self, key)
if not np.isfinite(value) or value <= 0:
raise ValueError(f"{key} must be finite and strictly positive")
for key in ("deletion_rate", "substitution_rate", "birth_rate"):
value = getattr(self, key)
if not np.isfinite(value) or value < 0:
raise ValueError(f"{key} must be finite and nonnegative")
p = np.asarray(self.aa_probabilities, dtype=float)
if p.shape != (20,) or not np.isfinite(p).all() or np.any(p <= 0):
raise ValueError("All 20 birth AA probabilities must be finite and positive")
if not np.isclose(p.sum(), 1.0, rtol=0, atol=1e-12):
raise ValueError("Birth AA probabilities must already be normalized")
object.__setattr__(self, "aa_probabilities", tuple(p.tolist()))
@dataclass(frozen=True)
class SourceCondition:
source: Endpoint
protection: np.ndarray
config: ReferenceConfig = field(default_factory=ReferenceConfig)
# A fixed supplied ligand context is permitted; no target ligand is stored.
fixed_ligand_context: Any = None
requested_shortening: float | None = None
def __post_init__(self):
protection = _immutable_array(self.protection, bool)
if protection.shape != (len(self.source.residues),) or not protection.any():
raise ValueError("v0 requires a source-length protection mask with >=1 protected original")
object.__setattr__(self, "protection", protection)
@property
def n(self):
return len(self.source.residues)
@property
def beta(self):
return np.full(self.n + 1, self.config.birth_rate)
def race_rates(self, origin):
if self.protection[origin]:
return 0.0, np.zeros(20)
a = self.source.residues[origin].aa
rates = np.full(20, self.config.substitution_rate / 19)
rates[AA.index(a)] = 0
return self.config.deletion_rate, rates
def original_probabilities(self, origin):
d, s = self.race_rates(origin)
q = d + s.sum()
if q == 0:
return 1.0, 0.0, np.zeros(20)
T = self.config.horizon
# Multiply rates by integrated survival rather than event*rate/q;
# the latter loses small positive support through premature underflow.
integral = T * _negative_exprel(q * T)
return np.exp(-q * T), d * integral, s * integral
def diffusion(self, aa, *, sidechain_only=False):
count = len(NAMES[aa])
values = np.full((count, 3), self.config.sidechain_diffusion_A2)
values[:4] = self.config.backbone_diffusion_A2
return values[4:] if sidechain_only else values
def gap_anchor(self, gap):
if not 0 <= gap <= self.n:
raise ValueError("Invalid ancestral gap")
residues = self.source.residues
if gap == 0:
return residues[0].coords[1]
if gap == self.n:
return residues[-1].coords[1]
return (residues[gap - 1].coords[1] + residues[gap].coords[1]) / 2
def entrance(self, aa, *, gap=None, origin=None):
if (gap is None) == (origin is None):
raise ValueError("Specify exactly one ancestral gap or substitution origin")
is_reset = origin is not None
anchor = self.source.residues[origin].coords[1] if is_reset else self.gap_anchor(gap)
count = len(NAMES[aa]) - (4 if is_reset else 0)
mean = np.broadcast_to(anchor, (count, 3)).copy()
v0 = self.config.reset_variance_A2 if is_reset else self.config.birth_variance_A2
variance = np.full_like(mean, v0)
return mean, variance, self.diffusion(aa, sidechain_only=is_reset)
def fingerprint(self):
h = hashlib.sha256(self.source.fingerprint().encode())
h.update(self.protection.tobytes())
h.update(json.dumps(self.config.__dict__, sort_keys=True).encode())
return h.hexdigest()
def log_gaussian(value, mean, variance):
"""Normalized diagonal-Gaussian log density, including zero-dimensional 1."""
value, mean = np.asarray(value, float), np.asarray(mean, float)
variance = np.broadcast_to(np.asarray(variance, float), value.shape)
if value.shape != mean.shape or not np.isfinite(value).all() or not np.isfinite(mean).all():
raise ValueError("Gaussian coordinate shapes/nonfinite values")
if np.any(variance <= 0) or not np.isfinite(variance).all():
raise ValueError("Gaussian variance must be finite and positive")
return float(-0.5 * np.sum(np.log(2 * np.pi * variance) + (value - mean) ** 2 / variance))
def bridge_moments(x0, endpoint, diffusion, t, horizon=1.0):
if not 0 <= t <= horizon or horizon <= 0:
raise ValueError("Invalid bridge time")
x0, endpoint, diffusion = np.broadcast_arrays(x0, endpoint, diffusion)
return x0 + (t / horizon) * (endpoint - x0), (t * (horizon - t) / horizon) * diffusion
def entrance_moments(mean0, variance0, diffusion, endpoint, t, horizon=1.0):
"""m_t(x) P_(T-t)(x,y) / m_T(y); stable diagonal conditional moments."""
if not 0 <= t <= horizon or horizon <= 0:
raise ValueError("Invalid entrance-law time")
mean0, variance0, diffusion, endpoint = np.broadcast_arrays(mean0, variance0, diffusion, endpoint)
vt, vT = variance0 + t * diffusion, variance0 + horizon * diffusion
mean = mean0 + vt / vT * (endpoint - mean0)
variance = vt * ((horizon - t) * diffusion) / vT
if np.any(variance < 0) or not np.isfinite(variance).all():
raise ValueError("Invalid conditional covariance")
return mean, variance
def draw_gaussian(mean, variance, rng):
variance = np.broadcast_to(variance, np.shape(mean))
if np.any(variance < 0) or not np.isfinite(variance).all():
raise ValueError("Invalid sampling covariance")
return np.asarray(mean) + np.sqrt(variance) * rng.normal(size=np.shape(mean))
def conditioned_event_cdf(q, t, horizon=1.0):
if q <= 0 or not 0 <= t <= horizon:
raise ValueError("A conditioned event requires q>0 and valid time")
return float((t / horizon) * _negative_exprel(q * t) / _negative_exprel(q * horizon))
def conditioned_event_survival(q, t, horizon=1.0):
"""Pending-event mass without subtracting a near-one CDF from one."""
if q <= 0 or not 0 <= t <= horizon:
raise ValueError("A conditioned event requires q>0 and valid time")
return float(np.exp(-q * t) * ((horizon - t) / horizon)
* _negative_exprel(q * (horizon - t)) / _negative_exprel(q * horizon))
def conditioned_event_hazard(q, t, horizon=1.0):
if q <= 0 or not 0 <= t < horizon:
raise ValueError("A conditioned event requires q>0 and t<T")
return float(1.0 / (horizon - t) / _negative_exprel(q * (horizon - t)))
def _negative_exprel(z):
"""(1-exp(-z))/z, with its limit evaluated without subnormal products."""
if abs(z) < 1e-8:
return 1.0 - z / 2.0 + z * z / 6.0
return float(-np.expm1(-z) / z)
@dataclass(frozen=True)
class CurrentResidue(Residue):
origin: int = -1
eligible: bool = False
gap: int = -1
rank: int = -1
@dataclass(frozen=True)
class ModelInputs:
condition: SourceCondition
t: float
residues: tuple[CurrentResidue, ...]
def __post_init__(self):
object.__setattr__(self, "residues", tuple(self.residues))
if not 0 <= self.t < self.condition.config.horizon:
raise ValueError("Model input time must be in [0,T)")
seen, keys, gap_ranks = set(), [], {}
for r in self.residues:
if r.origin >= 0:
if r.origin >= self.condition.n or r.origin in seen or r.gap != -1 or r.rank != -1:
raise ValueError("Invalid or repeated original ancestry")
seen.add(r.origin)
source = self.condition.source.residues[r.origin]
if self.condition.protection[r.origin] and (r.aa != source.aa or r.eligible):
raise ValueError("Protected original chemistry/eligibility changed")
if r.eligible and r.aa != source.aa:
raise ValueError("Substituted originals must be locked")
keys.append((2 * r.origin + 1, 0))
else:
if not 0 <= r.gap <= self.condition.n or r.rank < 0 or r.eligible:
raise ValueError("Invalid born-residue ancestral gap/rank/eligibility")
gap_ranks.setdefault(r.gap, []).append(r.rank)
keys.append((2 * r.gap, r.rank))
if keys != sorted(keys) or len(set(keys)) != len(keys):
raise ValueError("Current chain must preserve ancestral-gap/original ordering")
if any(ranks != list(range(len(ranks))) for ranks in gap_ranks.values()):
raise ValueError("Current born ranks must be consecutive within each gap")
if not set(np.flatnonzero(self.condition.protection)).issubset(seen):
raise ValueError("A protected original disappeared")
@property
def sequence(self):
return "".join(r.aa for r in self.residues)
def apply_delete(state, origin):
selected = [r for r in state.residues if r.origin == origin]
if len(selected) != 1 or not selected[0].eligible:
raise ValueError("Deletion requires an eligible original")
return replace(state, residues=tuple(r for r in state.residues if r.origin != origin))
def apply_substitute(state, origin, aa, sidechain_coords):
selected = [r for r in state.residues if r.origin == origin]
if len(selected) != 1 or not selected[0].eligible or selected[0].aa == aa:
raise ValueError("Substitution requires eligible original and a different AA")
old = selected[0]
new = CurrentResidue(aa, np.concatenate([old.coords[:4], np.asarray(sidechain_coords)]),
origin=origin, eligible=False)
return replace(state, residues=tuple(new if r is old else r for r in state.residues))
def apply_insert(state, gap, rank, aa, coords):
count = sum(r.origin < 0 and r.gap == gap for r in state.residues)
if not 0 <= gap <= state.condition.n or not 0 <= rank <= count:
raise ValueError("Invalid ancestral gap or insertion rank")
residues = [replace(r, rank=r.rank + 1) if r.origin < 0 and r.gap == gap and r.rank >= rank else r
for r in state.residues]
residues.append(CurrentResidue(aa, coords, gap=gap, rank=rank))
residues.sort(key=lambda r: (2 * r.origin + 1, 0) if r.origin >= 0 else (2 * r.gap, r.rank))
return replace(state, residues=tuple(residues))