nikki / ANTIMEME
NT revised integrity audit: evidence package, archive, card
44fc8dd verified
Raw History Blame Contribute Delete
5.66 kB
"""Shared primitives for the NT revised dataset integrity audit.
Everything here is deterministic and dependency-light (stdlib + numpy/polars).
No network access, no LLM judging.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
REPO_ID = "InstaDeepAI/nucleotide_transformer_downstream_tasks_revised"
REPO_TYPE = "dataset"
TASK_ORDER = [
"promoter_all",
"promoter_tata",
"promoter_no_tata",
"enhancers",
"enhancers_types",
"splice_sites_all",
"splice_sites_acceptors",
"splice_sites_donors",
"H2AFZ",
"H3K27ac",
"H3K27me3",
"H3K36me3",
"H3K4me1",
"H3K4me2",
"H3K4me3",
"H3K9ac",
"H3K9me3",
"H4K20me1",
]
# ---------------------------------------------------------------- sequences
_COMPLEMENT = str.maketrans(
"ACGTUNRYKMSWBDHVacgtunrykmswbdhv",
"TGCAANYRMKSWVHDBtgcaanyrmkswvhdb",
)
def revcomp(seq: str) -> str:
"""Reverse complement. Non-IUPAC characters are complemented to themselves."""
return seq.translate(_COMPLEMENT)[::-1]
def canon(seq: str) -> str:
"""Case/whitespace normalization only. Internal N and ambiguous bases are kept."""
return "".join(seq.split()).upper()
def sha256_text(s: str) -> str:
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def sha256_file(path: str | Path, chunk: int = 1 << 20) -> str:
h = hashlib.sha256()
with open(path, "rb") as fh:
while True:
b = fh.read(chunk)
if not b:
break
h.update(b)
return h.hexdigest()
def alphabet_counts(seq: str) -> dict:
out = {"A": 0, "C": 0, "G": 0, "T": 0, "N": 0, "other": 0}
for ch in seq:
if ch in "ACGT":
out[ch] += 1
elif ch == "N":
out["N"] += 1
else:
out["other"] += 1
return out
# ---------------------------------------------------------------- coordinates
# Grammar verified against real records in preflight (see PREFLIGHT.md).
# Strict: chr<1-2 digits|X|Y|M|MT>:<start>-<end>[|<label>]
STRICT_COORD = re.compile(
r"^chr(?P<chrom>[0-9]{1,2}|X|Y|M|MT):(?P<start>[0-9]+)-(?P<end>[0-9]+)(?:\|(?P<suffix>-?[0-9]+))?$",
re.IGNORECASE,
)
# Loose fallback: any chr token without ':' , any integer coordinates.
LOOSE_COORD = re.compile(
r"^(?P<chrom>[^:]+):(?P<start>[0-9]+)-(?P<end>[0-9]+)(?:\|(?P<suffix>[^|]*))?$"
)
@dataclass
class Coord:
ok: bool
tier: str # "strict" | "loose" | "fail"
chrom: str | None = None
start: int | None = None
end: int | None = None
suffix: str | None = None
error: str | None = None
def parse_coord(name: str) -> Coord:
"""Parse an interval out of the untrusted `name` field.
Never assumes the assembly. Accepts start<end only; a row with start>=end
is reported as a parse failure with an explicit error tag.
"""
if name is None:
return Coord(False, "fail", error="null_name")
raw = name.strip()
m = STRICT_COORD.match(raw)
tier = "strict"
if not m:
m = LOOSE_COORD.match(raw)
tier = "loose"
if not m:
return Coord(False, "fail", error="grammar_mismatch")
start, end = int(m.group("start")), int(m.group("end"))
chrom = m.group("chrom")
if start >= end:
return Coord(False, "fail", chrom=chrom, start=start, end=end,
suffix=m.group("suffix"), error="start_ge_end")
if start < 0:
return Coord(False, "fail", chrom=chrom, start=start, end=end,
suffix=m.group("suffix"), error="negative_start")
return Coord(True, tier, chrom=chrom, start=start, end=end,
suffix=m.group("suffix"), error=None)
# ---------------------------------------------------------------- io helpers
def json_dump(obj, path: str | Path) -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(obj, fh, indent=2, sort_keys=False, default=str)
fh.write("\n")
os.replace(tmp, path)
def json_load(path: str | Path):
with open(path, "r", encoding="utf-8") as fh:
return json.load(fh)
class StageLog:
"""Append-only JSONL stage log with wall time and peak RSS."""
def __init__(self, path: str | Path, stage: str):
self.path = Path(path)
self.path.parent.mkdir(parents=True, exist_ok=True)
self.stage = stage
self.t0 = time.time()
def info(self, msg: str, **kw) -> None:
rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"stage": self.stage, "msg": msg}
rec.update(kw)
with open(self.path, "a", encoding="utf-8") as fh:
fh.write(json.dumps(rec, default=str) + "\n")
print(f"[{self.stage}] {msg}", flush=True)
def done(self, **kw) -> None:
rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"stage": self.stage, "msg": "done",
"seconds": round(time.time() - self.t0, 2)}
try:
import resource
rec["maxrss_kb"] = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
except Exception:
pass
rec.update(kw)
with open(self.path, "a", encoding="utf-8") as fh:
fh.write(json.dumps(rec, default=str) + "\n")
print(f"[{self.stage}] done {rec.get('seconds')}s", flush=True)
def row_uid(task: str, split: str, idx: int) -> str:
return f"{task}|{split}|{idx}"