"""Independent discrete oracle for THEORY_HANDOFF.md (not the missing original). This module deliberately does not import the production ancestry DP or teacher. It enumerates a finite birth-cap CTMC, routing boundary births into overflow, and independently integrates all original outcomes and gap subsequences. """ from __future__ import annotations from dataclasses import dataclass from itertools import combinations, product from math import comb, exp, expm1, factorial from typing import Iterator import numpy as np from scipy.special import gammaln, logsumexp @dataclass(frozen=True) class State: originals: tuple[str, ...] # U, D, or S: gaps: tuple[tuple[str, ...], ...] @dataclass(frozen=True) class Reference: source: tuple[str, ...] = ("A", "B", "A") alphabet: tuple[str, ...] = ("A", "B") protected: tuple[bool, ...] = (False, True, False) deletion: tuple[float, ...] = (0.41, 0.0, 0.27) substitution: tuple[float, ...] = (0.33, 0.0, 0.52) beta: tuple[float, ...] = (0.19, 0.31, 0.23, 0.17) pi: tuple[tuple[float, ...], ...] = ((0.7, 0.3), (0.4, 0.6), (0.55, 0.45), (0.25, 0.75)) def __post_init__(self): n = len(self.source) if not (len(self.protected) == len(self.deletion) == len(self.substitution) == n): raise ValueError("Original-parameter sizes differ") if len(self.beta) != n + 1 or len(self.pi) != n + 1: raise ValueError("Gap-parameter sizes differ") for row in self.pi: if len(row) != len(self.alphabet) or min(row) < 0 or not np.isclose(sum(row), 1): raise ValueError("Invalid normalized AA distribution") if min((*self.deletion, *self.substitution, *self.beta)) < 0: raise ValueError("Negative reference rate") for i, flag in enumerate(self.protected): if flag and (self.deletion[i] or self.substitution[i]): raise ValueError("Protected original has a nonzero edit rate") @property def n(self): return len(self.source) @property def initial(self): return State(("U",) * self.n, ((),) * (self.n + 1)) def type_probability(self, g, aa): return self.pi[g][self.alphabet.index(aa)] if aa in self.alphabet else 0.0 def substitution_rate(self, i, aa): if aa == self.source[i] or aa not in self.alphabet: return 0.0 return self.substitution[i] / (len(self.alphabet) - 1) Token = tuple[str, int | None] # AA, explicit protected source identity Target = tuple[Token, ...] def observable(ref: Reference, state: State) -> Target: out = [] for g in range(ref.n + 1): out.extend((aa, None) for aa in state.gaps[g]) if g < ref.n and state.originals[g] != "D": aa = ref.source[g] if state.originals[g] == "U" else state.originals[g][2:] out.append((aa, g if ref.protected[g] else None)) return tuple(out) def _compositions(total: int, count: int): if count == 1: yield (total,) else: for k in range(total + 1): for tail in _compositions(total - k, count - 1): yield (k,) + tail def enumerate_states(ref: Reference, birth_cap: int = 2): options = [(("U",) if ref.protected[i] else ("U", "D") + tuple("S:" + a for a in ref.alphabet if a != ref.source[i])) for i in range(ref.n)] gap_options = [] for total in range(birth_cap + 1): for sizes in _compositions(total, ref.n + 1): for word in product(ref.alphabet, repeat=total): start, gaps = 0, [] for size in sizes: gaps.append(tuple(word[start:start + size])) start += size gap_options.append(tuple(gaps)) states = [State(tuple(o), g) for o in product(*options) for g in gap_options] states.append(None) # absorbing overflow, including all boundary birth mass return states def transitions(ref: Reference, state: State, birth_cap: int | None = None): """Physical channel rates, including multiplicities giving identical states.""" for i, status in enumerate(state.originals): if status != "U" or ref.protected[i]: continue new = list(state.originals) new[i] = "D" yield ("D", i), State(tuple(new), state.gaps), ref.deletion[i] for aa in ref.alphabet: rate = ref.substitution_rate(i, aa) if rate: new[i] = "S:" + aa yield ("S", i, aa), State(tuple(new), state.gaps), rate total = sum(map(len, state.gaps)) for g, gap in enumerate(state.gaps): for r in range(len(gap) + 1): for aa in ref.alphabet: rate = ref.beta[g] / (len(gap) + 1) * ref.type_probability(g, aa) gaps = list(state.gaps) gaps[g] = gap[:r] + (aa,) + gap[r:] nxt = None if birth_cap is not None and total >= birth_cap else State(state.originals, tuple(gaps)) yield ("I", g, r, aa), nxt, rate def generator(ref: Reference, birth_cap: int = 2): states = enumerate_states(ref, birth_cap) index = {state: i for i, state in enumerate(states)} q = np.zeros((len(states), len(states))) for i, state in enumerate(states[:-1]): for _, nxt, rate in transitions(ref, state, birth_cap): q[i, index[nxt]] += rate q[i, i] -= rate return states, index, q def gap_kernel(ref: Reference, g: int, current: tuple[str, ...], target: Target, delta: float, *, omit_binomial=False): """Uniform existing-subsequence embeddings, independent of the CTMC matrix.""" k, K = len(current), len(target) if k > K or delta < 0: return 0.0 ell = K - k poisson = exp(-ref.beta[g] * delta) * (ref.beta[g] * delta) ** ell / factorial(ell) total = 0.0 for positions in combinations(range(K), k): if any(target[j] != (aa, None) for aa, j in zip(current, positions)): continue selected = set(positions) weight = 1.0 for j, (aa, label) in enumerate(target): if j not in selected: weight *= ref.type_probability(g, aa) if label is None else 0.0 total += weight return poisson * total / (1 if omit_binomial else comb(K, k)) def gap_remaining_loglik(log_current, log_birth, beta: float, delta: float): """Generic independent continuous/discrete gap oracle, enumerating embeddings. log_current[r,j] is the transition log density from current born residue r to target j; log_birth[j] is its *terminal* entrance/type log density. All normalized densities must already include any type/protection zero support. Cost is binomial(K,k); use only for tiny validation cases. """ lc, lb = np.asarray(log_current, float), np.asarray(log_birth, float) if lc.ndim != 2 or lb.ndim != 1 or lc.shape[1] != len(lb): raise ValueError("Expected log_current[k,K], log_birth[K]") if beta < 0 or delta < 0: raise ValueError("Negative rate or remaining horizon") k, K = lc.shape ell = K - k if ell < 0 or ((beta == 0 or delta == 0) and ell): return -np.inf log_poisson = -beta * delta + (ell * np.log(beta * delta) if ell else 0.0) - gammaln(ell + 1) log_embeddings = [] for positions in combinations(range(K), k): chosen = set(positions) terms = [lc[r, j] for r, j in enumerate(positions)] terms.extend(lb[j] for j in range(K) if j not in chosen) log_embeddings.append(sum(terms)) log_binomial = gammaln(K + 1) - gammaln(k + 1) - gammaln(K - k + 1) return float(log_poisson - log_binomial + logsumexp(log_embeddings)) def original_weights(ref: Reference, state: State, i: int, token: Token | None, delta: float): status = state.originals[i] if status == "D": return float(token is None) if token is not None: aa, label = token expected = i if ref.protected[i] else None if label != expected: return 0.0 if status.startswith("S:"): return float(token is not None and token[0] == status[2:]) q = ref.deletion[i] + ref.substitution[i] event_integral = -expm1(-q * delta) / q if q else delta if token is None: return ref.deletion[i] * event_integral if token[0] == ref.source[i]: return exp(-q * delta) return ref.substitution_rate(i, token[0]) * event_integral def remaining_likelihood(ref: Reference, state: State | None, target: Target, delta: float): """Brute recursive sum over target blocks; no production recurrence imported.""" if state is None: return 0.0 def visit(g, j): value = 0.0 for stop in range(j, len(target) + 1): gap = gap_kernel(ref, g, state.gaps[g], target[j:stop], delta) if not gap: continue if g == ref.n: value += gap * float(stop == len(target)) else: value += gap * original_weights(ref, state, g, None, delta) * visit(g + 1, stop) if stop < len(target): value += gap * original_weights(ref, state, g, target[stop], delta) * visit(g + 1, stop + 1) return value return visit(0, 0) @dataclass(frozen=True) class Ancestry: source_to_target: tuple[int, ...] gaps: tuple[tuple[int, ...], ...] weight: float def enumerate_ancestries(ref: Reference, target: Target, horizon=1.0): """Unnormalized endpoint histories by explicit recursion (tiny cases only).""" histories = [] def visit(g, j, origins, gaps, weight): for stop in range(j, len(target) + 1): bw = gap_kernel(ref, g, (), target[j:stop], horizon) if not bw: continue newg = gaps + (tuple(range(j, stop)),) if g == ref.n: if stop == len(target): histories.append(Ancestry(origins, newg, weight * bw)) continue dw = original_weights(ref, ref.initial, g, None, horizon) if dw: visit(g + 1, stop, origins + (-1,), newg, weight * bw * dw) if stop < len(target): mw = original_weights(ref, ref.initial, g, target[stop], horizon) if mw: visit(g + 1, stop + 1, origins + (stop,), newg, weight * bw * mw) visit(0, 0, (), (), 1.0) return histories def direct_components(ref: Reference, target: Target, ancestry: Ancestry, t: float, horizon=1.0): """Enumerate random-time latent Bernoullis and their complete jump labels.""" if not 0 <= t < horizon: raise ValueError("Require 0 <= t < horizon") original_options = [] for i, j in enumerate(ancestry.source_to_target): outcome = "D" if j < 0 else ("U" if target[j][0] == ref.source[i] else "S:" + target[j][0]) if outcome == "U": original_options.append((("U", 1.0, None),)) else: q = ref.deletion[i] + ref.substitution[i] normalizer = -expm1(-q * horizon) p = -expm1(-q * t) / normalizer # Avoid subtracting p from one near T: flux multiplies this tiny # pending probability by the diverging conditioned edit hazard. pending_p = exp(-q * t) * -expm1(-q * (horizon - t)) / normalizer original_options.append((("U", pending_p, outcome), (outcome, p, None))) births = [(g, j) for g, js in enumerate(ancestry.gaps) for j in js] for originals in product(*original_options): for present in product((False, True), repeat=len(births)): probability = float(np.prod([x[1] for x in originals])) probability *= (t / horizon) ** sum(present) * (1 - t / horizon) ** (len(births) - sum(present)) gaps = tuple(tuple(target[j][0] for (gg, j), yes in zip(births, present) if gg == g and yes) for g in range(ref.n + 1)) state = State(tuple(x[0] for x in originals), gaps) jumps = [] for i, (_, _, pending) in enumerate(originals): if pending is not None: q = ref.deletion[i] + ref.substitution[i] rate = q / -expm1(-q * (horizon - t)) altered = list(state.originals) altered[i] = pending jumps.append((State(tuple(altered), state.gaps), rate)) for (g, j), yes in zip(births, present): if not yes: rank = sum(yes2 and gg == g and jj < j for (gg, jj), yes2 in zip(births, present)) altered = list(gaps) altered[g] = gaps[g][:rank] + (target[j][0],) + gaps[g][rank:] jumps.append((State(state.originals, tuple(altered)), 1 / (horizon - t))) yield state, probability, jumps def direct_marginal_flux(ref: Reference, target: Target, states, index, t, horizon=1.0): histories = enumerate_ancestries(ref, target, horizon) z = sum(a.weight for a in histories) if z <= 0: raise ValueError("Unreachable endpoint") marginal = np.zeros(len(states)) flux = np.zeros((len(states), len(states))) for ancestry in histories: for state, probability, jumps in direct_components(ref, target, ancestry, t, horizon): mass = ancestry.weight / z * probability i = index[state] marginal[i] += mass for nxt, rate in jumps: flux[i, index[nxt]] += mass * rate return marginal, flux