ntv3 / src /genome_annotation /metrics.py
ybornachot's picture
Replace the 2025 Space with the revised NTv3 release (#4)
3e211d2
Raw History Blame Contribute Delete
5.6 kB
"""Gene- and CDS-level accuracy of a predicted GFF3 (Tiberius / BRAKER style).
A CDS is correct if its chromosome, start, end, strand and phase all match the
reference; a gene is correct if its whole set of CDS matches a reference gene.
"""
import bisect
import gzip
from collections import defaultdict
from pathlib import Path
import numpy as np
CdsKey = tuple[str, int, int, str, str] # (chrom, start, end, strand, phase), 1-based
def _open_text(path: str | Path):
return gzip.open(path, "rt") if str(path).endswith(".gz") else open(path)
def _attribute(attributes: str, key: str) -> str | None:
for field in attributes.split(";"):
if field.startswith(f"{key}="):
return field[len(key) + 1 :]
return None
def parse_genes(
path: str | Path, chromosomes: set[str] | None = None
) -> dict[str, list[CdsKey]]:
"""Maps each gene ID to its CDS keys; CDS reach genes directly or via mRNAs."""
transcript_to_gene: dict[str, str] = {}
genes: dict[str, list[CdsKey]] = defaultdict(list)
with _open_text(path) as handle:
for line in handle:
if line.startswith("#"):
continue
cols = line.rstrip("\n").split("\t")
if len(cols) < 9 or (chromosomes and cols[0] not in chromosomes):
continue
kind = cols[2].lower()
if kind in ("mrna", "transcript"):
tid, parent = _attribute(cols[8], "ID"), _attribute(cols[8], "Parent")
if tid and parent:
transcript_to_gene[tid] = parent.split(",")[0]
elif kind == "cds":
parent = (_attribute(cols[8], "Parent") or "").split(",")[0]
gene = transcript_to_gene.get(parent, parent)
genes[gene].append(
(cols[0], int(cols[3]), int(cols[4]), cols[6], cols[7])
)
return dict(genes)
def read_regions(path: str | Path) -> dict[str, list[tuple[int, int]]]:
"""Reads a BED of regions into sorted, merged 1-based closed intervals."""
regions: dict[str, list[tuple[int, int]]] = defaultdict(list)
with _open_text(path) as handle:
for line in handle:
chrom, start, end = line.split("\t")[:3]
regions[chrom].append((int(start) + 1, int(end)))
merged: dict[str, list[tuple[int, int]]] = {}
for chrom, intervals in regions.items():
out: list[tuple[int, int]] = []
for start, end in sorted(intervals):
if out and start <= out[-1][1] + 1:
out[-1] = (out[-1][0], max(out[-1][1], end))
else:
out.append((start, end))
merged[chrom] = out
return merged
def _overlaps(regions: dict[str, list[tuple[int, int]]], key: CdsKey) -> bool:
intervals = regions.get(key[0])
if not intervals:
return False
i = bisect.bisect_left(intervals, (key[2] + 1,)) - 1
return i >= 0 and intervals[i][1] >= key[1]
def _prf(
tp_recall: int, n_ref: int, tp_precision: int, n_pred: int
) -> dict[str, float]:
recall = tp_recall / n_ref if n_ref else 0.0
precision = tp_precision / n_pred if n_pred else 0.0
f1 = 2 * recall * precision / (recall + precision) if recall + precision else 0.0
return {"Precision": 100 * precision, "Recall": 100 * recall, "F1": 100 * f1}
def evaluate_gff(
reference: dict[str, list[CdsKey]],
prediction: dict[str, list[CdsKey]],
pseudogenes: dict[str, list[tuple[int, int]]] | None = None,
min_cds_length: int = 201,
) -> dict[str, dict[str, float]]:
"""CDS- and gene-level precision, recall and F1 (in %).
Args:
reference: Reference genes, as returned by ``parse_genes``.
prediction: Predicted genes, restricted to the reference's chromosomes.
pseudogenes: Pseudogene regions away from reference CDS; predicted CDS
overlapping them are ignored.
min_cds_length: Predicted genes with less CDS than this (bp) are ignored.
Returns:
{"CDS": {...}, "Gene": {...}} with Precision, Recall and F1.
"""
ref_cds = {key for keys in reference.values() for key in keys}
kept = {
gid: keys
for gid, keys in prediction.items()
if sum(end - start + 1 for _, start, end, _, _ in keys) >= min_cds_length
}
dropped = {
key for gid, keys in prediction.items() if gid not in kept for key in keys
}
pred_cds = {key for keys in prediction.values() for key in keys} - dropped
if pseudogenes:
pred_cds = {key for key in pred_cds if not _overlaps(pseudogenes, key)}
kept = {gid: [k for k in keys if k in pred_cds] for gid, keys in kept.items()}
kept = {gid: keys for gid, keys in kept.items() if keys}
tp = len(ref_cds & pred_cds)
ref_structures = [frozenset(keys) for keys in reference.values()]
pred_structures = [frozenset(keys) for keys in kept.values()]
ref_set, pred_set = set(ref_structures), set(pred_structures)
return {
"CDS": _prf(tp, len(ref_cds), tp, len(pred_cds)),
"Gene": _prf(
sum(s in pred_set for s in ref_structures),
len(ref_structures),
sum(s in ref_set for s in pred_structures),
len(pred_structures),
),
}
def per_class_f1(confusion: np.ndarray) -> np.ndarray:
"""Per-class F1 from a (true, predicted) confusion matrix."""
tp = np.diag(confusion).astype(np.float64)
denominator = confusion.sum(axis=0) + confusion.sum(axis=1)
return np.divide(2 * tp, denominator, out=np.zeros_like(tp), where=denominator > 0)