uupmap 0.0.3__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.
uupmap/__init__.py ADDED
@@ -0,0 +1,90 @@
1
+ """UniWeave runtime adapter library.
2
+
3
+ UniWeave produces a UniProt-to-UniProt residue-level mapping resource;
4
+ this package is the thin Python adapter that downstream tools (AHoJ
5
+ and others) import to consume it.
6
+
7
+ Public surface:
8
+
9
+ - :class:`UUPMap` — the runtime handle on a UniWeave artifact.
10
+ - :class:`MappedIndex`,
11
+ :class:`Neighbor`,
12
+ :class:`EdgeSource`,
13
+ :class:`RepSource` — data shapes for adapter return values.
14
+ - :class:`ModelFrame` — how an AlphaFold-DB model's residue numbers map
15
+ onto the current UniProt entry (one ``model_frames.parquet`` row).
16
+ - :data:`CigarSourcePolicy` — type alias for the residue-map source enum.
17
+ - :func:`parse_unp_token` — ``'<UNP>_<idx>'`` token convenience parser.
18
+ - :data:`ARTIFACT_FORMAT`,
19
+ :data:`MIN_READER_VERSION` — the artifact contract this code writes and
20
+ the oldest reader that can read it (see the comments below).
21
+
22
+ The artifact files, their columns and the release notes are described on
23
+ the dataset card: https://huggingface.co/datasets/ioChris/uniweave
24
+ """
25
+
26
+ from uupmap.mapping import CigarSourcePolicy, UUPMap, parse_unp_token
27
+ from uupmap.residue_frame import ModelFrame
28
+ from uupmap.schema import EdgeSource, MappedIndex, Neighbor, RepSource
29
+
30
+ __all__ = [
31
+ "ARTIFACT_FORMAT",
32
+ "MIN_READER_VERSION",
33
+ "CigarSourcePolicy",
34
+ "EdgeSource",
35
+ "MappedIndex",
36
+ "ModelFrame",
37
+ "Neighbor",
38
+ "RepSource",
39
+ "UUPMap",
40
+ "parse_unp_token",
41
+ ]
42
+
43
+ # Three constants describe the reader/artifact contract. Every build writes
44
+ # all three into stats.json (uupmap_version, artifact_format,
45
+ # min_uupmap_version), and the published dataset_manifest.json carries them in
46
+ # its software block, so a consumer can check its installed uupmap against
47
+ # the artifact before reading it (decision D24). They are constants of the
48
+ # code that built the artifact, so stats.json stays a pure function of that
49
+ # code and the artifacts. They change only in a commit that changes the
50
+ # contract.
51
+ #
52
+ # __version__ — bump on any change to the consumption-side query contract, so
53
+ # a consumer can tell which semantics it is running against. The reader-only
54
+ # `uupmap` distribution on PyPI is published from this version, and a version
55
+ # is never re-published, so every contract change needs a bump.
56
+ # 0.0.2 — D18: min_cov is evidence-conditional; edges with no coverage in
57
+ # either channel (plain TM-align structure-only, ~80 % of the graph)
58
+ # are no longer dropped by a coverage floor.
59
+ # 0.0.3 — D19/D20: artifacts packed by this engine store tm_cigar/di_cigar in
60
+ # current-UniProt numbering (previously AFDB model numbering), and
61
+ # ship model_frames.parquet; UUPMap(model_frames_path=...) adds
62
+ # model_frame / unp_to_model / model_to_unp for consumers that open
63
+ # AFDB model files themselves.
64
+ __version__ = "0.0.3"
65
+
66
+ # ARTIFACT_FORMAT — bump when the packed artifact contract changes in a way a
67
+ # reader has to know about: a column a reader selects is added, removed,
68
+ # renamed or retyped; a column's values change meaning; or a new file becomes
69
+ # part of what a reader uses. Do not bump for row order (D21), for data
70
+ # corrections that keep every column's meaning (D22, D23), or for reader-only
71
+ # changes (D18, which raised MIN_READER_VERSION instead). Formats that predate
72
+ # this constant:
73
+ # 1 — the May 2026 contract: edges.parquet with the seq_* and tm_* channels
74
+ # only (e.g. v2026.06). Readers that know the di_* channel fail on it
75
+ # (uupmap 0.0.3: Polars ColumnNotFound on di_qcov).
76
+ # 2 — D12 (2026-05-27): edges.parquet gains the di_* 3Di/AA channel with
77
+ # di_alignment_type (D14 later added a second di_alignment_type value
78
+ # within the same columns).
79
+ # 3 — D19/D20 (2026-09-16): tm_cigar/di_cigar are in current-UniProt
80
+ # numbering (previously AFDB model numbering), and model_frames.parquet
81
+ # is published.
82
+ ARTIFACT_FORMAT = 3
83
+
84
+ # MIN_READER_VERSION — the oldest __version__ that reads an artifact written
85
+ # by this code correctly. Raise it when a format bump makes older readers fail
86
+ # or misread, or when a reader bug makes them wrong on every artifact. "0.0.2"
87
+ # since D18: older readers silently drop the ~80 % of edges that carry no
88
+ # coverage channel. Format 3 does not raise it: 0.0.2 already takes the
89
+ # CIGARs as current-UniProt numbering, and model_frames.parquet is opt-in.
90
+ MIN_READER_VERSION = "0.0.2"
uupmap/cigar.py ADDED
@@ -0,0 +1,327 @@
1
+ """CIGAR encoding for per-edge residue maps.
2
+
3
+ Edges in ``edges.parquet`` store a CIGAR-like string plus 1-based
4
+ start offsets in the two sequences. This module is the canonical
5
+ encoder/decoder so the rest of the package never reaches into the
6
+ string format directly.
7
+
8
+ Dialect:
9
+
10
+ - ``M`` — aligned position (match or mismatch).
11
+ - ``I`` — insertion in A relative to B (A has a residue here, B doesn't).
12
+ - ``D`` — deletion in A relative to B (B has a residue here, A doesn't).
13
+
14
+ Numeric prefix gives the run length. Example: ``"3M2D3M"`` =
15
+ 3 aligned positions, then B has 2 residues with no A counterpart,
16
+ then 3 more aligned positions.
17
+
18
+ All indices are 1-based positions in the **current** UniProt sequence on
19
+ both sides — the same sequence whose length ``uniprots.parquet`` records.
20
+
21
+ That is a real constraint on the structural channel, not a free property
22
+ of it: TM-align runs over AlphaFold-DB models numbered against whatever
23
+ UniProt said when AFDB was built, so stage 07 converts those indices into
24
+ current-UniProt numbering before encoding them here. See
25
+ :mod:`uupmap.residue_frame`.
26
+
27
+ ``model_frames.parquet`` reuses the dialect for the one mapping that is
28
+ *between* the two frames: there side A is the AlphaFold-DB model's own
29
+ residue numbering and side B is the current UniProt sequence.
30
+
31
+ The two operations are not perfectly inverse: :func:`cigar_to_pairs`
32
+ yields **only matched positions** (one ``(idx_a, idx_b)`` per ``M``
33
+ column), while :func:`pairs_to_cigar` accepts a full alignment column
34
+ stream including gap-bearing rows. Round-tripping a stream that
35
+ contains gaps therefore loses the gap rows on the way back through
36
+ :func:`cigar_to_pairs` — that is the intended downstream behaviour
37
+ (consumers want residue correspondences, not gap markers).
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ from collections.abc import Iterable, Iterator
43
+
44
+ _VALID_OPS = frozenset("MID")
45
+
46
+
47
+ def _iter_runs(cigar: str, *, caller: str) -> Iterator[tuple[str, int]]:
48
+ """Tokenise a CIGAR into ``(op, run_length)`` pairs.
49
+
50
+ Shared by every reader in this module so they agree on exactly which
51
+ strings are malformed. ``caller`` only shapes the error text.
52
+
53
+ Raises
54
+ ------
55
+ ValueError
56
+ If ``cigar`` is empty or malformed (missing run length, unknown
57
+ op, zero-length run, trailing junk).
58
+ """
59
+ if not cigar:
60
+ raise ValueError(f"{caller}: empty CIGAR string")
61
+
62
+ i = 0
63
+ n = len(cigar)
64
+ while i < n:
65
+ j = i
66
+ while j < n and cigar[j].isdigit():
67
+ j += 1
68
+ if j == i:
69
+ raise ValueError(
70
+ f"{caller}: expected run length at position {i}, "
71
+ f"got {cigar[i]!r} (cigar={cigar!r})"
72
+ )
73
+ if j >= n:
74
+ raise ValueError(
75
+ f"{caller}: run length with no op code at end of {cigar!r}"
76
+ )
77
+ run = int(cigar[i:j])
78
+ if run <= 0:
79
+ raise ValueError(
80
+ f"{caller}: non-positive run length {run} at position {i} "
81
+ f"(cigar={cigar!r})"
82
+ )
83
+ op = cigar[j]
84
+ if op not in _VALID_OPS:
85
+ raise ValueError(
86
+ f"{caller}: unknown op {op!r} at position {j} "
87
+ f"(cigar={cigar!r}); expected one of {sorted(_VALID_OPS)}"
88
+ )
89
+ i = j + 1
90
+ yield op, run
91
+
92
+
93
+ def cigar_to_pairs(
94
+ cigar: str,
95
+ qstart: int,
96
+ tstart: int,
97
+ ) -> Iterator[tuple[int, int]]:
98
+ """Yield 1-based ``(idx_a, idx_b)`` pairs for each aligned column.
99
+
100
+ ``qstart`` and ``tstart`` are the 1-based positions in the A and B
101
+ sequences where the alignment begins. Only ``M`` runs produce
102
+ output; ``I`` advances ``idx_a`` silently, ``D`` advances
103
+ ``idx_b`` silently.
104
+
105
+ Raises
106
+ ------
107
+ ValueError
108
+ If ``cigar`` is malformed (missing run length, unknown op,
109
+ zero-length run, trailing junk).
110
+ """
111
+ q = qstart
112
+ t = tstart
113
+ for op, run in _iter_runs(cigar, caller="cigar_to_pairs"):
114
+ if op == "M":
115
+ for _ in range(run):
116
+ yield (q, t)
117
+ q += 1
118
+ t += 1
119
+ elif op == "I":
120
+ q += run
121
+ else: # op == "D"
122
+ t += run
123
+
124
+
125
+ def cigar_extents(
126
+ cigar: str,
127
+ qstart: int,
128
+ tstart: int,
129
+ ) -> tuple[int, int, int, int] | None:
130
+ """Return ``(min_a, max_a, min_b, max_b)`` over the aligned columns.
131
+
132
+ The same numbers :func:`cigar_to_pairs` would give if you took the
133
+ min and max of its output, but computed from the run lengths alone —
134
+ O(number of runs) instead of O(alignment length). That is what makes
135
+ a bounds check over every edge in a multi-million-row artifact
136
+ affordable, where materialising each aligned position is not.
137
+
138
+ Returns ``None`` for a well-formed CIGAR with no ``M`` run at all
139
+ (no aligned column, hence no extent).
140
+
141
+ Raises
142
+ ------
143
+ ValueError
144
+ If ``cigar`` is malformed (same conditions as
145
+ :func:`cigar_to_pairs`).
146
+ """
147
+ q = qstart
148
+ t = tstart
149
+ min_a = min_b = max_a = max_b = None
150
+ for op, run in _iter_runs(cigar, caller="cigar_extents"):
151
+ if op == "M":
152
+ if min_a is None:
153
+ min_a, min_b = q, t
154
+ max_a, max_b = q + run - 1, t + run - 1
155
+ q += run
156
+ t += run
157
+ elif op == "I":
158
+ q += run
159
+ else: # op == "D"
160
+ t += run
161
+ if min_a is None or min_b is None or max_a is None or max_b is None:
162
+ return None
163
+ return min_a, max_a, min_b, max_b
164
+
165
+
166
+ def cigar_blocks(
167
+ cigar: str,
168
+ qstart: int,
169
+ tstart: int,
170
+ ) -> list[tuple[int, int, int]]:
171
+ """Return the ungapped blocks as ``(start_a, start_b, length)`` triples.
172
+
173
+ One triple per ``M`` run, in alignment order, so both ``start_a`` and
174
+ ``start_b`` strictly increase down the list. That ordering is what lets
175
+ a caller translate a single index in either direction by bisecting the
176
+ starts, instead of materialising :func:`cigar_to_pairs` into a table.
177
+
178
+ Raises
179
+ ------
180
+ ValueError
181
+ If ``cigar`` is malformed (same conditions as
182
+ :func:`cigar_to_pairs`).
183
+ """
184
+ q = qstart
185
+ t = tstart
186
+ blocks: list[tuple[int, int, int]] = []
187
+ for op, run in _iter_runs(cigar, caller="cigar_blocks"):
188
+ if op == "M":
189
+ blocks.append((q, t, run))
190
+ q += run
191
+ t += run
192
+ elif op == "I":
193
+ q += run
194
+ else: # op == "D"
195
+ t += run
196
+ return blocks
197
+
198
+
199
+ def pairs_to_cigar(
200
+ pairs: Iterable[tuple[int | None, int | None]],
201
+ ) -> tuple[str, int, int]:
202
+ """Encode an alignment column stream as ``(cigar, qstart, tstart)``.
203
+
204
+ The input is a stream of ``(idx_a, idx_b)`` rows, one per
205
+ alignment column, where either side may be ``None`` to mark a
206
+ gap. The first row must have both indices non-``None`` (local
207
+ alignments always start with an aligned column). Within each
208
+ side, non-``None`` indices must be strictly monotonic with
209
+ step +1.
210
+
211
+ Returns
212
+ -------
213
+ tuple
214
+ ``(cigar, qstart, tstart)`` — the CIGAR string and the 1-based
215
+ starting indices in A and B.
216
+
217
+ Raises
218
+ ------
219
+ ValueError
220
+ If the input is empty, starts with a gap-bearing row, has a
221
+ row with both indices ``None``, or violates monotonicity.
222
+ """
223
+ it = iter(pairs)
224
+ try:
225
+ first = next(it)
226
+ except StopIteration as exc:
227
+ raise ValueError("pairs_to_cigar: empty input") from exc
228
+
229
+ first_a, first_b = first
230
+ if first_a is None or first_b is None:
231
+ raise ValueError(
232
+ f"pairs_to_cigar: first column must have both indices, got {first!r}"
233
+ )
234
+
235
+ qstart, tstart = first_a, first_b
236
+ last_a: int = first_a
237
+ last_b: int = first_b
238
+
239
+ runs: list[tuple[str, int]] = []
240
+ current_op = "M"
241
+ current_len = 1
242
+
243
+ for row in it:
244
+ a, b = row
245
+ if a is None and b is None:
246
+ raise ValueError(
247
+ f"pairs_to_cigar: row with both indices None at "
248
+ f"(a after {last_a}, b after {last_b})"
249
+ )
250
+
251
+ if a is not None:
252
+ if a != last_a + 1:
253
+ raise ValueError(
254
+ f"pairs_to_cigar: non-monotonic A index {a} (expected {last_a + 1})"
255
+ )
256
+ last_a = a
257
+ if b is not None:
258
+ if b != last_b + 1:
259
+ raise ValueError(
260
+ f"pairs_to_cigar: non-monotonic B index {b} (expected {last_b + 1})"
261
+ )
262
+ last_b = b
263
+
264
+ if a is not None and b is not None:
265
+ op = "M"
266
+ elif a is not None:
267
+ op = "I"
268
+ else:
269
+ op = "D"
270
+
271
+ if op == current_op:
272
+ current_len += 1
273
+ else:
274
+ runs.append((current_op, current_len))
275
+ current_op = op
276
+ current_len = 1
277
+
278
+ runs.append((current_op, current_len))
279
+ cigar = "".join(f"{n}{op}" for op, n in runs)
280
+ return cigar, qstart, tstart
281
+
282
+
283
+ def matched_pairs_to_cigar(
284
+ pairs: Iterable[tuple[int, int]],
285
+ ) -> tuple[str, int, int]:
286
+ """Encode *aligned columns only*, synthesising the gap runs between them.
287
+
288
+ :func:`pairs_to_cigar` needs a full column stream: every row present,
289
+ gaps spelled out as ``None``, indices stepping by exactly +1. That is
290
+ the natural shape when you are transcribing an aligner's output. It is
291
+ the wrong shape after a coordinate-frame conversion, where you hold a
292
+ list of surviving ``(idx_a, idx_b)`` correspondences whose indices
293
+ **jump** wherever a position was dropped.
294
+
295
+ This wrapper bridges the two: indices must be strictly increasing on
296
+ both sides, and a jump of ``k`` positions is emitted as a ``k``-long
297
+ ``I`` run (side A) or ``D`` run (side B) — exactly what those skipped
298
+ residues mean, namely present in one sequence with no counterpart in
299
+ the other.
300
+
301
+ Raises
302
+ ------
303
+ ValueError
304
+ If the input is empty or the indices are not strictly increasing.
305
+ """
306
+
307
+ def _columns() -> Iterator[tuple[int | None, int | None]]:
308
+ last_a: int | None = None
309
+ last_b: int | None = None
310
+ for a, b in pairs:
311
+ if last_a is None or last_b is None:
312
+ yield (a, b)
313
+ last_a, last_b = a, b
314
+ continue
315
+ if a <= last_a or b <= last_b:
316
+ raise ValueError(
317
+ f"matched_pairs_to_cigar: indices must strictly increase, "
318
+ f"got ({a}, {b}) after ({last_a}, {last_b})"
319
+ )
320
+ for gap_a in range(last_a + 1, a):
321
+ yield (gap_a, None)
322
+ for gap_b in range(last_b + 1, b):
323
+ yield (None, gap_b)
324
+ yield (a, b)
325
+ last_a, last_b = a, b
326
+
327
+ return pairs_to_cigar(_columns())