uupmap 0.0.3__tar.gz → 0.0.4__tar.gz

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.
@@ -45,6 +45,10 @@ reps/
45
45
  !config/known_pairs.tsv
46
46
  # Exempt the landing-page data source (tracked; not a build-artifact dir).
47
47
  !site/data/
48
+ # Exempt the residue-frame figure inputs (tracked; see docs/figures/residue_frame/data/README.md).
49
+ !docs/figures/residue_frame/data/
50
+ !docs/figures/residue_frame/data/*.tsv
51
+ !docs/figures/residue_frame/data/*.fasta
48
52
  *.csv.gz
49
53
  fs_hits*
50
54
  mm_hits*
@@ -54,11 +54,16 @@ ProstT5 / ProtT5-XL-U50 (Rostlab)
54
54
 
55
55
  SWISS-MODEL Repository
56
56
  https://swissmodel.expasy.org/repository/uniprot/
57
- Data licensed under Creative Commons Attribution 4.0 (CC-BY-4.0).
57
+ Data licensed under Creative Commons Attribution-ShareAlike 4.0
58
+ (CC-BY-SA-4.0); see https://swissmodel.expasy.org/docs/terms_of_use.
58
59
  Homology and PDB-derived models consumed at build time as an optional
59
60
  AFDB-miss fallback (`structural_input.fallback: swiss_model`, stage 02c);
60
61
  superseded as the default by ProstT5 on 2026-05-27 but retained as a
61
62
  selectable path. Not redistributed by UniWeave. See decisions.md §D10.
63
+ A build that uses this fallback carries SWISS-MODEL-derived rows
64
+ (`rep_source = "swiss_model"`); publishing those rows under CC-BY-4.0
65
+ is not compatible with ShareAlike, so do not publish such a build as
66
+ CC-BY-4.0 data. Published builds use the ProstT5 fallback.
62
67
 
63
68
  ESM Atlas
64
69
  https://esmatlas.com/
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: uupmap
3
- Version: 0.0.3
3
+ Version: 0.0.4
4
4
  Summary: Reader for UniWeave, a residue-level UniProt-to-UniProt mapping resource
5
- Project-URL: Dataset, https://huggingface.co/datasets/ioChris/uniweave
5
+ Project-URL: Dataset, https://huggingface.co/datasets/UniWeave/uniweave
6
6
  Author: The UniWeave Authors
7
7
  License-Expression: Apache-2.0
8
8
  License-File: LICENSE
@@ -19,23 +19,27 @@ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
19
19
  Classifier: Typing :: Typed
20
20
  Requires-Python: >=3.10
21
21
  Requires-Dist: polars>=1.0
22
+ Provides-Extra: align
23
+ Requires-Dist: biopython>=1.81; extra == 'align'
22
24
  Description-Content-Type: text/markdown
23
25
 
24
26
  # uupmap
25
27
 
26
- `uupmap` reads [UniWeave](https://huggingface.co/datasets/ioChris/uniweave), a residue-level
28
+ `uupmap` reads [UniWeave](https://huggingface.co/datasets/UniWeave/uniweave), a residue-level
27
29
  UniProt-to-UniProt mapping resource. Every edge links two UniProt accessions by sequence
28
30
  (MMseqs2) and/or structural (FoldSeek TM-align, ProstT5 3Di) similarity and carries the residue
29
31
  correspondence between them, so a residue index in one protein can be carried over to its
30
32
  counterpart in another.
31
33
 
32
34
  This package is the reader only: it opens the published Parquet files and answers queries. It
33
- depends on [Polars](https://pola.rs) and nothing else.
35
+ depends on [Polars](https://pola.rs) and nothing else; classifying AlphaFold-DB models yourself
36
+ (below) also needs [Biopython](https://biopython.org), through the `align` extra.
34
37
 
35
38
  ## Install
36
39
 
37
40
  ```bash
38
- pip install uupmap
41
+ pip install uupmap # the reader
42
+ pip install "uupmap[align]" # plus Biopython, for uupmap.frame_classify
39
43
  ```
40
44
 
41
45
  ## Get the data
@@ -47,7 +51,7 @@ The artifacts are on Hugging Face (CC-BY-4.0). Each weekly release is tagged wit
47
51
  from pathlib import Path
48
52
  from huggingface_hub import snapshot_download # pip install huggingface_hub
49
53
 
50
- d = Path(snapshot_download("ioChris/uniweave", repo_type="dataset"))
54
+ d = Path(snapshot_download("UniWeave/uniweave", repo_type="dataset"))
51
55
  ```
52
56
 
53
57
  The release is about 0.4 GB: `edges.parquet`, `uniprots.parquet`, `sifts.parquet`,
@@ -86,6 +90,21 @@ for an accession with no AFDB model checked). A frame describes one model file:
86
90
  through a model you downloaded yourself, check that `uupmap.residue_frame.crc64(sequence)` of its
87
91
  modelled sequence equals the frame's `model_crc64`.
88
92
 
93
+ When it does not (another model version, or an accession the release does not cover),
94
+ `uupmap.frame_classify` classifies the model by the same rules UniWeave's build applies to write
95
+ `model_frames.parquet`, from the modelled sequence and the current UniProt sequence:
96
+
97
+ ```python
98
+ from uupmap.frame_classify import build_frame_map
99
+
100
+ fmap = build_frame_map(model_sequence, uniprot_sequence)
101
+ print(fmap.kind, fmap.identity, fmap.model_coverage) # identical | offset | aligned | unreliable
102
+ print(fmap.remap(15)) # model residue 15 -> UniProt position, or None
103
+ ```
104
+
105
+ Identical and offset frames need nothing beyond the reader. The `aligned` case (about one model
106
+ in a thousand) runs a Biopython alignment and needs `uupmap[align]`.
107
+
89
108
  ## Version contract
90
109
 
91
110
  Each release states which readers can read it. From the releases that carry them,
@@ -1,18 +1,20 @@
1
1
  # uupmap
2
2
 
3
- `uupmap` reads [UniWeave](https://huggingface.co/datasets/ioChris/uniweave), a residue-level
3
+ `uupmap` reads [UniWeave](https://huggingface.co/datasets/UniWeave/uniweave), a residue-level
4
4
  UniProt-to-UniProt mapping resource. Every edge links two UniProt accessions by sequence
5
5
  (MMseqs2) and/or structural (FoldSeek TM-align, ProstT5 3Di) similarity and carries the residue
6
6
  correspondence between them, so a residue index in one protein can be carried over to its
7
7
  counterpart in another.
8
8
 
9
9
  This package is the reader only: it opens the published Parquet files and answers queries. It
10
- depends on [Polars](https://pola.rs) and nothing else.
10
+ depends on [Polars](https://pola.rs) and nothing else; classifying AlphaFold-DB models yourself
11
+ (below) also needs [Biopython](https://biopython.org), through the `align` extra.
11
12
 
12
13
  ## Install
13
14
 
14
15
  ```bash
15
- pip install uupmap
16
+ pip install uupmap # the reader
17
+ pip install "uupmap[align]" # plus Biopython, for uupmap.frame_classify
16
18
  ```
17
19
 
18
20
  ## Get the data
@@ -24,7 +26,7 @@ The artifacts are on Hugging Face (CC-BY-4.0). Each weekly release is tagged wit
24
26
  from pathlib import Path
25
27
  from huggingface_hub import snapshot_download # pip install huggingface_hub
26
28
 
27
- d = Path(snapshot_download("ioChris/uniweave", repo_type="dataset"))
29
+ d = Path(snapshot_download("UniWeave/uniweave", repo_type="dataset"))
28
30
  ```
29
31
 
30
32
  The release is about 0.4 GB: `edges.parquet`, `uniprots.parquet`, `sifts.parquet`,
@@ -63,6 +65,21 @@ for an accession with no AFDB model checked). A frame describes one model file:
63
65
  through a model you downloaded yourself, check that `uupmap.residue_frame.crc64(sequence)` of its
64
66
  modelled sequence equals the frame's `model_crc64`.
65
67
 
68
+ When it does not (another model version, or an accession the release does not cover),
69
+ `uupmap.frame_classify` classifies the model by the same rules UniWeave's build applies to write
70
+ `model_frames.parquet`, from the modelled sequence and the current UniProt sequence:
71
+
72
+ ```python
73
+ from uupmap.frame_classify import build_frame_map
74
+
75
+ fmap = build_frame_map(model_sequence, uniprot_sequence)
76
+ print(fmap.kind, fmap.identity, fmap.model_coverage) # identical | offset | aligned | unreliable
77
+ print(fmap.remap(15)) # model residue 15 -> UniProt position, or None
78
+ ```
79
+
80
+ Identical and offset frames need nothing beyond the reader. The `aligned` case (about one model
81
+ in a thousand) runs a Biopython alignment and needs `uupmap[align]`.
82
+
66
83
  ## Version contract
67
84
 
68
85
  Each release states which readers can read it. From the releases that carry them,
@@ -33,8 +33,14 @@ classifiers = [
33
33
  ]
34
34
  dependencies = ["polars>=1.0"]
35
35
 
36
+ [project.optional-dependencies]
37
+ # uupmap.frame_classify aligns a model to its UniProt entry with Biopython,
38
+ # for the ~0.1% of AFDB models that need it. Imported lazily; nothing else
39
+ # in the reader uses it. Same floor as the build engine.
40
+ align = ["biopython>=1.81"]
41
+
36
42
  [project.urls]
37
- Dataset = "https://huggingface.co/datasets/ioChris/uniweave"
43
+ Dataset = "https://huggingface.co/datasets/UniWeave/uniweave"
38
44
 
39
45
  [tool.hatch.version]
40
46
  path = "src/uupmap/__init__.py"
@@ -20,7 +20,7 @@ Public surface:
20
20
  the oldest reader that can read it (see the comments below).
21
21
 
22
22
  The artifact files, their columns and the release notes are described on
23
- the dataset card: https://huggingface.co/datasets/ioChris/uniweave
23
+ the dataset card: https://huggingface.co/datasets/UniWeave/uniweave
24
24
  """
25
25
 
26
26
  from uupmap.mapping import CigarSourcePolicy, UUPMap, parse_unp_token
@@ -61,7 +61,13 @@ __all__ = [
61
61
  # ship model_frames.parquet; UUPMap(model_frames_path=...) adds
62
62
  # model_frame / unp_to_model / model_to_unp for consumers that open
63
63
  # AFDB model files themselves.
64
- __version__ = "0.0.3"
64
+ # 0.0.4 — D25 amendment (2026-11-16): the AFDB model-frame classifier of D19
65
+ # (classify_frame, FrameMap, build_frame_map, the acceptance floors and
66
+ # the aligner settings) moves from the pipeline module frame_build to
67
+ # the reader module uupmap.frame_classify, so consumers classify a
68
+ # model by the build's own rules. Biopython is an optional extra
69
+ # (uupmap[align]). The artifact contract is unchanged.
70
+ __version__ = "0.0.4"
65
71
 
66
72
  # ARTIFACT_FORMAT — bump when the packed artifact contract changes in a way a
67
73
  # reader has to know about: a column a reader selects is added, removed,
@@ -0,0 +1,397 @@
1
+ """Classify an AlphaFold-DB model's residue frame against the current UniProt sequence.
2
+
3
+ UniWeave's artifact contract (see :mod:`uupmap.cigar`) is that CIGAR
4
+ indices are 1-based positions in the **current** UniProt sequence on
5
+ both sides. The structural channel does not natively satisfy that:
6
+ TM-align runs over AlphaFold-DB models, whose residue numbering follows
7
+ the UniProt sequence **each model was predicted from**. UniProt is curated
8
+ several times a year; AFDB does not re-predict a model when its entry
9
+ changes (v6 added only ~500 models to v4 and carried the rest over), so
10
+ every re-versioned entry moves the two frames apart for good, and the
11
+ number of such entries only grows (decision D19).
12
+
13
+ Two things make this worse than a cosmetic tail problem:
14
+
15
+ - An N-terminal edit shifts the **whole** frame. Q9USH6's model is 204 aa
16
+ and the current UniProt entry is its last 190 aa, so every model index
17
+ is 14 too high -- not just the ones past the end.
18
+ - Only the fraction of a shifted alignment that happens to run off the end
19
+ of the current sequence is detectable as out-of-bounds. On the
20
+ v2026.08.17 build, 1,489 wrong edges were catchable that way and 9,133
21
+ were **in bounds and silently wrong**.
22
+
23
+ This module turns a model sequence + the current UniProt sequence into a
24
+ :class:`FrameMap` that converts model positions to current-UniProt
25
+ positions. It is the classifier UniWeave's build runs: stage 07 converts
26
+ the structural CIGARs it writes with it, and publishes the result per
27
+ accession as ``model_frames.parquet`` (decision D20). It ships with the
28
+ reader so that a consumer holding a model file the artifact does not
29
+ describe (a different model version, or an accession outside the build)
30
+ classifies that model by the same rules, floors and aligner settings
31
+ rather than by a copy of them.
32
+
33
+ Biopython is needed only for :data:`FRAME_ALIGNED` frames, about one model
34
+ in a thousand, and is imported only when one is reached. It is an optional
35
+ extra of the reader: ``pip install "uupmap[align]"``. Identical and offset
36
+ frames, the floors and :func:`classify_frame` work without it.
37
+
38
+ Sign convention throughout: ``uniprot_pos = model_pos + shift``.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ from dataclasses import dataclass
44
+ from fractions import Fraction
45
+ from typing import Any, Final
46
+
47
+ from uupmap.cigar import matched_pairs_to_cigar
48
+ from uupmap.residue_frame import (
49
+ FRAME_ALIGNED,
50
+ FRAME_IDENTICAL,
51
+ FRAME_KINDS,
52
+ FRAME_OFFSET,
53
+ FRAME_UNKNOWN,
54
+ FRAME_UNRELIABLE,
55
+ crc64,
56
+ )
57
+
58
+ __all__ = [
59
+ "FRAME_ALIGNED",
60
+ "FRAME_IDENTICAL",
61
+ "FRAME_KINDS",
62
+ "FRAME_OFFSET",
63
+ "FRAME_UNKNOWN",
64
+ "FRAME_UNRELIABLE",
65
+ "MIN_ALIGNED_IDENTITY",
66
+ "MIN_ALIGNED_MODEL_COVERAGE",
67
+ "FrameMap",
68
+ "align_positions",
69
+ "alignment_is_trustworthy",
70
+ "build_frame_map",
71
+ "classify_frame",
72
+ "crc64",
73
+ "identical_frame",
74
+ ]
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # Frame classification
78
+ # ---------------------------------------------------------------------------
79
+
80
+ # Floors for accepting an aligned frame. Both are measured on the real
81
+ # v2026.08.17 divergent set (74 accessions), which separates cleanly:
82
+ #
83
+ # - Substitution-heavy but genuinely the same protein bottoms out around
84
+ # 88% agreement (A0ABF7PQC2: a 35-residue peptide with 4 substitutions;
85
+ # the positions correspond exactly, only the residues differ). Those are
86
+ # correct mappings and must be kept.
87
+ # - A0A804HIH4 (model 285 aa, current entry 77 aa) aligns 6 positions at
88
+ # 33% agreement, and A0A0G2JZW1 sits at 72%. Those are entries that were
89
+ # re-annotated into something else; an alignment between them is noise.
90
+ # - G3MXC8 aligns only 61 of 149 model residues. Even at 88% agreement over
91
+ # that fragment, a mapping covering 41% of the model is not describing
92
+ # the same sequence any more.
93
+ #
94
+ # Emitting a wrong residue map is the harm this module exists to prevent, and
95
+ # dropping one costs only residue-level detail on a handful of edges (the
96
+ # structural scores survive) -- so the floors sit above the noise, not at it.
97
+ # A ratio exactly at a floor passes, compared exactly (see
98
+ # alignment_is_trustworthy).
99
+ MIN_ALIGNED_IDENTITY: Final = 0.80
100
+ MIN_ALIGNED_MODEL_COVERAGE: Final = 0.50
101
+
102
+
103
+ def classify_frame(model_seq: str, uniprot_seq: str) -> tuple[str, int | None]:
104
+ """Return ``(kind, shift)`` for a model/UniProt sequence pair.
105
+
106
+ ``shift`` is the constant to add to a model position to get the
107
+ current-UniProt position; it is ``None`` for :data:`FRAME_ALIGNED`,
108
+ where no single constant exists. Needs no Biopython: ``aligned`` only
109
+ says an alignment is needed, :func:`build_frame_map` runs it.
110
+
111
+ A UniProt entry truncated only at its C-terminus still classifies as
112
+ :data:`FRAME_OFFSET` with ``shift == 0``: positions up to the new
113
+ length map straight through, and the overhanging tail is dropped by
114
+ :meth:`FrameMap.remap`'s bounds check rather than by the shift.
115
+ """
116
+ if model_seq == uniprot_seq:
117
+ return FRAME_IDENTICAL, 0
118
+ if model_seq and uniprot_seq:
119
+ # UniProt is a window of the model (residues trimmed from the
120
+ # entry): model position i is UniProt position i - idx.
121
+ idx = model_seq.find(uniprot_seq)
122
+ if idx >= 0:
123
+ return FRAME_OFFSET, -idx
124
+ # The model is a window of UniProt (the entry grew).
125
+ idx = uniprot_seq.find(model_seq)
126
+ if idx >= 0:
127
+ return FRAME_OFFSET, idx
128
+ return FRAME_ALIGNED, None
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class FrameMap:
133
+ """Model-position → current-UniProt-position converter for one accession.
134
+
135
+ Build one with :func:`build_frame_map`. The common case by far
136
+ (99.89% of accessions on v2026.08.17) is :data:`FRAME_IDENTICAL`,
137
+ which costs a single string comparison and no per-residue state.
138
+
139
+ ``identity`` and ``model_coverage`` are the two numbers the acceptance
140
+ decision rests on: the fraction of mapped positions whose residues
141
+ agree, and the fraction of the model that maps at all. They are kept on
142
+ rejected (:data:`FRAME_UNRELIABLE`) frames too, so the published record
143
+ shows *why* a model was not salvaged. Both are ``None`` when nothing
144
+ was compared.
145
+ """
146
+
147
+ kind: str
148
+ n_model: int
149
+ n_uniprot: int
150
+ shift: int | None = None
151
+ table: dict[int, int] | None = None
152
+ identity: float | None = None
153
+ model_coverage: float | None = None
154
+
155
+ @property
156
+ def is_identity(self) -> bool:
157
+ """True when model and current UniProt numbering already agree.
158
+
159
+ Callers use this to skip remapping entirely on the hot path.
160
+ Note this is *not* the same as ``shift == 0``: a C-terminally
161
+ truncated entry has ``shift == 0`` but still needs the bounds
162
+ check that drops its overhanging tail.
163
+ """
164
+ return self.kind == FRAME_IDENTICAL
165
+
166
+ @property
167
+ def is_known(self) -> bool:
168
+ """False when no model sequence was available to compare against.
169
+
170
+ A :data:`FRAME_UNRELIABLE` frame *is* known: we established that
171
+ the two sequences no longer correspond. Callers must treat the two
172
+ differently — an unknown frame passes evidence through untouched,
173
+ an unreliable one drops the residue map.
174
+ """
175
+ return self.kind != FRAME_UNKNOWN
176
+
177
+ def remap(self, model_pos: int) -> int | None:
178
+ """Convert a 1-based model position; ``None`` if it has no counterpart.
179
+
180
+ Positions land on ``None`` when the residue was deleted from the
181
+ current UniProt entry, when it falls outside ``[1, n_uniprot]``
182
+ (the overhang left by a truncation), or when it is not a residue
183
+ of the model at all.
184
+ """
185
+ if not 1 <= model_pos <= self.n_model:
186
+ return None
187
+ if self.kind == FRAME_IDENTICAL:
188
+ return model_pos if model_pos <= self.n_uniprot else None
189
+ if self.kind == FRAME_OFFSET:
190
+ assert self.shift is not None
191
+ out = model_pos + self.shift
192
+ return out if 1 <= out <= self.n_uniprot else None
193
+ if self.kind == FRAME_ALIGNED:
194
+ assert self.table is not None
195
+ return self.table.get(model_pos)
196
+ # FRAME_UNKNOWN / FRAME_UNRELIABLE: refuse to guess.
197
+ return None
198
+
199
+ def to_cigar(self) -> tuple[str, int, int] | None:
200
+ """The whole model→UniProt correspondence as ``(cigar, model_start, unp_start)``.
201
+
202
+ This is the form ``model_frames.parquet`` publishes, in the
203
+ :mod:`uupmap.cigar` dialect with side A = the model and side B =
204
+ the current UniProt sequence. Identical and offset frames are a
205
+ single ``M`` run over the overlap; an aligned frame spells out its
206
+ indels. ``None`` for frames that must not be mapped through
207
+ (:data:`FRAME_UNRELIABLE`, :data:`FRAME_UNKNOWN`) or that share no
208
+ position at all.
209
+ """
210
+ if self.kind in (FRAME_IDENTICAL, FRAME_OFFSET):
211
+ shift = self.shift or 0
212
+ first = max(1, 1 - shift)
213
+ last = min(self.n_model, self.n_uniprot - shift)
214
+ if last < first:
215
+ return None
216
+ return f"{last - first + 1}M", first, first + shift
217
+ if self.kind == FRAME_ALIGNED:
218
+ assert self.table is not None
219
+ if not self.table:
220
+ return None
221
+ return matched_pairs_to_cigar(sorted(self.table.items()))
222
+ return None
223
+
224
+
225
+ def identical_frame(length: int) -> FrameMap:
226
+ """The frame of a model whose sequence *is* the current UniProt sequence.
227
+
228
+ For callers that established identity without holding the model
229
+ sequence — UniWeave's stage 07 compares the length and CRC64 stage 02
230
+ recorded against the current sequence, which spares parsing tens of
231
+ thousands of structures to rediscover that 99.9% of them are unchanged.
232
+ """
233
+ return FrameMap(
234
+ kind=FRAME_IDENTICAL,
235
+ n_model=length,
236
+ n_uniprot=length,
237
+ shift=0,
238
+ identity=1.0 if length else None,
239
+ model_coverage=1.0 if length else None,
240
+ )
241
+
242
+
243
+ def build_frame_map(model_seq: str | None, uniprot_seq: str) -> FrameMap:
244
+ """Build the position converter for one accession.
245
+
246
+ ``model_seq`` is the sequence of residues actually present in the
247
+ structure, in structure order — the frame FoldSeek's CIGAR indices
248
+ count in. Pass ``None`` when no model is available (e.g. a target that
249
+ came from a prebuilt FoldSeek database rather than a local rep); the
250
+ result is :data:`FRAME_UNKNOWN` and every :meth:`FrameMap.remap` call
251
+ returns ``None``.
252
+
253
+ The :data:`FRAME_ALIGNED` branch runs a Needleman-Wunsch global
254
+ alignment with **free end gaps**, so a terminal extension or
255
+ truncation costs nothing and only genuine internal indels open a gap.
256
+ That branch needs Biopython (``uupmap[align]``) and raises
257
+ :class:`ImportError` without it.
258
+ """
259
+ n_uni = len(uniprot_seq)
260
+ if model_seq is None:
261
+ return FrameMap(kind=FRAME_UNKNOWN, n_model=0, n_uniprot=n_uni)
262
+
263
+ n_model = len(model_seq)
264
+ kind, shift = classify_frame(model_seq, uniprot_seq)
265
+ if kind == FRAME_IDENTICAL:
266
+ return identical_frame(n_model)
267
+ if kind == FRAME_OFFSET:
268
+ assert shift is not None
269
+ # A substring match: every mapped residue agrees, and the model
270
+ # positions that map are exactly the overlap of the two windows.
271
+ overlap = min(n_model, n_uni - shift) - max(1, 1 - shift) + 1
272
+ return FrameMap(
273
+ kind=FRAME_OFFSET,
274
+ n_model=n_model,
275
+ n_uniprot=n_uni,
276
+ shift=shift,
277
+ identity=1.0,
278
+ model_coverage=overlap / n_model,
279
+ )
280
+
281
+ table = align_positions(model_seq, uniprot_seq)
282
+ n_agree = sum(
283
+ 1 for m_pos, u_pos in table.items() if model_seq[m_pos - 1] == uniprot_seq[u_pos - 1]
284
+ )
285
+ identity = n_agree / len(table) if table else None
286
+ coverage = len(table) / n_model if n_model else None
287
+ if not alignment_is_trustworthy(len(table), n_agree, n_model):
288
+ return FrameMap(
289
+ kind=FRAME_UNRELIABLE,
290
+ n_model=n_model,
291
+ n_uniprot=n_uni,
292
+ identity=identity,
293
+ model_coverage=coverage,
294
+ )
295
+ return FrameMap(
296
+ kind=FRAME_ALIGNED,
297
+ n_model=n_model,
298
+ n_uniprot=n_uni,
299
+ table=table,
300
+ identity=identity,
301
+ model_coverage=coverage,
302
+ )
303
+
304
+
305
+ def alignment_is_trustworthy(n_mapped: int, n_agree: int, n_model: int) -> bool:
306
+ """Decide whether an aligned frame is good enough to publish.
307
+
308
+ Two sequences that no longer describe the same protein will still
309
+ produce *an* alignment; believing it would put annotations on
310
+ unrelated residues, which is precisely the failure this module
311
+ exists to prevent. Reject when the alignment covers too little of
312
+ the model (``n_mapped / n_model`` below
313
+ :data:`MIN_ALIGNED_MODEL_COVERAGE`), or when too few of the positions
314
+ it does map agree (``n_agree / n_mapped`` below
315
+ :data:`MIN_ALIGNED_IDENTITY`).
316
+
317
+ Note that disagreement is measured over mapped positions only.
318
+ Mismatches are legal — a substitution keeps the numbering — so this
319
+ is a "same sequence?" test, not an "identical sequence?" one.
320
+
321
+ A ratio exactly at a floor passes, and that is decided in exact
322
+ arithmetic: in floating point ``0.8 * 35`` is ``28.000000000000004``,
323
+ which would reject 28 agreeing positions out of 35.
324
+ """
325
+ if n_mapped == 0:
326
+ return False
327
+ return _at_least(n_mapped, n_model, MIN_ALIGNED_MODEL_COVERAGE) and _at_least(
328
+ n_agree, n_mapped, MIN_ALIGNED_IDENTITY
329
+ )
330
+
331
+
332
+ def _at_least(count: int, total: int, floor: float) -> bool:
333
+ """``count / total >= floor``, with ``floor`` read as the decimal written."""
334
+ exact = Fraction(str(floor))
335
+ return count * exact.denominator >= exact.numerator * total
336
+
337
+
338
+ def _aligner() -> Any:
339
+ """Configure the pairwise aligner used for the messy minority.
340
+
341
+ Imported lazily: 99.89% of accessions never reach this path, the
342
+ Biopython import is not free, and the reader does not depend on
343
+ Biopython. Scoring is tuned for two versions of the *same* protein
344
+ rather than for homology search — a strong gap-open penalty keeps
345
+ indels rare and tight, and zero end-gap scores let a terminal
346
+ extension or truncation slide without dragging the alignment out of
347
+ register.
348
+ """
349
+ try:
350
+ from Bio.Align import PairwiseAligner
351
+ except ImportError as exc: # pragma: no cover — depends on the environment
352
+ raise ImportError(
353
+ 'aligning a model to its UniProt entry needs Biopython: pip install "uupmap[align]"'
354
+ ) from exc
355
+
356
+ aligner = PairwiseAligner() # type: ignore[no-untyped-call]
357
+ aligner.mode = "global"
358
+ aligner.match_score = 2.0
359
+ aligner.mismatch_score = -1.0
360
+ aligner.open_gap_score = -10.0
361
+ aligner.extend_gap_score = -0.5
362
+ # Free end gaps, under whichever spelling this Biopython has. 1.87
363
+ # renamed target/query end-gap scores to insertion/deletion ones and
364
+ # deprecated the old names; earlier releases only know the old ones.
365
+ # All four get the same value, so the rename's direction is moot.
366
+ try:
367
+ aligner.open_end_insertion_score = 0.0
368
+ aligner.extend_end_insertion_score = 0.0
369
+ aligner.open_end_deletion_score = 0.0
370
+ aligner.extend_end_deletion_score = 0.0
371
+ except AttributeError: # pragma: no cover — depends on Biopython version
372
+ aligner.target_end_open_gap_score = 0.0
373
+ aligner.target_end_extend_gap_score = 0.0
374
+ aligner.query_end_open_gap_score = 0.0
375
+ aligner.query_end_extend_gap_score = 0.0
376
+ return aligner
377
+
378
+
379
+ def align_positions(model_seq: str, uniprot_seq: str) -> dict[int, int]:
380
+ """Map every alignable model position to its current-UniProt position.
381
+
382
+ Returns a sparse 1-based table; model positions with no counterpart
383
+ are simply absent. Mismatched-but-aligned columns *are* included —
384
+ what we need is positional correspondence, not identity. An empty
385
+ sequence on either side aligns nothing (Biopython refuses to align
386
+ one), so :func:`build_frame_map` rejects such a frame as
387
+ :data:`FRAME_UNRELIABLE`.
388
+ """
389
+ if not model_seq or not uniprot_seq:
390
+ return {}
391
+ alignment = next(iter(_aligner().align(model_seq, uniprot_seq)))
392
+ model_blocks, uniprot_blocks = alignment.aligned
393
+ table: dict[int, int] = {}
394
+ for (m_start, m_end), (u_start, _u_end) in zip(model_blocks, uniprot_blocks, strict=True):
395
+ for k in range(int(m_end) - int(m_start)):
396
+ table[int(m_start) + k + 1] = int(u_start) + k + 1
397
+ return table
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes