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/mapping.py ADDED
@@ -0,0 +1,798 @@
1
+ """The generic, downstream-facing residue-mapping API.
2
+
3
+ This module is the canonical public surface of ``uupmap``. Earlier
4
+ versions of the package shipped the same class under
5
+ ``uupmap.ahoj_adapter`` with token-string I/O (``'<UNP>_<idx>'``);
6
+ the refactor in 2026-05 moved the implementation here and switched
7
+ the I/O to structured ``(unp_ac: str, idx: int)`` tuples / typed
8
+ :class:`MappedIndex` rows. The class name is still ``UUPMap`` (it
9
+ is not AHoJ-specific — any consumer can use it directly).
10
+
11
+ ``ahoj_adapter`` no longer exists. AHoJ and any other consumer
12
+ imports the class as ``from uupmap import UUPMap``.
13
+
14
+ Public surface:
15
+
16
+ - :class:`UUPMap` — the runtime handle on a UniWeave artifact.
17
+ - :class:`MappedIndex` — one expanded residue mapping row (re-exported).
18
+ - :class:`Neighbor` — one UNP-to-UNP edge row (re-exported).
19
+ - :data:`CigarSourcePolicy` — type alias for the residue-map source enum.
20
+ - :func:`parse_unp_token` — ``'<UNP>_<idx>'`` string → ``(unp, idx)``
21
+ helper for CLI tooling / ad-hoc scripts; no longer used internally.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import logging
27
+ from collections import OrderedDict
28
+ from collections.abc import Iterable
29
+ from dataclasses import dataclass
30
+ from pathlib import Path
31
+ from typing import Literal
32
+
33
+ from uupmap.reader import EdgeReader, ModelFrameReader, SiftsReader, UniprotReader
34
+ from uupmap.residue_frame import ModelFrame
35
+ from uupmap.schema import EdgeSource, MappedIndex, Neighbor
36
+
37
+ # Public type alias for the CIGAR-source policy. Lives here (not in
38
+ # schema.py) so the schema module stays free of API-policy vocabulary;
39
+ # MappedIndex.cigar_source records only the resolved source
40
+ # ("seq" / "tm" / "consensus" / None), not the requested policy.
41
+ CigarSourcePolicy = Literal[
42
+ "seq", "tm", "di", "prefer_seq", "prefer_tm", "prefer_di", "consensus"
43
+ ]
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+ # Cache key: (unp_a, seq_id_min, tm_min, min_plddt, min_cov, require_both,
48
+ # di_bits_per_res_min). All threshold values are coerced to their value
49
+ # type before keying so callers passing ``1`` vs ``1.0`` hit the same slot.
50
+ _NeighborCacheKey = tuple[
51
+ str, float, float | None, float, float, bool, float | None
52
+ ]
53
+
54
+
55
+ @dataclass
56
+ class _NeighborCacheStats:
57
+ """Hit/miss counters for the per-UNP neighbour cache."""
58
+
59
+ hits: int = 0
60
+ misses: int = 0
61
+ evictions: int = 0
62
+ size: int = 0
63
+ maxsize: int = 0
64
+
65
+
66
+ def parse_unp_token(token: str) -> tuple[str, int]:
67
+ """Split a ``'<UNP>_<idx>'`` token into ``(accession, idx)``.
68
+
69
+ Splits on the **last** underscore so isoform accessions like
70
+ ``P12345-2_402`` parse correctly. Indices are 1-based positive ints.
71
+
72
+ Not used internally after the 2026-05 refactor to structured I/O
73
+ (:meth:`UUPMap.expand_indices` accepts ``(unp, idx)`` tuples
74
+ directly). Kept as a public helper for CLI tooling, tests, and
75
+ ad-hoc scripts that still receive token strings from upstream
76
+ consumers.
77
+ """
78
+ if "_" not in token:
79
+ raise ValueError(f"expected '<UNP>_<idx>' format, got {token!r}")
80
+ acc, idx_str = token.rsplit("_", 1)
81
+ try:
82
+ idx = int(idx_str)
83
+ except ValueError as exc:
84
+ raise ValueError(
85
+ f"expected '<UNP>_<idx>' format, got {token!r}"
86
+ ) from exc
87
+ if not acc or idx <= 0:
88
+ raise ValueError(f"expected '<UNP>_<idx>' format, got {token!r}")
89
+ return acc, idx
90
+
91
+
92
+ def _edge_source_label(src: EdgeSource) -> str:
93
+ """Render :class:`EdgeSource` as the string used in provenance dicts.
94
+
95
+ ``EdgeSource`` is an IntFlag, so an edge can carry several channels
96
+ at once. Single-channel and the historical ``MMSEQS|FOLDSEEK``
97
+ combination keep their canonical labels (``"mmseqs"``,
98
+ ``"foldseek"``, ``"both"``); any other combination is rendered as
99
+ its set bits joined with ``"+"`` (e.g. ``"mmseqs+prostt5"``).
100
+ """
101
+ canonical = {
102
+ EdgeSource.MMSEQS: "mmseqs",
103
+ EdgeSource.FOLDSEEK: "foldseek",
104
+ EdgeSource.BOTH: "both",
105
+ }
106
+ label = canonical.get(src)
107
+ if label is not None:
108
+ return label
109
+ parts = []
110
+ if src & EdgeSource.MMSEQS:
111
+ parts.append("mmseqs")
112
+ if src & EdgeSource.FOLDSEEK:
113
+ parts.append("foldseek")
114
+ if src & EdgeSource.PROSTT5:
115
+ parts.append("prostt5")
116
+ return "+".join(parts) if parts else str(int(src))
117
+
118
+
119
+ class UUPMap:
120
+ """The downstream-facing handle on a UniWeave artifact set.
121
+
122
+ Construct once at consumer startup, pass to whichever code-path
123
+ needs cross-UniProt expansion. All ``expand_*`` methods accept
124
+ the full threshold set (``seq_id_min``, ``tm_min``,
125
+ ``min_plddt``, ``min_cov``, ``require_both``) as keyword
126
+ arguments. Defaults of ``1.0`` for the score floors mean the
127
+ feature is dormant unless explicitly enabled (the seq filter
128
+ requires identity ≥ 1.0; nothing cross-UniProt satisfies that).
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ edges_path: Path,
134
+ uniprots_path: Path,
135
+ sifts_path: Path | None = None,
136
+ *,
137
+ model_frames_path: Path | None = None,
138
+ cache_size: int = 10_000,
139
+ ) -> None:
140
+ """Construct a UUPMap handle on a UniWeave artifact set.
141
+
142
+ ``edges_path`` / ``uniprots_path`` are required; ``sifts_path``
143
+ is optional. Pass it (typically ``artifact_dir / "sifts.parquet"``)
144
+ to enable :meth:`expand_candidate_fragments`; omit it if the
145
+ consumer never calls that method.
146
+
147
+ ``model_frames_path`` (typically
148
+ ``artifact_dir / "model_frames.parquet"``) enables
149
+ :meth:`model_frame`, :meth:`unp_to_model` and :meth:`model_to_unp`,
150
+ which a consumer needs as soon as it opens an AlphaFold-DB model
151
+ file itself: the model's residue numbers are not always the current
152
+ UniProt positions the rest of this API speaks (decision D20).
153
+
154
+ ``cache_size`` bounds the per-UNP neighbour LRU cache. The
155
+ cache is keyed by ``(unp_a, seq_id_min, tm_min, min_plddt,
156
+ min_cov, require_both)`` so that batch consumers calling
157
+ ``neighbors`` / ``expand_indices`` /
158
+ ``expand_candidate_fragments`` on the same UNP at the same
159
+ thresholds hit memory instead of a fresh Polars scan. Pass
160
+ ``cache_size=0`` to disable; the typical AHoJ batch UNP set
161
+ fits comfortably under the default 10 000.
162
+
163
+ Cache state lives entirely on the instance — no cross-process
164
+ or cross-instance sharing. Reset with :meth:`clear_cache`.
165
+
166
+ The pre-2026.05 ``ahoj_sifts_reverse_index=...`` plumbing kwarg
167
+ (a pre-parsed dict from AHoJ's
168
+ ``pdb_chain_uniprot_REVERSE_SPnum.bin``) was removed in the
169
+ FU2 refactor — UniWeave now bundles its own SIFTS slice as
170
+ ``sifts.parquet`` in the artifact set. AHoJ stops loading the
171
+ reverse-SIFTS dict for the UniWeave path and points
172
+ ``sifts_path`` at the artifact directly.
173
+ """
174
+ self._edges = EdgeReader(edges_path)
175
+ self._uniprots = UniprotReader(uniprots_path)
176
+ self._sifts: SiftsReader | None = (
177
+ SiftsReader(sifts_path) if sifts_path is not None else None
178
+ )
179
+ self._model_frames: ModelFrameReader | None = (
180
+ ModelFrameReader(model_frames_path)
181
+ if model_frames_path is not None
182
+ else None
183
+ )
184
+ self._cache_maxsize = max(0, cache_size)
185
+ self._cache: OrderedDict[_NeighborCacheKey, list[Neighbor]] = OrderedDict()
186
+ self._cache_hits = 0
187
+ self._cache_misses = 0
188
+ self._cache_evictions = 0
189
+
190
+ @property
191
+ def has_sifts(self) -> bool:
192
+ """Whether ``expand_candidate_fragments`` is available on this instance.
193
+
194
+ ``True`` iff the adapter was constructed with a ``sifts_path``
195
+ pointing at a valid ``sifts.parquet``. Consumers gate their
196
+ candidate-fragment merge call on this property to skip
197
+ gracefully when the artifact set was built without stage 08.
198
+ """
199
+ return self._sifts is not None
200
+
201
+ @property
202
+ def has_model_frames(self) -> bool:
203
+ """Whether the model-numbering methods are available on this instance.
204
+
205
+ ``True`` iff the adapter was constructed with a
206
+ ``model_frames_path``. An artifact set that ships no
207
+ ``model_frames.parquet`` predates the residue-frame reconciliation
208
+ (decisions D19/D20): its structural residue maps are in AFDB model
209
+ numbering, and nothing here can say where that differs.
210
+ """
211
+ return self._model_frames is not None
212
+
213
+ # ------------------------------------------------------------------
214
+ # Per-UNP neighbour cache
215
+ # ------------------------------------------------------------------
216
+
217
+ def _neighbors_cached(
218
+ self,
219
+ unp_a: str,
220
+ *,
221
+ seq_id_min: float,
222
+ tm_min: float | None,
223
+ min_plddt: float,
224
+ min_cov: float,
225
+ require_both: bool,
226
+ di_bits_per_res_min: float | None = None,
227
+ ) -> list[Neighbor]:
228
+ """Cached wrapper around :meth:`EdgeReader.neighbors_of`.
229
+
230
+ Every public method that needs a UNP's neighbour list at a
231
+ given threshold tuple funnels through here, so a batch
232
+ consumer that hits the same UNP from multiple call paths
233
+ (``neighbors`` for the candidate scan, ``expand_indices``
234
+ for residue translation, ``expand_candidate_fragments`` for
235
+ the cnd-frag merge) only pays the parquet scan once.
236
+
237
+ When ``cache_size == 0`` the cache is bypassed entirely; the
238
+ bookkeeping cost is one branch and no allocations.
239
+ """
240
+ if self._cache_maxsize == 0:
241
+ return list(
242
+ self._edges.neighbors_of(
243
+ unp_a,
244
+ seq_id_min=seq_id_min,
245
+ tm_min=tm_min,
246
+ min_plddt=min_plddt,
247
+ min_cov=min_cov,
248
+ require_both=require_both,
249
+ di_bits_per_res_min=di_bits_per_res_min,
250
+ )
251
+ )
252
+
253
+ key: _NeighborCacheKey = (
254
+ unp_a,
255
+ float(seq_id_min),
256
+ None if tm_min is None else float(tm_min),
257
+ float(min_plddt),
258
+ float(min_cov),
259
+ bool(require_both),
260
+ None if di_bits_per_res_min is None else float(di_bits_per_res_min),
261
+ )
262
+ cached = self._cache.get(key)
263
+ if cached is not None:
264
+ self._cache.move_to_end(key)
265
+ self._cache_hits += 1
266
+ return cached
267
+
268
+ self._cache_misses += 1
269
+ result = list(
270
+ self._edges.neighbors_of(
271
+ unp_a,
272
+ seq_id_min=seq_id_min,
273
+ tm_min=tm_min,
274
+ min_plddt=min_plddt,
275
+ min_cov=min_cov,
276
+ require_both=require_both,
277
+ di_bits_per_res_min=di_bits_per_res_min,
278
+ )
279
+ )
280
+ self._cache[key] = result
281
+ if len(self._cache) > self._cache_maxsize:
282
+ self._cache.popitem(last=False)
283
+ self._cache_evictions += 1
284
+ return result
285
+
286
+ def clear_cache(self) -> None:
287
+ """Drop all cached neighbour lists and reset the counters.
288
+
289
+ Safe to call between batches that target different threshold
290
+ tuples — keeps memory bounded without rebuilding the adapter.
291
+ """
292
+ self._cache.clear()
293
+ self._cache_hits = 0
294
+ self._cache_misses = 0
295
+ self._cache_evictions = 0
296
+
297
+ def cache_info(self) -> _NeighborCacheStats:
298
+ """Snapshot of the cache's hit / miss / size counters."""
299
+ return _NeighborCacheStats(
300
+ hits=self._cache_hits,
301
+ misses=self._cache_misses,
302
+ evictions=self._cache_evictions,
303
+ size=len(self._cache),
304
+ maxsize=self._cache_maxsize,
305
+ )
306
+
307
+ # ------------------------------------------------------------------
308
+ # Neighbour scans
309
+ # ------------------------------------------------------------------
310
+
311
+ def neighbors(
312
+ self,
313
+ unp_a: str,
314
+ *,
315
+ seq_id_min: float = 1.0,
316
+ tm_min: float = 1.0,
317
+ min_plddt: float = 0.0,
318
+ min_cov: float = 0.5,
319
+ require_both: bool = False,
320
+ di_bits_per_res_min: float | None = None,
321
+ ) -> list[Neighbor]:
322
+ """Return all UniProts neighbouring ``unp_a`` above the thresholds.
323
+
324
+ Routes through the per-UNP LRU cache (see :meth:`__init__`
325
+ ``cache_size``) so a batch consumer that hits the same UNP
326
+ from multiple methods only pays the parquet scan once.
327
+ ``tm_min=1.0`` is passed verbatim (not translated to ``None``)
328
+ so a user calling with the defaults gets no cross-UNP matches
329
+ — the feature stays dormant until thresholds are loosened.
330
+
331
+ ``di_bits_per_res_min`` admits ProstT5 AFDB-miss fallback edges
332
+ (decision D12) whose ``di_bits_per_res`` clears the
333
+ floor; ``None`` (default) leaves the ProstT5 channel dormant.
334
+ A practical starting floor is ``1.5`` (the conservative
335
+ calibration cutoff). ``min_cov`` applies to ProstT5 coverage
336
+ (``di_qcov``/``di_tcov``) for di-only edges.
337
+
338
+ ``min_cov`` is evidence-conditional (decision D18):
339
+ it scores sequence coverage when present, else 3Di coverage,
340
+ and is skipped for edges carrying neither — plain TM-align
341
+ structure-only edges (``EdgeSource.FOLDSEEK``) pass on their
342
+ ``tm_score`` alone. The default ``min_cov=0.5`` therefore
343
+ tightens the sequence / 3Di channels without switching off the
344
+ structure-only one.
345
+
346
+ Defaults keep the feature dormant. Pass ``seq_id_min < 1.0``,
347
+ ``tm_min < 1.0``, and/or ``di_bits_per_res_min`` to admit
348
+ cross-UNP edges; a first-time call with no kwargs only returns
349
+ identity-like rows and is easily mistaken for a broken adapter.
350
+ """
351
+ return self._neighbors_cached(
352
+ unp_a,
353
+ seq_id_min=seq_id_min,
354
+ tm_min=tm_min,
355
+ min_plddt=min_plddt,
356
+ min_cov=min_cov,
357
+ require_both=require_both,
358
+ di_bits_per_res_min=di_bits_per_res_min,
359
+ )
360
+
361
+ # ------------------------------------------------------------------
362
+ # Expansion: query indices → neighbour-UniProt index space
363
+ # ------------------------------------------------------------------
364
+
365
+ def expand_indices(
366
+ self,
367
+ queries: Iterable[tuple[str, int]],
368
+ *,
369
+ seq_id_min: float = 1.0,
370
+ tm_min: float = 1.0,
371
+ min_plddt: float = 0.0,
372
+ min_cov: float = 0.5,
373
+ require_both: bool = False,
374
+ cigar_source: CigarSourcePolicy = "prefer_seq",
375
+ di_bits_per_res_min: float | None = None,
376
+ ) -> list[MappedIndex]:
377
+ """Translate query ``(unp_ac, idx)`` pairs into neighbour-UNP space.
378
+
379
+ The load-bearing call. For each input ``(unp_a, idx_a)``
380
+ always emits the identity row first (``unp_a == unp_b and
381
+ idx_a == idx_b``, ``cigar_source=None``); then, for each
382
+ neighbour UniProt B passing the thresholds, emits one row if
383
+ a residue correspondence exists at that index (no row if the
384
+ index falls in a gap region of the alignment).
385
+
386
+ AHoJ's matcher joins on
387
+ ``(unp_ac, unp_index)`` against the candidate's SIFTS map, so
388
+ the targets returned must be in the candidate UniProt's
389
+ coordinate space.
390
+
391
+ ``cigar_source`` selects which CIGAR provides the residue map:
392
+
393
+ - ``"prefer_seq"`` (default) — use the sequence CIGAR when
394
+ present, else fall through to the structural CIGAR. Matches
395
+ historical behaviour for sequence + structure-corroborated
396
+ edges while admitting structure-only edges that the prior
397
+ hard-coded ``"seq"`` would have silently dropped.
398
+ - ``"seq"`` / ``"tm"`` — strict; neighbours lacking the
399
+ requested CIGAR are skipped (the same neighbour-level skip
400
+ the old hardcoded ``"seq"`` used).
401
+ - ``"prefer_tm"`` — symmetric of ``"prefer_seq"``.
402
+ - ``"consensus"`` — only emit residues where both CIGARs agree
403
+ on the target position. Neighbours without both CIGARs are
404
+ skipped.
405
+
406
+ - ``"prefer_di"`` / ``"di"`` — prefer (or strictly require) the
407
+ ProstT5 3Di no-coordinate residue map. Use together with
408
+ ``di_bits_per_res_min`` to also admit the ProstT5 edges in the
409
+ neighbour scan; otherwise those edges never enter the loop.
410
+
411
+ The source used per mapped row is recorded on
412
+ :attr:`MappedIndex.cigar_source` (one of ``"seq"``, ``"tm"``,
413
+ ``"di"``, ``"consensus"``).
414
+
415
+ ``di_bits_per_res_min`` admits ProstT5 fallback edges
416
+ (decision D12); ``None`` (default) keeps them out.
417
+ The default ``cigar_source="prefer_seq"`` already falls through
418
+ to ``di`` for di-only edges, so passing ``di_bits_per_res_min``
419
+ alone is enough to start mapping through ProstT5 edges.
420
+
421
+ Defaults keep the feature dormant. Pass ``seq_id_min < 1.0``,
422
+ ``tm_min < 1.0``, and/or ``di_bits_per_res_min`` to admit
423
+ cross-UNP edges; calling with no kwargs returns identity rows
424
+ only.
425
+ """
426
+ # Group queries by UNP so we only resolve neighbours once per UNP.
427
+ by_unp: dict[str, list[int]] = {}
428
+ for unp_a, idx_a in queries:
429
+ by_unp.setdefault(unp_a, []).append(idx_a)
430
+
431
+ if not by_unp:
432
+ return []
433
+
434
+ out: list[MappedIndex] = []
435
+ for unp_a, idxs in by_unp.items():
436
+ # Identity rows (always emitted, even with no neighbours).
437
+ for idx_a in idxs:
438
+ out.append(
439
+ MappedIndex(
440
+ unp_a=unp_a,
441
+ idx_a=idx_a,
442
+ unp_b=unp_a,
443
+ idx_b=idx_a,
444
+ seq_id=1.0,
445
+ tm=1.0,
446
+ plddt=None,
447
+ cigar_source=None,
448
+ )
449
+ )
450
+
451
+ # Each neighbour: build its residue map once, then emit per query.
452
+ for neighbor in self._neighbors_cached(
453
+ unp_a,
454
+ seq_id_min=seq_id_min,
455
+ tm_min=tm_min,
456
+ min_plddt=min_plddt,
457
+ min_cov=min_cov,
458
+ require_both=require_both,
459
+ di_bits_per_res_min=di_bits_per_res_min,
460
+ ):
461
+ idx_a_to_b: dict[int, int] = {}
462
+ try:
463
+ source_used, pairs = self._edges.residue_map_with_source(
464
+ unp_a, neighbor.unp_b, source=cigar_source
465
+ )
466
+ for ia, ib in pairs:
467
+ idx_a_to_b[ia] = ib
468
+ except KeyError:
469
+ # Neighbour lacks the requested CIGAR (e.g. strict
470
+ # "seq" on a structure-only edge, or "consensus" on
471
+ # a BOTH-less edge). Skip silently — the threshold
472
+ # filter already admitted the neighbour for other
473
+ # workflows (provenance lookup, fragment merge).
474
+ continue
475
+
476
+ for idx_a in idxs:
477
+ mapped_b = idx_a_to_b.get(idx_a)
478
+ if mapped_b is None:
479
+ # Query idx falls in a gap on the A side of the edge.
480
+ continue
481
+ out.append(
482
+ MappedIndex(
483
+ unp_a=unp_a,
484
+ idx_a=idx_a,
485
+ unp_b=neighbor.unp_b,
486
+ idx_b=mapped_b,
487
+ seq_id=neighbor.seq_identity,
488
+ tm=neighbor.tm_score,
489
+ plddt=neighbor.min_plddt_aligned_b,
490
+ cigar_source=source_used,
491
+ )
492
+ )
493
+
494
+ return out
495
+
496
+ def expand_indices_grouped(
497
+ self,
498
+ queries: Iterable[tuple[str, int]],
499
+ *,
500
+ seq_id_min: float = 1.0,
501
+ tm_min: float = 1.0,
502
+ min_plddt: float = 0.0,
503
+ min_cov: float = 0.5,
504
+ require_both: bool = False,
505
+ cigar_source: CigarSourcePolicy = "prefer_seq",
506
+ di_bits_per_res_min: float | None = None,
507
+ ) -> dict[tuple[str, int], list[MappedIndex]]:
508
+ """Same as :meth:`expand_indices`, bucketed by originating query.
509
+
510
+ Returns ``{(unp_a, idx_a) → [MappedIndex, ...]}`` with the
511
+ identity row first in each list, followed by zero or more
512
+ mapped rows (one per neighbour UNP that resolved a residue at
513
+ that index). Every input query is a key — even if no cross-UNP
514
+ mapping resolved, the identity row is present.
515
+
516
+ Saves consumers from rebuilding the bucket dict themselves
517
+ (AHoJ's integration needs this shape). Filter semantics and the dormancy of
518
+ the defaults match :meth:`expand_indices` exactly.
519
+ """
520
+ flat = self.expand_indices(
521
+ queries,
522
+ seq_id_min=seq_id_min,
523
+ tm_min=tm_min,
524
+ min_plddt=min_plddt,
525
+ min_cov=min_cov,
526
+ require_both=require_both,
527
+ cigar_source=cigar_source,
528
+ di_bits_per_res_min=di_bits_per_res_min,
529
+ )
530
+ out: dict[tuple[str, int], list[MappedIndex]] = {}
531
+ for entry in flat:
532
+ out.setdefault((entry.unp_a, entry.idx_a), []).append(entry)
533
+ return out
534
+
535
+ # ------------------------------------------------------------------
536
+ # Expansion: candidate-fragment merge for cnd_unp_fragments
537
+ # ------------------------------------------------------------------
538
+
539
+ def expand_candidate_fragments(
540
+ self,
541
+ query_unps: set[str],
542
+ *,
543
+ seq_id_min: float = 1.0,
544
+ tm_min: float = 1.0,
545
+ min_plddt: float = 0.0,
546
+ min_cov: float = 0.5,
547
+ require_both: bool = False,
548
+ max_hops: int = 1,
549
+ original_query_unps: set[str] | None = None,
550
+ di_bits_per_res_min: float | None = None,
551
+ ) -> dict[str, list[str]]:
552
+ """Return extra ``cnd_unp_fragments``-style rows AHoJ should merge.
553
+
554
+ For each UniProt A in ``query_unps``:
555
+ * Pull each neighbour B above the thresholds.
556
+ * Look B up in UniWeave's bundled ``sifts.parquet`` (via
557
+ :class:`SiftsReader`), pulling its
558
+ ``"<structchain> <sp_beg> <sp_end>"`` fragment strings —
559
+ the same shape ``apoholo.py:2275`` consumes after its own
560
+ length-trimming reformat.
561
+
562
+ Dedupes per target UniProt. Same PDB chain reachable through
563
+ multiple neighbours appears at most once.
564
+
565
+ .. warning::
566
+
567
+ Pass **only the original query UNP set** as ``query_unps``.
568
+ Passing a set that already contains neighbours (for example
569
+ ``set(all_unp_fragments_obs.keys())`` *after* widening that
570
+ dict with the previous call's output) will silently double-
571
+ expand to neighbours of neighbours. Two opt-in defences:
572
+
573
+ - **``original_query_unps``**: pass the set the consumer
574
+ recorded at adapter construction time. ``query_unps`` is
575
+ then intersected against it, and any UNPs that fell
576
+ outside are logged at WARNING level. Lightweight; catches
577
+ the "I forgot I widened the dict" mistake without
578
+ changing call shapes elsewhere.
579
+ - **``max_hops``**: reserved for future multi-hop support.
580
+ Only ``1`` is implemented in v1; anything else raises
581
+ ``NotImplementedError``. Carries the hop-count intent in
582
+ the signature so future call sites are explicit.
583
+
584
+ Raises
585
+ ------
586
+ ValueError
587
+ If the adapter was constructed without a ``sifts_path``.
588
+ NotImplementedError
589
+ If ``max_hops`` is not ``1``.
590
+ """
591
+ if max_hops != 1:
592
+ raise NotImplementedError(
593
+ f"expand_candidate_fragments: only max_hops=1 is supported "
594
+ f"in v1, got max_hops={max_hops}. Multi-hop walks need "
595
+ "explicit edge-graph plumbing — file an issue if you need "
596
+ "this."
597
+ )
598
+ if self._sifts is None:
599
+ raise ValueError(
600
+ "expand_candidate_fragments requires UUPMap to be constructed "
601
+ "with sifts_path pointing at the artifact's sifts.parquet "
602
+ "(stage 08 output)."
603
+ )
604
+
605
+ if original_query_unps is not None:
606
+ outside = query_unps - original_query_unps
607
+ if outside:
608
+ logger.warning(
609
+ "expand_candidate_fragments: %d UNP(s) in query_unps fell "
610
+ "outside original_query_unps (sample: %s) — excluding "
611
+ "them to avoid multi-hop expansion. If this is "
612
+ "intentional, drop the original_query_unps kwarg.",
613
+ len(outside),
614
+ sorted(outside)[:5],
615
+ )
616
+ query_unps = query_unps & original_query_unps
617
+
618
+ out: dict[str, set[str]] = {}
619
+ for unp_a in query_unps:
620
+ for neighbor in self._neighbors_cached(
621
+ unp_a,
622
+ seq_id_min=seq_id_min,
623
+ tm_min=tm_min,
624
+ min_plddt=min_plddt,
625
+ min_cov=min_cov,
626
+ require_both=require_both,
627
+ di_bits_per_res_min=di_bits_per_res_min,
628
+ ):
629
+ b = neighbor.unp_b
630
+ for frag in self._sifts.fragments(b):
631
+ # SIFTS-derived fragments are always well-formed
632
+ # ("<pdbchain> <sp_beg> <sp_end>"); no defensive
633
+ # parts-length guard needed.
634
+ out.setdefault(b, set()).add(frag)
635
+
636
+ return {b: sorted(frags) for b, frags in out.items()}
637
+
638
+ # ------------------------------------------------------------------
639
+ # Residue-map and provenance
640
+ # ------------------------------------------------------------------
641
+
642
+ def residue_map_pair(
643
+ self,
644
+ unp_a: str,
645
+ unp_b: str,
646
+ *,
647
+ cigar_source: CigarSourcePolicy = "prefer_seq",
648
+ ) -> Iterable[tuple[int, int]]:
649
+ """Lazy CIGAR expansion to ``(idx_a, idx_b)`` residue pairs.
650
+
651
+ Self-loops (``unp_a == unp_b``) yield the identity mapping
652
+ ``[(1, 1), (2, 2), …, (L, L)]`` derived from
653
+ :meth:`UniprotReader.length`. Cross-UNP pairs delegate to
654
+ :meth:`EdgeReader.residue_map_with_source` using the given
655
+ policy (default: sequence first, structural fall-through —
656
+ the same default as :meth:`expand_indices`).
657
+
658
+ The source actually used is not surfaced through this method;
659
+ callers that need provenance should call
660
+ :meth:`EdgeReader.residue_map_with_source` directly to receive
661
+ the ``(source_used, iterator)`` tuple.
662
+
663
+ Raises
664
+ ------
665
+ KeyError
666
+ If the edge is not in the artifact, the requested
667
+ CIGAR(s) are absent under the chosen policy, or for a
668
+ self-loop if ``unp_a`` is not in ``uniprots.parquet``.
669
+ """
670
+ if unp_a == unp_b:
671
+ length = self._uniprots.length(unp_a)
672
+ return iter((i, i) for i in range(1, length + 1))
673
+ _, it = self._edges.residue_map_with_source(
674
+ unp_a, unp_b, source=cigar_source
675
+ )
676
+ return it
677
+
678
+ def provenance(
679
+ self,
680
+ unp_a: str,
681
+ unp_b: str,
682
+ ) -> dict[str, object] | None:
683
+ """Edge metadata for ``residue_level_info.csv``.
684
+
685
+ Returns ``None`` for same-UniProt (native) correspondences,
686
+ for unknown edges, or for malformed accessions. For cross-
687
+ UniProt correspondences, returns a dict with:
688
+
689
+ - ``seq_id``: MMseqs2 ``fident`` (``None`` for structure-only edges)
690
+ - ``tm``: FoldSeek TM-score (``None`` for sequence-only and
691
+ ProstT5 edges — a ProstT5 edge never carries a true TM-score)
692
+ - ``plddt``: ``min_plddt_aligned_b`` (``None`` for sequence-only
693
+ and ProstT5 edges)
694
+ - ``di_bits_per_res``: ProstT5 structural-similarity proxy
695
+ (``None`` unless the edge has the ``PROSTT5`` channel; see
696
+ decision D12 — it is a calibrated proxy, not a
697
+ TM-score)
698
+ - ``source``: ``"mmseqs"``, ``"foldseek"``, ``"both"``,
699
+ ``"prostt5"``, or a ``"+"``-joined combination
700
+
701
+ The ``"via"`` field present in the pre-refactor token-shape API
702
+ is gone — the caller has ``unp_a`` and ``unp_b`` already and
703
+ can compose ``f"{unp_a}->{unp_b}"`` directly when needed.
704
+
705
+ Returns ``None`` (not raising) when the edge is absent — the
706
+ caller is reporting after-the-fact and should tolerate gaps.
707
+ """
708
+ if not unp_a or not unp_b or unp_a == unp_b:
709
+ return None
710
+
711
+ edge = self._edges.edge(unp_a, unp_b)
712
+ if edge is None:
713
+ return None
714
+
715
+ return {
716
+ "seq_id": edge.seq_identity,
717
+ "tm": edge.tm_score,
718
+ "plddt": edge.min_plddt_aligned_b,
719
+ "di_bits_per_res": edge.di_bits_per_res,
720
+ "source": _edge_source_label(edge.source),
721
+ }
722
+
723
+ # ------------------------------------------------------------------
724
+ # AlphaFold-DB model numbering (decision D20)
725
+ # ------------------------------------------------------------------
726
+
727
+ def model_frame(self, unp_ac: str) -> ModelFrame | None:
728
+ """How ``unp_ac``'s AlphaFold-DB model maps onto its current entry.
729
+
730
+ Returns ``None`` when the accession has no row, i.e. its model was
731
+ never checked: it has no AFDB rep, or it is a prebuilt-DB target
732
+ (Build B/C). For those targets every index UniWeave stores is
733
+ already the model's own numbering, so the model can be addressed
734
+ with them as-is. See :class:`~uupmap.residue_frame.ModelFrame` for
735
+ what each ``frame_kind`` permits.
736
+
737
+ Raises
738
+ ------
739
+ ValueError
740
+ If the adapter was constructed without a ``model_frames_path``.
741
+ """
742
+ if self._model_frames is None:
743
+ raise ValueError(
744
+ "model_frame requires UUPMap to be constructed with "
745
+ "model_frames_path pointing at the artifact's "
746
+ "model_frames.parquet (stage 07 output)."
747
+ )
748
+ return self._model_frames.frame(unp_ac)
749
+
750
+ def _require_frame(self, unp_ac: str) -> ModelFrame:
751
+ frame = self.model_frame(unp_ac)
752
+ if frame is None:
753
+ raise KeyError(
754
+ f"{unp_ac}: no model frame in this artifact (no AlphaFold-DB "
755
+ "rep was checked for it); whether its model numbering matches "
756
+ "the current entry is unknown"
757
+ )
758
+ return frame
759
+
760
+ def unp_to_model(
761
+ self, unp_ac: str, unp_positions: Iterable[int]
762
+ ) -> dict[int, int | None]:
763
+ """Translate current-UniProt positions into model residue numbers.
764
+
765
+ The direction a consumer needs to select residues in the AFDB model
766
+ file (``model_frame(unp_ac).model_url``) from positions this API
767
+ returns. A position the model does not cover maps to ``None``, and
768
+ so does every position of an ``unreliable`` or ``unknown`` frame.
769
+
770
+ Raises
771
+ ------
772
+ KeyError
773
+ If the accession has no model frame. Deciding what to do then is
774
+ the caller's call; UniWeave does not guess.
775
+ ValueError
776
+ If the adapter was constructed without a ``model_frames_path``.
777
+ """
778
+ frame = self._require_frame(unp_ac)
779
+ return {pos: frame.to_model(pos) for pos in unp_positions}
780
+
781
+ def model_to_unp(
782
+ self, unp_ac: str, model_residues: Iterable[int]
783
+ ) -> dict[int, int | None]:
784
+ """Translate model residue numbers into current-UniProt positions.
785
+
786
+ The inverse of :meth:`unp_to_model`: model residues deleted from the
787
+ current entry map to ``None``, as does everything in an
788
+ ``unreliable`` or ``unknown`` frame.
789
+
790
+ Raises
791
+ ------
792
+ KeyError
793
+ If the accession has no model frame.
794
+ ValueError
795
+ If the adapter was constructed without a ``model_frames_path``.
796
+ """
797
+ frame = self._require_frame(unp_ac)
798
+ return {resi: frame.to_unp(resi) for resi in model_residues}