Metadata-Version: 2.5
Name: uupmap
Version: 0.0.5
Summary: Reader for UniWeave, a residue-level UniProt-to-UniProt mapping resource
Project-URL: Dataset, https://huggingface.co/datasets/UniWeave/uniweave
Author: The UniWeave Authors
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: alphafold,bioinformatics,protein structure,residue mapping,uniprot
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: polars>=1.0
Provides-Extra: align
Requires-Dist: biopython>=1.81; extra == 'align'
Description-Content-Type: text/markdown

# uupmap

`uupmap` reads [UniWeave](https://huggingface.co/datasets/UniWeave/uniweave), a residue-level
UniProt-to-UniProt mapping resource. Every edge links two UniProt accessions by sequence
(MMseqs2) and/or structural (FoldSeek TM-align, ProstT5 3Di) similarity and carries the residue
correspondence between them, so a residue index in one protein can be carried over to its
counterpart in another.

This package is the reader only: it opens the published Parquet files and answers queries. It
depends on [Polars](https://pola.rs) and nothing else; classifying AlphaFold-DB models yourself
(below) also needs [Biopython](https://biopython.org), through the `align` extra.

## Install

```bash
pip install uupmap            # the reader
pip install "uupmap[align]"   # plus Biopython, for uupmap.frame_classify
```

## Get the data

The artifacts are on Hugging Face (CC-BY-4.0). Each weekly release is tagged with its
`data_version`, so a release can be pinned with `revision=`:

```python
from pathlib import Path
from huggingface_hub import snapshot_download   # pip install huggingface_hub

d = Path(snapshot_download("UniWeave/uniweave", repo_type="dataset"))
```

The release is about 0.4 GB: `edges.parquet`, `uniprots.parquet`, `sifts.parquet`,
`model_frames.parquet`, `stats.json` and `dataset_manifest.json`. Releases built since the PDB
hop add `sifts_observed.parquet` and `sifts_rejected.parquet` (together with `sifts.parquet`, the
week's two SIFTS flat files, whole; about 17 MB). Releases built since the node-identity change add
`node_identity.parquet` (about 2 MB) and four status columns to `uniprots.parquet`, and
`retired_accessions.parquet` once a release is built from its predecessor. Releases built with
the per-entry SIFTS XML also carry `sifts_residues.parquet`, the exact per-residue table (19 MB
for the 2026-11-08 release). Releases built with carried nodes carry `sifts_retired.parquet` and
`sifts_retired_observed.parquet` (below).

## Query

```python
from uupmap import UUPMap

m = UUPMap(d / "edges.parquet", d / "uniprots.parquet",
           model_frames_path=d / "model_frames.parquet")

# UniProt neighbours of a protein. Thresholds default to 1.0, so pass the ones you want.
for n in m.neighbors("P69905", seq_id_min=0.3, tm_min=0.5):
    print(n.unp_b, n.seq_identity, n.tm_score)

# Carry residue 87 of P69905 over to its neighbours.
for hit in m.expand_indices([("P69905", 87)], seq_id_min=0.3, tm_min=0.5):
    print(hit.unp_b, hit.idx_b, hit.cigar_source)

# Scores and channels behind one pair.
print(m.provenance("P69905", "P68871"))

# The residue pairs both directions agree on (A -> B and B -> A are two alignments).
print(list(m.reciprocal_residue_map_pair("P69905", "P68871"))[:5])
```

Each pair is stored as two rows, `A -> B` and `B -> A`, each its own alignment with that row's
accession as the query. They agree on most residue pairs, not always on all. Releases packed with
the consistency columns record per row and channel how many residue pairs its map shares with the
reverse row's (`n.seq_n_shared`, `n.tm_n_shared`, `n.di_n_shared`) and whether the row was copied
from the reverse row because the pair was found in one direction only (`n.mirrored`); on older
releases these are `None` (the four `Neighbor` fields and `provenance()` keys exist with every
release, so `repr`/`asdict` of a `Neighbor` differ from uupmap 0.0.4). `reciprocal_residue_map_pair`
works on every release.

`neighbors` and `expand_indices` accept `min_cov`, `min_plddt`, `require_both` (sequence and
structure must both pass) and `di_bits_per_res_min` (admits ProstT5 3Di edges, off by default).

### From a PDB residue to a PDB residue

With the SIFTS tables, the reader goes from PDB structure X in UniProt A to PDB structure Y in
UniProt B without another resource. A PDB residue is `(entry, chain, res)`: the chain is the
author chain id (mmCIF `auth_asym_id`) and `res` the SEQRES position (mmCIF `label_seq_id`).

```python
m = UUPMap(d / "edges.parquet", d / "uniprots.parquet", d / "sifts.parquet",
           sifts_observed_path=d / "sifts_observed.parquet")

m.pdb_to_unp("4hhb", "A", [58, 87])            # {58: [SiftsResidue(... unp_ac='P69905', unp_pos=59 ...)], ...}
m.pdb_to_unp("4hhb", "A", ["87"], numbering="author")
m.unp_to_pdb("P69905", [88], observed_only=True)   # every modelled PDB residue at that position

# Chain to chain: through the edge P69905 -> P68871, or SIFTS alone for a shared accession.
for p in m.pdb_residue_map("4hhb", "A", "4hhb", "B"):
    print(p.res_x, p.unp_x, p.pos_x, "->", p.unp_y, p.pos_y, p.res_y, p.cigar_source)

# One edge to all its PDB chain pairs: count first, it can be tens of millions of residue pairs.
print(m.pdb_expansion_count("P69905", "P68871"))
for cp in m.iter_pdb_chain_pairs("P69905", "P68871", observed_only=True):
    print(cp.pdb_a, cp.chain_a, cp.pdb_b, cp.chain_b, cp.pairs.height)

# Residues of a chain to the residues of its neighbours and their PDB chains, in one call:
# the top 10 neighbours by sequence identity, each with the edge's scores.
for r in m.neighbor_residues(pdb="4hhb", chain="A", residues=[58], all_neighbors=True, top_n=10):
    print(r.rank, r.unp_b, r.neighbor and r.neighbor.seq_identity, r.residues.height)
```

SIFTS segments whose SEQRES and UniProt spans differ in length (an insertion or deletion inside
the segment, about 2% of rows) are left out unless you pass `include_nonlinear=True`; their
residues are then marked `approximate`. `m.has_pdb_hop` is `False` on releases built before the
PDB hop, whose `sifts.parquet` has no residue columns.

When the release has `sifts_residues.parquet`, pass it too:

```python
m = UUPMap(d / "edges.parquet", d / "uniprots.parquet", d / "sifts.parquet",
           sifts_observed_path=d / "sifts_observed.parquet",
           sifts_residues_path=d / "sifts_residues.parquet")

m.is_exact_chain("1a2c", "H")                                # True: mapped from the SIFTS XML
m.pdb_to_unp("1a2c", "H", ["60A", "60I"], numbering="author")  # insertion codes resolve
m.pdb_author_numbers("1a2c", "H", [47])                      # {47: '60A'}
```

Every chain the table covers is mapped exactly: no residue is `approximate`, `include_nonlinear`
changes nothing, a residue with several UniProt positions (a chromophore) returns all of them, and
every modelled residue has its author number. Chains it does not cover (`m.is_exact_chain` is
`False`) are mapped from the flat files as above. `m.has_sifts_residues` says whether the table is
loaded. A covered chain that PDBe maps to no UniProt entry returns no positions but has author
numbers (`m.pdb_author_numbers`). Loading the table with the other SIFTS tables on the first
PDB-residue call took 1.2 s instead of 0.4 s and left the process at 0.92 GB working set and
1.30 GB private bytes instead of 0.50 and 0.71 GB (2026-11-08 tables, Windows, 28 threads; with
`POLARS_MAX_THREADS=1`: 0.79 and 0.89 GB instead of 0.49 and 0.53 GB).

The first PDB-residue call loads both SIFTS tables (about 0.3 s, about 0.5 GB of memory). In batch
jobs that run many processes at once, set `POLARS_MAX_THREADS` (for example to 1) before polars is
imported: polars otherwise reserves memory per thread for every core.

### Node status and identity

`m.node_identity(acc)` says what UniProtKB says about a node's accession at the release the build
checked (`unp_status`: `active`, `deleted`, `merged` with `merged_into`, or `unknown` when it was
not checked or the check failed) and which sequence the node is (`uniparc_id`, and `seq_md5`, the
upper-case hex MD5 UniProt also reports). That is the sequence the node's alignments were
computed on, which is not always the one UniProt serves today: a deleted accession stays a node
while UniParc keeps its sequence. AlphaFold-only nodes of the larger builds (prebuilt-database
targets) carry `seq_md5` but no `uniparc_id` for now; their UniParc entry is one request away,
`https://rest.uniprot.org/uniparc/search?query=checksum:<seq_md5>`, which
`m.node_identity(acc).uniparc_search_url` builds (the reader itself never goes online). `node_identity.parquet` is read from beside `uniprots.parquet`
(`m.has_node_identity`); releases built before the change have neither, and the call raises
`ValueError` there.

### Accessions gone from UniProtKB

`retired_accessions.parquet` (releases built since the retired record) keeps accessions that
were nodes or in SIFTS and are deleted or merged now (or of `unknown` status: their check failed
when they left, and the next release checks them again). An accession enters the record when a
build finds it inactive while it is a node or in SIFTS, or finds it inactive or of unknown status
in the build in which it leaves them;
one that left while still active is not followed afterwards, so a later deletion of it is not
recorded. The first record was backfilled from all 25 published releases and is complete as of
its date. `m.retired(acc)`
returns its row, or `None` when the accession is not in the record (NOT proof that it is active:
it may never have been in a release, or may have left while still active and been deleted
later). A row gives the status and UniProt's reason,
`merged_into` for a merged one, the UniParc id and `seq_md5` of the last sequence known for it,
the last release in which it was a node and in SIFTS, and the PDB chains it had then
(`pdb_chains`, `(pdb, chain)` pairs). `m.has_retired` says whether the release has the file.

### Carried chains of deleted accessions (opt-in)

Releases built with carried nodes keep a UniProt-deleted accession whose PDB chains SIFTS no
longer maps as a node, with the chains its last `sifts.parquet` gave it in
`sifts_retired.parquet` / `sifts_retired_observed.parquet` (found beside `sifts.parquet`;
`m.has_retired_chains`). The node set of such a release is then not only the accessions SIFTS maps
that week. Nothing changes until a call asks: the chain and PDB-hop calls (the neighbour-residue calls included) take
`include_retired=False` by default and return what they return on a release without carried
chains; with `include_retired=True` the carried chains take part.

```python
m.expand_candidate_fragments({"P69905"}, seq_id_min=0.3, tm_min=0.5, include_retired=True)
m.retired_chains(unp_ac=acc)          # [RetiredChain(unp_ac, pdb, chain, last_sifts_release, residue_mappable)]
m.is_retired_chain("6old", "B")
m.pdb_to_unp("6old", "B", include_retired=True)
```

A carried chain's segments are those of its `last_sifts_release` (later remediation of the entry
is not followed). Chains carried from releases published before the SEQRES residue columns
existed have UniProt ranges only (`residue_mappable` is `False`): fragments and
`sifts_segments(..., include_retired=True)` return them; the residue calls that name such a
chain or its accession raise `RetiredChainNotMappable` (a `ValueError` listing the chains) rather
than map without them, and the paged neighbour calls list each such chain of a result in its
`unmapped_chains` (counted as `n_unmapped_chains` by `neighbor_residues_count`) instead of
failing the page.

The one-off seed of the carried tables derives the missing SEQRES positions of most such rows
by sequence alignment (linear segments only), and their author numbers and modelled residues
from the entry's mmCIF. Derived values are marked and never pass for SIFTS's own:

- `RetiredChain.residue_source` is `"sifts"` (SIFTS's positions), `"aligned"` (derived) or
  `None` (not `residue_mappable`). It is a trailing field with a default, left out of the `repr`
  and part of `==`.
- `sifts_segments(..., include_retired=True)` has two more columns before `last_sifts_release`:
  `residue_source` (`sifts` / `aligned`) and `author_source` (`sifts` / `mmcif`), null on SIFTS
  rows and on carried rows without positions. A carried observed row marked `aligned` was read
  from the mmCIF, not from SIFTS's observed file.
- A derived chain maps like any other carried chain (`observed_only` and `numbering="author"`
  included). A chain with any segment the derivation did not place stays not
  `residue_mappable` as a whole, so it never answers in part.

A carried node is listed among the neighbours of its neighbours by default. Every call that
returns, ranks, pages or counts neighbours (`neighbors`, `expand_indices`,
`expand_candidate_fragments`, the neighbour-residue calls) takes `include_retired_nodes=True`;
`False` leaves out the neighbours that are carried nodes (`m.is_retired_node(acc)`: a row in
`sifts_retired.parquet`; `m.retired_nodes()`) before ranking, `top_n` and paging. It raises
`ValueError` rather than guess when the reader cannot be certain which accessions are carried
(no `sifts_path`, or `uniprots.parquet` says the release has carried nodes and their table is
not beside `sifts.parquet`).

### AlphaFold-DB residue numbering

Residue maps are in current UniProt numbering. An AlphaFold-DB model can be numbered against an
older version of its UniProt entry; `model_frames.parquet` records the correspondence, and
`m.unp_to_model(acc, positions)` / `m.model_to_unp(acc, residues)` translate lists of numbers
between the two for tools that open the model files themselves (`m.model_frame(acc)` is `None`
for an accession with no AFDB model checked). A frame describes one model file: before mapping
through a model you downloaded yourself, check that `uupmap.residue_frame.crc64(sequence)` of its
modelled sequence equals the frame's `model_crc64`.

When it does not (another model version, or an accession the release does not cover),
`uupmap.frame_classify` classifies the model by the same rules UniWeave's build applies to write
`model_frames.parquet`, from the modelled sequence and the current UniProt sequence:

```python
from uupmap.frame_classify import build_frame_map

fmap = build_frame_map(model_sequence, uniprot_sequence)
print(fmap.kind, fmap.identity, fmap.model_coverage)   # identical | offset | aligned | unreliable
print(fmap.remap(15))                                  # model residue 15 -> UniProt position, or None
```

Identical and offset frames need nothing beyond the reader. The `aligned` case (about one model
in a thousand) runs a Biopython alignment and needs `uupmap[align]`.

### Search caps

MMseqs2 and FoldSeek first collect, for each query, a list of candidate targets with a fast filter
(the prefilter), keep at most `--max-seqs` of them, and align only those. If more targets than the
cap would have qualified, the query's neighbour list is cut off at the cap, and which neighbours
fall inside can change when the database changes. Builds made with an engine that records the caps
write `search_caps.parquet`; a release's dataset card says whether it carries it:

```python
m = UUPMap(d / "edges.parquet", d / "uniprots.parquet",
           search_caps_path=d / "search_caps.parquet")
for cap in m.search_caps("P69905"):    # one per channel and target set; [] if not a query
    print(cap.channel, cap.target_set, cap.max_seqs, cap.n_hits, cap.capped)
```

`capped` is `True` when the cap was certainly reached, `False` when certainly not, and `None` when
not known. `False` means the query's prefilter list was not cut: it was shorter than the cap (a
length recorded only for searches without a coverage threshold), or
the cap is above the number of targets searched (`cap.n_targets`) and the prefilter's split count
(`cap.target_splits`) shows that no part of it could be cut. `None`: the split count is unknown or
above 1 (a split prefilter concatenates its parts' lists), or the search returned fewer rows than
a cap within reach, which alone proves nothing (the rows are only the candidates that also passed
the tool's alignment filters), and the build did not record the prefilter list's length. Rows
replayed from a build's hits cache, and searches on the GPU prefilter, have neither count, so their
flags stay `None`. In a table built before prefilter counts required a search without a coverage
threshold, a `False` in a `seq` row resting on the recorded list length is not reliable. Tables
written before `n_targets` and `target_splits` existed read with both `None`. `n_hits` counts the rows the tool returned, after the filters the build passes to the tool
and before UniWeave's stage-07 thresholds; it is not an edge count. On a release without the file
`m.has_search_caps` is `False` and `m.search_caps(...)` raises `ValueError`.

### Assignments outside SIFTS

About a tenth of the PDB's protein chains have no UniProt accession in SIFTS. Builds made with the
optional stage 01c publish `sifts_complement.parquet`: for natural protein chains that SIFTS does
not map, the accessions the build's own sequence evidence names (tier `P`: the SEQRES string of a
chain SIFTS maps; `T0f`: identical, full length, to a UniProtKB sequence; `T1`: at least 95 %
identity over at least 90 % of the chain), with provenance `uniweave_seq`. Antibodies, T-cell
receptors, synthetic constructs and short peptides are left out; `sifts_complement_summary.json`
gives their numbers.

```python
m = UUPMap(d / "edges.parquet", d / "uniprots.parquet", d / "sifts.parquet",
           sifts_complement_path=d / "sifts_complement.parquet")
m.sifts_complement(pdb="1abc", chain="B")       # a polars frame; also unp_ac=..., tier=...
```

These rows never reach the SIFTS methods: `pdb_to_unp`, `unp_to_pdb`, `sifts_segments` and the
PDB hop return what they return without the table. Without the file `m.has_sifts_complement` is
`False` and `m.sifts_complement(...)` raises `ValueError`.

## Version contract

Each release states which readers can read it. From the releases that carry them,
`dataset_manifest.json` has `uupmap_version` (the reader that built it), `artifact_format` and
`min_uupmap_version` in its `software` block. The installed package exposes the matching
constants:

```python
import json, uupmap

software = json.loads((d / "dataset_manifest.json").read_text())["software"]
print(uupmap.__version__, uupmap.ARTIFACT_FORMAT, uupmap.MIN_READER_VERSION)
print(software.get("min_uupmap_version"), software.get("artifact_format"))
```

Below 0.0.2, a coverage floor silently dropped the structure-only edges, most of the graph.
Use 0.0.2 or later.

0.0.5 is the first release with the PDB hop, the exact residue table, edge consistency, search caps,
node identity and the retired record, the neighbour-residue calls, assignments outside SIFTS and
carried chains (all above). Each feature needs its table, and the instance says whether it has it
(`has_pdb_hop`, `has_sifts_residues`, `has_search_caps`, `has_node_identity`, `has_retired`,
`has_sifts_complement`, `has_retired_chains`). Without it the calls that need the table raise an
error rather than answer (the PDB-hop calls, `search_caps`, `node_identity`, `retired`,
`sifts_complement`, and `include_retired=True` where the call reads the SIFTS tables); a few answer
from what is there instead: `is_exact_chain` returns `False` (the chain is mapped from the flat
files), and `include_retired=True` on a neighbour-residue call for an accession at
`depth="positions"` or `"edges"` answers without carried chains. Releases built before the engine
wrote a table do not have it, and some tables are only in releases built with an option on (the
exact table, the assignments outside SIFTS, carried chains).
`reciprocal_residue_map_pair`, the neighbour-residue calls for an accession at `depth="positions"` or
`"edges"` (without `require_pdb_chain`), and every call of 0.0.4 work on every release.

## Licence

The code is Apache-2.0 (see `LICENSE` and `NOTICE`). The UniWeave data is CC-BY-4.0. A preprint
describing UniWeave is in preparation.
