File size: 7,158 Bytes
5305b07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""Exact null model for a SynthID Bio sequence g-value score.

WHY THIS EXISTS
---------------
The pilot's open question is calibration: two 95th-percentile thresholds gave
held-out negative flag rates of 12.5% and 4.7%, which is a spread you would not
expect from a well-determined threshold. Calibrating a threshold empirically
from a small cohort conflates two different things: the sampling noise of the
cohort, and the intrinsic score variance of each sequence. The second one has a
closed form, so it does not need to be estimated from a cohort at all.

THE MODEL
---------
A score is the mean of binary g-values over all (window, key) pairs:

    score = 1/(W*K) * sum_{w,k} b[w,k]

with ``W = len(sequence) - 3`` windows and ``K = 25`` keys. Each bit is a
deterministic hash of (initialisation vector, 4-residue context, key), so under
the null hypothesis of no watermark the bits behave as unbiased coin flips --
with one exception that matters:

    Identical 4-residue contexts produce IDENTICAL bits.

A sequence that repeats a 4-mer does not get an independent draw for the
repeat. So the naive standard error ``0.5/sqrt(W*K)`` is too small for any
sequence with repeated contexts. Writing the distinct contexts as ``1..D`` with
multiplicities ``m_i`` summing to ``W``:

    score   = 1/(W*K) * sum_i m_i * sum_k b[i,k]
    Var     = 1/4 * (sum_i m_i^2) / (W^2 * K)
    SE      = 0.5 * sqrt(R / (W*K)),   R = (sum_i m_i^2) / W

``R`` is the repeat inflation factor: 1.0 when every context is distinct, and
larger when contexts repeat. ``W*K/R`` is the effective number of independent
bits. This is exact under the null, needs no cohort, and gives a per-sequence
threshold instead of one shared constant -- which is the direct fix for the
instability the pilot observed.

A caveat worth stating: the model treats distinct contexts as independent
draws. The hash is not a random oracle, so that is an approximation for the
across-context term, though an unbiased-bit assumption is exactly what a
null threshold should be built on. The repeat correction itself is not an
approximation -- identical contexts are identically valued by construction.

Usage:
    python null_model.py                      # analyse the bundled vectors
    python null_model.py sequences.fa         # analyse a FASTA file
"""

from __future__ import annotations

import csv
import json
import math
import sys
from collections import Counter
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scorer"))

from synthidbio_sequence_scorer import (  # noqa: E402
    NGRAM_LEN,
    get_config,
    parse_fasta,
    score_sequence,
    validate_sequence,
)

KEYS = 25


def context_multiplicities(sequence: str) -> Counter:
    """Count how often each scorable 4-residue context appears."""
    cleaned = validate_sequence(sequence)
    return Counter(
        cleaned[end - (NGRAM_LEN - 1) : end + 1]
        for end in range(NGRAM_LEN - 1, len(cleaned))
    )


def null_stats(sequence: str, keys: int = KEYS) -> dict:
    """Closed-form null mean/SE for one sequence, with the repeat correction."""
    counts = context_multiplicities(sequence)
    windows = sum(counts.values())
    distinct = len(counts)
    sum_sq = sum(m * m for m in counts.values())
    inflation = sum_sq / windows
    naive_se = 0.5 / math.sqrt(windows * keys)
    corrected_se = 0.5 * math.sqrt(inflation / (windows * keys))
    return {
        "windows": windows,
        "distinct_contexts": distinct,
        "repeated_contexts": windows - distinct,
        "repeat_inflation_R": inflation,
        "effective_independent_bits": windows * keys / inflation,
        "null_mean": 0.5,
        "naive_se": naive_se,
        "corrected_se": corrected_se,
        "null_threshold_p95": 0.5 + 1.6448536269514722 * corrected_se,
        "null_threshold_p99": 0.5 + 2.3263478740408408 * corrected_se,
    }


def analyse(records: list[tuple[str, str]]) -> list[dict]:
    config = get_config("nd")
    rows = []
    for header, sequence in records:
        result = score_sequence(sequence, config)
        stats = null_stats(sequence)
        z = (result.score - 0.5) / stats["corrected_se"]
        rows.append(
            {
                "id": header,
                "score": result.score,
                "z": z,
                # Two-sided normal tail, via the erfc complement.
                "p_two_sided": math.erfc(abs(z) / math.sqrt(2)),
                **stats,
            }
        )
    return rows


def main(argv: list[str]) -> int:
    here = Path(__file__).resolve().parent
    if len(argv) > 1:
        records = parse_fasta(Path(argv[1]).read_text(encoding="utf-8"))
    else:
        # Default to every sequence in the dataset, not just the conformance
        # vectors, so the counts printed here match the ones quoted in the
        # README and docs/NULL-MODEL.md.
        table = here.parent / "data" / "sequences.csv"
        with table.open(encoding="utf-8", newline="") as fh:
            records = [
                (row["record_id"], row["sequence"]) for row in csv.DictReader(fh)
            ]

    rows = analyse(records)

    header = (
        f"{'id':<22} {'score':>9} {'W':>5} {'distinct':>9} {'R':>6} "
        f"{'SE':>8} {'p95 thr':>8} {'z':>7} {'p':>7}"
    )
    print(header)
    print("-" * len(header))
    for row in rows:
        print(
            f"{row['id']:<22} {row['score']:>9.6f} {row['windows']:>5} "
            f"{row['distinct_contexts']:>9} {row['repeat_inflation_R']:>6.3f} "
            f"{row['corrected_se']:>8.6f} {row['null_threshold_p95']:>8.6f} "
            f"{row['z']:>+7.2f} {row['p_two_sided']:>7.3f}"
        )

    print()
    exceed = [r for r in rows if r["score"] > r["null_threshold_p95"]]
    print(
        f"{len(exceed)}/{len(rows)} sequences exceed their own per-sequence "
        f"95th-percentile null threshold."
    )
    max_z = max(rows, key=lambda r: abs(r["z"]))
    print(
        f"Largest deviation: {max_z['id']} at z={max_z['z']:+.2f} "
        f"(two-sided p={max_z['p_two_sided']:.3f})."
    )
    print(
        "\nUnder public keys these scores carry no detection signal, which is "
        "expected:\nthe published g-values were produced with secret "
        "laboratory keys. Treat this\ntable as a null-calibration reference, "
        "not as a detector evaluation."
    )

    out = here.parent / "data" / "null_model_reference.json"
    out.write_text(
        json.dumps(
            {
                "description": (
                    "Closed-form null statistics for each bundled sequence. "
                    "corrected_se accounts for repeated 4-residue contexts, "
                    "which the naive 0.5/sqrt(W*K) standard error ignores."
                ),
                "keys": KEYS,
                "ngram": NGRAM_LEN,
                "formula": "SE = 0.5 * sqrt(R/(W*K)), R = sum(m_i^2)/W",
                "rows": rows,
            },
            indent=2,
        )
        + "\n",
        encoding="utf-8",
    )
    print(f"\nWrote {out.name}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))