Spaces:
Running on Zero

File size: 3,417 Bytes
0a96270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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