Spaces:
Running on Zero

File size: 2,723 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
# SPDX-License-Identifier: Apache-2.0
"""Online masked-marginal RNA substitution scoring."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

import numpy as np

from scripts.batching import batches, with_oom_retry
from scripts.logits import MLMScorer, MaskPattern
from scripts.model_io import LoadedRiboSpan
from scripts.requests import Job, Record, Variant, group_variants


@dataclass(frozen=True)
class ScoringGroup:
    record: Record
    start: int
    end: int
    positions: tuple[int, ...]
    variants: tuple[Variant, ...]

    @property
    def pattern(self) -> MaskPattern:
        return MaskPattern(self.record.sequence[self.start : self.end], tuple(pos - self.start for pos in self.positions))


def _score_log_odds(
    scorer: MLMScorer,
    group: ScoringGroup,
    log_probs: np.ndarray,
) -> dict[str, float]:
    """Sum log-probability differences conditioned on the jointly masked sites."""

    row_by_position = {position: i for i, position in enumerate(group.positions)}
    scores = {}
    for variant in group.variants:
        total = 0.0
        for mutation in variant.mutations:
            row = row_by_position[mutation.position]
            total += float(log_probs[row, scorer.nt_id(mutation.mt)] - log_probs[row, scorer.nt_id(mutation.wt)])
        if not np.isfinite(total):
            raise RuntimeError("non-finite variant score")
        scores[variant.label] = total
    return scores


def score_job(job: Job, models: dict[str, LoadedRiboSpan]) -> dict[str, Any]:
    groups = [
        ScoringGroup(record, start, end, positions, tuple(variants))
        for record in job.records
        for (start, end, positions), variants in group_variants(record)
    ]
    by_id: dict[str, dict[str, float]] = {record.id: {} for record in job.records}
    for chunk in batches(groups, key=lambda group: (group.record.model.name, group.end - group.start + 2)):
        scorer = MLMScorer(models[chunk[0].record.model.name])
        log_probs = with_oom_retry(lambda part: scorer.log_probs([item.pattern for item in part]), chunk)
        for group, values in zip(chunk, log_probs, strict=True):
            by_id[group.record.id].update(_score_log_odds(scorer, group, values))

    return {"results": [
        {
            "id": record.id,
            "model_id": record.model.name,
            "variants": [
                {
                    "variant": variant.label,
                    "score": by_id[record.id][variant.label],
                    "window": {"start": variant.start, "end": variant.end},
                }
                for variant in record.variants
            ],
        }
        for record in job.records
    ]}