mutlof 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mutlof/__init__.py +8 -0
- mutlof/cli.py +42 -0
- mutlof/codes.py +122 -0
- mutlof/model.py +223 -0
- mutlof/proteins.py +120 -0
- mutlof/score.py +97 -0
- mutlof/tokens.py +120 -0
- mutlof/weights/model_best.pt +0 -0
- mutlof-1.0.0.dist-info/METADATA +22 -0
- mutlof-1.0.0.dist-info/RECORD +13 -0
- mutlof-1.0.0.dist-info/WHEEL +5 -0
- mutlof-1.0.0.dist-info/entry_points.txt +2 -0
- mutlof-1.0.0.dist-info/top_level.txt +1 -0
mutlof/__init__.py
ADDED
mutlof/cli.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Command line for MutLoF 1.0.0."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from mutlof.model import load_model
|
|
11
|
+
from mutlof.score import score_table, write_scores
|
|
12
|
+
|
|
13
|
+
DEFAULT_WEIGHTS = Path(__file__).resolve().parent / "weights" / "model_best.pt"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def main() -> None:
|
|
17
|
+
parser = argparse.ArgumentParser(
|
|
18
|
+
description="Write MutLoF scores for a reference FASTA and a MutCode table.",
|
|
19
|
+
)
|
|
20
|
+
parser.add_argument("--reference", type=Path, required=True, help="Reference DNA FASTA")
|
|
21
|
+
parser.add_argument("--codes", type=Path, required=True, help="MutCode TSV")
|
|
22
|
+
parser.add_argument("--output", type=Path, required=True, help="TSV of gene, sample, lof_score")
|
|
23
|
+
parser.add_argument("--weights", type=Path, default=DEFAULT_WEIGHTS)
|
|
24
|
+
parser.add_argument("--device", default="cpu")
|
|
25
|
+
parser.add_argument("--batch-size", type=int, default=256)
|
|
26
|
+
args = parser.parse_args()
|
|
27
|
+
if not args.weights.is_file():
|
|
28
|
+
raise SystemExit(f"weights not found: {args.weights}")
|
|
29
|
+
model = load_model(args.weights, torch.device(args.device))
|
|
30
|
+
rows = score_table(
|
|
31
|
+
model,
|
|
32
|
+
args.reference,
|
|
33
|
+
args.codes,
|
|
34
|
+
device=torch.device(args.device),
|
|
35
|
+
batch_size=args.batch_size,
|
|
36
|
+
)
|
|
37
|
+
write_scores(args.output, rows)
|
|
38
|
+
print(f"wrote {len(rows)} scores to {args.output}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
if __name__ == "__main__":
|
|
42
|
+
main()
|
mutlof/codes.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""MutCode parsing and reference FASTA reading."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class MutCodeError(ValueError):
|
|
13
|
+
"""Invalid MutCode edit list."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_IUPAC = re.compile(r"^[ACGTRYSWKMBDHVNacgtryswkmbdhvn]*$")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def sha256_seq(sequence: str) -> str:
|
|
20
|
+
return hashlib.sha256(sequence.encode("ascii")).hexdigest()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_codes(raw: str | list | tuple | None) -> list[tuple[int, int, str]]:
|
|
24
|
+
if raw is None or raw == "" or raw == "[]":
|
|
25
|
+
return []
|
|
26
|
+
payload = json.loads(raw) if isinstance(raw, str) else raw
|
|
27
|
+
if not isinstance(payload, (list, tuple)):
|
|
28
|
+
raise MutCodeError("codes must be a JSON array")
|
|
29
|
+
edits: list[tuple[int, int, str]] = []
|
|
30
|
+
for index, item in enumerate(payload):
|
|
31
|
+
if not (isinstance(item, (list, tuple)) and len(item) == 3):
|
|
32
|
+
raise MutCodeError(f"codes[{index}] must be [start, delete_length, inserted]")
|
|
33
|
+
start, delete_length, inserted = item
|
|
34
|
+
if type(start) is not int or type(delete_length) is not int or not isinstance(inserted, str):
|
|
35
|
+
raise MutCodeError(f"codes[{index}] has a bad field type")
|
|
36
|
+
if not _IUPAC.fullmatch(inserted):
|
|
37
|
+
raise MutCodeError(f"inserted sequence contains non-IUPAC DNA: {inserted!r}")
|
|
38
|
+
edits.append((start, delete_length, inserted))
|
|
39
|
+
return edits
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def validate_edits(edits: list[tuple[int, int, str]], reference_length: int) -> None:
|
|
43
|
+
previous_end = 0
|
|
44
|
+
seen: set[int] = set()
|
|
45
|
+
for index, (start, delete_length, inserted) in enumerate(edits):
|
|
46
|
+
if start < 0 or delete_length < 0:
|
|
47
|
+
raise MutCodeError(f"edit {index} has a negative field")
|
|
48
|
+
if delete_length == 0 and inserted == "":
|
|
49
|
+
raise MutCodeError("empty insertion with delete_length 0 is illegal")
|
|
50
|
+
if start in seen:
|
|
51
|
+
raise MutCodeError(f"duplicate edit start {start}")
|
|
52
|
+
seen.add(start)
|
|
53
|
+
if start < previous_end or start + delete_length > reference_length:
|
|
54
|
+
raise MutCodeError(f"edit {index} overlaps or runs past the reference")
|
|
55
|
+
previous_end = start + delete_length
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def apply_edits(reference: str, edits: list[tuple[int, int, str]]) -> str:
|
|
59
|
+
validate_edits(edits, len(reference))
|
|
60
|
+
if not edits:
|
|
61
|
+
return reference
|
|
62
|
+
cursor = 0
|
|
63
|
+
parts: list[str] = []
|
|
64
|
+
for start, delete_length, inserted in edits:
|
|
65
|
+
parts.append(reference[cursor:start])
|
|
66
|
+
parts.append(inserted)
|
|
67
|
+
cursor = start + delete_length
|
|
68
|
+
parts.append(reference[cursor:])
|
|
69
|
+
return "".join(parts)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def read_fasta(path: str | Path) -> dict[str, str]:
|
|
73
|
+
sequences: dict[str, str] = {}
|
|
74
|
+
name: str | None = None
|
|
75
|
+
chunks: list[str] = []
|
|
76
|
+
with open(path, encoding="utf-8") as handle:
|
|
77
|
+
for line in handle:
|
|
78
|
+
if line.startswith(">"):
|
|
79
|
+
if name is not None:
|
|
80
|
+
sequences[name] = "".join(chunks)
|
|
81
|
+
name = line[1:].split()[0]
|
|
82
|
+
chunks = []
|
|
83
|
+
else:
|
|
84
|
+
chunks.append(line.strip())
|
|
85
|
+
if name is not None:
|
|
86
|
+
sequences[name] = "".join(chunks)
|
|
87
|
+
if not sequences:
|
|
88
|
+
raise ValueError(f"{path} has no FASTA records")
|
|
89
|
+
return sequences
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def read_code_table(path: str | Path) -> list[dict[str, str]]:
|
|
93
|
+
"""MutCode TSV or a LoF matrix. Gzip is accepted."""
|
|
94
|
+
import gzip
|
|
95
|
+
|
|
96
|
+
path = Path(path)
|
|
97
|
+
opener = gzip.open if path.suffix == ".gz" else open
|
|
98
|
+
with opener(path, "rt", encoding="utf-8", newline="") as handle:
|
|
99
|
+
lines = handle.readlines()
|
|
100
|
+
while lines and lines[0].startswith("#"):
|
|
101
|
+
lines.pop(0)
|
|
102
|
+
if not lines:
|
|
103
|
+
raise ValueError(f"{path} has no table header")
|
|
104
|
+
csv.field_size_limit(10_000_000)
|
|
105
|
+
rows = []
|
|
106
|
+
for raw in csv.DictReader(lines, delimiter="\t"):
|
|
107
|
+
gene = (raw.get("gene") or raw.get("Gene") or "").strip()
|
|
108
|
+
if not gene:
|
|
109
|
+
raise ValueError("code table row is missing gene/Gene")
|
|
110
|
+
codes = raw.get("codes")
|
|
111
|
+
if codes is None:
|
|
112
|
+
codes = raw.get("Mutation_Codes")
|
|
113
|
+
rows.append(
|
|
114
|
+
{
|
|
115
|
+
"gene": gene,
|
|
116
|
+
"sample": (raw.get("sample") or raw.get("Sample") or "").strip(),
|
|
117
|
+
"codes": codes if codes is not None else "[]",
|
|
118
|
+
"reference_sha256": (raw.get("reference_sha256") or "").strip(),
|
|
119
|
+
"target_sha256": (raw.get("target_sha256") or "").strip(),
|
|
120
|
+
}
|
|
121
|
+
)
|
|
122
|
+
return rows
|
mutlof/model.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""MutLoF network. Attribute names match the trained checkpoint."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
import torch.nn as nn
|
|
10
|
+
|
|
11
|
+
from mutlof.tokens import NUMERIC_DIM, REF_MAX_LEN, VOCAB_SIZE
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class EditEncoder(nn.Module):
|
|
15
|
+
def __init__(self, hidden_size: int, d_model: int, n_layers: int, n_heads: int, dropout: float):
|
|
16
|
+
super().__init__()
|
|
17
|
+
self.symbol_dim = 32
|
|
18
|
+
self.num_proj = nn.Linear(NUMERIC_DIM, d_model)
|
|
19
|
+
self.symbol = nn.Embedding(VOCAB_SIZE, self.symbol_dim, padding_idx=0)
|
|
20
|
+
self.edit_proj = nn.Linear(d_model + 3 * self.symbol_dim, d_model)
|
|
21
|
+
self.cls_proj = nn.Linear(3, d_model)
|
|
22
|
+
layer = nn.TransformerEncoderLayer(
|
|
23
|
+
d_model=d_model,
|
|
24
|
+
nhead=n_heads,
|
|
25
|
+
dim_feedforward=d_model * 4,
|
|
26
|
+
dropout=dropout,
|
|
27
|
+
activation="gelu",
|
|
28
|
+
batch_first=True,
|
|
29
|
+
norm_first=True,
|
|
30
|
+
)
|
|
31
|
+
self.transformer = nn.TransformerEncoder(layer, num_layers=n_layers, enable_nested_tensor=False)
|
|
32
|
+
self.to_mean = nn.Linear(d_model, hidden_size)
|
|
33
|
+
self.to_max = nn.Linear(d_model, hidden_size)
|
|
34
|
+
|
|
35
|
+
def _pool_symbols(self, ids: torch.Tensor) -> torch.Tensor:
|
|
36
|
+
embedded = self.symbol(ids)
|
|
37
|
+
mask = ids.ne(0).unsqueeze(-1).to(embedded.dtype)
|
|
38
|
+
return (embedded * mask).sum(dim=2) / mask.sum(dim=2).clamp(min=1.0)
|
|
39
|
+
|
|
40
|
+
def forward(self, edit_num, edit_mask, inserted_ids, deleted_ids, window_ids, n_edits):
|
|
41
|
+
pieces = torch.cat(
|
|
42
|
+
[
|
|
43
|
+
self.num_proj(edit_num),
|
|
44
|
+
self._pool_symbols(inserted_ids),
|
|
45
|
+
self._pool_symbols(deleted_ids),
|
|
46
|
+
self._pool_symbols(window_ids),
|
|
47
|
+
],
|
|
48
|
+
dim=-1,
|
|
49
|
+
)
|
|
50
|
+
tokens = self.edit_proj(pieces)
|
|
51
|
+
present = edit_mask.to(torch.bool)
|
|
52
|
+
n_kept = present.sum(dim=1).to(n_edits.dtype)
|
|
53
|
+
overflow = (n_edits - n_kept).clamp(min=0).to(edit_num.dtype)
|
|
54
|
+
cls_in = torch.stack(
|
|
55
|
+
[torch.log1p(n_edits.to(edit_num.dtype)), overflow, present.any(dim=1).to(edit_num.dtype)],
|
|
56
|
+
dim=-1,
|
|
57
|
+
)
|
|
58
|
+
hidden = torch.cat([self.cls_proj(cls_in).unsqueeze(1), tokens], dim=1)
|
|
59
|
+
pad = torch.cat(
|
|
60
|
+
[torch.zeros(present.shape[0], 1, dtype=torch.bool, device=present.device), ~present],
|
|
61
|
+
dim=1,
|
|
62
|
+
)
|
|
63
|
+
encoded = self.transformer(hidden, src_key_padding_mask=pad)
|
|
64
|
+
cls_out = encoded[:, 0]
|
|
65
|
+
edit_out = encoded[:, 1:].masked_fill(~present.unsqueeze(-1), torch.finfo(encoded.dtype).min)
|
|
66
|
+
max_out = edit_out.max(dim=1).values
|
|
67
|
+
max_out = torch.where(~present.any(dim=1, keepdim=True), cls_out, max_out)
|
|
68
|
+
return self.to_mean(cls_out), self.to_max(max_out)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _sinusoidal(length: int, d_model: int) -> torch.Tensor:
|
|
72
|
+
position = torch.arange(length, dtype=torch.float32).unsqueeze(1)
|
|
73
|
+
div = torch.exp(torch.arange(0, d_model, 2, dtype=torch.float32) * (-math.log(10000.0) / d_model))
|
|
74
|
+
angles = position * div
|
|
75
|
+
encoded = torch.zeros(length, d_model)
|
|
76
|
+
encoded[:, 0::2] = torch.sin(angles)
|
|
77
|
+
encoded[:, 1::2] = torch.cos(angles)
|
|
78
|
+
return encoded
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _LatentLayer(nn.Module):
|
|
82
|
+
def __init__(self, d_model: int, n_heads: int, dropout: float):
|
|
83
|
+
super().__init__()
|
|
84
|
+
self.norm_q = nn.LayerNorm(d_model)
|
|
85
|
+
self.norm_kv = nn.LayerNorm(d_model)
|
|
86
|
+
self.attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout, batch_first=True)
|
|
87
|
+
self.norm_ff = nn.LayerNorm(d_model)
|
|
88
|
+
self.ff = nn.Sequential(
|
|
89
|
+
nn.Linear(d_model, d_model * 4),
|
|
90
|
+
nn.GELU(),
|
|
91
|
+
nn.Dropout(dropout),
|
|
92
|
+
nn.Linear(d_model * 4, d_model),
|
|
93
|
+
nn.Dropout(dropout),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
def forward(self, latents, memory, pad):
|
|
97
|
+
attended, _ = self.attn(self.norm_q(latents), self.norm_kv(memory), self.norm_kv(memory), key_padding_mask=pad, need_weights=False)
|
|
98
|
+
latents = latents + attended
|
|
99
|
+
return latents + self.ff(self.norm_ff(latents))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class ReferenceEncoder(nn.Module):
|
|
103
|
+
def __init__(self, hidden_size: int, d_model: int, n_layers: int, n_heads: int, n_latents: int, dropout: float):
|
|
104
|
+
super().__init__()
|
|
105
|
+
self.max_length = REF_MAX_LEN
|
|
106
|
+
self.token = nn.Embedding(VOCAB_SIZE, d_model, padding_idx=0)
|
|
107
|
+
self.latents = nn.Parameter(torch.randn(1, n_latents, d_model) * 0.02)
|
|
108
|
+
self.register_buffer("pos", _sinusoidal(REF_MAX_LEN, d_model), persistent=False)
|
|
109
|
+
self.layers = nn.ModuleList([_LatentLayer(d_model, n_heads, dropout) for _ in range(n_layers)])
|
|
110
|
+
self.to_mean = nn.Linear(d_model, hidden_size)
|
|
111
|
+
self.to_max = nn.Linear(d_model, hidden_size)
|
|
112
|
+
|
|
113
|
+
def forward(self, ref_ids: torch.Tensor):
|
|
114
|
+
present = ref_ids.ne(0)
|
|
115
|
+
length = ref_ids.shape[1]
|
|
116
|
+
memory = self.token(ref_ids.long()) + self.pos[:length].unsqueeze(0).to(dtype=self.token.weight.dtype)
|
|
117
|
+
latents = self.latents.expand(ref_ids.shape[0], -1, -1)
|
|
118
|
+
for layer in self.layers:
|
|
119
|
+
latents = layer(latents, memory, ~present)
|
|
120
|
+
return self.to_mean(latents.mean(dim=1)), self.to_max(latents.max(dim=1).values)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class _Comparison(nn.Module):
|
|
124
|
+
def __init__(self, hidden_size: int):
|
|
125
|
+
super().__init__()
|
|
126
|
+
raw = 4 * hidden_size * 2
|
|
127
|
+
self._pre_norm = nn.LayerNorm(raw)
|
|
128
|
+
self._gate = nn.Sequential(
|
|
129
|
+
nn.Linear(raw, raw // 4),
|
|
130
|
+
nn.ReLU(),
|
|
131
|
+
nn.Linear(raw // 4, raw),
|
|
132
|
+
nn.Sigmoid(),
|
|
133
|
+
)
|
|
134
|
+
self._proj = nn.Sequential(
|
|
135
|
+
nn.Linear(raw, 2 * hidden_size),
|
|
136
|
+
nn.GELU(),
|
|
137
|
+
nn.Linear(2 * hidden_size, 4 * hidden_size),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
def forward(self, ref_mean, ref_max, var_mean, var_max):
|
|
141
|
+
ref_pool = torch.cat([ref_mean, ref_max], dim=-1)
|
|
142
|
+
var_pool = torch.cat([var_mean, var_max], dim=-1)
|
|
143
|
+
raw = torch.cat([ref_pool - var_pool, ref_pool * var_pool, ref_pool, var_pool], dim=-1)
|
|
144
|
+
normalized = self._pre_norm(raw)
|
|
145
|
+
return self._proj(normalized * self._gate(normalized))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class _Head(nn.Module):
|
|
149
|
+
def __init__(self, hidden_size: int, head_hidden: int, dropout: float):
|
|
150
|
+
super().__init__()
|
|
151
|
+
self.mlp = nn.Sequential(
|
|
152
|
+
nn.Linear(4 * hidden_size + 12, head_hidden),
|
|
153
|
+
nn.ReLU(),
|
|
154
|
+
nn.Dropout(dropout),
|
|
155
|
+
nn.Linear(head_hidden, head_hidden // 2),
|
|
156
|
+
nn.ReLU(),
|
|
157
|
+
nn.Dropout(dropout * 0.5),
|
|
158
|
+
nn.Linear(head_hidden // 2, 1),
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def forward(self, features: torch.Tensor) -> torch.Tensor:
|
|
162
|
+
return torch.sigmoid(self.mlp(features).squeeze(-1))
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class _HeadNet(nn.Module):
|
|
166
|
+
def __init__(self, hidden_size: int, head_hidden: int, dropout: float):
|
|
167
|
+
super().__init__()
|
|
168
|
+
self.comparison = _Comparison(hidden_size)
|
|
169
|
+
self.feature_norm = nn.LayerNorm(12)
|
|
170
|
+
self.head = _Head(hidden_size, head_hidden, dropout)
|
|
171
|
+
|
|
172
|
+
def forward(self, ref_mean, ref_max, var_mean, var_max, nucleotide_features):
|
|
173
|
+
compared = self.comparison(ref_mean, ref_max, var_mean, var_max)
|
|
174
|
+
return self.head(torch.cat([compared, self.feature_norm(nucleotide_features)], dim=-1))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class LoFModel(nn.Module):
|
|
178
|
+
def __init__(self, config: dict):
|
|
179
|
+
super().__init__()
|
|
180
|
+
hidden = int(config["hidden_size"])
|
|
181
|
+
d_model = int(config["code_d_model"])
|
|
182
|
+
dropout = float(config["dropout"])
|
|
183
|
+
encoder_dropout = float(config["code_encoder_dropout"])
|
|
184
|
+
self.encoder = EditEncoder(
|
|
185
|
+
hidden,
|
|
186
|
+
d_model,
|
|
187
|
+
int(config["code_layers"]),
|
|
188
|
+
int(config["code_heads"]),
|
|
189
|
+
encoder_dropout,
|
|
190
|
+
)
|
|
191
|
+
self.reference = ReferenceEncoder(
|
|
192
|
+
hidden,
|
|
193
|
+
d_model,
|
|
194
|
+
int(config["ref_layers"]),
|
|
195
|
+
int(config["ref_heads"]),
|
|
196
|
+
int(config["ref_latents"]),
|
|
197
|
+
float(config["ref_dropout"]),
|
|
198
|
+
)
|
|
199
|
+
self.head_net = _HeadNet(hidden, int(config["head_hidden"]), dropout)
|
|
200
|
+
|
|
201
|
+
def score(self, batch: dict) -> torch.Tensor:
|
|
202
|
+
ref_mean, ref_max = self.reference(batch["ref_ids"])
|
|
203
|
+
var_mean, var_max = self.encoder(
|
|
204
|
+
batch["edit_num"],
|
|
205
|
+
batch["edit_mask"],
|
|
206
|
+
batch["inserted_ids"],
|
|
207
|
+
batch["deleted_ids"],
|
|
208
|
+
batch["window_ids"],
|
|
209
|
+
batch["n_edits"],
|
|
210
|
+
)
|
|
211
|
+
return self.head_net(ref_mean, ref_max, var_mean, var_max, batch["nucleotide_features"])
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def load_model(path: str | Path, device: torch.device | None = None) -> LoFModel:
|
|
215
|
+
device = device or torch.device("cpu")
|
|
216
|
+
blob = torch.load(path, map_location=device, weights_only=False)
|
|
217
|
+
config = blob.get("model_config") or {}
|
|
218
|
+
if not config.get("encode_reference"):
|
|
219
|
+
raise ValueError(f"{path} is not a MutLoF sequence checkpoint")
|
|
220
|
+
model = LoFModel(config)
|
|
221
|
+
model.load_state_dict(blob["state_dict"])
|
|
222
|
+
model.eval()
|
|
223
|
+
return model.to(device)
|
mutlof/proteins.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Translation and the 12 protein features the score head was trained with."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
from Bio.Data.CodonTable import TranslationError
|
|
9
|
+
from Bio.Seq import Seq
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def translate_dna(dna_seq: str) -> str:
|
|
13
|
+
"""Bacterial codon table 11. Stops are kept as ``*``."""
|
|
14
|
+
dna = dna_seq.upper().replace("U", "T")
|
|
15
|
+
trimmed = dna[: len(dna) - len(dna) % 3]
|
|
16
|
+
if not trimmed:
|
|
17
|
+
return ""
|
|
18
|
+
try:
|
|
19
|
+
return str(Seq(trimmed).translate(table=11))
|
|
20
|
+
except TranslationError:
|
|
21
|
+
return ""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _find_mutations(ref_protein: str, var_protein: str) -> list[dict]:
|
|
25
|
+
mutations: list[dict] = []
|
|
26
|
+
min_len = min(len(ref_protein), len(var_protein))
|
|
27
|
+
for index in range(min_len):
|
|
28
|
+
ref_aa = ref_protein[index]
|
|
29
|
+
var_aa = var_protein[index]
|
|
30
|
+
if ref_aa == var_aa:
|
|
31
|
+
continue
|
|
32
|
+
if var_aa == "*":
|
|
33
|
+
kind = "nonsense"
|
|
34
|
+
elif ref_aa == "*":
|
|
35
|
+
kind = "readthrough"
|
|
36
|
+
else:
|
|
37
|
+
kind = "missense"
|
|
38
|
+
mutations.append({"position": index + 1, "type": kind})
|
|
39
|
+
if len(var_protein) < len(ref_protein):
|
|
40
|
+
mutations.append({"position": len(var_protein) + 1, "type": "truncation"})
|
|
41
|
+
elif len(var_protein) > len(ref_protein):
|
|
42
|
+
mutations.append({"position": len(ref_protein) + 1, "type": "extension"})
|
|
43
|
+
return mutations
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _has_premature_stop(ref_protein: str, var_protein: str) -> bool:
|
|
47
|
+
ref_stop = ref_protein.find("*")
|
|
48
|
+
var_stop = var_protein.find("*")
|
|
49
|
+
if var_stop == -1:
|
|
50
|
+
return False
|
|
51
|
+
if ref_stop == -1:
|
|
52
|
+
return True
|
|
53
|
+
return var_stop < ref_stop
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _truncation_fraction(ref_protein: str, var_protein: str) -> float:
|
|
57
|
+
if not ref_protein:
|
|
58
|
+
return 0.0
|
|
59
|
+
ref_stop = ref_protein.find("*")
|
|
60
|
+
var_stop = var_protein.find("*")
|
|
61
|
+
ref_len = ref_stop if ref_stop != -1 else len(ref_protein)
|
|
62
|
+
var_len = var_stop if var_stop != -1 else len(var_protein)
|
|
63
|
+
if ref_len == 0 or var_len >= ref_len:
|
|
64
|
+
return 0.0
|
|
65
|
+
return (ref_len - var_len) / ref_len
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _region(position: int, protein_length: int) -> str:
|
|
69
|
+
if protein_length == 0:
|
|
70
|
+
return "none"
|
|
71
|
+
frac = position / protein_length
|
|
72
|
+
if frac <= 0.2:
|
|
73
|
+
return "N-terminal"
|
|
74
|
+
if frac >= 0.8:
|
|
75
|
+
return "C-terminal"
|
|
76
|
+
return "middle"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _identity(ref: str, var: str) -> float:
|
|
80
|
+
if not ref and not var:
|
|
81
|
+
return 1.0
|
|
82
|
+
max_len = max(len(ref), len(var))
|
|
83
|
+
if max_len == 0:
|
|
84
|
+
return 1.0
|
|
85
|
+
matches = sum(1 for index in range(min(len(ref), len(var))) if ref[index] == var[index])
|
|
86
|
+
return matches / max_len
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def protein_features(ref_protein: str, var_protein: str) -> torch.Tensor:
|
|
90
|
+
"""The same 12 numbers the sequence model saw in training."""
|
|
91
|
+
ref_protein = ref_protein or ""
|
|
92
|
+
var_protein = var_protein or ""
|
|
93
|
+
mutations = _find_mutations(ref_protein, var_protein)
|
|
94
|
+
n_missense = sum(1 for item in mutations if item["type"] == "missense")
|
|
95
|
+
n_nonsense = sum(1 for item in mutations if item["type"] == "nonsense")
|
|
96
|
+
n_total = len(mutations)
|
|
97
|
+
protein_len = max(len(ref_protein), 1)
|
|
98
|
+
region_n = 0.0
|
|
99
|
+
region_c = 0.0
|
|
100
|
+
positioned = [item for item in mutations if "position" in item]
|
|
101
|
+
if positioned:
|
|
102
|
+
region_n = sum(1.0 for item in positioned if _region(item["position"], protein_len) == "N-terminal") / len(positioned)
|
|
103
|
+
region_c = sum(1.0 for item in positioned if _region(item["position"], protein_len) == "C-terminal") / len(positioned)
|
|
104
|
+
return torch.tensor(
|
|
105
|
+
[
|
|
106
|
+
float(len(var_protein) != len(ref_protein)),
|
|
107
|
+
float(_has_premature_stop(ref_protein, var_protein)),
|
|
108
|
+
float(len(ref_protein) > 0 and ref_protein[0] == "M" and (len(var_protein) == 0 or var_protein[0] != "M")),
|
|
109
|
+
n_missense / protein_len,
|
|
110
|
+
float(n_nonsense),
|
|
111
|
+
1.0 - _identity(ref_protein, var_protein),
|
|
112
|
+
_truncation_fraction(ref_protein, var_protein),
|
|
113
|
+
(n_total / protein_len) * 100,
|
|
114
|
+
region_n,
|
|
115
|
+
region_c,
|
|
116
|
+
math.log1p(n_total),
|
|
117
|
+
len(var_protein) / protein_len,
|
|
118
|
+
],
|
|
119
|
+
dtype=torch.float32,
|
|
120
|
+
)
|
mutlof/score.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Score MutCode rows against reference sequences."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from mutlof.codes import apply_edits, parse_codes, read_code_table, read_fasta, sha256_seq
|
|
11
|
+
from mutlof.model import LoFModel, load_model
|
|
12
|
+
from mutlof.proteins import protein_features, translate_dna
|
|
13
|
+
from mutlof.tokens import encode_protein, featurize_dna
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _row_tensors(reference_dna: str, codes: str) -> dict[str, torch.Tensor] | None:
|
|
17
|
+
edits = parse_codes(codes)
|
|
18
|
+
if not edits:
|
|
19
|
+
return None
|
|
20
|
+
variant_dna = apply_edits(reference_dna, edits)
|
|
21
|
+
ref_aa = translate_dna(reference_dna).replace("*", "")
|
|
22
|
+
var_aa = translate_dna(variant_dna).replace("*", "")
|
|
23
|
+
if not ref_aa:
|
|
24
|
+
raise ValueError("reference translation is empty")
|
|
25
|
+
features = featurize_dna(reference_dna, edits)
|
|
26
|
+
return {
|
|
27
|
+
"edit_num": features.edit_num,
|
|
28
|
+
"edit_mask": features.edit_mask,
|
|
29
|
+
"inserted_ids": features.inserted_ids,
|
|
30
|
+
"deleted_ids": features.deleted_ids,
|
|
31
|
+
"window_ids": features.window_ids,
|
|
32
|
+
"n_edits": features.n_edits,
|
|
33
|
+
"ref_ids": encode_protein(ref_aa),
|
|
34
|
+
"nucleotide_features": protein_features(ref_aa, var_aa),
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def score_table(
|
|
39
|
+
model: LoFModel,
|
|
40
|
+
reference_fasta: str | Path,
|
|
41
|
+
codes_tsv: str | Path,
|
|
42
|
+
*,
|
|
43
|
+
device: torch.device | None = None,
|
|
44
|
+
batch_size: int = 256,
|
|
45
|
+
) -> list[dict[str, str]]:
|
|
46
|
+
"""One score per code-table row. An empty code list scores 0."""
|
|
47
|
+
device = device or torch.device("cpu")
|
|
48
|
+
model = model.to(device).eval()
|
|
49
|
+
sequences = read_fasta(reference_fasta)
|
|
50
|
+
rows = read_code_table(codes_tsv)
|
|
51
|
+
prepared: list[dict[str, torch.Tensor] | None] = []
|
|
52
|
+
for row in rows:
|
|
53
|
+
gene = row["gene"]
|
|
54
|
+
if gene not in sequences:
|
|
55
|
+
raise KeyError(f"{gene} is not in {reference_fasta}")
|
|
56
|
+
reference = sequences[gene]
|
|
57
|
+
digest = row["reference_sha256"]
|
|
58
|
+
if digest and sha256_seq(reference) != digest.lower():
|
|
59
|
+
raise ValueError(f"{gene}: reference FASTA does not match reference_sha256")
|
|
60
|
+
prepared.append(_row_tensors(reference, row["codes"]))
|
|
61
|
+
|
|
62
|
+
scores = [0.0] * len(rows)
|
|
63
|
+
slots = [index for index, item in enumerate(prepared) if item is not None]
|
|
64
|
+
with torch.no_grad():
|
|
65
|
+
for start in range(0, len(slots), batch_size):
|
|
66
|
+
chunk = slots[start : start + batch_size]
|
|
67
|
+
batch = {
|
|
68
|
+
key: torch.stack([prepared[index][key] for index in chunk]).to(device)
|
|
69
|
+
for key in prepared[chunk[0]]
|
|
70
|
+
}
|
|
71
|
+
values = model.score(batch).detach().cpu()
|
|
72
|
+
for offset, index in enumerate(chunk):
|
|
73
|
+
scores[index] = float(values[offset])
|
|
74
|
+
results = []
|
|
75
|
+
for row, value in zip(rows, scores):
|
|
76
|
+
results.append(
|
|
77
|
+
{
|
|
78
|
+
"gene": row["gene"],
|
|
79
|
+
"sample": row["sample"],
|
|
80
|
+
"lof_score": f"{value:.6f}",
|
|
81
|
+
}
|
|
82
|
+
)
|
|
83
|
+
return results
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def write_scores(path: str | Path, rows: list[dict[str, str]]) -> None:
|
|
87
|
+
path = Path(path)
|
|
88
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
|
90
|
+
writer = csv.DictWriter(
|
|
91
|
+
handle,
|
|
92
|
+
fieldnames=("gene", "sample", "lof_score"),
|
|
93
|
+
delimiter="\t",
|
|
94
|
+
lineterminator="\n",
|
|
95
|
+
)
|
|
96
|
+
writer.writeheader()
|
|
97
|
+
writer.writerows(rows)
|
mutlof/tokens.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Edit tokens and reference-protein ids for MutLoF."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
MAX_EDITS = 16
|
|
10
|
+
INSERT_LEN = 12
|
|
11
|
+
DELETE_LEN = 12
|
|
12
|
+
WINDOW = 21
|
|
13
|
+
REF_MAX_LEN = 1024
|
|
14
|
+
NUMERIC_DIM = 8
|
|
15
|
+
|
|
16
|
+
PAD_ID = 0
|
|
17
|
+
UNK_ID = 1
|
|
18
|
+
DNA_BASE = 2
|
|
19
|
+
PROT_BASE = 32
|
|
20
|
+
VOCAB_SIZE = 64
|
|
21
|
+
|
|
22
|
+
_DNA = "ACGTNRYSWKMBDHV"
|
|
23
|
+
_PROT = "ACDEFGHIKLMNPQRSTVWY*X"
|
|
24
|
+
DNA_TO_ID = {base: DNA_BASE + i for i, base in enumerate(_DNA)}
|
|
25
|
+
PROT_TO_ID = {aa: PROT_BASE + i for i, aa in enumerate(_PROT)}
|
|
26
|
+
|
|
27
|
+
ALPHABET_DNA = 0
|
|
28
|
+
ALPHABET_AA = 1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True, slots=True)
|
|
32
|
+
class EditFeatures:
|
|
33
|
+
edit_num: torch.Tensor
|
|
34
|
+
edit_mask: torch.Tensor
|
|
35
|
+
inserted_ids: torch.Tensor
|
|
36
|
+
deleted_ids: torch.Tensor
|
|
37
|
+
window_ids: torch.Tensor
|
|
38
|
+
n_edits: torch.Tensor
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def symbol_id(char: str, alphabet: int) -> int:
|
|
42
|
+
table = DNA_TO_ID if alphabet == ALPHABET_DNA else PROT_TO_ID
|
|
43
|
+
return table.get(char.upper(), UNK_ID)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def encode_protein(sequence: str, max_length: int = REF_MAX_LEN) -> torch.Tensor:
|
|
47
|
+
"""Right-pad one protein. Pad id 0 is the attention mask."""
|
|
48
|
+
text = sequence.replace("*", "")[:max_length]
|
|
49
|
+
if not text:
|
|
50
|
+
raise ValueError("reference protein is empty")
|
|
51
|
+
ids = [symbol_id(char, ALPHABET_AA) for char in text]
|
|
52
|
+
out = torch.zeros(max_length, dtype=torch.long)
|
|
53
|
+
out[: len(ids)] = torch.tensor(ids, dtype=torch.long)
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _op_code(delete_length: int, inserted: str) -> int:
|
|
58
|
+
inserted_length = len(inserted)
|
|
59
|
+
if delete_length == 1 and inserted_length == 1:
|
|
60
|
+
return 1
|
|
61
|
+
if delete_length == inserted_length and delete_length > 1:
|
|
62
|
+
return 2
|
|
63
|
+
if delete_length == 0 and inserted_length > 0:
|
|
64
|
+
return 3
|
|
65
|
+
if inserted_length == 0 and delete_length > 0:
|
|
66
|
+
return 4
|
|
67
|
+
return 5
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _encode_text(text: str, width: int) -> list[int]:
|
|
71
|
+
ids = [symbol_id(char, ALPHABET_DNA) for char in text[:width]]
|
|
72
|
+
ids.extend([PAD_ID] * (width - len(ids)))
|
|
73
|
+
return ids
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _window_ids(reference: str, start: int) -> list[int]:
|
|
77
|
+
half = WINDOW // 2
|
|
78
|
+
ids = []
|
|
79
|
+
for index in range(start - half, start - half + WINDOW):
|
|
80
|
+
if index < 0 or index >= len(reference):
|
|
81
|
+
ids.append(PAD_ID)
|
|
82
|
+
else:
|
|
83
|
+
ids.append(symbol_id(reference[index], ALPHABET_DNA))
|
|
84
|
+
return ids
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def featurize_dna(reference: str, edits: list[tuple[int, int, str]]) -> EditFeatures:
|
|
88
|
+
"""MutCode edits against a DNA reference. At most 16 edits are kept."""
|
|
89
|
+
if not reference:
|
|
90
|
+
raise ValueError("reference sequence is empty")
|
|
91
|
+
kept = edits[:MAX_EDITS]
|
|
92
|
+
edit_num = torch.zeros(MAX_EDITS, NUMERIC_DIM, dtype=torch.float32)
|
|
93
|
+
edit_mask = torch.zeros(MAX_EDITS, dtype=torch.bool)
|
|
94
|
+
inserted_ids = torch.zeros(MAX_EDITS, INSERT_LEN, dtype=torch.long)
|
|
95
|
+
deleted_ids = torch.zeros(MAX_EDITS, DELETE_LEN, dtype=torch.long)
|
|
96
|
+
window_ids = torch.zeros(MAX_EDITS, WINDOW, dtype=torch.long)
|
|
97
|
+
ref_len = float(len(reference))
|
|
98
|
+
for slot, (start, delete_length, inserted) in enumerate(kept):
|
|
99
|
+
deleted = reference[start : start + delete_length]
|
|
100
|
+
length_delta = len(inserted) - delete_length
|
|
101
|
+
edit_num[slot, 0] = start / ref_len
|
|
102
|
+
edit_num[slot, 1] = delete_length / ref_len
|
|
103
|
+
edit_num[slot, 2] = len(inserted) / ref_len
|
|
104
|
+
edit_num[slot, 3] = length_delta / ref_len
|
|
105
|
+
edit_num[slot, 4] = float(length_delta % 3 != 0)
|
|
106
|
+
edit_num[slot, 5] = float(start % 3 == 0 and delete_length % 3 == 0 and len(inserted) % 3 == 0)
|
|
107
|
+
edit_num[slot, 6] = _op_code(delete_length, inserted) / 5.0
|
|
108
|
+
edit_num[slot, 7] = float(ALPHABET_DNA)
|
|
109
|
+
edit_mask[slot] = True
|
|
110
|
+
inserted_ids[slot] = torch.tensor(_encode_text(inserted, INSERT_LEN))
|
|
111
|
+
deleted_ids[slot] = torch.tensor(_encode_text(deleted, DELETE_LEN))
|
|
112
|
+
window_ids[slot] = torch.tensor(_window_ids(reference, start))
|
|
113
|
+
return EditFeatures(
|
|
114
|
+
edit_num=edit_num,
|
|
115
|
+
edit_mask=edit_mask,
|
|
116
|
+
inserted_ids=inserted_ids,
|
|
117
|
+
deleted_ids=deleted_ids,
|
|
118
|
+
window_ids=window_ids,
|
|
119
|
+
n_edits=torch.tensor(len(edits), dtype=torch.long),
|
|
120
|
+
)
|
|
Binary file
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mutlof
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Continuous LoF scores from a reference DNA FASTA and a MutCode table.
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: torch>=2.2
|
|
8
|
+
Requires-Dist: biopython>=1.81
|
|
9
|
+
|
|
10
|
+
# MutLoF
|
|
11
|
+
|
|
12
|
+
Continuous LoF scores from a reference DNA FASTA and a MutCode table. Version 1.0.0.
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install .
|
|
16
|
+
mutlof \
|
|
17
|
+
--reference genes.fa \
|
|
18
|
+
--codes mutation_codes.tsv \
|
|
19
|
+
--output scores.tsv
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
`genes.fa` headers must match the `gene` column. An empty code list scores 0. The weights ship inside the package. Add `--device cuda` on a GPU.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
mutlof/__init__.py,sha256=EyM5bOD_OeiTNazEuygrxhRgAR7K6JNF5SgVXFDh48o,236
|
|
2
|
+
mutlof/cli.py,sha256=HLq2z-U_0QHYZ0wmRQhfZ8Q40yu5RsAYNlFO2aoc1JM,1446
|
|
3
|
+
mutlof/codes.py,sha256=n0tul6Ukd5FfpTUStexxIRkJ9g1_4RKgmGNPOmaIbO0,4595
|
|
4
|
+
mutlof/model.py,sha256=BGvpk--qP6UeJOWlBUjFgWf83f9nM5y-hyUVovYmwxw,9152
|
|
5
|
+
mutlof/proteins.py,sha256=jWjlbCPQ3qfaQjpF1aat4sfjTzMJaoswse28UVXi2iI,4271
|
|
6
|
+
mutlof/score.py,sha256=LsMR7U028mOuMGpuri6lEt_7BmCzj0NKZBgD98_Rslc,3539
|
|
7
|
+
mutlof/tokens.py,sha256=ds8eybvxyAwI6OGzeSr6noanqDtBYo2euDxXyPvD8Qg,4195
|
|
8
|
+
mutlof/weights/model_best.pt,sha256=0MMbbY3ou3K0DCPfGZWg1EkWmrgKnPEnZfbo8dfVOeA,27709365
|
|
9
|
+
mutlof-1.0.0.dist-info/METADATA,sha256=4Er-VWpG6LD1jBfEdVjXxhYNlH1ijNafP5xbYCdB5TE,606
|
|
10
|
+
mutlof-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
mutlof-1.0.0.dist-info/entry_points.txt,sha256=H_F0mCcGhJ7UvIv6gTwOF-ToNE3inYgx05sQOGffYCk,43
|
|
12
|
+
mutlof-1.0.0.dist-info/top_level.txt,sha256=hR53TjAW0xn5-6J6ukI0cfN2AXYCyV-jdoDYQXrMBNk,7
|
|
13
|
+
mutlof-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mutlof
|