Download evaluation/src/aggregate.py from nikkikaelar/nt-revised-audit: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/datasets/nikkikaelar/nt-revised-audit/resolve/main/evaluation/src/aggregate.py
- Command line
-
hf download hf://datasets/nikkikaelar/nt-revised-audit/evaluation/src/aggregate.py
-
curl -L -o aggregate.py https://huggingface.co/datasets/nikkikaelar/nt-revised-audit/resolve/main/evaluation/src/aggregate.py
16.1 kB
| """Stage 6: assemble the package. Concatenates per-task evidence, writes | |
| facts.json / facts.md, results CSVs, and the reconciliation. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| from pathlib import Path | |
| import polars as pl | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from common import StageLog, json_dump, json_load # noqa: E402 | |
| 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"] | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--work", default="/workspace/nt-audit") | |
| ap.add_argument("--pkg", default="/workspace/nt-revised-audit") | |
| args = ap.parse_args() | |
| work, pkg = Path(args.work), Path(args.pkg) | |
| log = StageLog(pkg / "logs" / "stage.jsonl", "aggregate") | |
| (pkg / "results").mkdir(parents=True, exist_ok=True) | |
| pre = json_load(pkg / "preflight.json") | |
| lock = json_load(pkg / "SOURCE_LOCK.json") | |
| summaries = [json_load(p) for p in sorted((work / "out").glob("*_summary.json"))] | |
| summaries.sort(key=lambda s: s["task"]) | |
| cross = json_load(work / "out" / "cross_task.json") | |
| status_files = sorted((work / "out").glob("*_test_status.parquet")) | |
| match_files = sorted((work / "out").glob("*_matches.parquet")) | |
| status = pl.concat([pl.read_parquet(p) for p in status_files]) | |
| matches = pl.concat([pl.read_parquet(p) for p in match_files]) if match_files else pl.DataFrame() | |
| status.write_parquet(pkg / "results" / "test_status.parquet", compression="zstd") | |
| matches.write_parquet(pkg / "results" / "matches.parquet", compression="zstd") | |
| log.info("evidence tables written", test_rows=status.height, match_rows=matches.height) | |
| tier_rows = {t: int(status[t].fill_null(False).sum()) for t in TIERS} | |
| pair_counts = (dict(matches.group_by("tier").len().iter_rows()) if matches.height else {}) | |
| # per-task table | |
| by_task = [] | |
| for s in summaries: | |
| st = status.filter(pl.col("task") == s["task"]) | |
| prep = pl.read_parquet(work / "prep" / f"{s['task']}.parquet", | |
| columns=["split", "canon_sha", "chrom", "start", "end"]) | |
| trn = prep.filter(pl.col("split") == "train") | |
| tst = prep.filter(pl.col("split") == "test") | |
| rec = { | |
| "task": s["task"], | |
| "train_rows": s["train_rows"], | |
| "test_rows": s["test_rows"], | |
| "train_unique_sequences": trn["canon_sha"].n_unique(), | |
| "test_unique_sequences": tst["canon_sha"].n_unique(), | |
| "train_unique_loci": trn.filter(pl.col("chrom").is_not_null()).select( | |
| ["chrom", "start", "end"]).n_unique(), | |
| "test_unique_loci": tst.filter(pl.col("chrom").is_not_null()).select( | |
| ["chrom", "start", "end"]).n_unique(), | |
| "coord_rows_train": s["coordinate_parsed_train"], | |
| "coord_rows_test": s["coordinate_parsed_test"], | |
| "coord_coverage_test": s["coordinate_coverage_test"], | |
| "chromosomes_train_n": len(s["chromosomes"]["train_set"]), | |
| "chromosomes_test_n": len(s["chromosomes"]["test_set"]), | |
| "chromosome_intersection": ";".join(s["chromosomes"]["intersection"]), | |
| "chromosome_intersection_n": s["chromosomes"]["intersection_size"], | |
| "union_any_tier_test_rows": s["union_any_tier_test_rows"], | |
| "match_rows": s["match_rows"], | |
| } | |
| for t in TIERS: | |
| rec[f"test_rows_{t}"] = s["tiers"].get(t, 0) | |
| rec[f"pairs_{t}"] = int(matches.filter((pl.col("task") == s["task"]) & | |
| (pl.col("tier") == t)).height) if matches.height else 0 | |
| by_task.append(rec) | |
| pl.DataFrame(by_task).write_csv(pkg / "results" / "by_task.csv") | |
| hold = [] | |
| for s in summaries: | |
| c = s["chromosomes"] | |
| hold.append({ | |
| "task": s["task"], | |
| "chromosomes_train": ";".join(c["train_set"]), | |
| "chromosomes_test": ";".join(c["test_set"]), | |
| "intersection": ";".join(c["intersection"]), | |
| "intersection_n": c["intersection_size"], | |
| "coord_parsed_train_rows": c["train_denominator_rows"], | |
| "coord_parsed_test_rows": c["test_denominator_rows"], | |
| "coord_coverage_test": s["coordinate_coverage_test"], | |
| "test_rows_on_shared_chromosomes": c.get("test_rows_on_shared_chromosomes", 0), | |
| "test_rows_on_shared_chromosomes_fraction": | |
| c.get("test_rows_on_shared_chromosomes_fraction", 0.0), | |
| "holdout_contradicted_by_chromosome_sets": c["holdout_contradicted_by_chromosome_sets"], | |
| }) | |
| pl.DataFrame(hold).write_csv(pkg / "results" / "chromosome_holdout.csv") | |
| rep = [] | |
| for task, splits in pre["tasks"].items(): | |
| for split in ("train", "test"): | |
| r = splits[split] | |
| f = r.get("fna", {}) | |
| rep.append({ | |
| "task": task, "split": split, | |
| "parquet_exists": r.get("parquet_exists"), | |
| "parquet_rows": r.get("rows"), | |
| "fna_exists": r.get("fna_exists"), | |
| "fna_records": f.get("records"), | |
| "count_equal": f.get("count_equal"), | |
| "sequence_mismatches": f.get("sequence_mismatches_common_headers"), | |
| "headers_missing_in_fna": f.get("headers_missing_in_fna"), | |
| "fna_headers_missing_in_parquet": f.get("fna_headers_missing_in_parquet"), | |
| "parity": f.get("parity", "no_fna"), | |
| "parquet_sha256": r.get("file_sha256"), | |
| "fna_sha256": f.get("file_sha256"), | |
| }) | |
| pl.DataFrame(rep).write_csv(pkg / "results" / "representation_check.csv") | |
| # -------- full-corpus coordinate consistency checks | |
| coord_rows = 0 | |
| suffix_eq_label = 0 | |
| span_eq_len = 0 | |
| for path in sorted((work / "prep").glob("*.parquet")): | |
| d = pl.read_parquet(path, columns=["suffix", "label", "start", "end", | |
| "seq_len", "coord_ok"]) | |
| d = d.filter(pl.col("coord_ok")) | |
| coord_rows += d.height | |
| suffix_eq_label += d.filter( | |
| pl.col("suffix").cast(pl.String) == pl.col("label").cast(pl.String)).height | |
| span_eq_len += d.filter((pl.col("end") - pl.col("start")) == pl.col("seq_len")).height | |
| # -------- facts | |
| totals = pre["totals"] | |
| rec = pre["reconciliation"] | |
| union_total = int(status["any_within_task_match"].fill_null(False).sum()) | |
| union_near95 = int((status["near_sequence_95"].fill_null(False) | |
| | status["any_within_task_match"].fill_null(False)).sum()) | |
| n_tasks = len(summaries) | |
| tasks_with_hits = [s["task"] for s in summaries if s["union_any_tier_test_rows"] > 0] | |
| holdout_viol = [h for h in hold if h["intersection_n"] > 0] | |
| facts = { | |
| "generated_utc": pre["preflight_utc"], | |
| "source_sha": lock["revision"], | |
| "repo_id": lock["repo_id"], | |
| "tasks": n_tasks, | |
| "rows": {"train": totals["train"], "test": totals["test"], "all": totals["all"]}, | |
| "advertised_rows": rec["advertised"], | |
| "readme_rows": {"train": rec["readme_train_sum"], "test": rec["readme_test_sum"], | |
| "total": rec["readme_total"]}, | |
| "reconciliation": { | |
| "readme_minus_actual_train": rec["delta_readme_minus_actual_train"], | |
| "readme_minus_actual_test": rec["delta_readme_minus_actual_test"], | |
| "readme_minus_actual_total": rec["delta_readme_minus_actual_total"], | |
| "advertised_minus_actual_total": rec["delta_advertised_minus_actual"], | |
| "per_task": rec["per_task"], | |
| }, | |
| "within_task": { | |
| "tier_test_rows": tier_rows, | |
| "tier_pair_counts": pair_counts, | |
| "union_any_tier_test_rows": union_total, | |
| "union_reporting_tier_membership": ["exact_sequence", "reverse_complement", | |
| "exact_locus", "interval_overlap_any", | |
| "near_sequence_98"], | |
| "union_including_near95": union_near95, | |
| "union_note": "reporting-tier union and 95%-inclusive union are different definitions and are not additive", | |
| "union_denominator_test_rows": totals["test"], | |
| "tasks_with_any_match": tasks_with_hits, | |
| "n_tasks_with_any_match": len(tasks_with_hits), | |
| }, | |
| "chromosome_holdout": { | |
| "tasks_with_parsed_coordinates": sum(1 for h in hold if h["coord_parsed_test_rows"] > 0), | |
| "tasks_with_intersection": [h["task"] for h in holdout_viol], | |
| "n_tasks_with_intersection": len(holdout_viol), | |
| "total_test_rows_on_shared_chromosomes": sum( | |
| h["test_rows_on_shared_chromosomes"] for h in hold), | |
| "coverage_note": "denominators are rows whose `name` parsed to a valid interval", | |
| }, | |
| "cross_task": { | |
| "sequences_shared_across_tasks": cross["sequences_shared_across_tasks"], | |
| "loci_shared_across_tasks": cross["loci_shared_across_tasks"], | |
| "n_task_pairs": cross["n_pairs"], | |
| }, | |
| "coordinate_checks": { | |
| "parsed_rows": coord_rows, | |
| "suffix_equals_label": suffix_eq_label, | |
| "span_equals_sequence_length": span_eq_len, | |
| "suffix_equals_label_rate": round(suffix_eq_label / coord_rows, 6) if coord_rows else None, | |
| "span_equals_length_rate": round(span_eq_len / coord_rows, 6) if coord_rows else None, | |
| }, | |
| "per_task": by_task, | |
| "caveats": [ | |
| "Assembly (GRCh38/hg38) is not established by any field in the pinned files; names carry no assembly prefix.", | |
| "Coordinate convention is inferred from end-start == sequence length on all parsed rows; the assembly is not stated anywhere in the pinned files.", | |
| "near_sequence recall is probed with injected mutations, not proven exhaustive.", | |
| "exact_locus and interval_overlap are not_evaluated for rows whose name did not parse.", | |
| "Cross-task locus sharing is expected biology and is not counted as leakage.", | |
| ], | |
| } | |
| json_dump(facts, pkg / "facts.json") | |
| (pkg / "facts.md").write_text(render_facts_md(facts, hold, summaries), encoding="utf-8") | |
| (pkg / "results" / "reconciliation.md").write_text(render_reconciliation_md(pre), encoding="utf-8") | |
| log.done(tasks=n_tasks, union=union_total) | |
| return 0 | |
| def render_facts_md(f: dict, hold: list, summaries: list) -> str: | |
| L = [] | |
| A = L.append | |
| A("# Facts — definitions, denominators, numerators") | |
| A("") | |
| A(f"Source SHA `{f['source_sha']}`. Rows: train {f['rows']['train']:,}, " | |
| f"test {f['rows']['test']:,}, total {f['rows']['all']:,} across {f['tasks']} tasks.") | |
| A("") | |
| A("## Headline within-task reuse") | |
| A("") | |
| A("| tier | test rows | pair count | definition |") | |
| A("|---|---|---|---|") | |
| defs = { | |
| "exact_row": "same canonical sequence, name, label, task", | |
| "exact_sequence": "case-normalized identical nucleotide string", | |
| "reverse_complement": "test sequence equals revcomp of a train sequence (non-palindromic)", | |
| "exact_locus": "same parsed (chrom,start,end); only rows with parsed coordinates", | |
| "interval_overlap_any": "any positive overlap between test and train interval", | |
| "interval_overlap_50": "overlap covers >=50% of both intervals", | |
| "interval_overlap_90": "overlap covers >=90% of both intervals", | |
| "near_sequence_98": "edlib-verified >=98% identity and >=95% coverage of both, excluding byte-identical pairs", | |
| "near_sequence_95": "same at >=95% identity (sensitivity tier, superset of 98)", | |
| "label_conflict": "same-task identical sequence or same locus with different labels", | |
| } | |
| for t in TIERS: | |
| A(f"| `{t}` | {f['within_task']['tier_test_rows'][t]:,} | " | |
| f"{f['within_task']['tier_pair_counts'].get(t, 0):,} | {defs[t]} |") | |
| A("") | |
| A(f"Union of the reporting tiers: **{f['within_task']['union_any_tier_test_rows']:,}** " | |
| f"of {f['within_task']['union_denominator_test_rows']:,} test rows. " | |
| f"Union including the 95% sensitivity tier: **{f['within_task'].get('union_including_near95', 0):,}**. " | |
| "Tier numerators overlap and must not be summed; the two union figures are not additive.") | |
| A("") | |
| A("## Per-task") | |
| A("") | |
| A("| task | train | test | coord cov | exact_seq | revcomp | exact_locus | ovl any | ovl 90 | near98 | near95 | union | chr intersect |") | |
| A("|---|---|---|---|---|---|---|---|---|---|---|---|---|") | |
| for r in f["per_task"]: | |
| A(f"| {r['task']} | {r['train_rows']:,} | {r['test_rows']:,} | " | |
| f"{r['coord_coverage_test']} | {r['test_rows_exact_sequence']} | " | |
| f"{r['test_rows_reverse_complement']} | {r['test_rows_exact_locus']} | " | |
| f"{r['test_rows_interval_overlap_any']} | {r['test_rows_interval_overlap_90']} | " | |
| f"{r['test_rows_near_sequence_98']} | {r['test_rows_near_sequence_95']} | " | |
| f"{r['union_any_tier_test_rows']} | {r['chromosome_intersection_n']} |") | |
| A("") | |
| A("## Chromosome holdout") | |
| A("") | |
| A(f"Tasks with a train/test chromosome intersection: " | |
| f"{f['chromosome_holdout']['n_tasks_with_intersection']} of " | |
| f"{f['chromosome_holdout']['tasks_with_parsed_coordinates']} tasks with parsed coordinates.") | |
| A("") | |
| A("| task | train chroms | test chroms | intersection | test rows on shared chr | coverage |") | |
| A("|---|---|---|---|---|---|") | |
| for h in hold: | |
| A(f"| {h['task']} | {h['chromosomes_train']} | {h['chromosomes_test']} | " | |
| f"{h['intersection'] or 'none'} | {h['test_rows_on_shared_chromosomes']} | " | |
| f"{h['coord_coverage_test']} |") | |
| A("") | |
| return "\n".join(L) + "\n" | |
| def render_reconciliation_md(pre: dict) -> str: | |
| rec = pre["reconciliation"] | |
| L = [] | |
| A = L.append | |
| A("# Row-count reconciliation") | |
| A("") | |
| A("Three different numbers circulate for this dataset. All three are recorded " | |
| "here against the pinned Parquet contents.") | |
| A("") | |
| A("| source | train | test | total | provenance |") | |
| A("|---|---|---|---|---|") | |
| A(f"| README printed table (sum of 18 rows) | {rec['readme_train_sum']:,} | " | |
| f"{rec['readme_test_sum']:,} | {rec['readme_total']:,} | README.md at pinned SHA |") | |
| a = rec["advertised"] | |
| A(f"| HF datasets-server listing | {a.get('train', 'n/a')} | {a.get('test', 'n/a')} | " | |
| f"{a.get('total', 'n/a')} | datasets-server /size captured preflight |") | |
| A(f"| Actual pinned Parquet | {rec['actual_train']:,} | {rec['actual_test']:,} | " | |
| f"{rec['actual_total']:,} | sum of 18 train + 18 test parquet files |") | |
| A("") | |
| A("Deltas:") | |
| A("") | |
| A(f"- README minus actual: train {rec['delta_readme_minus_actual_train']:+,}, " | |
| f"test {rec['delta_readme_minus_actual_test']:+,}, total {rec['delta_readme_minus_actual_total']:+,}") | |
| A(f"- Listing minus actual: {rec['delta_advertised_minus_actual']:+,}") | |
| A("") | |
| A("| task | README train | actual train | train delta | README test | actual test | test delta |") | |
| A("|---|---|---|---|---|---|---|") | |
| for r in rec["per_task"]: | |
| A(f"| {r.get('readme_name', r['task'])} | {r.get('readme_train', 'n/a')} | " | |
| f"{r['actual_train']:,} | {r.get('train_delta', 'n/a')} | " | |
| f"{r.get('readme_test', 'n/a')} | {r['actual_test']:,} | {r.get('test_delta', 'n/a')} |") | |
| A("") | |
| return "\n".join(L) + "\n" | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |