Spaces:
Running on Zero

Ziyuan-Wang's picture
Upload folder using huggingface_hub
0a96270 verified
Raw History Blame
3.42 kB
# Copyright (c) 2026 RIBOSPAN Team Authors.
# SPDX-License-Identifier: Apache-2.0
"""Parse and window RNAGym-style substitution strings for online inference.
Adapted from RIBOSPAN-FM, RNAGym_Fitness_Benchmark/scripts/mutations.py.
The online interface adds strict reference validation and canonical RNA labels.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
SINGLE_MUT = re.compile(r"^([ACGTU])([0-9]+)([ACGTU])$")
@dataclass(frozen=True)
class PointMutation:
wt: str
position: int # 0-based
mt: str
def as_tuple(self) -> tuple[str, int, str]:
return self.wt, self.position, self.mt
def as_rna(self) -> str:
return f"{self.wt.replace('T', 'U')}{self.position + 1}{self.mt.replace('T', 'U')}"
def normalize_base(base: str) -> str:
value = str(base).strip().upper().replace("U", "T")
if value not in {"A", "C", "G", "T"}:
raise ValueError("unsupported nucleotide")
return value
def parse_mutant(raw: str) -> list[PointMutation]:
"""Parse substitutions, validating syntax, duplicate positions and changes."""
if not isinstance(raw, str) or not raw.strip():
raise ValueError("expected a substitution such as A123C")
text = raw.strip().upper().replace(" ", "")
parts = text.replace(";", ",").split(",")
parsed = []
for part in parts:
match = SINGLE_MUT.fullmatch(part)
if match is None:
raise ValueError("only nucleotide substitutions are supported")
wt, pos_s, mt = match.groups()
wt, mt = normalize_base(wt), normalize_base(mt)
position = int(pos_s) - 1
if position < 0 or wt == mt:
raise ValueError("invalid substitution position or unchanged base")
parsed.append(PointMutation(wt=wt, position=position, mt=mt))
positions = [item.position for item in parsed]
if len(positions) != len(set(positions)):
raise ValueError("a variant edits the same position more than once")
return sorted(parsed, key=lambda item: item.position)
def validate_reference(sequence: str, mutations: list[PointMutation]) -> None:
"""The normalized reference must match every declared reference base."""
for item in mutations:
if item.position >= len(sequence) or sequence[item.position] != item.wt:
raise ValueError("mutation position is outside the reference or the reference base does not match")
def mutation_window(
length: int,
positions: list[int],
*,
max_nucleotides: int,
) -> tuple[int, int]:
"""Mutation-centered crop, preserving the original RNAGym window definition."""
if max_nucleotides < 1:
raise ValueError("max_nucleotides must be positive")
if length <= max_nucleotides:
return 0, length
if not positions:
return 0, max_nucleotides
min_idx, max_idx = min(positions), max(positions)
if max_idx - min_idx + 1 > max_nucleotides:
raise ValueError("the mutated span exceeds the native checkpoint context")
center = (min_idx + max_idx) // 2
half = max_nucleotides // 2
start = max(0, center - half)
end = min(length, start + max_nucleotides)
if end == length:
start = max(0, length - max_nucleotides)
if not all(start <= idx < end for idx in positions):
raise ValueError("the mutation-centered window misses a requested site")
return start, end