File size: 8,458 Bytes
a80f3c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()