threadfin 4.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
threadfin/programs.py ADDED
@@ -0,0 +1,133 @@
1
+ """Community-level gene programmes: markers and signature scores."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+
7
+ import pandas as pd
8
+ import scanpy as sc
9
+
10
+
11
+ def _require_obs(adata, col: str) -> None:
12
+ if col not in adata.obs.columns:
13
+ raise KeyError(f"'{col}' not found in adata.obs.")
14
+
15
+
16
+ def _rank_genes_df(ad) -> pd.DataFrame:
17
+ """rank_genes_groups results as a tidy DataFrame across scanpy versions."""
18
+ if hasattr(sc.get, "rank_genes_groups_df"):
19
+ df = sc.get.rank_genes_groups_df(ad, group=None)
20
+ df = df.rename(
21
+ columns={
22
+ "group": "community",
23
+ "names": "gene",
24
+ "scores": "score",
25
+ "logfoldchanges": "logfoldchange",
26
+ "pvals_adj": "pval_adj",
27
+ }
28
+ )
29
+ else:
30
+ rgg = ad.uns["rank_genes_groups"]
31
+ rows = []
32
+ for group in rgg["names"].dtype.names:
33
+ n = len(rgg["names"][group])
34
+ rows.append(
35
+ pd.DataFrame(
36
+ {
37
+ "community": group,
38
+ "gene": rgg["names"][group],
39
+ "score": rgg["scores"][group],
40
+ "logfoldchange": rgg.get("logfoldchanges", [None] * n)[group],
41
+ "pval_adj": rgg.get("pvals_adj", [None] * n)[group],
42
+ }
43
+ )
44
+ )
45
+ df = pd.concat(rows, ignore_index=True)
46
+ return df[["community", "gene", "score", "logfoldchange", "pval_adj"]]
47
+
48
+
49
+ def community_markers(
50
+ adata,
51
+ *,
52
+ cluster_key: str = "clone_cluster",
53
+ method: str = "wilcoxon",
54
+ n_genes: int = 25,
55
+ layer: str | None = None,
56
+ ) -> pd.DataFrame:
57
+ """Differentially expressed genes per clone community.
58
+
59
+ Cells without a ``cluster_key`` label are excluded. Runs scanpy
60
+ ``rank_genes_groups`` (each community vs. the rest) on a copy of the
61
+ labelled cells.
62
+
63
+ Returns
64
+ -------
65
+ Tidy DataFrame with columns ``[community, gene, score, logfoldchange,
66
+ pval_adj]``, top ``n_genes`` per community.
67
+ """
68
+ _require_obs(adata, cluster_key)
69
+ ad = adata[adata.obs[cluster_key].notna()].copy()
70
+ if isinstance(ad.obs[cluster_key].dtype, pd.CategoricalDtype):
71
+ ad.obs[cluster_key] = ad.obs[cluster_key].cat.remove_unused_categories()
72
+ if ad.obs[cluster_key].nunique() < 2:
73
+ raise ValueError(f"Need at least two communities in '{cluster_key}'.")
74
+ sc.tl.rank_genes_groups(
75
+ ad,
76
+ groupby=cluster_key,
77
+ method=method,
78
+ layer=layer,
79
+ n_genes=min(n_genes, ad.n_vars),
80
+ )
81
+ return _rank_genes_df(ad).reset_index(drop=True)
82
+
83
+
84
+ def community_score(
85
+ adata,
86
+ signatures: dict[str, list[str]],
87
+ *,
88
+ cluster_key: str = "clone_cluster",
89
+ score_kwargs: dict | None = None,
90
+ ) -> pd.DataFrame:
91
+ """Mean per-community score of named gene programmes.
92
+
93
+ Each signature is scored per cell with scanpy ``score_genes`` over the
94
+ genes present in ``var_names`` (missing genes are dropped); signatures
95
+ with no gene present are skipped with a warning. Cells without a
96
+ ``cluster_key`` label are excluded from the per-community means.
97
+
98
+ Returns
99
+ -------
100
+ Tidy DataFrame with columns ``[community, signature, score, n_cells]``.
101
+ """
102
+ _require_obs(adata, cluster_key)
103
+ score_kwargs = dict(score_kwargs or {})
104
+ clusters = adata.obs[cluster_key]
105
+
106
+ rows = []
107
+ skipped = []
108
+ for name, genes in signatures.items():
109
+ present = [g for g in genes if g in adata.var_names]
110
+ if not present:
111
+ skipped.append(name)
112
+ continue
113
+ col = f"_threadfin_score_{name}"
114
+ sc.tl.score_genes(adata, gene_list=present, score_name=col, **score_kwargs)
115
+ df = pd.DataFrame({"community": clusters, "score": adata.obs[col]}).dropna()
116
+ del adata.obs[col]
117
+ for community, grp in df.groupby("community", observed=True):
118
+ rows.append(
119
+ {
120
+ "community": community,
121
+ "signature": name,
122
+ "score": float(grp["score"].mean()),
123
+ "n_cells": int(len(grp)),
124
+ }
125
+ )
126
+ if skipped:
127
+ warnings.warn(
128
+ f"Signatures skipped, no genes found in var_names: {skipped}",
129
+ UserWarning,
130
+ stacklevel=2,
131
+ )
132
+ out = pd.DataFrame(rows, columns=["community", "signature", "score", "n_cells"])
133
+ return out.sort_values(["signature", "community"]).reset_index(drop=True)
@@ -0,0 +1,68 @@
1
+ """Reproducible starting configurations for centroid-based clone reclustering.
2
+
3
+ These presets describe graph/UMAP settings, not biological classes. They do
4
+ not train on markers, select a preferred shape, or infer differentiation.
5
+ The v4 sampling-adjusted profile workflow remains a separate analysis.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from copy import deepcopy
11
+
12
+ import numpy as np
13
+
14
+ from ._utils import require_positive_int
15
+
16
+ _PRESETS = {
17
+ "cohesive": {
18
+ "description": "Compact, connected neighbourhoods; preserves legacy defaults.",
19
+ "n_neighbors": 20, "resolution": 0.3, "min_dist": 0.1,
20
+ "spread": 1.0, "learning_rate": 1.0,
21
+ },
22
+ "continuous": {
23
+ "description": "More space within connected neighbourhoods; report-style starting point.",
24
+ "n_neighbors": 20, "resolution": 0.1, "min_dist": 0.4,
25
+ "spread": 1.0, "learning_rate": 1.0,
26
+ },
27
+ "discrete": {
28
+ "description": "More local neighbourhoods and finer exploratory partitions.",
29
+ "n_neighbors": 10, "resolution": 0.8, "min_dist": 0.05,
30
+ "spread": 1.0, "learning_rate": 1.0,
31
+ },
32
+ }
33
+
34
+
35
+ def reclustering_presets() -> dict:
36
+ """Return independent copies of the three centroid-reclustering presets.
37
+
38
+ Pass a preset name to :func:`threadfin.clonotype_recluster`. Explicit
39
+ keyword values override that preset. A preset cannot establish whether
40
+ real data contain continuous or discrete biological populations.
41
+ """
42
+ return deepcopy(_PRESETS)
43
+
44
+
45
+ def _resolve_parameters(preset, **overrides) -> dict:
46
+ if not isinstance(preset, str) or preset not in _PRESETS:
47
+ raise ValueError("preset must be 'cohesive', 'continuous', or 'discrete'.")
48
+ settings = {k: v for k, v in _PRESETS[preset].items() if k != "description"}
49
+ settings.update({k: v for k, v in overrides.items() if v is not None})
50
+ require_positive_int(settings["n_neighbors"], "n_neighbors")
51
+ if settings["n_neighbors"] < 2:
52
+ raise ValueError("n_neighbors must be at least 2 for clone UMAP.")
53
+ for name in ("resolution", "min_dist", "spread", "learning_rate"):
54
+ value = settings[name]
55
+ if isinstance(value, (bool, np.bool_)):
56
+ raise ValueError(f"{name} must be a finite number.")
57
+ try:
58
+ value = float(value)
59
+ except (TypeError, ValueError):
60
+ raise ValueError(f"{name} must be a finite number.") from None
61
+ if not np.isfinite(value):
62
+ raise ValueError(f"{name} must be a finite number.")
63
+ settings[name] = value
64
+ if settings["resolution"] <= 0 or settings["spread"] <= 0 or settings["learning_rate"] <= 0:
65
+ raise ValueError("resolution, spread, and learning_rate must be greater than zero.")
66
+ if not 0 <= settings["min_dist"] <= settings["spread"]:
67
+ raise ValueError("min_dist must be between zero and spread.")
68
+ return settings
threadfin/sequence.py ADDED
@@ -0,0 +1,379 @@
1
+ """CDR3 sequence-distance utilities (optional sequence-aware integration)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ _AA = np.array(list("ACDEFGHIKLMNPQRSTVWY"), dtype="U1")
8
+ _AA_TO_INT = {aa: i for i, aa in enumerate(_AA)}
9
+
10
+
11
+ def _encode(seq: str) -> np.ndarray:
12
+ return np.array([_AA_TO_INT.get(a, 20) for a in seq], dtype=np.int8)
13
+
14
+
15
+ _BLOSUM62_ORDER = "ARNDCQEGHILKMFPSTWYVBZX*"
16
+ _BLOSUM62_ROWS = """\
17
+ 4 -1 -2 -2 0 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -3 -2 0 -2 -1 0 -4
18
+ -1 5 0 -2 -3 1 0 -2 0 -3 -2 2 -1 -3 -2 -1 -1 -3 -2 -3 -1 0 -1 -4
19
+ -2 0 6 1 -3 0 0 0 1 -3 -3 0 -2 -3 -2 1 0 -4 -2 -3 3 0 -1 -4
20
+ -2 -2 1 6 -3 0 2 -1 -1 -3 -4 -1 -3 -3 -1 0 -1 -4 -3 -3 4 1 -1 -4
21
+ 0 -3 -3 -3 9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4
22
+ -1 1 0 0 -3 5 2 -2 0 -3 -2 1 0 -3 -1 0 -1 -2 -1 -2 0 3 -1 -4
23
+ -1 0 0 2 -4 2 5 -2 0 -3 -3 1 -2 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4
24
+ 0 -2 0 -1 -3 -2 -2 6 -2 -4 -4 -2 -3 -3 -2 0 -2 -2 -3 -3 -1 -2 -1 -4
25
+ -2 0 1 -1 -3 0 0 -2 8 -3 -3 -1 -2 -1 -2 -1 -2 -2 2 -3 0 0 -1 -4
26
+ -1 -3 -3 -3 -1 -3 -3 -4 -3 4 2 -3 1 0 -3 -2 -1 -3 -1 3 -3 -3 -1 -4
27
+ -1 -2 -3 -4 -1 -2 -3 -4 -3 2 4 -2 2 0 -3 -2 -1 -2 -1 1 -4 -3 -1 -4
28
+ -1 2 0 -1 -3 1 1 -2 -1 -3 -2 5 -1 -3 -1 0 -1 -3 -2 -2 0 1 -1 -4
29
+ -1 -1 -2 -3 -1 0 -2 -3 -2 1 2 -1 5 0 -2 -1 -1 -1 -1 1 -3 -1 -1 -4
30
+ -2 -3 -3 -3 -2 -3 -3 -3 -1 0 0 -3 0 6 -4 -2 -2 1 3 -1 -3 -3 -1 -4
31
+ -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -2 -4
32
+ 1 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 0 -4
33
+ 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0 -4
34
+ -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2 -4
35
+ -2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -1 -4
36
+ 0 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1 -4
37
+ -2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1 -4
38
+ -1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4
39
+ 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1 -4
40
+ -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1
41
+ """
42
+
43
+
44
+ def _build_blosum62() -> dict:
45
+ rows = [list(map(int, line.split())) for line in _BLOSUM62_ROWS.strip().splitlines()]
46
+ return {
47
+ (a, b): rows[i][j]
48
+ for i, a in enumerate(_BLOSUM62_ORDER)
49
+ for j, b in enumerate(_BLOSUM62_ORDER)
50
+ }
51
+
52
+
53
+ BLOSUM62 = _build_blosum62()
54
+
55
+ _GAP_OPEN = -8
56
+ _GAP_EXTEND = -1
57
+ _MAX_LEN_DIFF = 4
58
+
59
+ try: # optional C-accelerated aligner; pure-Python fallback below
60
+ import parasail as _parasail
61
+
62
+ _PARASAIL_MATRIX = _parasail.blosum62
63
+ except ImportError: # pragma: no cover
64
+ _parasail = None
65
+ _PARASAIL_MATRIX = None
66
+
67
+ _ATCHLEY_TABLE = {
68
+ "A": (-0.591, -1.302, -0.733, 1.570, -0.146),
69
+ "R": (1.538, -0.055, 1.502, 0.440, 2.897),
70
+ "N": (0.945, 0.828, 1.299, -0.169, 0.933),
71
+ "D": (1.050, 0.302, -3.656, -0.259, -3.242),
72
+ "C": (-1.343, 0.465, -0.862, -1.020, -0.255),
73
+ "Q": (0.931, -0.179, -3.005, -0.503, -1.853),
74
+ "E": (1.357, -1.453, 1.477, 0.113, -0.837),
75
+ "G": (-0.384, 1.652, 1.330, 1.045, 2.064),
76
+ "H": (0.336, -0.417, -1.673, -1.474, -0.078),
77
+ "I": (-1.239, -0.547, 2.131, 0.393, 0.816),
78
+ "L": (-1.019, -0.987, -1.505, 1.266, -0.912),
79
+ "K": (1.831, -0.561, 0.533, -0.277, 1.648),
80
+ "M": (-1.329, -1.244, -0.663, 0.868, -0.500),
81
+ "F": (-1.006, -0.590, 1.891, -0.397, 0.412),
82
+ "P": (0.189, 2.081, -1.628, 0.421, -1.392),
83
+ "S": (-0.228, 1.399, -4.760, 0.670, -2.647),
84
+ "T": (-0.032, 0.326, 2.213, 0.908, 1.313),
85
+ "W": (-0.595, 0.009, 0.672, -2.128, -0.184),
86
+ "Y": (0.260, 0.830, 3.097, -0.838, 1.512),
87
+ "V": (-1.337, -0.279, -0.544, 1.242, -1.262),
88
+ }
89
+ ATCHLEY = {a: np.array(v, dtype=np.float64) for a, v in _ATCHLEY_TABLE.items()}
90
+
91
+ _MODES = ("auto", "hamming", "blosum")
92
+
93
+ _CODON_TABLE = {
94
+ "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L",
95
+ "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L",
96
+ "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M",
97
+ "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
98
+ "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S",
99
+ "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P",
100
+ "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T",
101
+ "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A",
102
+ "TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*",
103
+ "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q",
104
+ "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K",
105
+ "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E",
106
+ "TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W",
107
+ "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R",
108
+ "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R",
109
+ "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G",
110
+ }
111
+
112
+
113
+ def translate_nt(seq) -> str | None:
114
+ """Translate a nucleotide junction to amino acids (frame 0, stops at the
115
+ first stop codon). Returns None for invalid/short input or unknown codons
116
+ before any residue. Trailing partial codons are ignored."""
117
+ if not isinstance(seq, str) or len(seq) < 3:
118
+ return None
119
+ s = seq.upper()
120
+ aas = []
121
+ for i in range(0, len(s) - 2, 3):
122
+ aa = _CODON_TABLE.get(s[i:i + 3])
123
+ if aa is None:
124
+ return None if not aas else "".join(aas)
125
+ if aa == "*":
126
+ break
127
+ aas.append(aa)
128
+ return "".join(aas) if aas else None
129
+
130
+
131
+ def _sub(a: str, b: str) -> int:
132
+ return BLOSUM62.get((a, b), -1)
133
+
134
+
135
+ from functools import lru_cache
136
+
137
+
138
+ @lru_cache(maxsize=200_000)
139
+ def _self_score(seq: str) -> int:
140
+ return sum(_sub(c, c) for c in seq)
141
+
142
+
143
+ def _nw_score(a: str, b: str) -> float:
144
+ """Gotoh global alignment score with BLOSUM62 and affine gaps.
145
+
146
+ Uses parasail (C) when installed; falls back to a NumPy DP otherwise."""
147
+ if _parasail is not None:
148
+ return float(
149
+ _parasail.nw(a, b, -_GAP_OPEN, -_GAP_EXTEND, _PARASAIL_MATRIX).score
150
+ )
151
+ n, m = len(a), len(b)
152
+ M = np.full((n + 1, m + 1), -np.inf)
153
+ M[0, 0] = 0.0
154
+ Ix = np.full((n + 1, m + 1), -np.inf)
155
+ Iy = np.full((n + 1, m + 1), -np.inf)
156
+ Ix[1:, 0] = _GAP_OPEN + np.arange(n) * _GAP_EXTEND
157
+ Iy[0, 1:] = _GAP_OPEN + np.arange(m) * _GAP_EXTEND
158
+ for i in range(1, n + 1):
159
+ for j in range(1, m + 1):
160
+ Ix[i, j] = max(M[i - 1, j] + _GAP_OPEN, Ix[i - 1, j] + _GAP_EXTEND)
161
+ Iy[i, j] = max(M[i, j - 1] + _GAP_OPEN, Iy[i, j - 1] + _GAP_EXTEND)
162
+ M[i, j] = max(M[i - 1, j - 1], Ix[i - 1, j - 1], Iy[i - 1, j - 1]) + _sub(
163
+ a[i - 1], b[j - 1]
164
+ )
165
+ return max(M[n, m], Ix[n, m], Iy[n, m])
166
+
167
+
168
+ def _hamming_sim(a: str, b: str) -> float:
169
+ return 1.0 - float((_encode(a) != _encode(b)).mean())
170
+
171
+
172
+ def _aligned_sim(a: str, b: str) -> float:
173
+ denom = max(_self_score(a), _self_score(b))
174
+ if denom <= 0:
175
+ return 0.0
176
+ return float(min(1.0, max(0.0, _nw_score(a, b) / denom)))
177
+
178
+
179
+ def _valid(seq) -> bool:
180
+ return isinstance(seq, str) and len(seq) > 0
181
+
182
+
183
+ def cdr3_similarity(a: str, b: str, *, mode: str = "auto") -> float:
184
+ """Similarity in [0, 1]. Equal length -> 1 - Hamming/len (fast path);
185
+ otherwise BLOSUM62 global alignment normalized by self-scores.
186
+ 'auto': identical -> 1.0; len diff > 4 -> 0.0; equal len -> Hamming;
187
+ else alignment. 'hamming': equal-length fast path only. 'blosum': always
188
+ align."""
189
+ if mode not in _MODES:
190
+ raise ValueError(f"mode must be one of {_MODES}.")
191
+ if not (_valid(a) and _valid(b)):
192
+ return 0.0
193
+ if a == b:
194
+ return 1.0
195
+ if mode == "hamming":
196
+ return _hamming_sim(a, b) if len(a) == len(b) else 0.0
197
+ if mode == "auto":
198
+ if abs(len(a) - len(b)) > _MAX_LEN_DIFF:
199
+ return 0.0
200
+ if len(a) == len(b):
201
+ return _hamming_sim(a, b)
202
+ return _aligned_sim(a, b)
203
+
204
+
205
+ def cdr3_similarity_pairs(seqs_a, seqs_b, *, mode: str = "auto") -> np.ndarray:
206
+ """Vectorized pairwise similarity for pre-filtered candidate pairs (1-D
207
+ arrays of equal length). Used by bcrgraph; NOT an all-pairs API."""
208
+ if mode not in _MODES:
209
+ raise ValueError(f"mode must be one of {_MODES}.")
210
+ a = np.asarray(seqs_a, dtype=object)
211
+ b = np.asarray(seqs_b, dtype=object)
212
+ if a.ndim != 1 or b.ndim != 1 or a.shape != b.shape:
213
+ raise ValueError("seqs_a and seqs_b must be 1-D arrays of equal length.")
214
+ n = a.shape[0]
215
+ out = np.zeros(n, dtype=np.float64)
216
+ if n == 0:
217
+ return out
218
+
219
+ len_a = np.array([len(s) if _valid(s) else -1 for s in a])
220
+ len_b = np.array([len(s) if _valid(s) else -1 for s in b])
221
+ valid = (len_a >= 0) & (len_b >= 0)
222
+ equal_len = valid & (len_a == len_b)
223
+ identical = equal_len & (a == b)
224
+ out[identical] = 1.0
225
+
226
+ if mode in ("auto", "hamming"):
227
+ ham_idx = np.flatnonzero(equal_len & ~identical)
228
+ for length in np.unique(len_a[ham_idx]):
229
+ sel = ham_idx[len_a[ham_idx] == length]
230
+ ea = np.stack([_encode(a[i]) for i in sel])
231
+ eb = np.stack([_encode(b[i]) for i in sel])
232
+ out[sel] = 1.0 - (ea != eb).mean(axis=1)
233
+ if mode == "auto":
234
+ rest = valid & ~equal_len & (np.abs(len_a - len_b) <= _MAX_LEN_DIFF)
235
+ elif mode == "blosum":
236
+ rest = valid & ~identical
237
+ else:
238
+ rest = np.zeros(n, dtype=bool)
239
+ for i in np.flatnonzero(rest):
240
+ out[i] = _aligned_sim(a[i], b[i])
241
+ return out
242
+
243
+
244
+ def atchley_embedding(seqs: list) -> np.ndarray:
245
+ """(n, 21) deterministic embedding: mean/sd/min/max of the 5 Atchley
246
+ factors over residues + normalized length. Unknown chars map to zeros."""
247
+ seqs = list(seqs)
248
+ n = len(seqs)
249
+ out = np.zeros((n, 21), dtype=np.float64)
250
+ lengths = np.array([len(s) if _valid(s) else 0 for s in seqs], dtype=np.float64)
251
+ max_len = max(float(lengths.max()), 1.0) if n else 1.0
252
+ zero = np.zeros(5, dtype=np.float64)
253
+ for i, s in enumerate(seqs):
254
+ if not _valid(s):
255
+ continue
256
+ feats = np.stack([ATCHLEY.get(c, zero) for c in s])
257
+ out[i, :20] = np.concatenate(
258
+ [feats.mean(axis=0), feats.std(axis=0), feats.min(axis=0), feats.max(axis=0)]
259
+ )
260
+ out[:, 20] = lengths / max_len
261
+ return out
262
+
263
+
264
+ def _gene(call) -> str:
265
+ if not isinstance(call, str) or not call:
266
+ return ""
267
+ return call.split(",")[0].split("*")[0].strip()
268
+
269
+
270
+ def _family(gene: str) -> str:
271
+ return gene.split("-")[0]
272
+
273
+
274
+ def vj_distance(v1, j1, v2, j2, *, family_level: bool = False) -> float:
275
+ """0.0 same V&J gene; 0.5 same V&J families; 1.0 otherwise.
276
+ family_level=True collapses the 0.5 tier to 0.0."""
277
+ gv1, gv2, gj1, gj2 = _gene(v1), _gene(v2), _gene(j1), _gene(j2)
278
+ if not all([gv1, gv2, gj1, gj2]):
279
+ return 1.0
280
+ if gv1 == gv2 and gj1 == gj2:
281
+ return 0.0
282
+ if _family(gv1) == _family(gv2) and _family(gj1) == _family(gj2):
283
+ return 0.0 if family_level else 0.5
284
+ return 1.0
285
+
286
+
287
+ def cdr3_distance_matrix(cdr3s: list, *, mode: str = "hamming") -> np.ndarray:
288
+ """Pairwise amino-acid distance between CDR3 sequences.
289
+
290
+ ``mode="hamming"`` (default, v1 behavior): sequences of equal length are
291
+ compared position-wise (fraction of mismatches). Pairs with different
292
+ lengths receive the maximal normalized distance of 1.0 plus a
293
+ length-mismatch penalty, keeping the metric in a comparable range for
294
+ downstream blending. Missing sequences (None/NaN) get distance 1.0 to
295
+ everything.
296
+
297
+ ``mode="blosum"``: distance is ``1 - cdr3_similarity`` (BLOSUM62
298
+ alignment for near-equal lengths), with distance 1.0 for missing
299
+ sequences.
300
+
301
+ Parameters
302
+ ----------
303
+ cdr3s
304
+ List of CDR3 amino-acid sequences (may contain None/NaN).
305
+ mode
306
+ ``"hamming"`` or ``"blosum"``.
307
+
308
+ Returns
309
+ -------
310
+ Symmetric ``(n, n)`` float matrix with zero diagonal.
311
+ """
312
+ if mode == "blosum":
313
+ n = len(cdr3s)
314
+ dist = np.ones((n, n), dtype=np.float64)
315
+ seqs = [s if _valid(s) else None for s in cdr3s]
316
+ for i in range(n):
317
+ if seqs[i] is None:
318
+ continue
319
+ for j in range(i + 1, n):
320
+ if seqs[j] is None:
321
+ continue
322
+ dist[i, j] = dist[j, i] = 1.0 - cdr3_similarity(seqs[i], seqs[j])
323
+ np.fill_diagonal(dist, 0.0)
324
+ return dist
325
+ if mode != "hamming":
326
+ raise ValueError("mode must be 'hamming' or 'blosum'.")
327
+
328
+ n = len(cdr3s)
329
+ dist = np.ones((n, n), dtype=np.float64)
330
+ np.fill_diagonal(dist, 0.0)
331
+
332
+ seqs = [s if isinstance(s, str) and len(s) > 0 else None for s in cdr3s]
333
+ lengths = np.array([len(s) if s else -1 for s in seqs])
334
+
335
+ for length in sorted({len(s) for s in seqs if s}):
336
+ idx = np.flatnonzero(lengths == length)
337
+ if len(idx) < 1:
338
+ continue
339
+ mat = np.stack([_encode(seqs[i]) for i in idx])
340
+ # pairwise mismatch fraction via broadcasting
341
+ sub = (mat[:, None, :] != mat[None, :, :]).mean(axis=2)
342
+ dist[np.ix_(idx, idx)] = sub
343
+
344
+ # length-mismatch penalty on top of the maximal base distance
345
+ valid = lengths >= 0
346
+ valid_pair = valid[:, None] & valid[None, :]
347
+ len_diff = np.abs(lengths[:, None] - lengths[None, :]).astype(np.float64)
348
+ len_diff[~valid_pair] = 0.0
349
+ max_len = max(lengths.max(), 1)
350
+ dist += (len_diff / max_len) * 0.5
351
+ dist[~valid_pair] = 1.0
352
+ np.fill_diagonal(dist, 0.0)
353
+ return dist
354
+
355
+
356
+ def _zscore(mat: np.ndarray) -> np.ndarray:
357
+ iu = np.triu_indices_from(mat, k=1)
358
+ vals = mat[iu]
359
+ mu, sd = vals.mean(), vals.std()
360
+ if sd == 0:
361
+ return mat - mu
362
+ return (mat - mu) / sd
363
+
364
+
365
+ def blend_distances(
366
+ d_transcriptional: np.ndarray, d_sequence: np.ndarray, weight: float
367
+ ) -> np.ndarray:
368
+ """Convex blend of two distance matrices after z-scoring.
369
+
370
+ ``D = (1 - weight) * z(D_transcriptional) + weight * z(D_sequence)``.
371
+ The blended matrix is shifted so its minimum is 0 (kNN/UMAP expect
372
+ non-negative distances).
373
+ """
374
+ if d_transcriptional.shape != d_sequence.shape:
375
+ raise ValueError("Distance matrices must have the same shape.")
376
+ out = (1.0 - weight) * _zscore(d_transcriptional) + weight * _zscore(d_sequence)
377
+ out = out - out.min()
378
+ np.fill_diagonal(out, 0.0)
379
+ return out