File size: 21,614 Bytes
44fc8dd | 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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | """Stage 3: per-task integrity matching.
Tiers (each individually testable, overlapping by construction):
exact_row same canonical sequence + name + label + task
exact_sequence case-insensitive identical nucleotide string
reverse_complement test sequence equals revcomp of a train sequence
exact_locus same (chrom, start, end) parsed from `name`
interval_overlap positive genomic overlap (any / >=50% / >=90% of either interval)
near_sequence k-mer candidate then edlib-verified alignment (>=98% id, >=95% cov;
sensitivity tier at >=95% id), excluding byte-identical pairs
label_conflict same-task identical sequence or same locus with incompatible labels
Outputs per task:
work/out/{task}_test_status.parquet one row per real test row
work/out/{task}_matches.parquet evidence-linked pairs
work/out/{task}_summary.json counters + denominators + coverage
"""
from __future__ import annotations
import argparse
import json
import math
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path
import edlib
import numpy as np
import polars as pl
sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import (StageLog, canon, json_dump, parse_coord, revcomp,
row_uid, sha256_text) # noqa: E402
LUT = np.full(256, 4, dtype=np.uint8)
for _b, _v in zip(b"ACGT", range(4)):
LUT[_b] = _v
K = 21
SKETCH = 32
MIN_SHARED = 6
MAX_CANDIDATES = 25
MAX_DF = 600 # ignore sketch hashes present in more train sequences than this
IDENT_MAIN = 0.98
IDENT_SENS = 0.95
COV_MAIN = 0.95
# --------------------------------------------------------------- preparation
def prepare_split(df: pl.DataFrame, task: str, split: str) -> pl.DataFrame:
seqs = df["sequence"].to_list()
names = df["name"].to_list()
labels = df["label"].to_list()
coords = [parse_coord(n) for n in names]
canon_seqs = [canon(s) for s in seqs]
rc_seqs = [revcomp(s) for s in canon_seqs]
recs = {
"uid": [row_uid(task, split, i) for i in range(len(seqs))],
"row_index": list(range(len(seqs))),
"name": names,
"label": labels,
"sequence": seqs,
"canon": canon_seqs,
"canon_sha": [sha256_text(s) for s in canon_seqs],
"rc_sha": [sha256_text(s) for s in rc_seqs],
"strand_sha": [sha256_text(min(s, r)) for s, r in zip(canon_seqs, rc_seqs)],
"seq_len": [len(s) for s in canon_seqs],
"palindrome": [s == r for s, r in zip(canon_seqs, rc_seqs)],
"chrom": [c.chrom if c.ok else None for c in coords],
"start": [c.start if c.ok else None for c in coords],
"end": [c.end if c.ok else None for c in coords],
"coord_ok": [c.ok for c in coords],
"coord_tier": [c.tier for c in coords],
"coord_error": [c.error for c in coords],
"suffix": [c.suffix for c in coords],
}
return pl.DataFrame(recs, schema_overrides={
"chrom": pl.String, "start": pl.Int64, "end": pl.Int64,
"suffix": pl.String, "coord_ok": pl.Boolean, "coord_tier": pl.String,
"coord_error": pl.String, "palindrome": pl.Boolean,
"row_index": pl.Int64, "label": pl.Int64, "seq_len": pl.Int64,
})
# --------------------------------------------------------------- sketching
def kmer_bottomk(seq: str, k: int = K, size: int = SKETCH) -> np.ndarray:
n = len(seq)
if n < k:
return np.zeros(0, dtype=np.uint64)
codes = LUT[np.frombuffer(seq.encode("ascii", "replace"), dtype=np.uint8)]
m = n - k + 1
fwd = np.zeros(m, dtype=np.uint64)
bad = np.zeros(m, dtype=np.int32)
for j in range(k):
c = codes[j:j + m].astype(np.uint64)
fwd = (fwd << np.uint64(2)) | c
bad += (codes[j:j + m] >= 4).astype(np.int32)
rseq = revcomp(seq)
rcodes = LUT[np.frombuffer(rseq.encode("ascii", "replace"), dtype=np.uint8)]
rev = np.zeros(m, dtype=np.uint64)
for j in range(k):
c = rcodes[j:j + m].astype(np.uint64)
rev = (rev << np.uint64(2)) | c
rev = rev[::-1]
vals = np.minimum(fwd, rev)
vals = vals[bad == 0]
if vals.size == 0:
return np.zeros(0, dtype=np.uint64)
u = np.unique(vals)
return u[:size]
def build_index(train: pl.DataFrame):
seqs = train["canon"].to_list()
index: dict[int, list[int]] = defaultdict(list)
sketches = []
for i, s in enumerate(seqs):
sk = kmer_bottomk(s)
sketches.append(sk)
for h in sk:
index[int(h)].append(i)
# drop ultra-common hashes (repeat families) but keep a record of how many
dropped = {h: len(v) for h, v in index.items() if len(v) > MAX_DF}
for h in dropped:
del index[h]
return index, sketches, dropped
def candidates_for(sk: np.ndarray, index: dict, cap: int = MAX_CANDIDATES):
if sk.size == 0:
return []
counts: Counter = Counter()
for h in sk:
lst = index.get(int(h))
if lst:
for i in lst:
counts[i] += 1
if not counts:
return []
ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
ranked = [kv for kv in ranked if kv[1] >= MIN_SHARED]
return ranked[:cap]
# --------------------------------------------------------------- alignment
def align_hw(query: str, target: str):
"""edlib infix alignment: whole query aligned to a substring of target."""
r = edlib.align(query, target, mode="HW", task="locations")
if r["editDistance"] < 0:
return None
span = r["locations"][0][1] - r["locations"][0][0] + 1 if r["locations"] else 0
L = len(query)
matches = L - r["editDistance"]
return {
"identity": matches / L if L else 0.0,
"q_cov": 1.0,
"r_cov": span / len(target) if target else 0.0,
"edits": r["editDistance"],
}
def near_verify(test_seq: str, train_seq: str):
best = None
for orient, target in (("forward", train_seq), ("opposite", revcomp(train_seq))):
a = align_hw(test_seq, target)
if a is None:
continue
a["orientation"] = orient
if best is None or (a["identity"], a["r_cov"]) > (best["identity"], best["r_cov"]):
best = a
return best
# --------------------------------------------------------------- intervals
def interval_pairs(test: pl.DataFrame, train: pl.DataFrame, cap_pairs: int = 300000):
"""Interval-tree overlap per chromosome. Returns (pairs, totals)."""
from intervaltree import IntervalTree
pairs = []
truncated = False
trees = defaultdict(IntervalTree)
for r in train.select("row_index", "chrom", "start", "end").iter_rows(named=True):
if r["chrom"] is not None:
trees[r["chrom"]][r["start"]:r["end"]] = r["row_index"]
for r in test.select("row_index", "chrom", "start", "end").iter_rows(named=True):
if r["chrom"] is None:
continue
tree = trees.get(r["chrom"])
if tree is None:
continue
for iv in sorted(tree.overlap(r["start"], r["end"])):
ti = iv.data
ov = min(iv.end, r["end"]) - max(iv.begin, r["start"])
if ov <= 0:
continue
pairs.append((r["row_index"], ti, ov,
ov / max(1, r["end"] - r["start"]),
ov / max(1, iv.end - iv.begin),
r["chrom"], r["start"], r["end"]))
if len(pairs) > cap_pairs:
truncated = True
break
if truncated:
break
return pairs, truncated
# --------------------------------------------------------------- main match
def match_task(task: str, work: Path, pkg: Path, log: StageLog) -> dict:
data = work / "data" / task
outdir = work / "out"
outdir.mkdir(parents=True, exist_ok=True)
tr = prepare_split(pl.read_parquet(data / "train.parquet"), task, "train")
te = prepare_split(pl.read_parquet(data / "test.parquet"), task, "test")
prepdir = work / "prep"
prepdir.mkdir(parents=True, exist_ok=True)
pl.concat([tr.with_columns(pl.lit("train").alias("split")),
te.with_columns(pl.lit("test").alias("split"))]).write_parquet(
prepdir / f"{task}.parquet", compression="zstd")
train_rows = tr.to_dicts()
test_rows = te.to_dicts()
# ---------------- exact tiers
by_sha = defaultdict(list)
by_rcsha = defaultdict(list)
by_row = defaultdict(list)
by_locus = defaultdict(list)
for r in train_rows:
by_sha[r["canon_sha"]].append(r)
by_rcsha[r["rc_sha"]].append(r)
by_row[(r["canon_sha"], r["name"], r["label"])].append(r)
if r["coord_ok"]:
by_locus[(r["chrom"], r["start"], r["end"])].append(r)
matches = []
flags = defaultdict(dict)
for r in test_rows:
f = flags[r["uid"]]
for t in ("exact_row", "exact_sequence", "reverse_complement", "exact_locus",
"interval_overlap_any", "interval_overlap_50", "interval_overlap_90",
"near_sequence_98", "near_sequence_95", "label_conflict"):
f[t] = False
f["coordinate_parsed"] = r["coord_ok"]
f["coordinate_error"] = r["coord_error"]
if not r["coord_ok"]:
for t in ("exact_locus", "interval_overlap_any", "interval_overlap_50",
"interval_overlap_90"):
f[t] = None # not_evaluated: no validated coordinate
for r in test_rows:
uid = r["uid"]
f = flags[uid]
exact = by_sha.get(r["canon_sha"], [])
if exact:
f["exact_sequence"] = True
for t in exact:
matches.append(_m(task, "exact_sequence", r, t, note="identical canonical sequence"))
if (t["name"], t["label"]) == (r["name"], r["label"]):
f["exact_row"] = True
matches.append(_m(task, "exact_row", r, t, note="sequence+name+label equal"))
else:
f["exact_sequence"] = False
rc = by_rcsha.get(r["canon_sha"], [])
rc_hits = [t for t in rc if t["canon_sha"] != r["canon_sha"]]
if rc_hits:
f["reverse_complement"] = True
for t in rc_hits:
matches.append(_m(task, "reverse_complement", r, t,
orientation="opposite", note="test = revcomp(train)"))
else:
f["reverse_complement"] = False
f["palindrome"] = r["palindrome"]
if r["coord_ok"]:
loc = by_locus.get((r["chrom"], r["start"], r["end"]), [])
f["exact_locus"] = bool(loc)
for t in loc:
matches.append(_m(task, "exact_locus", r, t, chrom=r["chrom"],
note="same parsed interval"))
else:
f["exact_locus"] = None # not_evaluated
# ---------------- interval overlap
pairs, truncated = interval_pairs(te, tr)
test_by_idx = {r["row_index"]: r for r in test_rows}
train_by_idx = {r["row_index"]: r for r in train_rows}
ov_any = defaultdict(int)
ov50 = defaultdict(int)
ov90 = defaultdict(int)
for (ti, tri, ov, ft, fr, chrom, s, e) in pairs:
r, t = test_by_idx[ti], train_by_idx[tri]
ov_any[ti] += 1
if ft >= 0.5 and fr >= 0.5:
ov50[ti] += 1
if ft >= 0.9 and fr >= 0.9:
ov90[ti] += 1
matches.append(_m(task, "interval_overlap", r, t, chrom=chrom, overlap_bp=ov,
frac_test=round(ft, 6), frac_train=round(fr, 6),
note="positive interval overlap"))
for r in test_rows:
f = flags[r["uid"]]
f["interval_overlap_any"] = bool(ov_any.get(r["row_index"])) if r["coord_ok"] else None
f["interval_overlap_50"] = bool(ov50.get(r["row_index"])) if r["coord_ok"] else None
f["interval_overlap_90"] = bool(ov90.get(r["row_index"])) if r["coord_ok"] else None
# ---------------- near sequence
index, train_sketches, dropped = build_index(tr)
near_counts = defaultdict(int)
near_sens = defaultdict(int)
cand_rows = 0
for r in test_rows:
sk = kmer_bottomk(r["canon"])
cands = candidates_for(sk, index)
cand_rows += len(cands)
for ci, shared in cands:
t = train_rows[ci]
if t["canon_sha"] == r["canon_sha"]:
continue # exact tier already covers byte-identical pairs
v = near_verify(r["canon"], t["canon"])
if v is None:
continue
ok_main = (v["identity"] >= IDENT_MAIN and v["q_cov"] >= COV_MAIN
and v["r_cov"] >= COV_MAIN)
ok_sens = (v["identity"] >= IDENT_SENS and v["q_cov"] >= COV_MAIN
and v["r_cov"] >= COV_MAIN)
if ok_sens:
near_sens[r["uid"]] += 1
if ok_main:
near_counts[r["uid"]] += 1
if ok_sens:
matches.append(_m(task, "near_sequence_98" if ok_main else "near_sequence_95",
r, t,
identity=round(v["identity"], 6),
q_cov=round(v["q_cov"], 6), r_cov=round(v["r_cov"], 6),
orientation=v["orientation"],
note=f"shared_sketch={shared}"))
for r in test_rows:
f = flags[r["uid"]]
f["near_sequence_98"] = near_counts.get(r["uid"], 0) > 0
f["near_sequence_95"] = near_sens.get(r["uid"], 0) > 0
f["n_near_98_matches"] = near_counts.get(r["uid"], 0)
f["n_near_95_matches"] = near_sens.get(r["uid"], 0)
# ---------------- label conflicts
conflict_pairs = 0
for r in test_rows:
for t in by_sha.get(r["canon_sha"], []):
if t["label"] != r["label"]:
flags[r["uid"]]["label_conflict"] = True
conflict_pairs += 1
matches.append(_m(task, "label_conflict", r, t,
note=f"identical sequence, labels {t['label']} vs {r['label']}"))
if r["coord_ok"]:
for t in by_locus.get((r["chrom"], r["start"], r["end"]), []):
if t["label"] != r["label"]:
flags[r["uid"]]["label_conflict"] = True
# ---------------- status table
tiers = ["exact_row", "exact_sequence", "reverse_complement", "exact_locus",
"interval_overlap_any", "interval_overlap_50", "interval_overlap_90",
"near_sequence_98", "near_sequence_95", "label_conflict"]
status_rows = []
for r in test_rows:
f = flags[r["uid"]]
row = {"uid": r["uid"], "task": task, "split": "test",
"row_index": r["row_index"], "name": r["name"], "label": r["label"],
"seq_len": r["seq_len"], "chrom": r["chrom"], "start": r["start"],
"end": r["end"], "coord_ok": r["coord_ok"],
"coord_tier": r["coord_tier"], "coord_error": r["coord_error"]}
for t in tiers:
v = f.get(t)
row[t] = bool(v) if v is not None else None
row[f"{t}_not_evaluated"] = v is None
union = any(bool(f.get(t)) for t in
["exact_sequence", "reverse_complement", "exact_locus",
"interval_overlap_any", "near_sequence_98"])
row["any_within_task_match"] = union
row["chromosome_in_train"] = None
status_rows.append(row)
status = pl.DataFrame(status_rows, schema_overrides={
t: pl.Boolean for t in tiers + [f"{x}_not_evaluated" for x in tiers]
} | {"coordinate_parsed": pl.Boolean, "any_within_task_match": pl.Boolean,
"coord_ok": pl.Boolean, "chromosome_in_train": pl.Boolean})
# ---------------- summary
n_test = te.height
n_train = tr.height
summary = {
"task": task,
"train_rows": n_train,
"test_rows": n_test,
"coordinate_parsed_train": int(tr["coord_ok"].sum()),
"coordinate_parsed_test": int(te["coord_ok"].sum()),
"coordinate_coverage_test": round(float(te["coord_ok"].sum()) / n_test, 6) if n_test else None,
"interval_overlap_pairs": len(pairs),
"interval_truncated": truncated,
"near_candidate_pairs": cand_rows,
"near_sketch_hashes_dropped_common": len(dropped),
"label_conflict_pairs_identical_sequence": conflict_pairs,
"tiers": {},
}
for t in tiers:
if t in ("near_sequence_98", "near_sequence_95"):
summary["tiers"][t] = int(sum(1 for r in test_rows
if flags[r["uid"]].get(t) is True))
elif t == "label_conflict":
summary["tiers"][t] = int(sum(1 for r in test_rows
if flags[r["uid"]].get(t) is True))
elif t in ("interval_overlap_any", "interval_overlap_50", "interval_overlap_90"):
summary["tiers"][t] = int(sum(1 for r in test_rows
if flags[r["uid"]].get(t) is True))
elif t == "exact_locus":
summary["tiers"][t] = int(sum(1 for r in test_rows
if flags[r["uid"]].get(t) is True))
else:
summary["tiers"][t] = int(sum(1 for r in test_rows
if flags[r["uid"]].get(t) is True))
summary["union_any_tier_test_rows"] = int(status["any_within_task_match"].sum())
# ---------------- chromosome holdout
tr_chroms = set(tr.filter(pl.col("coord_ok"))["chrom"].to_list())
te_chroms = set(te.filter(pl.col("coord_ok"))["chrom"].to_list())
inter = sorted(tr_chroms & te_chroms)
summary["chromosomes"] = {
"train_set": sorted(tr_chroms), "test_set": sorted(te_chroms),
"intersection": inter,
"intersection_size": len(inter),
"train_denominator_rows": int(tr["coord_ok"].sum()),
"test_denominator_rows": int(te["coord_ok"].sum()),
"holdout_contradicted_by_chromosome_sets": len(inter) > 0,
}
if inter:
m = te.filter(pl.col("coord_ok") & pl.col("chrom").is_in(inter))
summary["chromosomes"]["test_rows_on_shared_chromosomes"] = m.height
summary["chromosomes"]["test_rows_on_shared_chromosomes_fraction"] = round(m.height / n_test, 6)
# mark chromosome_in_train on status rows
status = status.with_columns(
pl.when(pl.col("coord_ok"))
.then(pl.col("chrom").is_in(sorted(tr_chroms)))
.otherwise(None)
.alias("chromosome_in_train")
)
# ---------------- write
status.write_parquet(outdir / f"{task}_test_status.parquet")
if matches:
mdf = pl.DataFrame(matches, schema=MATCH_SCHEMA, strict=False)
else:
mdf = pl.DataFrame(schema=MATCH_SCHEMA)
mdf.write_parquet(outdir / f"{task}_matches.parquet")
summary["match_rows"] = mdf.height
summary["match_rows_by_tier"] = dict(Counter(mdf["tier"].to_list())) if mdf.height else {}
summary["test_rows_with_any_match"] = int(status["any_within_task_match"].sum())
json_dump(summary, outdir / f"{task}_summary.json")
log.info("task matched", task=task, test=n_test,
matches=mdf.height, union=summary["test_rows_with_any_match"],
near98=summary["tiers"]["near_sequence_98"],
chrom_inter=len(inter))
return summary
MATCH_SCHEMA = {
"task": pl.String, "tier": pl.String, "test_uid": pl.String, "train_uid": pl.String,
"test_name": pl.String, "train_name": pl.String,
"test_label": pl.Int64, "train_label": pl.Int64,
"identity": pl.Float64, "q_cov": pl.Float64, "r_cov": pl.Float64,
"orientation": pl.String, "overlap_bp": pl.Int64,
"frac_test": pl.Float64, "frac_train": pl.Float64,
"chrom": pl.String, "note": pl.String,
}
def _m(task, tier, test, train, identity=None, q_cov=None, r_cov=None,
orientation=None, overlap_bp=None, frac_test=None, frac_train=None,
chrom=None, note=None):
return {
"task": task, "tier": tier,
"test_uid": test["uid"], "train_uid": train["uid"],
"test_name": test["name"], "train_name": train["name"],
"test_label": test["label"], "train_label": train["label"],
"identity": identity, "q_cov": q_cov, "r_cov": r_cov,
"orientation": orientation, "overlap_bp": overlap_bp,
"frac_test": frac_test, "frac_train": frac_train,
"chrom": chrom, "note": note,
}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--task", required=True)
ap.add_argument("--work", default="/workspace/nt-audit")
ap.add_argument("--pkg", default="/workspace/nt-revised-audit")
args = ap.parse_args()
log = StageLog(Path(args.pkg) / "logs" / "stage.jsonl", f"match:{args.task}")
s = match_task(args.task, Path(args.work), Path(args.pkg), log)
log.done(test_rows=s["test_rows"])
return 0
if __name__ == "__main__":
raise SystemExit(main())
|