-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprot_ction.py
More file actions
4893 lines (4255 loc) · 186 KB
/
prot_ction.py
File metadata and controls
4893 lines (4255 loc) · 186 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Protein sequence conservation calculator.
Similarity metric: normalized inverted Hamming distance
similarity = 1 - (mismatches / comparable_positions)
Modes (--mode):
auto Auto-detect: equal-length → MSA column comparison;
unequal-length → sliding approach. (default)
aligned Input is a pre-computed MSA. All sequences must be the same
length. Gap characters (- .) are respected as alignment columns
and skipped when computing similarity. Per-position conservation
is derived directly from the alignment columns.
unaligned Treat all sequences as raw/ungapped, regardless of length.
Any gap characters are stripped before processing. The sliding
approach is always used.
Taxonomy (--rank): fetches full taxonomic lineage from UniProt / NCBI for
each accession, groups sequences by the chosen rank (e.g. genus, family),
and reports the median pairwise similarity within and between groups.
Sequences for which taxonomy cannot be retrieved are automatically dropped.
Input: FASTA file with UniProt (sp|P12345|GENE_HUMAN) or GenBank (NP_000001.1)
identifiers in the definition line.
"""
from __future__ import annotations
VERSION = "1.1.1"
import re
import sys
import csv
import json
import math
import time
import hashlib
import logging
import pathlib
import argparse
import tempfile
import statistics
import urllib.request
import urllib.error
from collections import defaultdict
from dataclasses import dataclass, field
from itertools import combinations
from xml.etree import ElementTree as ET
# Gap characters recognised in aligned sequences
_GAP: frozenset[str] = frozenset("-.")
# Module-level logger (reconfigured by setup_logging / _analyse_fasta)
_log = logging.getLogger("prot_ction")
# ---------------------------------------------------------------------------
# Identifier parsing
# ---------------------------------------------------------------------------
def parse_identifier(header: str) -> tuple[str, str]:
"""
Extract accession and database type from a FASTA header line.
Supported formats:
UniProt >sp|P12345|GENE_HUMAN ... or >tr|A0A000|GENE_SPECIES ...
GenBank >NP_000001.1 ... / >XP_... / >gi|...|ref|NP_...|
Plain >MYPROT (falls back to first whitespace-delimited token)
Returns (accession, db_type) where db_type is 'uniprot', 'genbank', or 'unknown'.
"""
header = header.lstrip(">").strip()
# UniProt Swiss-Prot / TrEMBL
m = re.match(r"(?:sp|tr)\|([A-Z0-9]+)\|\S+", header)
if m:
return m.group(1), "uniprot"
# NCBI gi pipe format gi|12345|ref|NP_000001.1|
m = re.search(r"gi\|\d+\|\w+\|([A-Z_0-9.]+)\|?", header)
if m:
return m.group(1), "genbank"
# Bare GenBank/RefSeq accession (e.g. NP_000001.1, XP_001234567.2, P12345)
m = re.match(r"([A-Z]{1,3}[_]?\d+\.?\d*)", header)
if m:
return m.group(1), "genbank"
# Fall back: first token
return header.split()[0], "unknown"
# ---------------------------------------------------------------------------
# FASTA parser
# ---------------------------------------------------------------------------
def _extract_org_hint(header: str) -> str:
"""
Best-effort extraction of an organism name from a raw FASTA header line.
Handles:
UniProt ``OS=Homo sapiens OX=...`` → ``Homo sapiens``
GenBank ``... [Homo sapiens]`` → ``Homo sapiens``
Returns an empty string when nothing can be found.
"""
h = header.lstrip(">").strip()
# UniProt OS= field
m = re.search(r"\bOS=(.+?)(?:\s+OX=|\s+GN=|\s+PE=|\s+SV=|$)", h)
if m:
return m.group(1).strip()
# GenBank/RefSeq bracketed organism at (or near) end of description
m = re.search(r"\[([^\[\]]+)\]\s*$", h)
if m:
return m.group(1).strip()
return ""
def _extract_protein_name(header: str) -> str:
"""
Best-effort extraction of the protein/product name from a FASTA header.
Handles:
UniProt ``>sp|P12345|GENE_HUMAN Serine protease OS=Homo sapiens ...``
→ ``Serine protease``
GenBank ``>NP_000001.1 alpha-1-B glycoprotein precursor [Homo sapiens]``
→ ``alpha-1-B glycoprotein precursor``
Returns an empty string when no name can be extracted.
"""
h = header.lstrip(">").strip()
# UniProt: accession block ends at first space; name runs until OS=/OX=/GN=/PE=/SV=
m = re.match(r"(?:sp|tr)\|[A-Z0-9]+\|\S+\s+(.*?)(?:\s+OS=|\s+OX=|\s+GN=|\s+PE=|\s+SV=|$)", h)
if m:
return m.group(1).strip()
# GenBank/RefSeq: first token is accession, rest is description, remove trailing [Organism]
parts = h.split(None, 1)
if len(parts) < 2:
return ""
desc = parts[1].strip()
# Remove trailing bracketed organism
desc = re.sub(r"\s*\[[^\[\]]+\]\s*$", "", desc)
return desc.strip()
def _infer_protein_label(
path: str,
db_protein_names: "dict[str, str] | None" = None,
) -> str:
"""
Infer a consensus/majority protein name for the sequences in *path*.
**Priority**: if *db_protein_names* (accession → name from a UniProt /
NCBI lookup) is provided and non-empty, the majority name from those
database records is used — this is far more reliable than header parsing.
**Fallback**: parse FASTA headers for protein descriptions.
Returns the file stem if nothing can be determined.
"""
# ── Attempt 1: database-fetched protein names (most authoritative) ────
if db_protein_names:
counts: "dict[str, int]" = {}
for name in db_protein_names.values():
key = name.rstrip(".,; ")
if key:
counts[key] = counts.get(key, 0) + 1
if counts:
best = max(counts, key=counts.get) # type: ignore[arg-type]
total = sum(counts.values())
if counts[best] / total <= 0.5:
return f"{best} (+{len(counts) - 1} others)"
return best
# ── Attempt 2: parse FASTA headers ────────────────────────────────────
counts2: "dict[str, int]" = {}
with open(path) as fh:
for raw in fh:
if raw.startswith(">"):
name = _extract_protein_name(raw)
if name:
key = name.rstrip(".,; ")
counts2[key] = counts2.get(key, 0) + 1
if counts2:
best = max(counts2, key=counts2.get) # type: ignore[arg-type]
total = sum(counts2.values())
if counts2[best] < total and counts2[best] / total < 0.5:
return f"{best} (+{len(counts2) - 1} others)"
return best
return pathlib.Path(path).stem
def parse_fasta(path: str) -> list[tuple[str, str, str, str]]:
"""
Parse a FASTA file.
Returns list of ``(accession, db_type, sequence, org_hint)`` tuples.
*org_hint* is the organism name extracted from the header line (empty
string when not present).
Sequences are uppercased; ambiguous/gap characters are preserved.
"""
records = []
acc = db = org = None
buf: list[str] = []
with open(path) as fh:
for raw in fh:
line = raw.strip()
if not line:
continue
if line.startswith(">"):
if acc is not None:
records.append((acc, db, "".join(buf).upper(), org))
acc, db = parse_identifier(line)
org = _extract_org_hint(line)
buf = []
else:
buf.append(line)
if acc is not None:
records.append((acc, db, "".join(buf).upper(), org))
return records
# ---------------------------------------------------------------------------
# Additional alignment format parsers (Stockholm, Clustal, NEXUS)
# ---------------------------------------------------------------------------
def detect_format(path: str) -> str:
"""Auto-detect alignment format from the first non-blank line."""
with open(path) as fh:
for line in fh:
line = line.strip()
if not line:
continue
if line.startswith("# STOCKHOLM"):
return "stockholm"
if line.startswith("CLUSTAL"):
return "clustal"
if line.upper().startswith("#NEXUS"):
return "nexus"
return "fasta"
return "fasta"
def parse_stockholm(path: str) -> list[tuple[str, str, str, str]]:
"""Parse a Stockholm (.sto/.sth) alignment file."""
seqs: dict[str, list[str]] = {}
order: list[str] = []
with open(path) as fh:
for line in fh:
line = line.rstrip()
if line.startswith("#") or line.startswith("//") or not line.strip():
continue
parts = line.split()
if len(parts) == 2:
name, seq = parts
if name not in seqs:
order.append(name)
seqs[name] = []
seqs[name].append(seq)
records: list[tuple[str, str, str, str]] = []
for name in order:
full_seq = "".join(seqs[name]).upper()
acc, db = parse_identifier(">" + name)
org = _extract_org_hint(">" + name)
records.append((acc, db, full_seq, org))
return records
def parse_clustal(path: str) -> list[tuple[str, str, str, str]]:
"""Parse a Clustal (.aln) alignment file."""
seqs: dict[str, list[str]] = {}
order: list[str] = []
with open(path) as fh:
for i, line in enumerate(fh):
line = line.rstrip()
if i == 0 and line.startswith("CLUSTAL"):
continue
if not line.strip() or line[0] == " ":
continue
parts = line.split()
if len(parts) >= 2:
name, seq = parts[0], parts[1]
if name not in seqs:
order.append(name)
seqs[name] = []
seqs[name].append(seq)
records: list[tuple[str, str, str, str]] = []
for name in order:
full_seq = "".join(seqs[name]).upper()
acc, db = parse_identifier(">" + name)
org = _extract_org_hint(">" + name)
records.append((acc, db, full_seq, org))
return records
def parse_nexus(path: str) -> list[tuple[str, str, str, str]]:
"""Parse a NEXUS (.nex/.nexus) alignment file."""
seqs: dict[str, list[str]] = {}
order: list[str] = []
in_matrix = False
with open(path) as fh:
for line in fh:
stripped = line.strip()
low = stripped.lower()
if low == "matrix":
in_matrix = True
continue
if in_matrix:
if stripped == ";" or low.startswith("end"):
in_matrix = False
continue
parts = stripped.split()
if len(parts) >= 2:
name, seq = parts[0], parts[1]
if name not in seqs:
order.append(name)
seqs[name] = []
seqs[name].append(seq)
records: list[tuple[str, str, str, str]] = []
for name in order:
full_seq = "".join(seqs[name]).upper()
acc, db = parse_identifier(">" + name)
org = _extract_org_hint(">" + name)
records.append((acc, db, full_seq, org))
return records
def parse_alignment(path: str) -> list[tuple[str, str, str, str]]:
"""Auto-detect format and parse an alignment file.
Supported formats: FASTA, Stockholm, Clustal, NEXUS.
"""
fmt = detect_format(path)
if fmt == "stockholm":
return parse_stockholm(path)
if fmt == "clustal":
return parse_clustal(path)
if fmt == "nexus":
return parse_nexus(path)
return parse_fasta(path)
# ---------------------------------------------------------------------------
# Taxonomy – data structures
# ---------------------------------------------------------------------------
NCBI_BASE = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
UNIPROT_BASE = "https://rest.uniprot.org/uniprotkb"
# NCBI rate limit: ≤3 req/s without key, ≤10 req/s with key
_NCBI_DELAY = 0.34
_NCBI_DELAY_KEY = 0.11
@dataclass
class TaxNode:
taxon_id: int
name: str
rank: str # lowercase NCBI rank string, e.g. 'species', 'genus', 'no rank'
@dataclass
class TaxInfo:
taxon_id: int
scientific_name: str
lineage: list[TaxNode] = field(default_factory=list)
# lineage is ordered root → organism (organism itself is the last entry)
def at_rank(self, rank: str) -> TaxNode | None:
"""Return the lineage node whose rank matches, or None."""
rank = rank.strip().lower()
for node in self.lineage:
if node.rank == rank:
return node
return None
def available_ranks(self) -> list[str]:
return sorted({n.rank for n in self.lineage if n.rank != "no rank"})
# ---------------------------------------------------------------------------
# Taxonomy – persistent cache
# ---------------------------------------------------------------------------
_CACHE_VERSION = 1
_DEFAULT_CACHE = "~/.protein_conservation_cache.json"
class TaxCache:
"""
Persistent JSON cache for taxonomy lookups.
Two independent lookup tables are stored:
taxids – protein accession (str) → NCBI taxon ID (int)
taxonomy – NCBI taxon ID (int) → TaxInfo (full lineage)
Because a taxon ID is shared by many proteins, caching the taxonomy entry
keyed on the taxon ID avoids redundant NCBI Taxonomy calls for proteins
from the same organism.
The cache is loaded from disk in ``__init__`` and written back only when
``save()`` is called and new entries have been added (dirty flag). A safe
write-then-rename strategy prevents corruption on interrupted runs.
"""
def __init__(self, path: str) -> None:
self._path = pathlib.Path(path).expanduser()
self._taxids: dict[str, int] = {}
self._taxonomy: dict[int, TaxInfo] = {}
self._protein_names: dict[str, str] = {} # accession → protein name
self._dirty = False
self._load()
# ------------------------------------------------------------------
# Serialisation helpers
# ------------------------------------------------------------------
@staticmethod
def _info_to_dict(info: TaxInfo) -> dict:
return {
"taxon_id": info.taxon_id,
"scientific_name": info.scientific_name,
"lineage": [
{"taxon_id": n.taxon_id, "name": n.name, "rank": n.rank}
for n in info.lineage
],
}
@staticmethod
def _dict_to_info(d: dict) -> TaxInfo:
return TaxInfo(
taxon_id=d["taxon_id"],
scientific_name=d["scientific_name"],
lineage=[
TaxNode(taxon_id=n["taxon_id"], name=n["name"], rank=n["rank"])
for n in d.get("lineage", [])
],
)
# ------------------------------------------------------------------
# Persistence
# ------------------------------------------------------------------
def _load(self) -> None:
if not self._path.exists():
return
try:
with self._path.open() as fh:
data = json.load(fh)
if data.get("version") != _CACHE_VERSION:
return # incompatible format – start fresh
self._taxids = {k: int(v) for k, v in data.get("taxids", {}).items()}
self._taxonomy = {
int(k): self._dict_to_info(v)
for k, v in data.get("taxonomy", {}).items()
}
self._protein_names = dict(data.get("protein_names", {}))
except Exception as exc:
print(f" Warning: cache file {self._path} could not be read "
f"({exc}); starting with empty cache.", file=sys.stderr)
def save(self) -> None:
"""Flush new entries to disk; no-op when nothing changed."""
if not self._dirty:
return
payload = {
"version": _CACHE_VERSION,
"taxids": self._taxids,
"taxonomy": {
str(k): self._info_to_dict(v)
for k, v in self._taxonomy.items()
},
"protein_names": self._protein_names,
}
try:
self._path.parent.mkdir(parents=True, exist_ok=True)
tmp = self._path.with_suffix(".tmp")
with tmp.open("w") as fh:
json.dump(payload, fh, indent=2)
tmp.replace(self._path)
self._dirty = False
except Exception as exc:
print(f" Warning: could not write cache to {self._path}: {exc}",
file=sys.stderr)
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def get_taxid(self, accession: str) -> int | None:
return self._taxids.get(accession)
def set_taxid(self, accession: str, taxid: int) -> None:
if self._taxids.get(accession) != taxid:
self._taxids[accession] = taxid
self._dirty = True
def get_taxonomy(self, taxid: int) -> TaxInfo | None:
return self._taxonomy.get(taxid)
def set_taxonomy(self, taxid: int, info: TaxInfo) -> None:
if taxid not in self._taxonomy:
self._taxonomy[taxid] = info
self._dirty = True
def get_protein_name(self, accession: str) -> str:
"""Return the cached protein name for *accession* (empty if absent)."""
return self._protein_names.get(accession, "")
def set_protein_name(self, accession: str, name: str) -> None:
if name and self._protein_names.get(accession) != name:
self._protein_names[accession] = name
self._dirty = True
def stats(self) -> tuple[int, int]:
"""Return (n_accessions_cached, n_taxa_cached)."""
return len(self._taxids), len(self._taxonomy)
# ---------------------------------------------------------------------------
# Taxonomy – API helpers
# ---------------------------------------------------------------------------
def _http_get(url: str, timeout: int = 20) -> str:
req = urllib.request.Request(
url, headers={"User-Agent": "protein_conservation/2.0 (github)"}
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read().decode()
def _ncbi_delay(api_key: str | None) -> None:
time.sleep(_NCBI_DELAY_KEY if api_key else _NCBI_DELAY)
def _taxonomy_from_ncbi(taxid: int, api_key: str | None = None) -> TaxInfo | None:
"""
Fetch full taxonomic lineage from the NCBI Taxonomy database.
Returns a TaxInfo with the complete LineageEx plus the organism itself.
"""
url = (f"{NCBI_BASE}/efetch.fcgi?db=taxonomy&id={taxid}&retmode=xml"
+ (f"&api_key={api_key}" if api_key else ""))
_ncbi_delay(api_key)
try:
body = _http_get(url)
except Exception:
return None
try:
root = ET.fromstring(body)
except ET.ParseError:
return None
taxon_el = root.find("Taxon")
if taxon_el is None:
return None
sci_name = taxon_el.findtext("ScientificName", "").strip()
rank = taxon_el.findtext("Rank", "no rank").strip().lower()
lineage: list[TaxNode] = []
lineage_ex = taxon_el.find("LineageEx")
if lineage_ex is not None:
for node in lineage_ex.findall("Taxon"):
lineage.append(TaxNode(
taxon_id=int(node.findtext("TaxId") or "0"),
name=node.findtext("ScientificName", "").strip(),
rank=node.findtext("Rank", "no rank").strip().lower(),
))
lineage.append(TaxNode(taxon_id=taxid, name=sci_name, rank=rank))
return TaxInfo(taxon_id=taxid, scientific_name=sci_name, lineage=lineage)
def _taxid_from_uniprot(accession: str) -> "tuple[int | None, str]":
"""
Look up the NCBI taxon ID for a UniProt accession via the UniProt REST API.
Returns ``(taxid, protein_name)`` where *protein_name* is the
recommended or submitted full protein name (empty string if unavailable).
"""
url = f"{UNIPROT_BASE}/{accession}.json"
try:
body = _http_get(url)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return None, ""
raise
data = json.loads(body)
taxid = data.get("organism", {}).get("taxonId")
# Extract protein name from the response
prot_name = ""
pdesc = data.get("proteinDescription", {})
rec = pdesc.get("recommendedName")
if rec:
prot_name = rec.get("fullName", {}).get("value", "")
if not prot_name:
sub = pdesc.get("submissionNames", [])
if sub:
prot_name = sub[0].get("fullName", {}).get("value", "")
return taxid, prot_name
def _taxid_from_ncbi_protein(accession: str, api_key: str | None = None) -> "tuple[int | None, str]":
"""
Look up the NCBI taxon ID for a GenBank/RefSeq protein accession.
Parses the taxon:XXXXXX qualifier from the GenPept source feature.
Returns ``(taxid, protein_name)`` where *protein_name* is the
``<GBSeq_definition>`` text (empty string if unavailable).
"""
url = (f"{NCBI_BASE}/efetch.fcgi?db=protein&id={accession}"
f"&rettype=gp&retmode=xml"
+ (f"&api_key={api_key}" if api_key else ""))
_ncbi_delay(api_key)
try:
body = _http_get(url)
except Exception:
return None, ""
try:
root = ET.fromstring(body)
except ET.ParseError:
return None, ""
# Extract protein name from <GBSeq_definition>
prot_name = ""
defn = root.findtext(".//GBSeq_definition")
if defn:
# Strip trailing "[Organism name]" bracket
prot_name = re.sub(r"\s*\[[^\[\]]+\]\s*$", "", defn).strip()
taxid = None
for qual in root.iter("GBQualifier"):
if qual.findtext("GBQualifier_name") == "db_xref":
val = qual.findtext("GBQualifier_value", "")
if val.startswith("taxon:"):
taxid = int(val.split(":")[1])
break
return taxid, prot_name
def fetch_taxonomy(accession: str, db_type: str,
api_key: str | None = None,
cache: "TaxCache | None" = None) -> "tuple[TaxInfo | None, bool, str]":
"""
Fetch full taxonomy for one protein accession.
Workflow
--------
UniProt → UniProt REST API (taxon ID) → NCBI Taxonomy (lineage)
GenBank → NCBI EUtils protein fetch → NCBI Taxonomy (lineage)
Both the accession→taxid mapping and the taxid→TaxInfo record are
checked in *cache* before making any network request, and stored there
after a successful fetch. The protein name obtained from the same API
call is cached separately for column labelling in focus-group output.
Returns ``(TaxInfo | None, from_cache: bool, protein_name: str)``.
"""
try:
# ── Step 1: resolve accession → taxon ID ──────────────────────────
taxid: "int | None" = cache.get_taxid(accession) if cache else None
taxid_from_cache = taxid is not None
prot_name: str = ""
if cache:
prot_name = cache.get_protein_name(accession)
if taxid is None:
if db_type == "uniprot":
taxid, prot_name = _taxid_from_uniprot(accession)
else:
taxid, prot_name = _taxid_from_ncbi_protein(accession, api_key)
if taxid is None:
return None, False, ""
if cache:
cache.set_taxid(accession, taxid)
if prot_name:
cache.set_protein_name(accession, prot_name)
# ── Step 2: resolve taxon ID → full lineage ────────────────────────
info: "TaxInfo | None" = cache.get_taxonomy(taxid) if cache else None
info_from_cache = info is not None
if info is None:
info = _taxonomy_from_ncbi(taxid, api_key)
if info is None:
return None, False, ""
if cache:
cache.set_taxonomy(taxid, info)
from_cache = taxid_from_cache and info_from_cache
return info, from_cache, prot_name
except Exception as exc:
_log.debug("fetch_taxonomy(%s): unexpected error: %s", accession, exc)
return None, False, ""
def fetch_all_taxonomies(
records: list[tuple[str, str, str]],
api_key: str | None = None,
cache: "TaxCache | None" = None,
) -> "tuple[dict[str, TaxInfo], dict[str, str]]":
"""
Fetch taxonomy for every record in *records*, printing progress.
Cache hits are served instantly without any network call and are
labelled ``[cached]`` in the progress output. After all records are
processed the cache is flushed to disk (if it is dirty).
Returns ``(tax_map, protein_names)`` where *tax_map* maps accession →
TaxInfo and *protein_names* maps accession → protein/product name
obtained from the database lookup (empty string when unavailable).
Accessions for which taxonomy cannot be retrieved are omitted from
*tax_map*.
"""
if cache:
n_acc, n_tax = cache.stats()
if n_acc or n_tax:
print(f" Cache: {n_acc} accession(s), {n_tax} taxon record(s) "
f"loaded from {cache._path}")
tax_map: dict[str, TaxInfo] = {}
prot_names: dict[str, str] = {}
n = len(records)
n_hits = 0
for idx, (acc, db, *_rest) in enumerate(records, 1):
print(f" [{idx}/{n}] {acc} ({db})… ", end="", flush=True)
info, from_cache, prot_name = fetch_taxonomy(acc, db, api_key, cache)
if prot_name:
prot_names[acc] = prot_name
if info is None:
print("not found – skipped")
else:
label = " [cached]" if from_cache else ""
print(f"{info.scientific_name}{label}")
tax_map[acc] = info
if from_cache:
n_hits += 1
if cache:
cache.save()
if n_hits:
print(f" {n_hits}/{n} record(s) served from cache "
f"(no network call needed).")
return tax_map, prot_names
# ---------------------------------------------------------------------------
# Taxonomy – rank-based conservation
# ---------------------------------------------------------------------------
def group_by_rank(
ids: list[str],
tax_map: dict[str, TaxInfo],
rank: str,
) -> dict[str, list[int]]:
"""
Return {taxon_name: [sequence_indices]} grouped by the given rank.
Sequences without taxonomy or without that rank are omitted.
"""
groups: dict[str, list[int]] = {}
for i, acc in enumerate(ids):
info = tax_map.get(acc)
if info is None:
continue
node = info.at_rank(rank)
if node is None:
continue
groups.setdefault(node.name, []).append(i)
return groups
def rank_conservation(
ids: list[str],
seqs: list[str],
sim_mat: list[list[float]],
tax_map: dict[str, TaxInfo],
rank: str,
n_bootstrap: int = 0,
) -> dict:
"""
Compute median pairwise similarity within and between taxa at *rank*.
Returns a dict with keys:
'rank' – the requested rank string
'groups' – {taxon_name: {'members': [accessions],
'intra_pairs': [(sim, id1, id2)],
'intra_median': float | None}}
'inter_pairs' – [(sim, taxon_a, taxon_b, id1, id2)]
'intra_median' – overall median across all within-group pairs
'inter_median' – overall median across all between-group pairs
"""
groups = group_by_rank(ids, tax_map, rank)
group_data: dict[str, dict] = {}
for taxon, indices in groups.items():
intra = [
(sim_mat[i][j], ids[i], ids[j])
for i, j in combinations(indices, 2)
]
group_data[taxon] = {
"members": [ids[i] for i in indices],
"intra_pairs": intra,
"intra_median": statistics.median(s for s, *_ in intra) if intra else None,
}
taxon_names = list(groups.keys())
inter_pairs: list[tuple] = []
for ta, tb in combinations(taxon_names, 2):
for i in groups[ta]:
for j in groups[tb]:
inter_pairs.append((sim_mat[i][j], ta, tb, ids[i], ids[j]))
all_intra = [s for g in group_data.values() for s, *_ in g["intra_pairs"]]
all_inter = [s for s, *_ in inter_pairs]
result = {
"rank": rank,
"groups": group_data,
"inter_pairs": inter_pairs,
"intra_median": statistics.median(all_intra) if all_intra else None,
"inter_median": statistics.median(all_inter) if all_inter else None,
"all_intra": all_intra,
"all_inter": all_inter,
"intra_ci": None,
"inter_ci": None,
}
if n_bootstrap > 0:
if all_intra:
result["intra_ci"] = bootstrap_ci(all_intra, n_bootstrap)
if all_inter:
result["inter_ci"] = bootstrap_ci(all_inter, n_bootstrap)
return result
def bootstrap_ci(
values: list[float],
n_bootstrap: int = 1000,
ci: float = 0.95,
seed: "int | None" = None,
) -> "tuple[float, float]":
"""
Percentile bootstrap 95% confidence interval for the median.
Returns ``(lower, upper)``.
"""
import random
if not values or n_bootstrap < 1:
return (float("nan"), float("nan"))
rng = random.Random(seed)
n = len(values)
medians: list[float] = []
for _ in range(n_bootstrap):
sample = [values[rng.randint(0, n - 1)] for _ in range(n)]
medians.append(statistics.median(sample))
medians.sort()
alpha = (1.0 - ci) / 2.0
lo_idx = max(0, int(math.floor(alpha * len(medians))))
hi_idx = min(len(medians) - 1, int(math.floor((1.0 - alpha) * len(medians))))
return (medians[lo_idx], medians[hi_idx])
def group_sim_matrix(rank_result: dict):
"""Build a group-level similarity matrix from a rank_conservation result.
Diagonal = per-group intra_median (1.0 when the group has only one member).
Off-diag = median of all pairwise similarities between the two groups.
Returns ``(group_names, sim_matrix)`` where *sim_matrix* is a
``list[list[float]]`` of size N×N (N = number of groups), suitable for
passing directly to ``plot_dendrogram`` or ``export_phyloxml``.
"""
groups = rank_result["groups"]
inter_pairs = rank_result["inter_pairs"] # (sim, ta, tb, id1, id2)
group_names = sorted(groups.keys())
n = len(group_names)
gidx = {name: i for i, name in enumerate(group_names)}
# Collect inter-group pairwise sims grouped by taxon pair
pair_sims: dict = {}
for sim, ta, tb, _id1, _id2 in inter_pairs:
key = (ta, tb) if ta <= tb else (tb, ta)
if key not in pair_sims:
pair_sims[key] = []
pair_sims[key].append(sim)
mat = [[0.0] * n for _ in range(n)]
# Diagonal: intra-group median (1.0 for singletons)
for name, gdata in groups.items():
i = gidx[name]
med = gdata["intra_median"]
mat[i][i] = med if med is not None else 1.0
# Off-diagonal: per-pair inter-group median
for (ta, tb), sims in pair_sims.items():
i, j = gidx[ta], gidx[tb]
med = statistics.median(sims) if sims else 0.0
mat[i][j] = med
mat[j][i] = med
return group_names, mat
def permutation_test_rank(
ids: list[str],
sim_mat: list[list[float]],
tax_map: dict[str, "TaxInfo"],
rank: str,
n_permutations: int = 1000,
seed: "int | None" = None,
) -> dict:
"""
Permutation test for rank-based conservation significance.
Observed test statistic: T = intra_median − inter_median.
Null distribution: shuffle group labels (preserving group sizes) and
recompute T for each permutation.
Returns a dict with keys:
'observed_stat' – observed T value (float | None)
'p_value' – fraction of permuted T ≥ observed T (float | None)
'n_permutations' – number of permutations actually run
'perm_mean' – mean of permuted T values (float | None)
'perm_stdev' – stdev of permuted T values (float | None)
'reason' – non-empty string if test could not run
"""
import random
result = rank_conservation(ids, [], sim_mat, tax_map, rank)
obs_intra = result["intra_median"]
obs_inter = result["inter_median"]
if obs_intra is None or obs_inter is None:
return {
"observed_stat": None, "p_value": None,
"n_permutations": 0, "perm_mean": None, "perm_stdev": None,
"reason": "cannot compute test statistic (need ≥2 groups with ≥2 members each)",
}
observed_stat = obs_intra - obs_inter
# Build the assignment vector: list of group labels parallel to ids
groups = result["groups"]
label_vector: list[str] = [""] * len(ids)
id_to_idx = {acc: i for i, acc in enumerate(ids)}
for taxon, gdata in groups.items():
for acc in gdata["members"]:
if acc in id_to_idx:
label_vector[id_to_idx[acc]] = taxon
# Only keep indices that were assigned to a group
valid_indices = [i for i, lbl in enumerate(label_vector) if lbl]
if len(valid_indices) < 4:
return {
"observed_stat": observed_stat, "p_value": None,
"n_permutations": 0, "perm_mean": None, "perm_stdev": None,
"reason": "too few sequences for permutation test",
}
# Preserve group sizes
group_sizes = [len(gdata["members"]) for gdata in groups.values()]
group_labels = list(groups.keys())
rng = random.Random(seed)
perm_stats: list[float] = []
for _ in range(n_permutations):
# Shuffle valid_indices, then re-assign group labels by size
shuffled = valid_indices[:]
rng.shuffle(shuffled)
perm_assignment: dict[int, str] = {}
pos = 0
for taxon, size in zip(group_labels, group_sizes):
for idx in shuffled[pos:pos + size]:
perm_assignment[idx] = taxon
pos += size
# Compute intra and inter medians for this permutation
intra_sims: list[float] = []
inter_sims: list[float] = []
for ii, jj in combinations(valid_indices, 2):
ta = perm_assignment.get(ii, "")
tb = perm_assignment.get(jj, "")
if not ta or not tb:
continue
if ta == tb:
intra_sims.append(sim_mat[ii][jj])
else:
inter_sims.append(sim_mat[ii][jj])