#!/usr/bin/env python3 import argparse import json from collections import Counter, defaultdict from itertools import combinations from pathlib import Path from typing import Dict, Iterable, List import numpy as np import pandas as pd DNA = set("ACGT") def read_jsonl(path: Path) -> List[dict]: rows = [] with open(path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows def get_sequence(row: dict) -> str: for key in ["generated_sequence", "sequence", "reference_sequence"]: value = row.get(key) if isinstance(value, str) and value: return value.upper() return "" def load_generated(path: Path, method: str) -> pd.DataFrame: rows = read_jsonl(path) out = [] for row in rows: seq = get_sequence(row) if not seq: continue out.append( { "method": method, "source": row.get("source", "generated"), "activity_bucket": row.get("activity_bucket"), "condition_token": row.get("condition_token"), "sequence": seq, "prediction_sum": row.get("generated_prediction_sum", row.get("prediction_sum")), "prediction_label_0": ( row.get("generated_prediction", [None, None])[0] if isinstance(row.get("generated_prediction"), list) else row.get("prediction_label_0") ), "prediction_label_1": ( row.get("generated_prediction", [None, None])[1] if isinstance(row.get("generated_prediction"), list) and len(row.get("generated_prediction")) > 1 else row.get("prediction_label_1") ), "diffusion_pll": row.get("diffusion_pll"), } ) return pd.DataFrame(out) def load_reference(dataset_dir: Path, split: str = "valid", limit: int = 20000) -> pd.DataFrame: path = dataset_dir / f"{split}.parquet" df = pd.read_parquet(path) if limit and len(df) > limit: df = df.sample(n=limit, random_state=42) return pd.DataFrame( { "method": "reference", "source": "reference", "activity_bucket": None, "condition_token": None, "sequence": df["sequence"].astype(str).str.upper(), "prediction_sum": np.nan, "prediction_label_0": np.nan, "prediction_label_1": np.nan, "diffusion_pll": np.nan, } ) def gc_content(seq: str) -> float: bases = [c for c in seq if c in DNA] if not bases: return np.nan return sum(c in "GC" for c in bases) / len(bases) def valid_dna(seq: str) -> bool: return bool(seq) and set(seq).issubset(DNA) def max_homopolymer(seq: str) -> int: best = cur = 0 last = None for char in seq: if char == last: cur += 1 else: last = char cur = 1 best = max(best, cur) return best def kmers(seq: str, k: int) -> Iterable[str]: for i in range(0, max(0, len(seq) - k + 1)): mer = seq[i : i + k] if set(mer).issubset(DNA): yield mer def kmer_distribution(seqs: Iterable[str], k: int) -> Dict[str, float]: counts = Counter() total = 0 for seq in seqs: for mer in kmers(seq, k): counts[mer] += 1 total += 1 if total == 0: return {} return {key: value / total for key, value in counts.items()} def js_divergence(p: Dict[str, float], q: Dict[str, float]) -> float: keys = sorted(set(p) | set(q)) pv = np.asarray([p.get(key, 0.0) for key in keys], dtype=float) qv = np.asarray([q.get(key, 0.0) for key in keys], dtype=float) m = 0.5 * (pv + qv) def kl(a, b): mask = a > 0 return float(np.sum(a[mask] * np.log2(a[mask] / b[mask]))) return 0.5 * kl(pv, m) + 0.5 * kl(qv, m) def hamming_distance(a: str, b: str) -> int: n = min(len(a), len(b)) return sum(x != y for x, y in zip(a[:n], b[:n])) + abs(len(a) - len(b)) def mean_pairwise_distance(seqs: List[str], max_pairs: int = 20000) -> float: if len(seqs) < 2: return np.nan pairs = list(combinations(range(len(seqs)), 2)) if len(pairs) > max_pairs: rng = np.random.default_rng(42) pairs = [pairs[i] for i in rng.choice(len(pairs), size=max_pairs, replace=False)] return float(np.mean([hamming_distance(seqs[i], seqs[j]) for i, j in pairs])) def nearest_reference_distance(seqs: List[str], refs: List[str], max_refs: int = 5000) -> List[float]: if not refs: return [np.nan] * len(seqs) if len(refs) > max_refs: rng = np.random.default_rng(42) refs = [refs[i] for i in rng.choice(len(refs), size=max_refs, replace=False)] out = [] for seq in seqs: out.append(float(min(hamming_distance(seq, ref) for ref in refs))) return out def summarize(df: pd.DataFrame, reference_df: pd.DataFrame, k_values: List[int]) -> dict: reference_kmers = { k: kmer_distribution(reference_df["sequence"].tolist(), k) for k in k_values } reference_sequences = reference_df["sequence"].tolist() summary = {"methods": {}} annotated_frames = [] for method, group in df.groupby("method"): group = group.copy() seqs = group["sequence"].tolist() group["length"] = group["sequence"].str.len() group["valid_dna"] = group["sequence"].map(valid_dna) group["gc_content"] = group["sequence"].map(gc_content) group["max_homopolymer"] = group["sequence"].map(max_homopolymer) group["nearest_reference_hamming"] = nearest_reference_distance(seqs, reference_sequences) annotated_frames.append(group) method_summary = { "num_sequences": int(len(group)), "valid_dna_rate": float(group["valid_dna"].mean()), "unique_rate": float(group["sequence"].nunique() / len(group)), "mean_length": float(group["length"].mean()), "mean_gc_content": float(group["gc_content"].mean()), "mean_max_homopolymer": float(group["max_homopolymer"].mean()), "mean_pairwise_hamming": mean_pairwise_distance(seqs), "mean_nearest_reference_hamming": float(group["nearest_reference_hamming"].mean()), } for k in k_values: method_summary[f"kmer{k}_js_to_reference"] = js_divergence( kmer_distribution(seqs, k), reference_kmers[k] ) for col in ["prediction_sum", "prediction_label_0", "prediction_label_1", "diffusion_pll"]: if col in group and group[col].notna().any(): method_summary[f"mean_{col}"] = float(pd.to_numeric(group[col], errors="coerce").mean()) summary["methods"][method] = method_summary annotated = pd.concat(annotated_frames, ignore_index=True) if annotated_frames else pd.DataFrame() return summary, annotated def main(): parser = argparse.ArgumentParser(description="Compute paper-level sequence quality metrics.") parser.add_argument("--dataset_dir", required=True) parser.add_argument("--reference_split", default="valid") parser.add_argument("--input", action="append", default=[], help="method=path/to/jsonl. Repeatable.") parser.add_argument("--output_dir", required=True) parser.add_argument("--k_values", default="3,4") args = parser.parse_args() frames = [] for item in args.input: method, path = item.split("=", 1) frames.append(load_generated(Path(path), method)) reference_df = load_reference(Path(args.dataset_dir), split=args.reference_split) frames.append(reference_df) all_df = pd.concat(frames, ignore_index=True) k_values = [int(k) for k in args.k_values.split(",") if k.strip()] summary, annotated = summarize(all_df, reference_df, k_values) output_dir = Path(args.output_dir) output_dir.mkdir(parents=True, exist_ok=True) annotated.to_csv(output_dir / "sequence_metrics_rows.csv", index=False) (output_dir / "sequence_metrics_summary.json").write_text( json.dumps(summary, indent=2), encoding="utf-8" ) print(output_dir / "sequence_metrics_summary.json") if __name__ == "__main__": main()