QPromaQ commited on
Commit
fc80ca6
·
verified ·
1 Parent(s): e5f7066

Reset repository and upload final project (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. .venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM30 +34 -0
  3. .venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM70 +34 -0
  4. .venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RAO +27 -0
  5. .venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RISLER +27 -0
  6. .venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/SCHNEIDER +70 -0
  7. .venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/STR +26 -0
  8. .venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/TRANS +12 -0
  9. .venv_haddock/lib/python3.12/site-packages/Bio/Align/tabular.py +408 -0
  10. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._ClustalIO.py +0 -0
  11. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._EmbossIO.py +0 -0
  12. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._FastaIO.py +0 -0
  13. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._Interfaces.py +0 -0
  14. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._MafIO.py +0 -0
  15. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._MauveIO.py +0 -0
  16. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._MsfIO.py +0 -0
  17. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._NexusIO.py +0 -0
  18. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._PhylipIO.py +0 -0
  19. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._StockholmIO.py +0 -0
  20. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/.___init__.py +0 -0
  21. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/.___pycache__ +0 -0
  22. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/ClustalIO.py +313 -0
  23. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/EmbossIO.py +220 -0
  24. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/FastaIO.py +346 -0
  25. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/Interfaces.py +158 -0
  26. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MafIO.py +869 -0
  27. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MauveIO.py +343 -0
  28. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MsfIO.py +333 -0
  29. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/NexusIO.py +173 -0
  30. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/PhylipIO.py +454 -0
  31. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/StockholmIO.py +620 -0
  32. .venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__init__.py +474 -0
  33. .venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/.___init__.py +0 -0
  34. .venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/.___pycache__ +0 -0
  35. .venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__init__.py +22 -0
  36. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/._NCBIWWW.py +0 -0
  37. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/._NCBIXML.py +0 -0
  38. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/.___init__.py +0 -0
  39. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/.___pycache__ +0 -0
  40. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/.__parser.py +0 -0
  41. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/.__writers.py +0 -0
  42. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIWWW.py +373 -0
  43. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIXML.py +1331 -0
  44. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/__init__.py +1352 -0
  45. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/_parser.py +1226 -0
  46. .venv_haddock/lib/python3.12/site-packages/Bio/Blast/_writers.py +1520 -0
  47. .venv_haddock/lib/python3.12/site-packages/Bio/CAPS/.___init__.py +0 -0
  48. .venv_haddock/lib/python3.12/site-packages/Bio/CAPS/.___pycache__ +0 -0
  49. .venv_haddock/lib/python3.12/site-packages/Bio/CAPS/__init__.py +130 -0
  50. .venv_haddock/lib/python3.12/site-packages/Bio/Cluster/.___init__.py +0 -0
.gitattributes CHANGED
@@ -62,3 +62,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
62
  .venv_haddock/bin/python3 filter=lfs diff=lfs merge=lfs -text
63
  .venv_haddock/bin/python3.12 filter=lfs diff=lfs merge=lfs -text
64
  .venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
 
 
62
  .venv_haddock/bin/python3 filter=lfs diff=lfs merge=lfs -text
63
  .venv_haddock/bin/python3.12 filter=lfs diff=lfs merge=lfs -text
64
  .venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
65
+ .venv_haddock/lib/python3.12/site-packages/Bio/Cluster/_cluster.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM30 ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This matrix was produced by "pam" Version 1.0.6 [28-Jul-93]
3
+ #
4
+ # PAM 30 substitution matrix, scale = ln(2)/2 = 0.346574
5
+ #
6
+ # Expected score = -5.06, Entropy = 2.57 bits
7
+ #
8
+ # Lowest score = -17, Highest score = 13
9
+ #
10
+ A R N D C Q E G H I L K M F P S T W Y V B Z X *
11
+ A 6 -7 -4 -3 -6 -4 -2 -2 -7 -5 -6 -7 -5 -8 -2 0 -1 -13 -8 -2 -3 -3 -3 -17
12
+ R -7 8 -6 -10 -8 -2 -9 -9 -2 -5 -8 0 -4 -9 -4 -3 -6 -2 -10 -8 -7 -4 -6 -17
13
+ N -4 -6 8 2 -11 -3 -2 -3 0 -5 -7 -1 -9 -9 -6 0 -2 -8 -4 -8 6 -3 -3 -17
14
+ D -3 -10 2 8 -14 -2 2 -3 -4 -7 -12 -4 -11 -15 -8 -4 -5 -15 -11 -8 6 1 -5 -17
15
+ C -6 -8 -11 -14 10 -14 -14 -9 -7 -6 -15 -14 -13 -13 -8 -3 -8 -15 -4 -6 -12 -14 -9 -17
16
+ Q -4 -2 -3 -2 -14 8 1 -7 1 -8 -5 -3 -4 -13 -3 -5 -5 -13 -12 -7 -3 6 -5 -17
17
+ E -2 -9 -2 2 -14 1 8 -4 -5 -5 -9 -4 -7 -14 -5 -4 -6 -17 -8 -6 1 6 -5 -17
18
+ G -2 -9 -3 -3 -9 -7 -4 6 -9 -11 -10 -7 -8 -9 -6 -2 -6 -15 -14 -5 -3 -5 -5 -17
19
+ H -7 -2 0 -4 -7 1 -5 -9 9 -9 -6 -6 -10 -6 -4 -6 -7 -7 -3 -6 -1 -1 -5 -17
20
+ I -5 -5 -5 -7 -6 -8 -5 -11 -9 8 -1 -6 -1 -2 -8 -7 -2 -14 -6 2 -6 -6 -5 -17
21
+ L -6 -8 -7 -12 -15 -5 -9 -10 -6 -1 7 -8 1 -3 -7 -8 -7 -6 -7 -2 -9 -7 -6 -17
22
+ K -7 0 -1 -4 -14 -3 -4 -7 -6 -6 -8 7 -2 -14 -6 -4 -3 -12 -9 -9 -2 -4 -5 -17
23
+ M -5 -4 -9 -11 -13 -4 -7 -8 -10 -1 1 -2 11 -4 -8 -5 -4 -13 -11 -1 -10 -5 -5 -17
24
+ F -8 -9 -9 -15 -13 -13 -14 -9 -6 -2 -3 -14 -4 9 -10 -6 -9 -4 2 -8 -10 -13 -8 -17
25
+ P -2 -4 -6 -8 -8 -3 -5 -6 -4 -8 -7 -6 -8 -10 8 -2 -4 -14 -13 -6 -7 -4 -5 -17
26
+ S 0 -3 0 -4 -3 -5 -4 -2 -6 -7 -8 -4 -5 -6 -2 6 0 -5 -7 -6 -1 -5 -3 -17
27
+ T -1 -6 -2 -5 -8 -5 -6 -6 -7 -2 -7 -3 -4 -9 -4 0 7 -13 -6 -3 -3 -6 -4 -17
28
+ W -13 -2 -8 -15 -15 -13 -17 -15 -7 -14 -6 -12 -13 -4 -14 -5 -13 13 -5 -15 -10 -14 -11 -17
29
+ Y -8 -10 -4 -11 -4 -12 -8 -14 -3 -6 -7 -9 -11 2 -13 -7 -6 -5 10 -7 -6 -9 -7 -17
30
+ V -2 -8 -8 -8 -6 -7 -6 -5 -6 2 -2 -9 -1 -8 -6 -6 -3 -15 -7 7 -8 -6 -5 -17
31
+ B -3 -7 6 6 -12 -3 1 -3 -1 -6 -9 -2 -10 -10 -7 -1 -3 -10 -6 -8 6 0 -5 -17
32
+ Z -3 -4 -3 1 -14 6 6 -5 -1 -6 -7 -4 -5 -13 -4 -5 -6 -14 -9 -6 0 6 -5 -17
33
+ X -3 -6 -3 -5 -9 -5 -5 -5 -5 -5 -6 -5 -5 -8 -5 -3 -4 -11 -7 -5 -5 -5 -5 -17
34
+ * -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 1
.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM70 ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # This matrix was produced by "pam" Version 1.0.6 [28-Jul-93]
3
+ #
4
+ # PAM 70 substitution matrix, scale = ln(2)/2 = 0.346574
5
+ #
6
+ # Expected score = -2.77, Entropy = 1.60 bits
7
+ #
8
+ # Lowest score = -11, Highest score = 13
9
+ #
10
+ A R N D C Q E G H I L K M F P S T W Y V B Z X *
11
+ A 5 -4 -2 -1 -4 -2 -1 0 -4 -2 -4 -4 -3 -6 0 1 1 -9 -5 -1 -1 -1 -2 -11
12
+ R -4 8 -3 -6 -5 0 -5 -6 0 -3 -6 2 -2 -7 -2 -1 -4 0 -7 -5 -4 -2 -3 -11
13
+ N -2 -3 6 3 -7 -1 0 -1 1 -3 -5 0 -5 -6 -3 1 0 -6 -3 -5 5 -1 -2 -11
14
+ D -1 -6 3 6 -9 0 3 -1 -1 -5 -8 -2 -7 -10 -4 -1 -2 -10 -7 -5 5 2 -3 -11
15
+ C -4 -5 -7 -9 9 -9 -9 -6 -5 -4 -10 -9 -9 -8 -5 -1 -5 -11 -2 -4 -8 -9 -6 -11
16
+ Q -2 0 -1 0 -9 7 2 -4 2 -5 -3 -1 -2 -9 -1 -3 -3 -8 -8 -4 -1 5 -2 -11
17
+ E -1 -5 0 3 -9 2 6 -2 -2 -4 -6 -2 -4 -9 -3 -2 -3 -11 -6 -4 2 5 -3 -11
18
+ G 0 -6 -1 -1 -6 -4 -2 6 -6 -6 -7 -5 -6 -7 -3 0 -3 -10 -9 -3 -1 -3 -3 -11
19
+ H -4 0 1 -1 -5 2 -2 -6 8 -6 -4 -3 -6 -4 -2 -3 -4 -5 -1 -4 0 1 -3 -11
20
+ I -2 -3 -3 -5 -4 -5 -4 -6 -6 7 1 -4 1 0 -5 -4 -1 -9 -4 3 -4 -4 -3 -11
21
+ L -4 -6 -5 -8 -10 -3 -6 -7 -4 1 6 -5 2 -1 -5 -6 -4 -4 -4 0 -6 -4 -4 -11
22
+ K -4 2 0 -2 -9 -1 -2 -5 -3 -4 -5 6 0 -9 -4 -2 -1 -7 -7 -6 -1 -2 -3 -11
23
+ M -3 -2 -5 -7 -9 -2 -4 -6 -6 1 2 0 10 -2 -5 -3 -2 -8 -7 0 -6 -3 -3 -11
24
+ F -6 -7 -6 -10 -8 -9 -9 -7 -4 0 -1 -9 -2 8 -7 -4 -6 -2 4 -5 -7 -9 -5 -11
25
+ P 0 -2 -3 -4 -5 -1 -3 -3 -2 -5 -5 -4 -5 -7 7 0 -2 -9 -9 -3 -4 -2 -3 -11
26
+ S 1 -1 1 -1 -1 -3 -2 0 -3 -4 -6 -2 -3 -4 0 5 2 -3 -5 -3 0 -2 -1 -11
27
+ T 1 -4 0 -2 -5 -3 -3 -3 -4 -1 -4 -1 -2 -6 -2 2 6 -8 -4 -1 -1 -3 -2 -11
28
+ W -9 0 -6 -10 -11 -8 -11 -10 -5 -9 -4 -7 -8 -2 -9 -3 -8 13 -3 -10 -7 -10 -7 -11
29
+ Y -5 -7 -3 -7 -2 -8 -6 -9 -1 -4 -4 -7 -7 4 -9 -5 -4 -3 9 -5 -4 -7 -5 -11
30
+ V -1 -5 -5 -5 -4 -4 -4 -3 -4 3 0 -6 0 -5 -3 -3 -1 -10 -5 6 -5 -4 -2 -11
31
+ B -1 -4 5 5 -8 -1 2 -1 0 -4 -6 -1 -6 -7 -4 0 -1 -7 -4 -5 5 1 -2 -11
32
+ Z -1 -2 -1 2 -9 5 5 -3 1 -4 -4 -2 -3 -9 -2 -2 -3 -10 -7 -4 1 5 -3 -11
33
+ X -2 -3 -2 -3 -6 -2 -3 -3 -3 -3 -4 -3 -3 -5 -3 -1 -2 -7 -5 -2 -2 -3 -3 -11
34
+ * -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 1
.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RAO ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # J.K. Mohana Rao:
2
+ # "New scoring matrix for amino acid residue exchanges based on residue
3
+ # characteristic physical parameters."
4
+ # International Journal of Peptide and Protein Research: 29(2): 276-281 (1987).
5
+ # Figure 1, lower triangle.
6
+ # PMID 3570667
7
+ A C D E F G H I K L M N P Q R S T V W Y
8
+ A 16 11 9 10 10 8 11 9 10 11 11 9 6 11 8 10 10 9 11 9
9
+ C 11 16 8 9 10 8 10 8 9 11 10 9 7 10 8 10 10 8 11 10
10
+ D 9 8 16 11 4 9 9 3 11 6 5 11 8 11 10 10 9 3 6 7
11
+ E 10 9 11 16 6 6 11 4 11 7 8 10 5 11 9 9 8 4 7 6
12
+ F 10 10 4 6 16 7 9 12 6 11 10 6 4 7 5 8 10 11 11 10
13
+ G 8 8 9 6 7 16 7 6 7 6 4 10 11 8 7 11 10 6 8 10
14
+ H 11 10 9 11 9 7 16 8 11 10 10 10 5 11 10 10 10 9 10 9
15
+ I 9 8 3 4 12 6 8 16 4 10 9 5 3 6 4 8 10 12 11 10
16
+ K 10 9 11 11 6 7 11 4 16 7 8 11 6 12 11 10 9 5 7 7
17
+ L 11 11 6 7 11 6 10 10 7 16 11 7 4 9 6 8 9 10 11 9
18
+ M 11 10 5 8 10 4 10 9 8 11 16 6 2 9 6 7 8 9 10 8
19
+ N 9 9 11 10 6 10 10 5 11 7 6 16 9 11 10 11 10 5 8 8
20
+ P 6 7 8 5 4 11 5 3 6 4 2 9 16 7 6 10 8 3 6 8
21
+ Q 11 10 11 11 7 8 11 6 12 9 9 11 7 16 10 10 10 6 9 8
22
+ R 8 8 10 9 5 7 10 4 11 6 6 10 6 10 16 9 9 5 7 7
23
+ S 10 10 10 9 8 11 10 8 10 8 7 11 10 10 9 16 11 8 10 11
24
+ T 10 10 9 8 10 10 10 10 9 9 8 10 8 10 9 11 16 10 11 11
25
+ V 9 8 3 4 11 6 9 12 5 10 9 5 3 6 5 8 10 16 11 10
26
+ W 11 11 6 7 11 8 10 11 7 11 10 8 6 9 7 10 11 11 16 11
27
+ Y 9 10 7 6 10 10 9 10 7 9 8 8 8 8 7 11 11 10 11 16
.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RISLER ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # J.L. Risler, M.O. Delorme, H. Delacroix, A. Henaut:
2
+ # "Amino acid substitutions in structurally related proteins. A pattern
3
+ # recognition approach. Determination of a new and efficient scoring matrix."
4
+ # Journal of Molecular Biology 204(4): 1019-1029 (1988).
5
+ # Figure 5.
6
+ # PMID 3221397
7
+ A C D E F G H I K L M N P Q R S T V W Y
8
+ A 2.2 -1.5 0.2 1.7 0.6 0.6 -0.6 1.7 1.4 1.3 1.0 1.3 -0.2 1.8 1.5 2.0 1.9 2.0 -0.9 0.2
9
+ C -1.5 2.2 -1.7 -1.5 -1.6 -1.7 -1.8 -1.6 -1.6 -1.5 -1.6 -1.6 -1.8 -1.4 -1.5 -1.3 -1.4 -1.4 -1.8 -1.1
10
+ D 0.2 -1.7 2.2 1.0 -0.3 -0.4 -1.3 0.0 0.1 -0.2 -0.5 0.8 -1.2 0.6 -0.1 0.7 0.0 0.0 -1.4 -0.4
11
+ E 1.7 -1.5 1.0 2.2 0.6 0.3 -0.6 1.5 1.4 0.9 0.6 1.4 -0.1 2.1 1.9 1.8 1.6 1.6 -1.0 0.2
12
+ F 0.6 -1.6 -0.3 0.6 2.2 -0.4 -1.1 1.0 0.1 1.0 -0.2 0.4 -1.1 0.7 0.4 0.5 0.3 0.8 -0.9 2.0
13
+ G 0.6 -1.7 -0.4 0.3 -0.4 2.2 -1.2 0.0 -0.1 -0.2 -0.4 0.2 -1.2 0.2 0.1 0.7 0.2 0.1 -1.3 -0.2
14
+ H -0.6 -1.8 -1.3 -0.6 -1.1 -1.2 2.2 -0.8 -1.0 -0.9 -1.2 -0.3 -1.6 -0.5 -0.4 -0.4 -0.9 -0.7 -1.7 -0.8
15
+ I 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1.4 -1.0 -0.9 -1.3 -1.7 -0.7 -1.1 -0.8 -1.3 -1.1 -1.6 -1.0 -0.8 -0.8 -1.0 -0.7 2.2 -0.6
27
+ Y 0.2 -1.1 -0.4 0.2 2.0 -0.2 -0.8 0.4 0.5 0.5 -0.2 -0.1 -1.2 0.5 0.8 0.4 0.3 0.3 -0.6 2.2
.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/SCHNEIDER ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adrian Schneider, Gina M. Cannarozzi, and Gaston H. Gonnet:
2
+ # "Empirical codon substitution matrix."
3
+ # BMC Bioinformatics 6:134 (2005).
4
+ # Additional File 3.
5
+ # PMID 15927081
6
+ AAA AAC AAG AAT ACA ACC ACG ACT AGA AGC AGG AGT ATA ATC ATG ATT CAA CAC CAG CAT CCA CCC CCG CCT CGA CGC CGG CGT CTA CTC CTG CTT GAA GAC GAG GAT GCA GCC GCG GCT GGA GGC GGG GGT GTA GTC GTG GTT TAA TAC TAG TAT TCA TCC TCG TCT TGA TGC TGG TGT TTA TTC TTG TTT
7
+ AAA 11.6 -2.7 9.7 -1.7 -2.7 -6.4 -3.9 -5.6 5.1 -5.0 3.6 -4.2 -6.3 -13.0 -7.1 -11.5 0.4 -6.0 -1.9 -5.3 -8.5 -11.2 -8.9 -10.8 2.1 0.0 1.4 0.2 -10.2 -13.5 -13.0 -12.5 -2.6 -8.5 -5.0 -8.1 -6.3 -9.9 -7.5 -9.0 -7.1 -10.2 -8.2 -9.2 -8.2 -12.5 -11.1 -11.4 -50.0 -14.8 -50.0 -13.8 -7.3 -10.1 -8.4 -9.1 -50.0 -13.0 -13.5 -12.4 -10.7 -18.1 -11.8 -17.2
8
+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3.1 -11.8 -4.4 -15.5 -14.3 -14.8 -15.4 -6.6 -4.7 -7.1 -5.8 -12.5 -10.3 -11.0 -12.2 -13.4 -10.6 -12.5 -11.8 -17.4 -15.1 -17.7 -15.7 2.9 12.5 3.1 10.3 -7.7 -5.2 -6.2 -7.3 -5.4 -1.7 -5.4 -3.7 -11.6 -9.1 -13.0 -10.8 -50.0 -10.3 -50.0 -11.2 -9.8 -8.3 -9.1 -9.7 -50.0 -12.7 -20.6 -13.1 -16.0 -16.6 -17.0 -18.4
41
+ GAG -5.0 -6.4 -3.4 -5.6 -7.5 -9.3 -7.1 -8.8 -8.8 -7.4 -6.9 -6.9 -11.4 -15.2 -9.7 -13.7 -1.8 -7.8 -0.8 -7.2 -9.4 -10.6 -8.7 -11.2 -10.0 -10.1 -7.8 -10.5 -13.2 -14.6 -13.0 -14.5 9.2 3.1 10.8 3.0 -4.5 -6.7 -2.7 -6.7 -5.0 -6.8 -2.5 -6.7 -7.5 -10.4 -7.4 -10.2 -50.0 -15.5 -50.0 -14.2 -8.9 -10.2 -8.5 -10.0 -50.0 -15.6 -15.3 -15.5 -13.0 -18.8 -12.6 -18.3
42
+ GAT -8.1 -1.1 -8.9 1.4 -8.6 -9.2 -9.4 -6.8 -11.0 -4.9 -11.5 -2.6 -13.7 -16.8 -14.5 -12.6 -6.0 -6.7 -7.2 -4.2 -11.6 -11.9 -11.2 -10.9 -13.1 -12.2 -12.5 -10.3 -16.8 -17.2 -17.8 -14.6 3.5 10.3 3.0 12.4 -6.9 -7.5 -6.8 -4.9 -5.4 -4.2 -5.4 -1.3 -10.8 -11.5 -12.4 -8.2 -50.0 -12.5 -50.0 -8.9 -9.2 -10.0 -9.4 -7.9 -50.0 -14.3 -19.9 -11.4 -16.2 -19.2 -15.8 -15.9
43
+ GCA -6.3 -7.4 -8.0 -6.0 2.8 -0.7 0.9 0.3 -7.5 -4.4 -8.4 -3.6 -3.0 -7.7 -3.7 -6.2 -5.3 -10.0 -7.2 -8.9 -0.7 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+ GTG -11.1 -11.9 -10.6 -11.3 -2.6 -4.1 -1.7 -3.5 -11.4 -9.6 -9.6 -9.2 3.7 2.5 1.6 2.5 -9.6 -12.3 -9.5 -11.8 -8.0 -9.4 -7.2 -9.3 -13.3 -12.8 -10.9 -12.6 -1.8 -2.9 -0.8 -2.9 -8.6 -13.0 -7.4 -12.4 -0.4 -2.3 1.3 -2.0 -8.1 -9.3 -5.4 -8.4 10.0 8.6 11.4 8.9 -50.0 -13.7 -50.0 -13.2 -6.1 -8.1 -5.5 -7.5 -50.0 -11.3 -12.7 -10.1 -1.6 -7.8 -0.3 -7.2
54
+ GTT -11.4 -10.0 -12.7 -8.2 -3.1 -3.1 -2.8 -0.9 -11.7 -7.3 -12.1 -5.8 3.6 3.6 -1.1 5.8 -9.4 -11.9 -10.7 -10.0 -8.5 -8.8 -8.2 -6.5 -13.9 -13.0 -12.9 -10.9 -3.1 -2.3 -3.2 -0.2 -9.5 -10.8 -10.2 -8.2 -1.1 -1.3 -0.8 1.2 -8.6 -7.8 -7.8 -5.0 9.0 9.5 8.9 12.0 -50.0 -13.0 -50.0 -10.3 -6.2 -7.0 -7.1 -5.4 -50.0 -9.3 -14.0 -8.2 -2.4 -6.3 -2.4 -3.9
55
+ TAA -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 33.3 -50.0 30.6 -50.0 -50.0 -50.0 -50.0 -50.0 29.2 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0
56
+ TAC -14.8 -6.2 -14.9 -7.6 -14.6 -11.6 -13.0 -12.2 -14.0 -9.0 -14.1 -10.1 -13.6 -11.2 -12.4 -12.5 -8.1 2.2 -8.7 0.4 -15.3 -11.3 -13.2 -13.3 -11.9 -7.2 -11.8 -7.9 -10.7 -7.4 -10.8 -8.9 -15.5 -10.3 -15.5 -12.5 -14.5 -12.1 -11.9 -12.8 -18.3 -12.7 -16.4 -14.7 -14.2 -10.4 -13.7 -13.0 -50.0 15.1 -50.0 13.3 -9.9 -5.8 -8.9 -7.6 -50.0 -1.5 -7.8 -3.0 -8.1 3.6 -9.4 2.0
57
+ TAG -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 30.6 -50.0 35.2 -50.0 -50.0 -50.0 -50.0 -50.0 28.5 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0
58
+ TAT -13.8 -7.5 -14.4 -5.1 -12.6 -11.6 -11.5 -10.1 -13.2 -9.7 -12.7 -7.4 -11.9 -11.9 -11.5 -10.2 -7.2 0.9 -8.6 2.6 -14.1 -12.8 -13.3 -11.0 -9.7 -8.4 -11.2 -5.3 -9.3 -8.7 -9.9 -7.1 -13.9 -11.2 -14.2 -8.9 -12.9 -12.6 -12.6 -10.9 -15.4 -13.8 -14.8 -11.4 -12.8 -11.6 -13.2 -10.3 -50.0 13.3 -50.0 15.2 -8.6 -7.0 -8.4 -4.8 -50.0 -3.0 -7.1 -0.1 -7.3 2.3 -8.7 3.9
59
+ TCA -7.3 -6.3 -8.9 -5.5 2.9 0.2 1.5 1.2 -8.5 -2.3 -10.0 -1.7 -5.6 -10.5 -5.5 -9.6 -4.3 -7.9 -6.1 -7.2 2.3 -0.6 0.5 -0.0 -8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 -7.2 -5.0 -6.5 -7.4 -7.5 -5.4 -50.0 -7.6 -50.0 -4.8 9.8 10.0 10.2 12.1 -50.0 -3.1 -11.4 -0.7 -4.6 -6.6 -4.9 -3.9
63
+ TGA -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 29.2 -50.0 28.5 -50.0 -50.0 -50.0 -50.0 -50.0 33.3 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0
64
+ TGC -13.0 -7.0 -13.1 -8.3 -9.2 -6.5 -8.9 -7.6 -9.8 -0.7 -9.2 -2.1 -12.4 -10.3 -12.4 -11.6 -9.5 -4.6 -10.4 -5.7 -13.6 -10.1 -11.4 -10.9 -6.5 -1.5 -6.2 -3.6 -12.8 -8.0 -12.3 -9.7 -16.5 -12.7 -15.6 -14.3 -8.7 -6.0 -7.1 -7.5 -9.5 -4.1 -8.4 -6.1 -11.0 -8.6 -11.3 -9.3 -50.0 -1.5 -50.0 -3.0 -4.8 -1.5 -4.2 -3.1 -50.0 16.4 -5.1 14.2 -10.1 -4.3 -10.0 -5.4
65
+ TGG -13.5 -16.3 -11.8 -15.5 -13.6 -15.3 -12.1 -16.1 -7.7 -13.3 -4.2 -12.6 -14.1 -16.2 -10.3 -15.4 -9.6 -11.6 -7.7 -9.8 -14.3 -17.5 -11.1 -17.2 -5.3 -7.1 -2.2 -7.1 -9.6 -11.9 -8.7 -11.4 -17.1 -20.6 -15.3 -19.9 -14.1 -14.8 -12.4 -16.5 -11.7 -12.8 -6.4 -13.4 -14.3 -15.7 -12.7 -14.0 -50.0 -7.8 -50.0 -7.1 -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
+ TTG -11.8 -13.1 -11.5 -12.0 -6.2 -8.3 -5.4 -7.4 -11.8 -12.3 -11.1 -11.4 0.5 -2.5 2.4 -1.6 -6.8 -9.9 -6.4 -8.9 -6.1 -8.6 -5.0 -7.8 -10.4 -11.6 -8.5 -9.9 8.2 6.4 8.7 6.9 -12.4 -17.0 -12.6 -15.8 -6.5 -8.5 -5.0 -7.8 -13.2 -13.6 -10.3 -13.7 -0.7 -3.2 -0.3 -2.4 -50.0 -9.4 -50.0 -8.7 -2.1 -5.6 -1.2 -4.9 -50.0 -10.0 -4.5 -8.9 9.7 -1.8 11.3 -0.9
70
+ TTT -17.2 -13.3 -17.8 -11.6 -11.0 -11.1 -10.4 -9.0 -16.0 -12.7 -16.1 -11.1 -5.2 -5.4 -6.0 -3.3 -11.8 -7.3 -13.3 -5.9 -12.7 -11.9 -11.9 -9.3 -15.2 -15.0 -14.9 -11.0 -2.8 -1.8 -2.9 0.4 -17.4 -18.4 -18.3 -15.9 -10.7 -11.2 -10.6 -9.0 -15.4 -14.8 -15.8 -13.3 -6.8 -5.9 -7.2 -3.9 -50.0 2.0 -50.0 3.9 -7.0 -6.8 -6.8 -3.9 -50.0 -5.4 -7.3 -3.4 -0.3 11.6 -0.9 14.1
.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/STR ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Steven Henikoff and Jorja G. Henikoff:
2
+ # "Performance evaluation of amino acid substitution matrices."
3
+ # Proteins: Structure, Function, and Genetics: 17(1): 49-61 (1993).
4
+ # Figure 1, lower triangle.
5
+ # PMID 8234244
6
+ A C D E F G H I K L M N P Q R S T V W Y
7
+ A 4 -2 -1 0 -3 0 -2 -2 -1 -2 0 -1 -1 0 -1 0 -1 0 -3 -3
8
+ C -2 11 -7 -3 -2 -6 -6 -4 -4 -6 -5 -6 -8 -3 -2 -4 -5 -4 -6 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3 -6 -3 -2 3 -3 0 -1 -2 -2 -1 -1 -6 -3 -1 -2 -2 -1 2 7
.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/TRANS ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # David Wheeler,
2
+ # Department of Cell Biology, Baylor College of Medicine, Houston, Texas:
3
+ # "Weight matrices for sequence similarity scoring."
4
+ # Version 2.0, May 1996.
5
+ # David Wheeler defined the Transition/Transversion Matrix as a penalty
6
+ # matrix; the matrix below is a similarity matrix where
7
+ # similarity = 5 - penalty.
8
+ A T C G
9
+ A 5 0 0 4
10
+ T 0 5 4 0
11
+ C 0 4 5 0
12
+ G 4 0 0 5
.venv_haddock/lib/python3.12/site-packages/Bio/Align/tabular.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 by Michiel de Hoon. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Bio.Align support for tabular output from BLAST or FASTA.
8
+
9
+ This module contains a parser for tabular output from BLAST run with the
10
+ '-outfmt 7' argument, as well as tabular output from William Pearson's
11
+ FASTA alignment tools using the '-m 8CB' or '-m 8CC' arguments.
12
+ """
13
+
14
+ import enum
15
+ import re
16
+
17
+ import numpy as np
18
+
19
+ from Bio.Align import Alignment
20
+ from Bio.Align import interfaces
21
+ from Bio.Seq import Seq
22
+ from Bio.SeqRecord import SeqRecord
23
+
24
+
25
+ class State(enum.Enum):
26
+ """Enumerate alignment states needed when parsing a BTOP string."""
27
+
28
+ MATCH = enum.auto()
29
+ QUERY_GAP = enum.auto()
30
+ TARGET_GAP = enum.auto()
31
+ NONE = enum.auto()
32
+
33
+
34
+ class AlignmentIterator(interfaces.AlignmentIterator):
35
+ """Alignment iterator for tabular output from BLAST or FASTA.
36
+
37
+ For reading (pairwise) alignments from tabular output generated by BLAST
38
+ run with the '-outfmt 7' argument, as well as tabular output generated by
39
+ William Pearson's FASTA alignment programs with the '-m 8CB' or '-m 8CC'
40
+ output formats.
41
+ """
42
+
43
+ fmt = "Tabular"
44
+
45
+ def _read_header(self, stream):
46
+ line = stream.readline()
47
+ if not line:
48
+ raise ValueError("Empty file.")
49
+ if not line.startswith("# "):
50
+ raise ValueError("Missing header.")
51
+ line = line.rstrip()
52
+ self._parse_header(stream, line)
53
+
54
+ def _parse_header(self, stream, line):
55
+ metadata = {}
56
+ blast_programs = (
57
+ "BLASTN",
58
+ "BLASTP",
59
+ "BLASTX",
60
+ "TBLASTN",
61
+ "TBLASTX",
62
+ "DELTABLAST",
63
+ "PSIBLAST",
64
+ "RPSBLAST",
65
+ "RPSTBLASTN",
66
+ )
67
+ try:
68
+ program, version = line[2:].split(None, 1)
69
+ if program not in blast_programs:
70
+ raise ValueError("Not a BLAST program")
71
+ except ValueError:
72
+ # FASTA
73
+ metadata["Command line"] = line[2:]
74
+ line = stream.readline()
75
+ assert line.startswith("# ")
76
+ metadata["Program"], metadata["Version"] = line[2:].rstrip().split(None, 1)
77
+ self._final_prefix = "# FASTA processed "
78
+ else:
79
+ # BLAST
80
+ metadata["Program"], metadata["Version"] = program, version
81
+ self._final_prefix = "# BLAST processed "
82
+ for line in stream:
83
+ line = line.strip()
84
+ assert line.startswith("# ")
85
+ try:
86
+ prefix, value = line[2:].split(": ")
87
+ except ValueError:
88
+ suffix = " hits found"
89
+ assert line.endswith(suffix)
90
+ hits = int(line[2 : -len(suffix)])
91
+ break
92
+ if prefix == "Query":
93
+ if metadata["Program"] == "FASTA":
94
+ query_line, query_size = value.rsplit(" - ", 1)
95
+ query_size, unit = query_size.split()
96
+ self._query_size = int(query_size)
97
+ assert unit in ("nt", "aa")
98
+ else:
99
+ query_line = value
100
+ self._query_size = None
101
+ try:
102
+ self._query_id, self._query_description = query_line.split(None, 1)
103
+ except ValueError:
104
+ self._query_id = query_line.strip()
105
+ self._query_description = None
106
+ elif prefix == "Database":
107
+ metadata["Database"] = value
108
+ elif prefix == "Fields":
109
+ self._fields = value.split(", ")
110
+ elif prefix == "RID":
111
+ metadata["RID"] = value
112
+ self.metadata = metadata
113
+
114
+ def _read_next_alignment(self, stream):
115
+ for line in stream:
116
+ line = line.rstrip()
117
+ if line.startswith("# "):
118
+ if line.startswith(self._final_prefix) and line.endswith(" queries"):
119
+ del self._fields
120
+ del self._query_id
121
+ del self._query_description
122
+ del self._query_size
123
+ del self._final_prefix
124
+ return
125
+ self._parse_header(stream, line)
126
+ else:
127
+ break
128
+ alignment_length = None
129
+ identical = None
130
+ btop = None
131
+ cigar = None
132
+ score = None
133
+ query_id = None
134
+ target_id = None
135
+ query_start = None
136
+ query_end = None
137
+ target_start = None
138
+ target_end = None
139
+ query_sequence = None
140
+ target_sequence = None
141
+ target_length = None
142
+ coordinates = None
143
+ query_size = self._query_size
144
+ columns = line.split("\t")
145
+ assert len(columns) == len(self._fields)
146
+ annotations = {}
147
+ query_annotations = {}
148
+ target_annotations = {}
149
+ for column, field in zip(columns, self._fields):
150
+ if field == "query id":
151
+ query_id = column
152
+ if self._query_id is not None:
153
+ assert query_id == self._query_id
154
+ elif field == "subject id":
155
+ target_id = column
156
+ elif field == "% identity":
157
+ annotations[field] = float(column)
158
+ elif field == "alignment length":
159
+ alignment_length = int(column)
160
+ elif field == "mismatches":
161
+ annotations[field] = int(column)
162
+ elif field == "gap opens":
163
+ annotations[field] = int(column)
164
+ elif field == "q. start":
165
+ query_start = int(column)
166
+ elif field == "q. end":
167
+ query_end = int(column)
168
+ elif field == "s. start":
169
+ target_start = int(column)
170
+ elif field == "s. end":
171
+ target_end = int(column)
172
+ elif field == "evalue":
173
+ annotations["evalue"] = float(column)
174
+ elif field == "bit score":
175
+ annotations["bit score"] = float(column)
176
+ elif field == "BTOP":
177
+ coordinates = self.parse_btop(column)
178
+ elif field == "aln_code":
179
+ coordinates = self.parse_cigar(column)
180
+ elif field == "query gi":
181
+ query_annotations["gi"] = column
182
+ elif field == "query acc.":
183
+ query_annotations["acc."] = column
184
+ elif field == "query acc.ver":
185
+ query_annotations["acc.ver"] = column
186
+ if query_id is None:
187
+ query_id = column
188
+ elif field == "query length":
189
+ if query_size is None:
190
+ query_size = int(column)
191
+ else:
192
+ assert query_size == int(column)
193
+ elif field == "subject ids":
194
+ target_annotations["ids"] = column
195
+ elif field == "subject gi":
196
+ target_annotations["gi"] = column
197
+ elif field == "subject gis":
198
+ target_annotations["gis"] = column
199
+ elif field == "subject acc.":
200
+ target_annotations["acc."] = column
201
+ elif field == "subject accs.":
202
+ target_annotations["accs."] = column
203
+ elif field == "subject tax ids":
204
+ target_annotations["tax ids"] = column
205
+ elif field == "subject sci names":
206
+ target_annotations["sci names"] = column
207
+ elif field == "subject com names":
208
+ target_annotations["com names"] = column
209
+ elif field == "subject blast names":
210
+ target_annotations["blast names"] = column
211
+ elif field == "subject super kingdoms":
212
+ target_annotations["super kingdoms"] = column
213
+ elif field == "subject title":
214
+ target_annotations["title"] = column
215
+ elif field == "subject titles":
216
+ target_annotations["titles"] = column
217
+ elif field == "subject strand":
218
+ target_annotations["strand"] = column
219
+ elif field == "% subject coverage":
220
+ target_annotations["% coverage"] = float(column)
221
+ elif field == "subject acc.ver":
222
+ target_annotations["acc.ver"] = column
223
+ if target_id is None:
224
+ target_id = column
225
+ elif field == "subject length":
226
+ target_length = int(column)
227
+ elif field == "query seq":
228
+ query_sequence = column
229
+ elif field == "subject seq":
230
+ target_sequence = column
231
+ elif field == "score":
232
+ score = int(column)
233
+ elif field == "identical":
234
+ identical = int(column)
235
+ annotations[field] = identical
236
+ elif field == "positives":
237
+ annotations[field] = int(column)
238
+ elif field == "gaps":
239
+ annotations[field] = int(column)
240
+ elif field == "% positives":
241
+ annotations[field] = float(column)
242
+ elif field == "% hsp coverage":
243
+ annotations[field] = float(column)
244
+ elif field == "query/sbjct frames":
245
+ annotations[field] = column
246
+ elif field == "query frame":
247
+ query_annotations["frame"] = column
248
+ elif field == "sbjct frame":
249
+ target_annotations["frame"] = column
250
+ else:
251
+ raise ValueError("Unexpected field '%s'" % field)
252
+ program = self.metadata["Program"]
253
+ if coordinates is None:
254
+ if alignment_length is not None:
255
+ annotations["alignment length"] = alignment_length
256
+ # otherwise, get it from alignment.shape
257
+ if query_start is not None and query_end is not None:
258
+ if query_start < query_end:
259
+ query_start -= 1
260
+ else:
261
+ query_end -= 1
262
+ if target_start is not None and target_end is not None:
263
+ if target_start < target_end:
264
+ target_start -= 1
265
+ else:
266
+ target_end -= 1
267
+ if coordinates is None or program in ("BLASTX", "TBLASTX"):
268
+ if query_start is not None:
269
+ query_annotations["start"] = query_start
270
+ if query_end is not None:
271
+ query_annotations["end"] = query_end
272
+ elif coordinates is not None:
273
+ if query_start < query_end:
274
+ coordinates[1, :] += query_start
275
+ else:
276
+ # mapped to reverse strand
277
+ coordinates[1, :] = query_start - coordinates[1, :]
278
+ if coordinates is None or program in ("TBLASTN", "TBLASTX"):
279
+ if target_start is not None:
280
+ target_annotations["start"] = target_start
281
+ if target_end is not None:
282
+ target_annotations["end"] = target_end
283
+ elif coordinates is not None:
284
+ coordinates[0, :] += target_start
285
+ if query_sequence is None:
286
+ if query_size is None:
287
+ query_seq = None
288
+ else:
289
+ query_seq = Seq(None, length=query_size)
290
+ else:
291
+ query_sequence = query_sequence.replace("-", "")
292
+ if program == "TBLASTN":
293
+ assert len(query_sequence) == query_end - query_start
294
+ query_seq = Seq({query_start: query_sequence}, length=query_size)
295
+ elif program == "TBLASTX":
296
+ query_annotations["start"] = query_start
297
+ query_annotations["end"] = query_end
298
+ query_seq = Seq(query_sequence)
299
+ else:
300
+ raise Exception("Unknown program %s" % program)
301
+ query = SeqRecord(query_seq, id=query_id)
302
+ if self._query_description is not None:
303
+ query.description = self._query_description
304
+ if query_annotations:
305
+ query.annotations = query_annotations
306
+ if self.metadata["Program"] in ("TBLASTN", "TBLASTX"):
307
+ target_annotations["length"] = target_length
308
+ if target_sequence is None:
309
+ target_seq = None
310
+ else:
311
+ target_sequence = target_sequence.replace("-", "")
312
+ target_seq = Seq(target_sequence)
313
+ else:
314
+ if target_sequence is None:
315
+ if target_end is None:
316
+ target_seq = None
317
+ else:
318
+ target_seq = Seq(None, length=target_end)
319
+ else:
320
+ target_sequence = target_sequence.replace("-", "")
321
+ if target_start is not None and target_end is not None:
322
+ assert len(target_sequence) == target_end - target_start
323
+ target_seq = Seq({target_start: target_sequence}, length=target_end)
324
+ target = SeqRecord(target_seq, id=target_id)
325
+ if target_annotations:
326
+ target.annotations = target_annotations
327
+ records = [target, query]
328
+ alignment = Alignment(records, coordinates)
329
+ alignment.annotations = annotations
330
+ if score is not None:
331
+ alignment.score = score
332
+ return alignment
333
+
334
+ def parse_btop(self, btop):
335
+ """Parse a BTOP string and return alignment coordinates.
336
+
337
+ A BTOP (Blast trace-back operations) string is used by BLAST to
338
+ describe a sequence alignment.
339
+ """
340
+ target_coordinates = []
341
+ query_coordinates = []
342
+ target_coordinates.append(0)
343
+ query_coordinates.append(0)
344
+ state = State.NONE
345
+ tokens = re.findall("([A-Z-*]{2}|\\d+)", btop)
346
+ # each token is now
347
+ # - an integer
348
+ # - a pair of characters, which may include dashes
349
+ for token in tokens:
350
+ if token.startswith("-"):
351
+ if state != State.QUERY_GAP:
352
+ target_coordinates.append(target_coordinates[-1])
353
+ query_coordinates.append(query_coordinates[-1])
354
+ state = State.QUERY_GAP
355
+ target_coordinates[-1] += 1
356
+ elif token.endswith("-"):
357
+ if state != State.TARGET_GAP:
358
+ target_coordinates.append(target_coordinates[-1])
359
+ query_coordinates.append(query_coordinates[-1])
360
+ state = State.TARGET_GAP
361
+ query_coordinates[-1] += 1
362
+ else:
363
+ try:
364
+ length = int(token)
365
+ except ValueError:
366
+ # pair of mismatched letters
367
+ length = 1
368
+ if state == State.MATCH:
369
+ target_coordinates[-1] += length
370
+ query_coordinates[-1] += length
371
+ else:
372
+ target_coordinates.append(target_coordinates[-1] + length)
373
+ query_coordinates.append(query_coordinates[-1] + length)
374
+ state = State.MATCH
375
+ coordinates = np.array([target_coordinates, query_coordinates], np.intp)
376
+ return coordinates
377
+
378
+ def parse_cigar(self, cigar):
379
+ """Parse a CIGAR string and return alignment coordinates.
380
+
381
+ A CIGAR string, as defined by the SAM Sequence Alignment/Map format,
382
+ describes a sequence alignment as a series of lengths and operation
383
+ (alignment/insertion/deletion) codes.
384
+ """
385
+ target_coordinates = []
386
+ query_coordinates = []
387
+ target_coordinate = 0
388
+ query_coordinate = 0
389
+ target_coordinates.append(target_coordinate)
390
+ query_coordinates.append(query_coordinate)
391
+ state = State.NONE
392
+ tokens = re.findall("(M|D|I|\\d+)", cigar)
393
+ # each token is now
394
+ # - the length of the operation
395
+ # - the operation
396
+ for length, operation in zip(tokens[::2], tokens[1::2]):
397
+ length = int(length)
398
+ if operation == "M":
399
+ target_coordinate += length
400
+ query_coordinate += length
401
+ elif operation == "I":
402
+ target_coordinate += length
403
+ elif operation == "D":
404
+ query_coordinate += length
405
+ target_coordinates.append(target_coordinate)
406
+ query_coordinates.append(query_coordinate)
407
+ coordinates = np.array([target_coordinates, query_coordinates], np.intp)
408
+ return coordinates
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._ClustalIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._EmbossIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._FastaIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._Interfaces.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._MafIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._MauveIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._MsfIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._NexusIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._PhylipIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/._StockholmIO.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/.___init__.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/.___pycache__ ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/ClustalIO.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006-2016 by Peter Cock. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Bio.AlignIO support for "clustal" output from CLUSTAL W and other tools.
8
+
9
+ You are expected to use this module via the Bio.AlignIO functions (or the
10
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
11
+ """
12
+
13
+ from Bio.Align import MultipleSeqAlignment
14
+ from Bio.AlignIO.Interfaces import AlignmentIterator
15
+ from Bio.AlignIO.Interfaces import SequentialAlignmentWriter
16
+ from Bio.Seq import Seq
17
+ from Bio.SeqRecord import SeqRecord
18
+
19
+
20
+ class ClustalWriter(SequentialAlignmentWriter):
21
+ """Clustalw alignment writer."""
22
+
23
+ def write_alignment(self, alignment):
24
+ """Use this to write (another) single alignment to an open file."""
25
+ if len(alignment) == 0:
26
+ raise ValueError("Must have at least one sequence")
27
+ if alignment.get_alignment_length() == 0:
28
+ # This doubles as a check for an alignment object
29
+ raise ValueError("Non-empty sequences are required")
30
+
31
+ # Old versions of the parser in Bio.Clustalw used a ._version property
32
+ try:
33
+ version = str(alignment._version)
34
+ except AttributeError:
35
+ version = ""
36
+ if not version:
37
+ version = "1.81"
38
+ if version.startswith("2."):
39
+ # e.g. 2.0.x
40
+ output = f"CLUSTAL {version} multiple sequence alignment\n\n\n"
41
+ else:
42
+ # e.g. 1.81 or 1.83
43
+ output = f"CLUSTAL X ({version}) multiple sequence alignment\n\n\n"
44
+
45
+ cur_char = 0
46
+ max_length = len(alignment[0])
47
+
48
+ if max_length <= 0:
49
+ raise ValueError("Non-empty sequences are required")
50
+
51
+ if "clustal_consensus" in alignment.column_annotations:
52
+ star_info = alignment.column_annotations["clustal_consensus"]
53
+ else:
54
+ try:
55
+ # This was originally stored by Bio.Clustalw as ._star_info
56
+ star_info = alignment._star_info
57
+ except AttributeError:
58
+ star_info = None
59
+
60
+ # keep displaying sequences until we reach the end
61
+ while cur_char != max_length:
62
+ # calculate the number of sequences to show, which will
63
+ # be less if we are at the end of the sequence
64
+ if (cur_char + 50) > max_length:
65
+ show_num = max_length - cur_char
66
+ else:
67
+ show_num = 50
68
+
69
+ # go through all of the records and print out the sequences
70
+ # when we output, we do a nice 80 column output, although this
71
+ # may result in truncation of the ids.
72
+ for record in alignment:
73
+ # Make sure we don't get any spaces in the record
74
+ # identifier when output in the file by replacing
75
+ # them with underscores:
76
+ line = record.id[0:30].replace(" ", "_").ljust(36)
77
+ line += str(record.seq[cur_char : (cur_char + show_num)])
78
+ output += line + "\n"
79
+
80
+ # now we need to print out the star info, if we've got it
81
+ if star_info:
82
+ output += (
83
+ (" " * 36) + star_info[cur_char : (cur_char + show_num)] + "\n"
84
+ )
85
+
86
+ output += "\n"
87
+ cur_char += show_num
88
+
89
+ # Want a trailing blank new line in case the output is concatenated
90
+ self.handle.write(output + "\n")
91
+
92
+
93
+ class ClustalIterator(AlignmentIterator):
94
+ """Clustalw alignment iterator."""
95
+
96
+ _header = None # for caching lines between __next__ calls
97
+
98
+ def __next__(self):
99
+ """Parse the next alignment from the handle."""
100
+ handle = self.handle
101
+
102
+ if self._header is None:
103
+ line = handle.readline()
104
+ else:
105
+ # Header we saved from when we were parsing
106
+ # the previous alignment.
107
+ line = self._header
108
+ self._header = None
109
+
110
+ if not line:
111
+ raise StopIteration
112
+
113
+ # Whitelisted headers we know about
114
+ known_headers = [
115
+ "CLUSTAL",
116
+ "PROBCONS",
117
+ "MUSCLE",
118
+ "MSAPROBS",
119
+ "Kalign",
120
+ "Biopython",
121
+ ]
122
+ if line.strip().split()[0] not in known_headers:
123
+ raise ValueError(
124
+ "%s is not a known CLUSTAL header: %s"
125
+ % (line.strip().split()[0], ", ".join(known_headers))
126
+ )
127
+
128
+ # find the clustal version in the header line
129
+ version = None
130
+ for word in line.split():
131
+ if word[0] == "(" and word[-1] == ")":
132
+ word = word[1:-1]
133
+ if word[0] in "0123456789":
134
+ version = word
135
+ break
136
+
137
+ # There should be two blank lines after the header line
138
+ line = handle.readline()
139
+ while line.strip() == "":
140
+ line = handle.readline()
141
+
142
+ # If the alignment contains entries with the same sequence
143
+ # identifier (not a good idea - but seems possible), then this
144
+ # dictionary based parser will merge their sequences. Fix this?
145
+ ids = []
146
+ seqs = []
147
+ consensus = ""
148
+ seq_cols = None # Used to extract the consensus
149
+
150
+ # Use the first block to get the sequence identifiers
151
+ while True:
152
+ if line[0] != " " and line.strip() != "":
153
+ # Sequences identifier...
154
+ fields = line.rstrip().split()
155
+
156
+ # We expect there to be two fields, there can be an optional
157
+ # "sequence number" field containing the letter count.
158
+ if len(fields) < 2 or len(fields) > 3:
159
+ raise ValueError(f"Could not parse line:\n{line}")
160
+
161
+ ids.append(fields[0])
162
+ seqs.append(fields[1])
163
+
164
+ # Record the sequence position to get the consensus
165
+ if seq_cols is None:
166
+ start = len(fields[0]) + line[len(fields[0]) :].find(fields[1])
167
+ end = start + len(fields[1])
168
+ seq_cols = slice(start, end)
169
+ del start, end
170
+ assert fields[1] == line[seq_cols]
171
+
172
+ if len(fields) == 3:
173
+ # This MAY be an old style file with a letter count...
174
+ try:
175
+ letters = int(fields[2])
176
+ except ValueError:
177
+ raise ValueError(
178
+ f"Could not parse line, bad sequence number:\n{line}"
179
+ ) from None
180
+ if len(fields[1].replace("-", "")) != letters:
181
+ raise ValueError(
182
+ f"Could not parse line, invalid sequence number:\n{line}"
183
+ )
184
+ elif line[0] == " ":
185
+ # Sequence consensus line...
186
+ assert len(ids) == len(seqs)
187
+ assert len(ids) > 0
188
+ assert seq_cols is not None
189
+ consensus = line[seq_cols]
190
+ assert not line[: seq_cols.start].strip()
191
+ assert not line[seq_cols.stop :].strip()
192
+ # Check for blank line (or end of file)
193
+ line = handle.readline()
194
+ assert line.strip() == ""
195
+ break
196
+ else:
197
+ # No consensus
198
+ break
199
+ line = handle.readline()
200
+ if not line:
201
+ break # end of file
202
+
203
+ assert line.strip() == ""
204
+ assert seq_cols is not None
205
+
206
+ # Confirm all same length
207
+ for s in seqs:
208
+ assert len(s) == len(seqs[0])
209
+ if consensus:
210
+ assert len(consensus) == len(seqs[0])
211
+
212
+ # Loop over any remaining blocks...
213
+ done = False
214
+ while not done:
215
+ # There should be a blank line between each block.
216
+ # Also want to ignore any consensus line from the
217
+ # previous block.
218
+ while (not line) or line.strip() == "":
219
+ line = handle.readline()
220
+ if not line:
221
+ break # end of file
222
+ if not line:
223
+ break # end of file
224
+
225
+ if line.split(None, 1)[0] in known_headers:
226
+ # Found concatenated alignment.
227
+ self._header = line
228
+ break
229
+
230
+ for i in range(len(ids)):
231
+ if line[0] == " ":
232
+ raise ValueError(f"Unexpected line:\n{line!r}")
233
+ fields = line.rstrip().split()
234
+
235
+ # We expect there to be two fields, there can be an optional
236
+ # "sequence number" field containing the letter count.
237
+ if len(fields) < 2 or len(fields) > 3:
238
+ raise ValueError(f"Could not parse line:\n{line!r}")
239
+
240
+ if fields[0] != ids[i]:
241
+ raise ValueError(
242
+ "Identifiers out of order? Got '%s' but expected '%s'"
243
+ % (fields[0], ids[i])
244
+ )
245
+
246
+ if fields[1] != line[seq_cols]:
247
+ start = len(fields[0]) + line[len(fields[0]) :].find(fields[1])
248
+ if start != seq_cols.start:
249
+ raise ValueError("Old location %s -> %i:XX" % (seq_cols, start))
250
+ end = start + len(fields[1])
251
+ seq_cols = slice(start, end)
252
+ del start, end
253
+
254
+ # Append the sequence
255
+ seqs[i] += fields[1]
256
+ assert len(seqs[i]) == len(seqs[0])
257
+
258
+ if len(fields) == 3:
259
+ # This MAY be an old style file with a letter count...
260
+ try:
261
+ letters = int(fields[2])
262
+ except ValueError:
263
+ raise ValueError(
264
+ f"Could not parse line, bad sequence number:\n{line}"
265
+ ) from None
266
+ if len(seqs[i].replace("-", "")) != letters:
267
+ raise ValueError(
268
+ f"Could not parse line, invalid sequence number:\n{line}"
269
+ )
270
+
271
+ # Read in the next line
272
+ line = handle.readline()
273
+ # There should now be a consensus line
274
+ if consensus:
275
+ assert line[0] == " "
276
+ assert seq_cols is not None
277
+ consensus += line[seq_cols]
278
+ assert len(consensus) == len(seqs[0])
279
+ assert not line[: seq_cols.start].strip()
280
+ assert not line[seq_cols.stop :].strip()
281
+ # Read in the next line
282
+ line = handle.readline()
283
+
284
+ assert len(ids) == len(seqs)
285
+ if len(seqs) == 0 or len(seqs[0]) == 0:
286
+ raise StopIteration
287
+
288
+ if (
289
+ self.records_per_alignment is not None
290
+ and self.records_per_alignment != len(ids)
291
+ ):
292
+ raise ValueError(
293
+ "Found %i records in this alignment, told to expect %i"
294
+ % (len(ids), self.records_per_alignment)
295
+ )
296
+
297
+ records = (SeqRecord(Seq(s), id=i, description=i) for (i, s) in zip(ids, seqs))
298
+ alignment = MultipleSeqAlignment(records)
299
+ # TODO - Handle alignment annotation better, for now
300
+ # mimic the old parser in Bio.Clustalw
301
+ if version:
302
+ alignment._version = version
303
+ if consensus:
304
+ alignment_length = len(seqs[0])
305
+ if len(consensus) != alignment_length:
306
+ raise ValueError(
307
+ "Alignment length is %i, consensus length is %i, '%s'"
308
+ % (alignment_length, len(consensus), consensus)
309
+ )
310
+ alignment.column_annotations["clustal_consensus"] = consensus
311
+ # For backward compatibility prior to .column_annotations:
312
+ alignment._star_info = consensus
313
+ return alignment
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/EmbossIO.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2008-2016 by Peter Cock. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Bio.AlignIO support for "emboss" alignment output from EMBOSS tools.
8
+
9
+ You are expected to use this module via the Bio.AlignIO functions (or the
10
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
11
+
12
+ This module contains a parser for the EMBOSS pairs/simple file format, for
13
+ example from the alignret, water and needle tools.
14
+ """
15
+
16
+ from Bio.Align import MultipleSeqAlignment
17
+ from Bio.AlignIO.Interfaces import AlignmentIterator
18
+ from Bio.Seq import Seq
19
+ from Bio.SeqRecord import SeqRecord
20
+
21
+
22
+ class EmbossIterator(AlignmentIterator):
23
+ """Emboss alignment iterator.
24
+
25
+ For reading the (pairwise) alignments from EMBOSS tools in what they
26
+ call the "pairs" and "simple" formats.
27
+ """
28
+
29
+ _header = None # for caching lines between __next__ calls
30
+
31
+ def __next__(self):
32
+ """Parse the next alignment from the handle."""
33
+ handle = self.handle
34
+
35
+ if self._header is None:
36
+ line = handle.readline()
37
+ else:
38
+ # Header we saved from when we were parsing
39
+ # the previous alignment.
40
+ line = self._header
41
+ self._header = None
42
+
43
+ if not line:
44
+ raise StopIteration
45
+
46
+ while line.rstrip() != "#=======================================":
47
+ line = handle.readline()
48
+ if not line:
49
+ raise StopIteration
50
+
51
+ length_of_seqs = None
52
+ number_of_seqs = None
53
+ ids = []
54
+ header_dict = {}
55
+
56
+ while line[0] == "#":
57
+ # Read in the rest of this alignment header,
58
+ # try and discover the number of records expected
59
+ # and their length
60
+ parts = line[1:].split(":", 1)
61
+ key = parts[0].lower().strip()
62
+ if key == "aligned_sequences":
63
+ number_of_seqs = int(parts[1].strip())
64
+ assert len(ids) == 0
65
+ # Should now expect the record identifiers...
66
+ for i in range(number_of_seqs):
67
+ line = handle.readline()
68
+ parts = line[1:].strip().split(":", 1)
69
+ assert i + 1 == int(parts[0].strip())
70
+ ids.append(parts[1].strip())
71
+ assert len(ids) == number_of_seqs
72
+ if key == "length":
73
+ length_of_seqs = int(parts[1].strip())
74
+
75
+ # Parse the rest of the header
76
+ if key == "identity":
77
+ header_dict["identity"] = int(parts[1].strip().split("/")[0])
78
+ if key == "similarity":
79
+ header_dict["similarity"] = int(parts[1].strip().split("/")[0])
80
+ if key == "gaps":
81
+ header_dict["gaps"] = int(parts[1].strip().split("/")[0])
82
+ if key == "score":
83
+ header_dict["score"] = float(parts[1].strip())
84
+
85
+ # And read in another line...
86
+ line = handle.readline()
87
+
88
+ if number_of_seqs is None:
89
+ raise ValueError("Number of sequences missing!")
90
+ if length_of_seqs is None:
91
+ raise ValueError("Length of sequences missing!")
92
+
93
+ if (
94
+ self.records_per_alignment is not None
95
+ and self.records_per_alignment != number_of_seqs
96
+ ):
97
+ raise ValueError(
98
+ "Found %i records in this alignment, told to expect %i"
99
+ % (number_of_seqs, self.records_per_alignment)
100
+ )
101
+
102
+ seqs = [""] * len(ids)
103
+ seq_starts = []
104
+ index = 0
105
+
106
+ # Parse the seqs
107
+ while line:
108
+ if len(line) > 21:
109
+ id_start = line[:21].strip().split(None, 1)
110
+ seq_end = line[21:].strip().split(None, 1)
111
+ if len(id_start) == 2 and len(seq_end) == 2:
112
+ # identifier, seq start position, seq, seq end position
113
+ # (an aligned seq is broken up into multiple lines)
114
+ id, start = id_start
115
+ seq, end = seq_end
116
+ if start >= end:
117
+ # Special case, either a single letter is present,
118
+ # or no letters at all.
119
+ if seq.replace("-", "") == "":
120
+ start = int(start)
121
+ end = int(end)
122
+ else:
123
+ start = int(start) - 1
124
+ end = int(end)
125
+ else:
126
+ assert seq.replace("-", "") != "", repr(line)
127
+ start = int(start) - 1 # python counting
128
+ end = int(end)
129
+
130
+ if index < 0 or index >= number_of_seqs:
131
+ raise ValueError(
132
+ "Expected index %i in range [0,%i)"
133
+ % (index, number_of_seqs)
134
+ )
135
+ # The identifier is truncated...
136
+ assert id == ids[index] or id == ids[index][: len(id)]
137
+
138
+ if len(seq_starts) == index:
139
+ # Record the start
140
+ seq_starts.append(start)
141
+
142
+ # Check the start...
143
+ if start >= end:
144
+ assert seq.replace("-", "") == "", line
145
+ elif start - seq_starts[index] != len(seqs[index].replace("-", "")):
146
+ raise ValueError(
147
+ "Found %i chars so far for sequence %i (%s, %r), line says start %i:\n%s"
148
+ % (
149
+ len(seqs[index].replace("-", "")),
150
+ index,
151
+ id,
152
+ seqs[index],
153
+ start,
154
+ line,
155
+ )
156
+ )
157
+ seqs[index] += seq
158
+
159
+ # Check the end ...
160
+ if end != seq_starts[index] + len(seqs[index].replace("-", "")):
161
+ raise ValueError(
162
+ "Found %i chars so far for sequence %i (%s, %r, start=%i), file says end %i:\n%s"
163
+ % (
164
+ len(seqs[index].replace("-", "")),
165
+ index,
166
+ id,
167
+ seqs[index],
168
+ seq_starts[index],
169
+ end,
170
+ line,
171
+ )
172
+ )
173
+
174
+ index += 1
175
+ if index >= number_of_seqs:
176
+ index = 0
177
+ else:
178
+ # just a start value, this is just alignment annotation (?)
179
+ # print("Skipping: " + line.rstrip())
180
+ pass
181
+ elif line.strip() == "":
182
+ # Just a spacer?
183
+ pass
184
+ else:
185
+ raise ValueError(f"Unrecognised EMBOSS pairwise line: {line!r}\n")
186
+
187
+ line = handle.readline()
188
+ if (
189
+ line.rstrip() == "#---------------------------------------"
190
+ or line.rstrip() == "#======================================="
191
+ ):
192
+ # End of alignment
193
+ self._header = line
194
+ break
195
+
196
+ assert index == 0
197
+
198
+ if (
199
+ self.records_per_alignment is not None
200
+ and self.records_per_alignment != len(ids)
201
+ ):
202
+ raise ValueError(
203
+ "Found %i records in this alignment, told to expect %i"
204
+ % (len(ids), self.records_per_alignment)
205
+ )
206
+
207
+ records = []
208
+ for id, seq in zip(ids, seqs):
209
+ if len(seq) != length_of_seqs:
210
+ # EMBOSS 2.9.0 is known to use spaces instead of minus signs
211
+ # for leading gaps, and thus fails to parse. This old version
212
+ # is still used as of Dec 2008 behind the EBI SOAP webservice:
213
+ # http://www.ebi.ac.uk/Tools/webservices/wsdl/WSEmboss.wsdl
214
+ raise ValueError(
215
+ "Error parsing alignment - sequences of "
216
+ "different length? You could be using an "
217
+ "old version of EMBOSS."
218
+ )
219
+ records.append(SeqRecord(Seq(seq), id=id, description=id))
220
+ return MultipleSeqAlignment(records, annotations=header_dict)
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/FastaIO.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2008-2016 by Peter Cock. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Bio.AlignIO support for "fasta-m10" output from Bill Pearson's FASTA tools.
8
+
9
+ You are expected to use this module via the Bio.AlignIO functions (or the
10
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
11
+
12
+ This module contains a parser for the pairwise alignments produced by Bill
13
+ Pearson's FASTA tools, for use from the Bio.AlignIO interface where it is
14
+ referred to as the "fasta-m10" file format (as we only support the machine
15
+ readable output format selected with the -m 10 command line option).
16
+
17
+ This module does NOT cover the generic "fasta" file format originally
18
+ developed as an input format to the FASTA tools. The Bio.AlignIO and
19
+ Bio.SeqIO both use the Bio.SeqIO.FastaIO module to deal with these files,
20
+ which can also be used to store a multiple sequence alignments.
21
+ """
22
+
23
+ from Bio.Align import MultipleSeqAlignment
24
+ from Bio.Seq import Seq
25
+ from Bio.SeqRecord import SeqRecord
26
+
27
+
28
+ def _extract_alignment_region(alignment_seq_with_flanking, annotation):
29
+ """Extract alignment region (PRIVATE).
30
+
31
+ Helper function for the main parsing code.
32
+
33
+ To get the actual pairwise alignment sequences, we must first
34
+ translate the un-gapped sequence based coordinates into positions
35
+ in the gapped sequence (which may have a flanking region shown
36
+ using leading - characters). To date, I have never seen any
37
+ trailing flanking region shown in the m10 file, but the
38
+ following code should also cope with that.
39
+
40
+ Note that this code seems to work fine even when the "sq_offset"
41
+ entries are present as a result of using the -X command line option.
42
+ """
43
+ align_stripped = alignment_seq_with_flanking.strip("-")
44
+ display_start = int(annotation["al_display_start"])
45
+ if int(annotation["al_start"]) <= int(annotation["al_stop"]):
46
+ start = int(annotation["al_start"]) - display_start
47
+ end = int(annotation["al_stop"]) - display_start + 1
48
+ else:
49
+ # FASTA has flipped this sequence...
50
+ start = display_start - int(annotation["al_start"])
51
+ end = display_start - int(annotation["al_stop"]) + 1
52
+
53
+ end += align_stripped.count("-")
54
+ if start < 0 or start >= end or end > len(align_stripped):
55
+ raise ValueError(
56
+ "Problem with sequence start/stop,\n%s[%i:%i]\n%s"
57
+ % (alignment_seq_with_flanking, start, end, annotation)
58
+ )
59
+ return align_stripped[start:end]
60
+
61
+
62
+ def FastaM10Iterator(handle, seq_count=None):
63
+ """Alignment iterator for the FASTA tool's pairwise alignment output.
64
+
65
+ This is for reading the pairwise alignments output by Bill Pearson's
66
+ FASTA program when called with the -m 10 command line option for machine
67
+ readable output. For more details about the FASTA tools, see the website
68
+ http://fasta.bioch.virginia.edu/ and the paper:
69
+
70
+ W.R. Pearson & D.J. Lipman PNAS (1988) 85:2444-2448
71
+
72
+ This class is intended to be used via the Bio.AlignIO.parse() function
73
+ by specifying the format as "fasta-m10" as shown in the following code::
74
+
75
+ from Bio import AlignIO
76
+ handle = ...
77
+ for a in AlignIO.parse(handle, "fasta-m10"):
78
+ assert len(a) == 2, "Should be pairwise!"
79
+ print("Alignment length %i" % a.get_alignment_length())
80
+ for record in a:
81
+ print("%s %s %s" % (record.seq, record.name, record.id))
82
+
83
+ Note that this is not a full blown parser for all the information
84
+ in the FASTA output - for example, most of the header and all of the
85
+ footer is ignored. Also, the alignments are not batched according to
86
+ the input queries.
87
+
88
+ Also note that there can be up to about 30 letters of flanking region
89
+ included in the raw FASTA output as contextual information. This is NOT
90
+ part of the alignment itself, and is not included in the resulting
91
+ MultipleSeqAlignment objects returned.
92
+ """
93
+ state_PREAMBLE = -1
94
+ state_NONE = 0
95
+ state_QUERY_HEADER = 1
96
+ state_ALIGN_HEADER = 2
97
+ state_ALIGN_QUERY = 3
98
+ state_ALIGN_MATCH = 4
99
+ state_ALIGN_CONS = 5
100
+
101
+ def build_hsp():
102
+ if not query_tags and not match_tags:
103
+ raise ValueError(f"No data for query {query_id!r}, match {match_id!r}")
104
+ assert query_tags, query_tags
105
+ assert match_tags, match_tags
106
+ evalue = align_tags.get("fa_expect")
107
+ tool = global_tags.get("tool", "").upper()
108
+
109
+ q = _extract_alignment_region(query_seq, query_tags)
110
+ if tool in ["TFASTX"] and len(match_seq) == len(q):
111
+ m = match_seq
112
+ # Quick hack until I can work out how -, * and / characters
113
+ # and the apparent mix of aa and bp coordinates works.
114
+ else:
115
+ m = _extract_alignment_region(match_seq, match_tags)
116
+ if len(q) != len(m):
117
+ raise ValueError(
118
+ f"""\
119
+ Darn... amino acids vs nucleotide coordinates?
120
+ tool: {tool}
121
+ query_seq: {query_seq}
122
+ query_tags: {query_tags}
123
+ {q} length: {len(q)}
124
+ match_seq: {match_seq}
125
+ match_tags: {match_tags}
126
+ {m} length: {len(m)}
127
+ handle.name: {handle.name}
128
+ """
129
+ )
130
+
131
+ annotations = {}
132
+ records = []
133
+
134
+ # Want to record both the query header tags, and the alignment tags.
135
+ annotations.update(header_tags)
136
+ annotations.update(align_tags)
137
+
138
+ # Query
139
+ # =====
140
+ record = SeqRecord(
141
+ Seq(q),
142
+ id=query_id,
143
+ name="query",
144
+ description=query_descr,
145
+ annotations={"original_length": int(query_tags["sq_len"])},
146
+ )
147
+ # TODO - handle start/end coordinates properly. Short term hack for now:
148
+ record._al_start = int(query_tags["al_start"])
149
+ record._al_stop = int(query_tags["al_stop"])
150
+
151
+ # TODO - Can FASTA output RNA?
152
+ if "sq_type" in query_tags:
153
+ if query_tags["sq_type"] == "D":
154
+ record.annotations["molecule_type"] = "DNA"
155
+ elif query_tags["sq_type"] == "p":
156
+ record.annotations["molecule_type"] = "protein"
157
+
158
+ records.append(record)
159
+
160
+ # Match
161
+ # =====
162
+ record = SeqRecord(
163
+ Seq(m),
164
+ id=match_id,
165
+ name="match",
166
+ description=match_descr,
167
+ annotations={"original_length": int(match_tags["sq_len"])},
168
+ )
169
+ # TODO - handle start/end coordinates properly. Short term hack for now:
170
+ record._al_start = int(match_tags["al_start"])
171
+ record._al_stop = int(match_tags["al_stop"])
172
+
173
+ if "sq_type" in match_tags:
174
+ if match_tags["sq_type"] == "D":
175
+ record.annotations["molecule_type"] = "DNA"
176
+ elif match_tags["sq_type"] == "p":
177
+ record.annotations["molecule_type"] = "protein"
178
+
179
+ records.append(record)
180
+
181
+ return MultipleSeqAlignment(records, annotations=annotations)
182
+
183
+ state = state_PREAMBLE
184
+ query_id = None
185
+ match_id = None
186
+ query_descr = ""
187
+ match_descr = ""
188
+ global_tags = {}
189
+ header_tags = {}
190
+ align_tags = {}
191
+ query_tags = {}
192
+ match_tags = {}
193
+ query_seq = ""
194
+ match_seq = ""
195
+ cons_seq = ""
196
+ for line in handle:
197
+ if ">>>" in line and not line.startswith(">>>"):
198
+ if query_id and match_id:
199
+ # This happens on old FASTA output which lacked an end of
200
+ # query >>><<< marker line.
201
+ yield build_hsp()
202
+ state = state_NONE
203
+ query_descr = line[line.find(">>>") + 3 :].strip()
204
+ query_id = query_descr.split(None, 1)[0]
205
+ match_id = None
206
+ header_tags = {}
207
+ align_tags = {}
208
+ query_tags = {}
209
+ match_tags = {}
210
+ query_seq = ""
211
+ match_seq = ""
212
+ cons_seq = ""
213
+ elif line.startswith("!! No "):
214
+ # e.g.
215
+ # !! No library sequences with E() < 0.5
216
+ # or on more recent versions,
217
+ # No sequences with E() < 0.05
218
+ assert state == state_NONE
219
+ assert not header_tags
220
+ assert not align_tags
221
+ assert not match_tags
222
+ assert not query_tags
223
+ assert match_id is None
224
+ assert not query_seq
225
+ assert not match_seq
226
+ assert not cons_seq
227
+ query_id = None
228
+ elif line.strip() in [">>><<<", ">>>///"]:
229
+ # End of query, possible end of all queries
230
+ if query_id and match_id:
231
+ yield build_hsp()
232
+ state = state_NONE
233
+ query_id = None
234
+ match_id = None
235
+ header_tags = {}
236
+ align_tags = {}
237
+ query_tags = {}
238
+ match_tags = {}
239
+ query_seq = ""
240
+ match_seq = ""
241
+ cons_seq = ""
242
+ elif line.startswith(">>>"):
243
+ # Should be start of a match!
244
+ assert query_id is not None
245
+ assert line[3:].split(", ", 1)[0] == query_id, line
246
+ assert match_id is None
247
+ assert not header_tags
248
+ assert not align_tags
249
+ assert not query_tags
250
+ assert not match_tags
251
+ assert not match_seq
252
+ assert not query_seq
253
+ assert not cons_seq
254
+ state = state_QUERY_HEADER
255
+ elif line.startswith(">>"):
256
+ # Should now be at start of a match alignment!
257
+ if query_id and match_id:
258
+ yield build_hsp()
259
+ align_tags = {}
260
+ query_tags = {}
261
+ match_tags = {}
262
+ query_seq = ""
263
+ match_seq = ""
264
+ cons_seq = ""
265
+ match_descr = line[2:].strip()
266
+ match_id = match_descr.split(None, 1)[0]
267
+ state = state_ALIGN_HEADER
268
+ elif line.startswith(">--"):
269
+ # End of one HSP
270
+ assert query_id and match_id, line
271
+ yield build_hsp()
272
+ # Clean up read for next HSP
273
+ # but reuse header_tags
274
+ align_tags = {}
275
+ query_tags = {}
276
+ match_tags = {}
277
+ query_seq = ""
278
+ match_seq = ""
279
+ cons_seq = ""
280
+ state = state_ALIGN_HEADER
281
+ elif line.startswith(">"):
282
+ if state == state_ALIGN_HEADER:
283
+ # Should be start of query alignment seq...
284
+ assert query_id is not None, line
285
+ assert match_id is not None, line
286
+ assert query_id.startswith(line[1:].split(None, 1)[0]), line
287
+ state = state_ALIGN_QUERY
288
+ elif state == state_ALIGN_QUERY:
289
+ # Should be start of match alignment seq
290
+ assert query_id is not None, line
291
+ assert match_id is not None, line
292
+ assert match_id.startswith(line[1:].split(None, 1)[0]), line
293
+ state = state_ALIGN_MATCH
294
+ elif state == state_NONE:
295
+ # Can get > as the last line of a histogram
296
+ pass
297
+ else:
298
+ raise RuntimeError("state %i got %r" % (state, line))
299
+ elif line.startswith("; al_cons"):
300
+ assert state == state_ALIGN_MATCH, line
301
+ state = state_ALIGN_CONS
302
+ # Next line(s) should be consensus seq...
303
+ elif line.startswith("; "):
304
+ if ": " in line:
305
+ key, value = (s.strip() for s in line[2:].split(": ", 1))
306
+ else:
307
+ import warnings
308
+
309
+ from Bio import BiopythonParserWarning
310
+
311
+ # Seen in lalign36, specifically version 36.3.4 Apr, 2011
312
+ # Fixed in version 36.3.5b Oct, 2011(preload8)
313
+ warnings.warn(
314
+ f"Missing colon in line: {line!r}", BiopythonParserWarning
315
+ )
316
+ try:
317
+ key, value = (s.strip() for s in line[2:].split(" ", 1))
318
+ except ValueError:
319
+ raise ValueError(f"Bad line: {line!r}") from None
320
+ if state == state_QUERY_HEADER:
321
+ header_tags[key] = value
322
+ elif state == state_ALIGN_HEADER:
323
+ align_tags[key] = value
324
+ elif state == state_ALIGN_QUERY:
325
+ query_tags[key] = value
326
+ elif state == state_ALIGN_MATCH:
327
+ match_tags[key] = value
328
+ else:
329
+ raise RuntimeError(f"Unexpected state {state!r}, {line!r}")
330
+ elif state == state_ALIGN_QUERY:
331
+ query_seq += line.strip()
332
+ elif state == state_ALIGN_MATCH:
333
+ match_seq += line.strip()
334
+ elif state == state_ALIGN_CONS:
335
+ cons_seq += line.strip("\n")
336
+ elif state == state_PREAMBLE:
337
+ if line.startswith("#"):
338
+ global_tags["command"] = line[1:].strip()
339
+ elif line.startswith(" version "):
340
+ global_tags["version"] = line[9:].strip()
341
+ elif " compares a " in line:
342
+ global_tags["tool"] = line[: line.find(" compares a ")].strip()
343
+ elif " searches a " in line:
344
+ global_tags["tool"] = line[: line.find(" searches a ")].strip()
345
+ else:
346
+ pass
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/Interfaces.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2008-2018 by Peter Cock. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """AlignIO support module (not for general use).
8
+
9
+ Unless you are writing a new parser or writer for Bio.AlignIO, you should not
10
+ use this module. It provides base classes to try and simplify things.
11
+ """
12
+
13
+
14
+ class AlignmentIterator:
15
+ """Base class for building MultipleSeqAlignment iterators.
16
+
17
+ You should write a next() method to return Alignment
18
+ objects. You may wish to redefine the __init__
19
+ method as well.
20
+ """
21
+
22
+ def __init__(self, handle, seq_count=None):
23
+ """Create an AlignmentIterator object.
24
+
25
+ Arguments:
26
+ - handle - input file
27
+ - count - optional, expected number of records per alignment
28
+ Recommend for fasta file format.
29
+
30
+ Note when subclassing:
31
+ - there should be a single non-optional argument, the handle,
32
+ and optional count IN THAT ORDER.
33
+ - you can add additional optional arguments.
34
+
35
+ """
36
+ self.handle = handle
37
+ self.records_per_alignment = seq_count
38
+ #####################################################
39
+ # You may want to subclass this, for example #
40
+ # to read through the file to find the first record,#
41
+ # or if additional arguments are required. #
42
+ #####################################################
43
+
44
+ def __next__(self):
45
+ """Return the next alignment in the file.
46
+
47
+ This method should be replaced by any derived class to do something
48
+ useful.
49
+ """
50
+ raise NotImplementedError("This object should be subclassed")
51
+ #####################################################
52
+ # You SHOULD subclass this, to split the file up #
53
+ # into your individual alignments and convert these #
54
+ # into MultipleSeqAlignment objects. #
55
+ #####################################################
56
+
57
+ def __iter__(self):
58
+ """Iterate over the entries as MultipleSeqAlignment objects.
59
+
60
+ Example usage for (concatenated) PHYLIP files::
61
+
62
+ with open("many.phy","r") as myFile:
63
+ for alignment in PhylipIterator(myFile):
64
+ print("New alignment:")
65
+ for record in alignment:
66
+ print(record.id)
67
+ print(record.seq)
68
+
69
+ """
70
+ return iter(self.__next__, None)
71
+
72
+
73
+ class AlignmentWriter:
74
+ """Base class for building MultipleSeqAlignment writers.
75
+
76
+ You should write a write_alignment() method.
77
+ You may wish to redefine the __init__ method as well.
78
+ """
79
+
80
+ def __init__(self, handle):
81
+ """Initialize the class."""
82
+ self.handle = handle
83
+
84
+ def write_file(self, alignments):
85
+ """Use this to write an entire file containing the given alignments.
86
+
87
+ Arguments:
88
+ - alignments - A list or iterator returning MultipleSeqAlignment objects
89
+
90
+ In general, this method can only be called once per file.
91
+
92
+ This method should be replaced by any derived class to do something
93
+ useful. It should return the number of alignments..
94
+ """
95
+ raise NotImplementedError("This object should be subclassed")
96
+ #####################################################
97
+ # You SHOULD subclass this, to write the alignment #
98
+ # objects to the file handle #
99
+ #####################################################
100
+
101
+ def clean(self, text):
102
+ """Use this to avoid getting newlines in the output."""
103
+ return text.replace("\n", " ").replace("\r", " ")
104
+
105
+
106
+ class SequentialAlignmentWriter(AlignmentWriter):
107
+ """Base class for building MultipleSeqAlignment writers.
108
+
109
+ This assumes each alignment can be simply appended to the file.
110
+ You should write a write_alignment() method.
111
+ You may wish to redefine the __init__ method as well.
112
+ """
113
+
114
+ def __init__(self, handle):
115
+ """Initialize the class."""
116
+ self.handle = handle
117
+
118
+ def write_file(self, alignments):
119
+ """Use this to write an entire file containing the given alignments.
120
+
121
+ Arguments:
122
+ - alignments - A list or iterator returning MultipleSeqAlignment objects
123
+
124
+ In general, this method can only be called once per file.
125
+ """
126
+ self.write_header()
127
+ count = 0
128
+ for alignment in alignments:
129
+ self.write_alignment(alignment)
130
+ count += 1
131
+ self.write_footer()
132
+ return count
133
+
134
+ def write_header(self):
135
+ """Use this to write any header.
136
+
137
+ This method should be replaced by any derived class to do something
138
+ useful.
139
+ """
140
+
141
+ def write_footer(self):
142
+ """Use this to write any footer.
143
+
144
+ This method should be replaced by any derived class to do something
145
+ useful.
146
+ """
147
+
148
+ def write_alignment(self, alignment):
149
+ """Use this to write a single alignment.
150
+
151
+ This method should be replaced by any derived class to do something
152
+ useful.
153
+ """
154
+ raise NotImplementedError("This object should be subclassed")
155
+ #####################################################
156
+ # You SHOULD subclass this, to write the alignment #
157
+ # objects to the file handle #
158
+ #####################################################
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MafIO.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2011, 2012 by Andrew Sczesnak. All rights reserved.
2
+ # Revisions Copyright 2011, 2017 by Peter Cock. All rights reserved.
3
+ # Revisions Copyright 2014, 2015 by Adam Novak. All rights reserved.
4
+ # Revisions Copyright 2015, 2017 by Blaise Li. All rights reserved.
5
+ #
6
+ # This file is part of the Biopython distribution and governed by your
7
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
8
+ # Please see the LICENSE file that should have been included as part of this
9
+ # package.
10
+ """Bio.AlignIO support for the "maf" multiple alignment format.
11
+
12
+ The Multiple Alignment Format, described by UCSC, stores a series of
13
+ multiple alignments in a single file. It is suitable for whole-genome
14
+ to whole-genome alignments, metadata such as source chromosome, start
15
+ position, size, and strand can be stored.
16
+
17
+ See http://genome.ucsc.edu/FAQ/FAQformat.html#format5
18
+
19
+ You are expected to use this module via the Bio.AlignIO functions(or the
20
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
21
+
22
+ Coordinates in the MAF format are defined in terms of zero-based start
23
+ positions (like Python) and aligning region sizes.
24
+
25
+ A minimal aligned region of length one and starting at first position in the
26
+ source sequence would have ``start == 0`` and ``size == 1``.
27
+
28
+ As we can see on this example, ``start + size`` will give one more than the
29
+ zero-based end position. We can therefore manipulate ``start`` and
30
+ ``start + size`` as python list slice boundaries.
31
+
32
+ For an inclusive end coordinate, we need to use ``end = start + size - 1``.
33
+ A 1-column wide alignment would have ``start == end``.
34
+ """
35
+
36
+ import os
37
+ from itertools import islice
38
+
39
+ try:
40
+ from sqlite3 import dbapi2
41
+ except ImportError:
42
+ dbapi2 = None # type: ignore
43
+
44
+ from Bio.Align import MultipleSeqAlignment
45
+ from Bio.Seq import Seq
46
+ from Bio.SeqRecord import SeqRecord
47
+
48
+ from .Interfaces import SequentialAlignmentWriter
49
+
50
+ MAFINDEX_VERSION = 2
51
+
52
+
53
+ class MafWriter(SequentialAlignmentWriter):
54
+ """Accepts a MultipleSeqAlignment object, writes a MAF file."""
55
+
56
+ def write_header(self):
57
+ """Write the MAF header."""
58
+ self.handle.write("##maf version=1 scoring=none\n")
59
+ self.handle.write("# generated by Biopython\n\n")
60
+
61
+ def _write_record(self, record):
62
+ """Write a single SeqRecord object to an 's' line in a MAF block (PRIVATE)."""
63
+ # convert biopython-style 1/-1 strand to MAF-style +/- strand
64
+ if record.annotations.get("strand") == 1:
65
+ strand = "+"
66
+ elif record.annotations.get("strand") == -1:
67
+ strand = "-"
68
+ else:
69
+ # TODO: issue warning?
70
+ strand = "+"
71
+
72
+ fields = [
73
+ "s",
74
+ # In the MAF file format, spaces are not allowed in the id
75
+ "%-40s" % record.id.replace(" ", "_"),
76
+ "%15s" % record.annotations.get("start", 0),
77
+ "%5s"
78
+ % record.annotations.get("size", len(str(record.seq).replace("-", ""))),
79
+ strand,
80
+ "%15s" % record.annotations.get("srcSize", 0),
81
+ str(record.seq),
82
+ ]
83
+ self.handle.write(f"{' '.join(fields)}\n")
84
+
85
+ def write_alignment(self, alignment):
86
+ """Write a complete alignment to a MAF block.
87
+
88
+ Writes every SeqRecord in a MultipleSeqAlignment object to its own
89
+ MAF block (beginning with an 'a' line, containing 's' lines).
90
+ """
91
+ if not isinstance(alignment, MultipleSeqAlignment):
92
+ raise TypeError("Expected an alignment object")
93
+
94
+ if len({len(x) for x in alignment}) > 1:
95
+ raise ValueError("Sequences must all be the same length")
96
+
97
+ # We allow multiple sequences with the same IDs; for example, there may
98
+ # be a MAF aligning the + and - strands of the same sequence together.
99
+
100
+ # for now, use ._annotations private property, but restrict keys to those
101
+ # specifically supported by the MAF format, according to spec
102
+ try:
103
+ anno = " ".join(
104
+ [
105
+ f"{x}={y}"
106
+ for x, y in alignment._annotations.items()
107
+ if x in ("score", "pass")
108
+ ]
109
+ )
110
+ except AttributeError:
111
+ anno = "score=0.00"
112
+
113
+ self.handle.write(f"a {anno}\n")
114
+
115
+ recs_out = 0
116
+
117
+ for record in alignment:
118
+ self._write_record(record)
119
+
120
+ recs_out += 1
121
+
122
+ self.handle.write("\n")
123
+
124
+ return recs_out
125
+
126
+
127
+ # Invalid function name according to pylint, but kept for compatibility
128
+ # with Bio* conventions.
129
+ def MafIterator(handle, seq_count=None):
130
+ """Iterate over a MAF file handle as MultipleSeqAlignment objects.
131
+
132
+ Iterates over lines in a MAF file-like object (handle), yielding
133
+ MultipleSeqAlignment objects. SeqRecord IDs generally correspond to
134
+ species names.
135
+ """
136
+ in_a_bundle = False
137
+
138
+ annotations = []
139
+ records = []
140
+
141
+ while True:
142
+ # allows parsing of the last bundle without duplicating code
143
+ line = handle.readline()
144
+
145
+ try:
146
+ # Will be in binary mode if called via the indexing code
147
+ # (which needs the raw offsets for cross platform indexing)
148
+ line = line.decode("ASCII")
149
+ except AttributeError:
150
+ pass
151
+
152
+ if in_a_bundle:
153
+ if line.startswith("s"):
154
+ # add a SeqRecord to the bundle
155
+ line_split = line.strip().split()
156
+
157
+ if len(line_split) != 7:
158
+ raise ValueError(
159
+ "Error parsing alignment - 's' line must have 7 fields"
160
+ )
161
+
162
+ # convert MAF-style +/- strand to biopython-type 1/-1
163
+ if line_split[4] == "+":
164
+ strand = 1
165
+ elif line_split[4] == "-":
166
+ strand = -1
167
+ else:
168
+ # TODO: issue warning, set to 0?
169
+ strand = 1
170
+
171
+ # s (literal), src (ID), start, size, strand, srcSize, text (sequence)
172
+ anno = {
173
+ "start": int(line_split[2]),
174
+ "size": int(line_split[3]),
175
+ "strand": strand,
176
+ "srcSize": int(line_split[5]),
177
+ }
178
+
179
+ sequence = line_split[6]
180
+
181
+ # interpret a dot/period to mean the same as the first sequence
182
+ if "." in sequence:
183
+ if not records:
184
+ raise ValueError(
185
+ "Found dot/period in first sequence of alignment"
186
+ )
187
+
188
+ ref = records[0].seq
189
+ new = []
190
+
191
+ for letter, ref_letter in zip(sequence, ref):
192
+ new.append(ref_letter if letter == "." else letter)
193
+
194
+ sequence = "".join(new)
195
+
196
+ records.append(
197
+ SeqRecord(
198
+ Seq(sequence),
199
+ id=line_split[1],
200
+ name=line_split[1],
201
+ description="",
202
+ annotations=anno,
203
+ )
204
+ )
205
+ elif line.startswith("i"):
206
+ # TODO: information about what is in the aligned species DNA before
207
+ # and after the immediately preceding "s" line
208
+ pass
209
+ elif line.startswith("e"):
210
+ # TODO: information about the size of the gap between the alignments
211
+ # that span the current block
212
+ pass
213
+ elif line.startswith("q"):
214
+ # TODO: quality of each aligned base for the species.
215
+ # Need to find documentation on this, looks like ASCII 0-9 or gap?
216
+ # Can then store in each SeqRecord's .letter_annotations dictionary,
217
+ # perhaps as the raw string or turned into integers / None for gap?
218
+ pass
219
+ elif line.startswith("#"):
220
+ # ignore comments
221
+ # (not sure whether comments
222
+ # are in the maf specification, though)
223
+ pass
224
+ elif not line.strip():
225
+ # end a bundle of records
226
+ if seq_count is not None:
227
+ assert len(records) == seq_count
228
+
229
+ alignment = MultipleSeqAlignment(records)
230
+ # TODO - Introduce an annotated alignment class?
231
+ # See also Bio/AlignIO/FastaIO.py for same requirement.
232
+ # For now, store the annotation a new private property:
233
+ alignment._annotations = annotations
234
+
235
+ yield alignment
236
+
237
+ in_a_bundle = False
238
+
239
+ annotations = []
240
+ records = []
241
+ else:
242
+ raise ValueError(f"Error parsing alignment - unexpected line:\n{line}")
243
+ elif line.startswith("a"):
244
+ # start a bundle of records
245
+ in_a_bundle = True
246
+ annot_strings = line.strip().split()[1:]
247
+ if len(annot_strings) != line.count("="):
248
+ raise ValueError("Error parsing alignment - invalid key in 'a' line")
249
+ annotations = dict(a_string.split("=") for a_string in annot_strings)
250
+ elif line.startswith("#"):
251
+ # ignore comments
252
+ pass
253
+ elif not line:
254
+ break
255
+
256
+
257
+ class MafIndex:
258
+ """Index for a MAF file.
259
+
260
+ The index is a sqlite3 database that is built upon creation of the object
261
+ if necessary, and queried when methods *search* or *get_spliced* are
262
+ used.
263
+ """
264
+
265
+ def __init__(self, sqlite_file, maf_file, target_seqname):
266
+ """Indexes or loads the index of a MAF file."""
267
+ if dbapi2 is None:
268
+ # Python was compiled without sqlite3 support
269
+ from Bio import MissingPythonDependencyError
270
+
271
+ raise MissingPythonDependencyError(
272
+ "Python was compiled without the sqlite3 module"
273
+ )
274
+
275
+ self._target_seqname = target_seqname
276
+ # example: Tests/MAF/ucsc_mm9_chr10.mafindex
277
+ self._index_filename = sqlite_file
278
+ # example: /home/bli/src/biopython/Tests/MAF
279
+ self._relative_path = os.path.abspath(os.path.dirname(sqlite_file))
280
+ # example: Tests/MAF/ucsc_mm9_chr10.maf
281
+ self._maf_file = maf_file
282
+
283
+ # Opening in bytes mode as want real offsets, not where
284
+ # Python attempts to hide cross-platform newline differences etc
285
+ self._maf_fp = open(self._maf_file, "rb")
286
+
287
+ # if sqlite_file exists, use the existing db, otherwise index the file
288
+ if os.path.isfile(sqlite_file):
289
+ self._con = dbapi2.connect(sqlite_file)
290
+ try:
291
+ self._record_count = self.__check_existing_db()
292
+ except ValueError as err:
293
+ self._maf_fp.close()
294
+ self._con.close()
295
+ raise err from None
296
+ else:
297
+ self._con = dbapi2.connect(sqlite_file)
298
+ try:
299
+ self._record_count = self.__make_new_index()
300
+ except ValueError as err:
301
+ self._maf_fp.close()
302
+ self._con.close()
303
+ raise err from None
304
+
305
+ # lastly, setup a MafIterator pointing at the open maf_file
306
+ self._mafiter = MafIterator(self._maf_fp)
307
+
308
+ def close(self):
309
+ """Close the file handle being used to read the data.
310
+
311
+ Once called, further use of the index won't work. The sole
312
+ purpose of this method is to allow explicit handle closure
313
+ - for example if you wish to delete the file, on Windows
314
+ you must first close all open handles to that file.
315
+ """
316
+ self._con.close()
317
+ self._record_count = 0
318
+
319
+ def __check_existing_db(self):
320
+ """Perform basic sanity checks upon loading an existing index (PRIVATE)."""
321
+ try:
322
+ idx_version = int(
323
+ self._con.execute(
324
+ "SELECT value FROM meta_data WHERE key = 'version'"
325
+ ).fetchone()[0]
326
+ )
327
+ if idx_version != MAFINDEX_VERSION:
328
+ msg = "\n".join(
329
+ [
330
+ "Index version (%s) incompatible with this version "
331
+ "of MafIndex" % idx_version,
332
+ "You might erase the existing index %s "
333
+ "for it to be rebuilt." % self._index_filename,
334
+ ]
335
+ )
336
+ raise ValueError(msg)
337
+
338
+ filename = self._con.execute(
339
+ "SELECT value FROM meta_data WHERE key = 'filename'"
340
+ ).fetchone()[0]
341
+ # Compute absolute path of the original maf file
342
+ if os.path.isabs(filename):
343
+ # It was already stored as absolute
344
+ tmp_mafpath = filename
345
+ else:
346
+ # It should otherwise have been stored as relative to the index
347
+ # Would be stored with Unix / path separator, so convert
348
+ # it to the local OS path separator here:
349
+ tmp_mafpath = os.path.join(
350
+ self._relative_path, filename.replace("/", os.path.sep)
351
+ )
352
+ if tmp_mafpath != os.path.abspath(self._maf_file):
353
+ # Original and given absolute paths differ.
354
+ raise ValueError(
355
+ f"Index uses a different file ({filename} != {self._maf_file})"
356
+ )
357
+
358
+ db_target = self._con.execute(
359
+ "SELECT value FROM meta_data WHERE key = 'target_seqname'"
360
+ ).fetchone()[0]
361
+ if db_target != self._target_seqname:
362
+ raise ValueError(
363
+ "Provided database indexed for %s, expected %s"
364
+ % (db_target, self._target_seqname)
365
+ )
366
+
367
+ record_count = int(
368
+ self._con.execute(
369
+ "SELECT value FROM meta_data WHERE key = 'record_count'"
370
+ ).fetchone()[0]
371
+ )
372
+ if record_count == -1:
373
+ raise ValueError("Unfinished/partial database provided")
374
+
375
+ records_found = int(
376
+ self._con.execute("SELECT COUNT(*) FROM offset_data").fetchone()[0]
377
+ )
378
+ if records_found != record_count:
379
+ raise ValueError(
380
+ "Expected %s records, found %s. Corrupt index?"
381
+ % (record_count, records_found)
382
+ )
383
+
384
+ return records_found
385
+
386
+ except (dbapi2.OperationalError, dbapi2.DatabaseError) as err:
387
+ raise ValueError(f"Problem with SQLite database: {err}") from None
388
+
389
+ def __make_new_index(self):
390
+ """Read MAF file and generate SQLite index (PRIVATE)."""
391
+ # make the tables
392
+ self._con.execute("CREATE TABLE meta_data (key TEXT, value TEXT);")
393
+ self._con.execute(
394
+ "INSERT INTO meta_data (key, value) VALUES (?, ?);",
395
+ ("version", MAFINDEX_VERSION),
396
+ )
397
+ self._con.execute(
398
+ "INSERT INTO meta_data (key, value) VALUES ('record_count', -1);"
399
+ )
400
+ self._con.execute(
401
+ "INSERT INTO meta_data (key, value) VALUES (?, ?);",
402
+ ("target_seqname", self._target_seqname),
403
+ )
404
+ # Determine whether to store maf file as relative to the index or absolute
405
+ # See https://github.com/biopython/biopython/pull/381
406
+ if not os.path.isabs(self._maf_file) and not os.path.isabs(
407
+ self._index_filename
408
+ ):
409
+ # Since the user gave both maf file and index as relative paths,
410
+ # we will store the maf file relative to the index.
411
+ # Note for cross platform use (e.g. shared drive over SAMBA),
412
+ # convert any Windows slash into Unix style for rel paths.
413
+ # example: ucsc_mm9_chr10.maf
414
+ mafpath = os.path.relpath(self._maf_file, self._relative_path).replace(
415
+ os.path.sep, "/"
416
+ )
417
+ elif (
418
+ os.path.dirname(os.path.abspath(self._maf_file)) + os.path.sep
419
+ ).startswith(self._relative_path + os.path.sep):
420
+ # Since maf file is in same directory or sub directory,
421
+ # might as well make this into a relative path:
422
+ mafpath = os.path.relpath(self._maf_file, self._relative_path).replace(
423
+ os.path.sep, "/"
424
+ )
425
+ else:
426
+ # Default to storing as an absolute path
427
+ # example: /home/bli/src/biopython/Tests/MAF/ucsc_mm9_chr10.maf
428
+ mafpath = os.path.abspath(self._maf_file)
429
+ self._con.execute(
430
+ "INSERT INTO meta_data (key, value) VALUES (?, ?);",
431
+ ("filename", mafpath),
432
+ )
433
+ self._con.execute(
434
+ "CREATE TABLE offset_data (bin INTEGER, start INTEGER, end INTEGER, offset INTEGER);"
435
+ )
436
+
437
+ insert_count = 0
438
+
439
+ # iterate over the entire file and insert in batches
440
+ mafindex_func = self.__maf_indexer()
441
+
442
+ while True:
443
+ batch = list(islice(mafindex_func, 100))
444
+ if not batch:
445
+ break
446
+
447
+ # batch is made from self.__maf_indexer(),
448
+ # which yields zero-based "inclusive" start and end coordinates
449
+ self._con.executemany(
450
+ "INSERT INTO offset_data (bin, start, end, offset) VALUES (?,?,?,?);",
451
+ batch,
452
+ )
453
+ self._con.commit()
454
+ insert_count += len(batch)
455
+
456
+ # then make indexes on the relevant fields
457
+ self._con.execute("CREATE INDEX IF NOT EXISTS bin_index ON offset_data(bin);")
458
+ self._con.execute(
459
+ "CREATE INDEX IF NOT EXISTS start_index ON offset_data(start);"
460
+ )
461
+ self._con.execute("CREATE INDEX IF NOT EXISTS end_index ON offset_data(end);")
462
+
463
+ self._con.execute(
464
+ f"UPDATE meta_data SET value = '{insert_count}' WHERE key = 'record_count'"
465
+ )
466
+
467
+ self._con.commit()
468
+
469
+ return insert_count
470
+
471
+ def __maf_indexer(self):
472
+ """Return index information for each bundle (PRIVATE).
473
+
474
+ Yields index information for each bundle in the form of
475
+ (bin, start, end, offset) tuples where start and end are
476
+ 0-based inclusive coordinates.
477
+ """
478
+ line = self._maf_fp.readline()
479
+
480
+ while line:
481
+ if line.startswith(b"a"):
482
+ # note the offset
483
+ offset = self._maf_fp.tell() - len(line)
484
+
485
+ # search the following lines for a match to target_seqname
486
+ while True:
487
+ line = self._maf_fp.readline()
488
+
489
+ if not line.strip() or line.startswith(b"a"):
490
+ # Empty line or new alignment record
491
+ raise ValueError(
492
+ "Target for indexing (%s) not found in this bundle"
493
+ % (self._target_seqname,)
494
+ )
495
+ elif line.startswith(b"s"):
496
+ # s (literal), src (ID), start, size, strand, srcSize, text (sequence)
497
+ line_split = line.decode("ASCII").strip().split()
498
+
499
+ if line_split[1] == self._target_seqname:
500
+ start = int(line_split[2])
501
+ size = int(line_split[3])
502
+ if size != len(line_split[6].replace("-", "")):
503
+ raise ValueError(
504
+ "Invalid length for target coordinates "
505
+ "(expected %s, found %s)"
506
+ % (size, len(line_split[6].replace("-", "")))
507
+ )
508
+
509
+ # "inclusive" end position is start + length - 1
510
+ end = start + size - 1
511
+
512
+ # _ucscbin takes end-exclusive coordinates
513
+ yield (self._ucscbin(start, end + 1), start, end, offset)
514
+
515
+ break
516
+
517
+ line = self._maf_fp.readline()
518
+
519
+ # TODO: check coordinate correctness for the two bin-related static methods
520
+ @staticmethod
521
+ def _region2bin(start, end):
522
+ """Find bins that a region may belong to (PRIVATE).
523
+
524
+ Converts a region to a list of bins that it may belong to, including largest
525
+ and smallest bins.
526
+ """
527
+ bins = [0, 1]
528
+
529
+ bins.extend(range(1 + (start >> 26), 2 + ((end - 1) >> 26)))
530
+ bins.extend(range(9 + (start >> 23), 10 + ((end - 1) >> 23)))
531
+ bins.extend(range(73 + (start >> 20), 74 + ((end - 1) >> 20)))
532
+ bins.extend(range(585 + (start >> 17), 586 + ((end - 1) >> 17)))
533
+
534
+ return set(bins)
535
+
536
+ @staticmethod
537
+ def _ucscbin(start, end):
538
+ """Return the smallest bin a given region will fit into (PRIVATE).
539
+
540
+ Adapted from http://genomewiki.ucsc.edu/index.php/Bin_indexing_system
541
+ """
542
+ bin_offsets = [512 + 64 + 8 + 1, 64 + 8 + 1, 8 + 1, 1, 0]
543
+
544
+ _bin_first_shift = 17
545
+ _bin_next_shift = 3
546
+
547
+ start_bin = start
548
+ end_bin = end - 1
549
+
550
+ start_bin >>= _bin_first_shift
551
+ end_bin >>= _bin_first_shift
552
+
553
+ for bin_offset in bin_offsets:
554
+ if start_bin == end_bin:
555
+ return bin_offset + start_bin
556
+ start_bin >>= _bin_next_shift
557
+ end_bin >>= _bin_next_shift
558
+
559
+ return 0
560
+
561
+ def _get_record(self, offset):
562
+ """Retrieve a single MAF record located at the offset provided (PRIVATE)."""
563
+ self._maf_fp.seek(offset)
564
+ return next(self._mafiter)
565
+
566
+ def search(self, starts, ends):
567
+ """Search index database for MAF records overlapping ranges provided.
568
+
569
+ Returns *MultipleSeqAlignment* results in order by start, then end, then
570
+ internal offset field.
571
+
572
+ *starts* should be a list of 0-based start coordinates of segments in the reference.
573
+ *ends* should be the list of the corresponding segment ends
574
+ (in the half-open UCSC convention:
575
+ http://genome.ucsc.edu/blog/the-ucsc-genome-browser-coordinate-counting-systems/).
576
+ """
577
+ # verify the provided exon coordinates
578
+ if len(starts) != len(ends):
579
+ raise ValueError("Every position in starts must have a match in ends")
580
+
581
+ # Could it be safer to sort the (exonstart, exonend) pairs?
582
+ for exonstart, exonend in zip(starts, ends):
583
+ exonlen = exonend - exonstart
584
+ if exonlen < 1:
585
+ raise ValueError(
586
+ "Exon coordinates (%d, %d) invalid: exon length (%d) < 1"
587
+ % (exonstart, exonend, exonlen)
588
+ )
589
+ con = self._con
590
+
591
+ # Keep track of what blocks have already been yielded
592
+ # in order to avoid duplicating them
593
+ # (see https://github.com/biopython/biopython/issues/1083)
594
+ yielded_rec_coords = set()
595
+ # search for every exon
596
+ for exonstart, exonend in zip(starts, ends):
597
+ try:
598
+ possible_bins = ", ".join(
599
+ map(str, self._region2bin(exonstart, exonend))
600
+ )
601
+ except TypeError:
602
+ raise TypeError(
603
+ "Exon coordinates must be integers "
604
+ "(start=%d, end=%d)" % (exonstart, exonend)
605
+ ) from None
606
+
607
+ # https://www.sqlite.org/lang_expr.html
608
+ # -----
609
+ # The BETWEEN operator
610
+ #
611
+ # The BETWEEN operator is logically equivalent to a pair of
612
+ # comparisons. "x BETWEEN y AND z" is equivalent to "x>=y AND x<=z"
613
+ # except that with BETWEEN, the x expression is only evaluated
614
+ # once. The precedence of the BETWEEN operator is the same as the
615
+ # precedence as operators == and != and LIKE and groups left to
616
+ # right.
617
+ # -----
618
+
619
+ # We are testing overlap between the query segment and records in
620
+ # the index, using non-strict coordinates comparisons.
621
+ # The query segment end must be passed as end-inclusive
622
+ # The index should also have been build with end-inclusive
623
+ # end coordinates.
624
+ # See https://github.com/biopython/biopython/pull/1086#issuecomment-285069073
625
+
626
+ result = con.execute(
627
+ "SELECT DISTINCT start, end, offset FROM offset_data "
628
+ "WHERE bin IN (%s) "
629
+ "AND (end BETWEEN %s AND %s OR %s BETWEEN start AND end) "
630
+ "ORDER BY start, end, offset ASC;"
631
+ % (possible_bins, exonstart, exonend - 1, exonend - 1)
632
+ )
633
+
634
+ rows = result.fetchall()
635
+
636
+ # rows come from the sqlite index,
637
+ # which should have been written using __make_new_index,
638
+ # so rec_start and rec_end should be zero-based "inclusive" coordinates
639
+ for rec_start, rec_end, offset in rows:
640
+ # Avoid yielding multiple time the same block
641
+ if (rec_start, rec_end) in yielded_rec_coords:
642
+ continue
643
+ else:
644
+ yielded_rec_coords.add((rec_start, rec_end))
645
+ # Iterate through hits, fetching alignments from the MAF file
646
+ # and checking to be sure we've retrieved the expected record.
647
+
648
+ fetched = self._get_record(int(offset))
649
+
650
+ for record in fetched:
651
+ if record.id == self._target_seqname:
652
+ # start and size come from the maf lines
653
+ start = record.annotations["start"]
654
+ # "inclusive" end is start + length - 1
655
+ end = start + record.annotations["size"] - 1
656
+
657
+ if not (start == rec_start and end == rec_end):
658
+ raise ValueError(
659
+ "Expected %s-%s @ offset %s, found %s-%s"
660
+ % (rec_start, rec_end, offset, start, end)
661
+ )
662
+
663
+ yield fetched
664
+
665
+ def get_spliced(self, starts, ends, strand=1):
666
+ """Return a multiple alignment of the exact sequence range provided.
667
+
668
+ Accepts two lists of start and end positions on target_seqname, representing
669
+ exons to be spliced in silico. Returns a *MultipleSeqAlignment* of the
670
+ desired sequences spliced together.
671
+
672
+ *starts* should be a list of 0-based start coordinates of segments in the reference.
673
+ *ends* should be the list of the corresponding segment ends
674
+ (in the half-open UCSC convention:
675
+ http://genome.ucsc.edu/blog/the-ucsc-genome-browser-coordinate-counting-systems/).
676
+
677
+ To ask for the alignment portion corresponding to the first 100
678
+ nucleotides of the reference sequence, you would use
679
+ ``search([0], [100])``
680
+ """
681
+ # validate strand
682
+ if strand not in (1, -1):
683
+ raise ValueError(f"Strand must be 1 or -1, got {strand}")
684
+
685
+ # pull all alignments that span the desired intervals
686
+ fetched = list(self.search(starts, ends))
687
+
688
+ # keep track of the expected letter count
689
+ # (sum of lengths of [start, end) segments,
690
+ # where [start, end) half-open)
691
+ expected_letters = sum(end - start for start, end in zip(starts, ends))
692
+
693
+ # if there's no alignment, return filler for the assembly of the length given
694
+ if len(fetched) == 0:
695
+ return MultipleSeqAlignment(
696
+ [SeqRecord(Seq("N" * expected_letters), id=self._target_seqname)]
697
+ )
698
+
699
+ # find the union of all IDs in these alignments
700
+ all_seqnames = {sequence.id for multiseq in fetched for sequence in multiseq}
701
+
702
+ # split every record by base position
703
+ # key: sequence name
704
+ # value: dictionary
705
+ # key: position in the reference sequence
706
+ # value: letter(s) (including letters
707
+ # aligned to the "-" preceding the letter
708
+ # at the position in the reference, if any)
709
+ split_by_position = {seq_name: {} for seq_name in all_seqnames}
710
+
711
+ # keep track of what the total number of (unspliced) letters should be
712
+ total_rec_length = 0
713
+
714
+ # track first strand encountered on the target seqname
715
+ ref_first_strand = None
716
+
717
+ for multiseq in fetched:
718
+ # find the target_seqname in this MultipleSeqAlignment and use it to
719
+ # set the parameters for the rest of this iteration
720
+ for seqrec in multiseq:
721
+ if seqrec.id == self._target_seqname:
722
+ try:
723
+ if ref_first_strand is None:
724
+ ref_first_strand = seqrec.annotations["strand"]
725
+
726
+ if ref_first_strand not in (1, -1):
727
+ raise ValueError("Strand must be 1 or -1")
728
+ elif ref_first_strand != seqrec.annotations["strand"]:
729
+ raise ValueError(
730
+ "Encountered strand='%s' on target seqname, "
731
+ "expected '%s'"
732
+ % (seqrec.annotations["strand"], ref_first_strand)
733
+ )
734
+ except KeyError:
735
+ raise ValueError(
736
+ "No strand information for target seqname (%s)"
737
+ % self._target_seqname
738
+ ) from None
739
+ # length including gaps (i.e. alignment length)
740
+ rec_length = len(seqrec)
741
+ rec_start = seqrec.annotations["start"]
742
+ ungapped_length = seqrec.annotations["size"]
743
+ # inclusive end in zero-based coordinates of the reference
744
+ rec_end = rec_start + ungapped_length - 1
745
+ # This is length in terms of actual letters in the reference
746
+ total_rec_length += ungapped_length
747
+
748
+ # blank out these positions for every seqname
749
+ for seqrec in multiseq:
750
+ for pos in range(rec_start, rec_end + 1):
751
+ split_by_position[seqrec.id][pos] = ""
752
+
753
+ break
754
+ # http://psung.blogspot.fr/2007/12/for-else-in-python.html
755
+ # https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
756
+ else:
757
+ raise ValueError(
758
+ f"Did not find {self._target_seqname} in alignment bundle"
759
+ )
760
+
761
+ # the true, chromosome/contig/etc position in the target seqname
762
+ real_pos = rec_start
763
+
764
+ # loop over the alignment to fill split_by_position
765
+ for gapped_pos in range(rec_length):
766
+ for seqrec in multiseq:
767
+ # keep track of this position's value for the target seqname
768
+ if seqrec.id == self._target_seqname:
769
+ track_val = seqrec.seq[gapped_pos]
770
+
771
+ # Here, a real_pos that corresponds to just after a series of "-"
772
+ # in the reference will "accumulate" the letters found in other sequences
773
+ # in front of the "-"s
774
+ split_by_position[seqrec.id][real_pos] += seqrec.seq[gapped_pos]
775
+
776
+ # increment the real_pos counter only when non-gaps are found in
777
+ # the target_seqname, and we haven't reached the end of the record
778
+ if track_val != "-" and real_pos < rec_end:
779
+ real_pos += 1
780
+
781
+ # make sure the number of bp entries equals the sum of the record lengths
782
+ if len(split_by_position[self._target_seqname]) != total_rec_length:
783
+ raise ValueError(
784
+ "Target seqname (%s) has %s records, expected %s"
785
+ % (
786
+ self._target_seqname,
787
+ len(split_by_position[self._target_seqname]),
788
+ total_rec_length,
789
+ )
790
+ )
791
+
792
+ # translates a position in the target_seqname sequence to its gapped length
793
+ realpos_to_len = {
794
+ pos: len(gapped_fragment)
795
+ for pos, gapped_fragment in split_by_position[self._target_seqname].items()
796
+ if len(gapped_fragment) > 1
797
+ }
798
+
799
+ # splice together the exons
800
+ subseq = {}
801
+
802
+ for seqid in all_seqnames:
803
+ seq_split = split_by_position[seqid]
804
+ seq_splice = []
805
+
806
+ filler_char = "N" if seqid == self._target_seqname else "-"
807
+
808
+ # iterate from start to end, taking bases from split_by_position when
809
+ # they exist, using N or - for gaps when there is no alignment.
810
+ append = seq_splice.append
811
+
812
+ for exonstart, exonend in zip(starts, ends):
813
+ # exonend is exclusive
814
+ for real_pos in range(exonstart, exonend):
815
+ # if this seqname has this position, add it
816
+ if real_pos in seq_split:
817
+ append(seq_split[real_pos])
818
+ # if not, but it's in the target_seqname, add length-matched filler
819
+ elif real_pos in realpos_to_len:
820
+ append(filler_char * realpos_to_len[real_pos])
821
+ # it's not in either, so add a single filler character
822
+ else:
823
+ append(filler_char)
824
+
825
+ subseq[seqid] = "".join(seq_splice)
826
+
827
+ # make sure we're returning the right number of letters
828
+ if len(subseq[self._target_seqname].replace("-", "")) != expected_letters:
829
+ raise ValueError(
830
+ "Returning %s letters for target seqname (%s), expected %s"
831
+ % (
832
+ len(subseq[self._target_seqname].replace("-", "")),
833
+ self._target_seqname,
834
+ expected_letters,
835
+ )
836
+ )
837
+
838
+ # check to make sure all sequences are the same length as the target seqname
839
+ ref_subseq_len = len(subseq[self._target_seqname])
840
+
841
+ for seqid, seq in subseq.items():
842
+ if len(seq) != ref_subseq_len:
843
+ raise ValueError(
844
+ "Returning length %s for %s, expected %s"
845
+ % (len(seq), seqid, ref_subseq_len)
846
+ )
847
+
848
+ # finally, build a MultipleSeqAlignment object for our final sequences
849
+ result_multiseq = []
850
+
851
+ for seqid, seq in subseq.items():
852
+ seq = Seq(seq)
853
+
854
+ seq = seq if strand == ref_first_strand else seq.reverse_complement()
855
+
856
+ result_multiseq.append(SeqRecord(seq, id=seqid, name=seqid, description=""))
857
+
858
+ return MultipleSeqAlignment(result_multiseq)
859
+
860
+ def __repr__(self):
861
+ """Return a string representation of the index."""
862
+ return "MafIO.MafIndex(%r, target_seqname=%r)" % (
863
+ self._maf_fp.name,
864
+ self._target_seqname,
865
+ )
866
+
867
+ def __len__(self):
868
+ """Return the number of records in the index."""
869
+ return self._record_count
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MauveIO.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015-2015 by Eric Rasche. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Bio.AlignIO support for "xmfa" output from Mauve/ProgressiveMauve.
8
+
9
+ You are expected to use this module via the Bio.AlignIO functions (or the
10
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
11
+
12
+ For example, consider a progressiveMauve alignment file containing the following::
13
+
14
+ #FormatVersion Mauve1
15
+ #Sequence1File a.fa
16
+ #Sequence1Entry 1
17
+ #Sequence1Format FastA
18
+ #Sequence2File b.fa
19
+ #Sequence2Entry 2
20
+ #Sequence2Format FastA
21
+ #Sequence3File c.fa
22
+ #Sequence3Entry 3
23
+ #Sequence3Format FastA
24
+ #BackboneFile three.xmfa.bbcols
25
+ > 1:0-0 + a.fa
26
+ --------------------------------------------------------------------------------
27
+ --------------------------------------------------------------------------------
28
+ --------------------------------------------------------------------------------
29
+ > 2:5417-5968 + b.fa
30
+ TTTAAACATCCCTCGGCCCGTCGCCCTTTTATAATAGCAGTACGTGAGAGGAGCGCCCTAAGCTTTGGGAAATTCAAGC-
31
+ --------------------------------------------------------------------------------
32
+ CTGGAACGTACTTGCTGGTTTCGCTACTATTTCAAACAAGTTAGAGGCCGTTACCTCGGGCGAACGTATAAACCATTCTG
33
+ > 3:9476-10076 - c.fa
34
+ TTTAAACACCTTTTTGGATG--GCCCAGTTCGTTCAGTTGTG-GGGAGGAGATCGCCCCAAACGTATGGTGAGTCGGGCG
35
+ TTTCCTATAGCTATAGGACCAATCCACTTACCATACGCCCGGCGTCGCCCAGTCCGGTTCGGTACCCTCCATGACCCACG
36
+ ---------------------------------------------------------AAATGAGGGCCCAGGGTATGCTT
37
+ =
38
+ > 2:5969-6015 + b.fa
39
+ -----------------------
40
+ GGGCGAACGTATAAACCATTCTG
41
+ > 3:9429-9476 - c.fa
42
+ TTCGGTACCCTCCATGACCCACG
43
+ AAATGAGGGCCCAGGGTATGCTT
44
+
45
+ This is a multiple sequence alignment with multiple aligned sections, so you
46
+ would probably load this using the Bio.AlignIO.parse() function:
47
+
48
+ >>> from Bio import AlignIO
49
+ >>> align = AlignIO.parse("Mauve/simple_short.xmfa", "mauve")
50
+ >>> alignments = list(align)
51
+ >>> for aln in alignments:
52
+ ... print(aln)
53
+ ...
54
+ Alignment with 3 rows and 240 columns
55
+ --------------------------------------------...--- a.fa
56
+ TTTAAACATCCCTCGGCCCGTCGCCCTTTTATAATAGCAGTACG...CTG b.fa/5416-5968
57
+ TTTAAACACCTTTTTGGATG--GCCCAGTTCGTTCAGTTGTG-G...CTT c.fa/9475-10076
58
+ Alignment with 2 rows and 46 columns
59
+ -----------------------GGGCGAACGTATAAACCATTCTG b.fa/5968-6015
60
+ TTCGGTACCCTCCATGACCCACGAAATGAGGGCCCAGGGTATGCTT c.fa/9428-9476
61
+
62
+ Additional information is extracted from the XMFA file and available through
63
+ the annotation attribute of each record::
64
+
65
+ >>> for record in alignments[0]:
66
+ ... print(record.id, len(record))
67
+ ... print(" start: %d, end: %d, strand: %d" %(
68
+ ... record.annotations['start'], record.annotations['end'],
69
+ ... record.annotations['strand']))
70
+ ...
71
+ a.fa 240
72
+ start: 0, end: 0, strand: 1
73
+ b.fa/5416-5968 240
74
+ start: 5416, end: 5968, strand: 1
75
+ c.fa/9475-10076 240
76
+ start: 9475, end: 10076, strand: -1
77
+
78
+ """
79
+
80
+ import re
81
+
82
+ from Bio.Align import MultipleSeqAlignment
83
+ from Bio.Seq import Seq
84
+ from Bio.SeqRecord import SeqRecord
85
+
86
+ from .Interfaces import AlignmentIterator
87
+ from .Interfaces import SequentialAlignmentWriter
88
+
89
+ XMFA_HEADER_REGEX = re.compile(
90
+ r"> (?P<id>\d+):(?P<start>\d+)-(?P<end>\d+) (?P<strand>[+-]) (?P<name>.*)"
91
+ )
92
+ XMFA_HEADER_REGEX_BIOPYTHON = re.compile(
93
+ r"> (?P<id>\d+):(?P<start>\d+)-(?P<end>\d+) (?P<strand>[+-]) (?P<name>[^#]*) # (?P<realname>.*)"
94
+ )
95
+ ID_LINE_FMT = "> {seq_name}:{start}-{end} {strand} {filename} # {ugly_hack}"
96
+
97
+
98
+ def _identifier_split(identifier):
99
+ """Return (name, start, end) string tuple from an identifier (PRIVATE)."""
100
+ id, loc, strand = identifier.split(":")
101
+ start, end = map(int, loc.split("-"))
102
+ start -= 1
103
+ return id, start, end, strand
104
+
105
+
106
+ class MauveWriter(SequentialAlignmentWriter):
107
+ """Mauve/XMFA alignment writer."""
108
+
109
+ def __init__(self, *args, **kwargs):
110
+ """Initialize the class."""
111
+ super().__init__(*args, **kwargs)
112
+ self._wrote_header = False
113
+ self._wrote_first = False
114
+
115
+ def write_alignment(self, alignment):
116
+ """Use this to write (another) single alignment to an open file.
117
+
118
+ Note that sequences and their annotation are recorded
119
+ together (rather than having a block of annotation followed
120
+ by a block of aligned sequences).
121
+ """
122
+ count = len(alignment)
123
+
124
+ self._length_of_sequences = alignment.get_alignment_length()
125
+
126
+ # NOTE - For now, the alignment object does not hold any per column
127
+ # or per alignment annotation - only per sequence.
128
+
129
+ if count == 0:
130
+ raise ValueError("Must have at least one sequence")
131
+ if self._length_of_sequences == 0:
132
+ raise ValueError("Non-empty sequences are required")
133
+
134
+ if not self._wrote_header:
135
+ self._wrote_header = True
136
+ self.handle.write("#FormatVersion Mauve1\n")
137
+ # There are some more headers, but we ignore those for now.
138
+ # Sequence1File unknown.fa
139
+ # Sequence1Entry 1
140
+ # Sequence1Format FastA
141
+ for i in range(1, count + 1):
142
+ self.handle.write(f"#Sequence{i}Entry\t{i}\n")
143
+
144
+ for idx, record in enumerate(alignment):
145
+ self._write_record(record, record_idx=idx)
146
+ self.handle.write("=\n")
147
+
148
+ def _write_record(self, record, record_idx=0):
149
+ """Write a single SeqRecord to the file (PRIVATE)."""
150
+ if self._length_of_sequences != len(record.seq):
151
+ raise ValueError("Sequences must all be the same length")
152
+
153
+ seq_name = record.name
154
+ try:
155
+ seq_name = str(int(record.name))
156
+ except ValueError:
157
+ seq_name = str(record_idx + 1)
158
+
159
+ # We remove the "/{start}-{end}" before writing, as it cannot be part
160
+ # of the produced XMFA file.
161
+ if "start" in record.annotations and "end" in record.annotations:
162
+ suffix0 = f"/{record.annotations['start']}-{record.annotations['end']}"
163
+ suffix1 = f"/{record.annotations['start'] + 1}-{record.annotations['end']}"
164
+ if seq_name[-len(suffix0) :] == suffix0:
165
+ seq_name = seq_name[: -len(suffix0)]
166
+ if seq_name[-len(suffix1) :] == suffix1:
167
+ seq_name = seq_name[: -len(suffix1)]
168
+
169
+ if (
170
+ "start" in record.annotations
171
+ and "end" in record.annotations
172
+ and "strand" in record.annotations
173
+ ):
174
+ id_line = ID_LINE_FMT.format(
175
+ seq_name=seq_name,
176
+ start=record.annotations["start"] + 1,
177
+ end=record.annotations["end"],
178
+ strand=("+" if record.annotations["strand"] == 1 else "-"),
179
+ filename=record.name + ".fa",
180
+ ugly_hack=record.id,
181
+ )
182
+ lacking_annotations = False
183
+ else:
184
+ id_line = ID_LINE_FMT.format(
185
+ seq_name=seq_name,
186
+ start=0,
187
+ end=0,
188
+ strand="+",
189
+ filename=record.name + ".fa",
190
+ ugly_hack=record.id,
191
+ )
192
+ lacking_annotations = True
193
+
194
+ # If the sequence is an empty one, skip writing it out
195
+ if (":0-0 " in id_line or ":1-0 " in id_line) and not lacking_annotations:
196
+ # Except in the first LCB
197
+ if not self._wrote_first:
198
+ self._wrote_first = True
199
+ # The first LCB we write out is special, and must list ALL
200
+ # sequences, for the Mauve GUI
201
+ # http://darlinglab.org/mauve/user-guide/files.html#non-standard-xmfa-formatting-used-by-the-mauve-gui
202
+ id_line = ID_LINE_FMT.format(
203
+ seq_name=seq_name,
204
+ start=0,
205
+ end=0,
206
+ strand="+",
207
+ filename=record.name + ".fa",
208
+ ugly_hack=record.id,
209
+ )
210
+ id_line = id_line.replace("\n", " ").replace("\r", " ")
211
+ self.handle.write(id_line + "\n\n")
212
+ # Alignments lacking a start/stop/strand were generated by
213
+ # Biopython on load, and shouldn't exist according to XMFA
214
+ else:
215
+ # In other blocks, we only write sequences if they exist in a given
216
+ # alignment.
217
+ id_line = id_line.replace("\n", " ").replace("\r", " ")
218
+ self.handle.write(id_line + "\n")
219
+ for i in range(0, len(record.seq), 80):
220
+ self.handle.write(f"{record.seq[i : i + 80]}\n")
221
+
222
+
223
+ class MauveIterator(AlignmentIterator):
224
+ """Mauve xmfa alignment iterator."""
225
+
226
+ _ids: list[str] = [] # for caching IDs between __next__ calls
227
+
228
+ def __next__(self):
229
+ """Parse the next alignment from the handle."""
230
+ handle = self.handle
231
+ line = handle.readline()
232
+
233
+ if not line:
234
+ raise StopIteration
235
+
236
+ # Strip out header comments
237
+ while line and line.strip().startswith("#"):
238
+ line = handle.readline()
239
+
240
+ seqs = {}
241
+ seq_regions = {}
242
+ passed_end_alignment = False
243
+
244
+ latest_id = None
245
+ while True:
246
+ if not line:
247
+ break # end of file
248
+ line = line.strip()
249
+
250
+ if line.startswith("="):
251
+ # There may be more data, but we've reached the end of this
252
+ # alignment
253
+ break
254
+ elif line.startswith(">"):
255
+ m = XMFA_HEADER_REGEX_BIOPYTHON.match(line)
256
+ if not m:
257
+ m = XMFA_HEADER_REGEX.match(line)
258
+ if not m:
259
+ raise ValueError("Malformed header line: %s", line)
260
+
261
+ parsed_id = m.group("id")
262
+ parsed_data = {}
263
+ for key in ("start", "end", "id", "strand", "name", "realname"):
264
+ try:
265
+ value = m.group(key)
266
+ if key == "start":
267
+ value = int(value)
268
+ # Convert to zero based counting
269
+ if value > 0:
270
+ value -= 1
271
+
272
+ if key == "end":
273
+ value = int(value)
274
+ parsed_data[key] = value
275
+ except IndexError:
276
+ # This will occur if we're asking for a group that
277
+ # doesn't exist. It's fine.
278
+ pass
279
+ seq_regions[parsed_id] = parsed_data
280
+
281
+ if parsed_id not in self._ids:
282
+ self._ids.append(parsed_id)
283
+
284
+ seqs.setdefault(parsed_id, "")
285
+ latest_id = parsed_id
286
+ else:
287
+ assert not passed_end_alignment
288
+ if latest_id is None:
289
+ raise ValueError("Saw sequence before definition line")
290
+ seqs[latest_id] += line
291
+ line = handle.readline()
292
+
293
+ assert len(seqs) <= len(self._ids)
294
+
295
+ self.ids = self._ids
296
+ self.sequences = seqs
297
+
298
+ if self._ids and seqs:
299
+ alignment_length = max(map(len, list(seqs.values())))
300
+ records = []
301
+ for id in self._ids:
302
+ if id not in seqs or len(seqs[id]) == 0 or len(seqs[id]) == 0:
303
+ seq = "-" * alignment_length
304
+ else:
305
+ seq = seqs[id]
306
+
307
+ if alignment_length != len(seq):
308
+ raise ValueError(
309
+ "Sequences have different lengths, or repeated identifier"
310
+ )
311
+
312
+ # Sometimes we don't see a particular sequence in the
313
+ # alignment, so we skip that record since it isn't present in
314
+ # that LCB/alignment
315
+ if id not in seq_regions:
316
+ continue
317
+
318
+ if seq_regions[id]["start"] != 0 or seq_regions[id]["end"] != 0:
319
+ suffix = "/{start}-{end}".format(**seq_regions[id])
320
+ if "realname" in seq_regions[id]:
321
+ corrected_id = seq_regions[id]["realname"]
322
+ else:
323
+ corrected_id = seq_regions[id]["name"]
324
+ if corrected_id.count(suffix) == 0:
325
+ corrected_id += suffix
326
+ else:
327
+ if "realname" in seq_regions[id]:
328
+ corrected_id = seq_regions[id]["realname"]
329
+ else:
330
+ corrected_id = seq_regions[id]["name"]
331
+
332
+ record = SeqRecord(Seq(seq), id=corrected_id, name=id)
333
+
334
+ record.annotations["start"] = seq_regions[id]["start"]
335
+ record.annotations["end"] = seq_regions[id]["end"]
336
+ record.annotations["strand"] = (
337
+ 1 if seq_regions[id]["strand"] == "+" else -1
338
+ )
339
+
340
+ records.append(record)
341
+ return MultipleSeqAlignment(records)
342
+ else:
343
+ raise StopIteration
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MsfIO.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019, National Marrow Donor Program (NMPD). All rights reserved.
2
+ # Written by Peter Cock, The James Hutton Institute, under contract to NMDP.
3
+ #
4
+ # This file is part of the Biopython distribution and governed by your
5
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
6
+ # Please see the LICENSE file that should have been included as part of this
7
+ # package.
8
+ """Bio.AlignIO support for GCG MSF format.
9
+
10
+ The file format was produced by the GCG PileUp and and LocalPileUp tools,
11
+ and later tools such as T-COFFEE and MUSCLE support it as an optional
12
+ output format.
13
+
14
+ The original GCG tool would write gaps at ends of each sequence which could
15
+ be missing data as tildes (``~``), whereas internal gaps were periods (``.``)
16
+ instead. This parser replaces both with minus signs (``-``) for consistency
17
+ with the rest of ``Bio.AlignIO``.
18
+
19
+ You are expected to use this module via the Bio.AlignIO functions (or the
20
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
21
+ """
22
+
23
+ from Bio.Align import MultipleSeqAlignment
24
+ from Bio.Seq import Seq
25
+ from Bio.SeqRecord import SeqRecord
26
+
27
+ from .Interfaces import AlignmentIterator
28
+
29
+
30
+ class MsfIterator(AlignmentIterator):
31
+ """GCG MSF alignment iterator."""
32
+
33
+ _header = None # for caching lines between __next__ calls
34
+
35
+ def __next__(self):
36
+ """Parse the next alignment from the handle."""
37
+ handle = self.handle
38
+
39
+ if self._header is None:
40
+ line = handle.readline()
41
+ else:
42
+ # Header we saved from when we were parsing
43
+ # the previous alignment.
44
+ line = self._header
45
+ self._header = None
46
+
47
+ if not line:
48
+ raise StopIteration
49
+
50
+ # Whitelisted headers we know about.
51
+ known_headers = ["!!NA_MULTIPLE_ALIGNMENT", "!!AA_MULTIPLE_ALIGNMENT", "PileUp"]
52
+ # Examples in "Molecular Biology Software Training Manual GCG version 10"
53
+ # by BBSRC Bioscuences IT Services (BITS), Harpenden, UK, Copyright 1996-2001
54
+ # would often start as follows:
55
+ #
56
+ # !!AA_MUTIPLE_ALIGNMENT 1.0
57
+ # PileUp of: @/usr/users2/culhane/...
58
+ #
59
+ # etc with other seemingly free format text before getting to the
60
+ # MSF/Type/Check line and the following Name: lines block and // line.
61
+ #
62
+ # MUSCLE just has a line "PileUp", while other sources just use the line
63
+ # "!!AA_MULTIPLE_ALIGNMENT" (amino acid) or "!!NA_MULTIPLE_ALIGNMENT"
64
+ # (nucleotide).
65
+ if line.strip().split()[0] not in known_headers:
66
+ raise ValueError(
67
+ "%s is not a known GCG MSF header: %s"
68
+ % (line.strip().split()[0], ", ".join(known_headers))
69
+ )
70
+
71
+ while line and " MSF: " not in line:
72
+ line = handle.readline()
73
+
74
+ if not line:
75
+ raise ValueError("Reached end of file without MSF/Type/Check header line")
76
+
77
+ # Quoting from "Molecular Biology Software Training Manual GCG version 10"
78
+ # by BBSRC Bioscuences IT Services (BITS), Harpenden, UK. Copyright 1996-2001.
79
+ # Page 31:
80
+ #
81
+ # "Header information is before a .. (double dot) in a GCG format file.
82
+ # The file will also have a checksum specific for that file."
83
+ #
84
+ # This was followed by a single non-aligned sequence, but this convention
85
+ # appears to also be used in the GCG MSF files. Quoting other examples in
86
+ # this reference, page 31:
87
+ #
88
+ # localpileup_17.msf MSF: 195 Type: P January 6, 2000 15:41 Check: 4365 ..
89
+ #
90
+ # Except from page 148:
91
+ #
92
+ # localpileup_106.msf MSF: 457 Type: P November 28, 2000 16:09 Check: 2396 ..
93
+ #
94
+ # Quoting output from MUSCLE v3.8, have two leading spaces and a zero checksum:
95
+ #
96
+ # MSF: 689 Type: N Check: 0000 ..
97
+ #
98
+ # By observation, the MSF value is the column count, type is N (nucleotide)
99
+ # or P (protein / amino acid).
100
+ #
101
+ # In a possible bug, EMBOSS v6.6.0.0 uses CompCheck: rather than Check: as shown,
102
+ #
103
+ # $ seqret -sequence Tests/Fasta/f002 -auto -stdout -osformat msf
104
+ # !!NA_MULTIPLE_ALIGNMENT 1.0
105
+ #
106
+ # stdout MSF: 633 Type: N 01/08/19 CompCheck: 8543 ..
107
+ #
108
+ # Name: G26680 Len: 633 Check: 4334 Weight: 1.00
109
+ # Name: G26685 Len: 633 Check: 3818 Weight: 1.00
110
+ # Name: G29385 Len: 633 Check: 391 Weight: 1.00
111
+ #
112
+ # //
113
+ #
114
+ parts = line.strip("\n").split()
115
+ offset = parts.index("MSF:")
116
+ if (
117
+ parts[offset + 2] != "Type:"
118
+ or parts[-3] not in ("Check:", "CompCheck:")
119
+ or parts[-1] != ".."
120
+ ):
121
+ raise ValueError(
122
+ "GCG MSF header line should be "
123
+ "'<optional text> MSF: <int> Type: <letter> <optional date> Check: <int> ..', "
124
+ " not: %r" % line
125
+ )
126
+ try:
127
+ aln_length = int(parts[offset + 1])
128
+ except ValueError:
129
+ aln_length = -1
130
+ if aln_length < 0:
131
+ raise ValueError(
132
+ "GCG MSF header line should have MDF: <int> for column count, not %r"
133
+ % parts[offset + 1]
134
+ )
135
+ seq_type = parts[offset + 3]
136
+ if seq_type not in ["P", "N"]:
137
+ raise ValueError(
138
+ "GCG MSF header line should have 'Type: P' (protein) "
139
+ "or 'Type: N' (nucleotide), not 'Type: %s'" % seq_type
140
+ )
141
+
142
+ # There should be a blank line after that header line, then the Name: lines
143
+ #
144
+ # In a possible bug, T-COFFEE v12.00 adds 'oo' after the names, as shown here,
145
+ #
146
+ # PileUp
147
+ #
148
+ #
149
+ #
150
+ # MSF: 628 Type: P Check: 147 ..
151
+ #
152
+ # Name: AK1H_ECOLI/1-378 oo Len: 628 Check: 3643 Weight: 1.000
153
+ # Name: AKH_HAEIN/1-382 oo Len: 628 Check: 6504 Weight: 1.000
154
+ #
155
+ # //
156
+ ids = []
157
+ lengths = []
158
+ checks = []
159
+ weights = []
160
+ line = handle.readline()
161
+ while line and line.strip() != "//":
162
+ line = handle.readline()
163
+ if line.strip().startswith("Name: "):
164
+ if " Len: " in line and " Check: " in line and " Weight: " in line:
165
+ rest = line[line.index("Name: ") + 6 :].strip()
166
+ name, rest = rest.split(" Len: ")
167
+ length, rest = rest.split(" Check: ")
168
+ check, weight = rest.split(" Weight: ")
169
+ name = name.strip()
170
+ if name.endswith(" oo"):
171
+ # T-COFFEE oddity, ignore this
172
+ name = name[:-3]
173
+ if name in ids:
174
+ raise ValueError(f"Duplicated ID of {name!r}")
175
+ if " " in name:
176
+ raise NotImplementedError(f"Space in ID {name!r}")
177
+ ids.append(name)
178
+ # Expect aln_length <= int(length.strip()), see below
179
+ lengths.append(int(length.strip()))
180
+ checks.append(int(check.strip()))
181
+ weights.append(float(weight.strip()))
182
+ else:
183
+ raise ValueError(f"Malformed GCG MSF name line: {line!r}")
184
+ if not line:
185
+ raise ValueError("End of file while looking for end of header // line.")
186
+
187
+ if aln_length != max(lengths):
188
+ # In broken examples from IMGTHLA was possible to continue
189
+ # https://github.com/ANHIG/IMGTHLA/issues/201
190
+ max_length = max(lengths)
191
+ max_count = sum(1 for _ in lengths if _ == max_length)
192
+ raise ValueError(
193
+ "GCG MSF header said alignment length %i, but %s of %i sequences said Len: %s"
194
+ % (aln_length, max_count, len(ids), max_length)
195
+ )
196
+
197
+ line = handle.readline()
198
+ if not line:
199
+ raise ValueError("End of file after // line, expected sequences.")
200
+ if line.strip():
201
+ raise ValueError("After // line, expected blank line before sequences.")
202
+
203
+ # Now load the sequences
204
+ seqs = [[] for _ in ids] # list of empty lists
205
+ completed_length = 0
206
+ while completed_length < aln_length:
207
+ # Note might have a coordinate header line (seems to be optional)
208
+ for idx, name in enumerate(ids):
209
+ line = handle.readline()
210
+ if idx == 0 and not line.strip():
211
+ # T-COFFEE uses two blank lines between blocks, rather than one
212
+ while line and not line.strip():
213
+ line = handle.readline()
214
+ if not line:
215
+ raise ValueError("End of file where expecting sequence data.")
216
+ # print("Looking for seq for %s in line: %r" % (name, line))
217
+ words = line.strip().split()
218
+ # Should we use column numbers, rather than assuming no spaces in names?
219
+ if idx == 0 and words and words[0] != name:
220
+ # print("Actually have a coord line")
221
+ # Hopefully this is a coordinate header before the first seq
222
+ try:
223
+ i = int(words[0])
224
+ except ValueError:
225
+ i = -1
226
+ if i != completed_length + 1:
227
+ raise ValueError(
228
+ "Expected GCG MSF coordinate line starting %i, got: %r"
229
+ % (completed_length + 1, line)
230
+ )
231
+ if len(words) > 1:
232
+ # Final block usually not full 50 chars, so expect start only.
233
+ if len(words) != 2:
234
+ i = -1
235
+ else:
236
+ try:
237
+ i = int(words[1])
238
+ except ValueError:
239
+ i = -1
240
+ if i != (
241
+ completed_length + 50
242
+ if completed_length + 50 < aln_length
243
+ else aln_length
244
+ ):
245
+ raise ValueError(
246
+ "Expected GCG MSF coordinate line %i to %i, got: %r"
247
+ % (
248
+ completed_length + 1,
249
+ (
250
+ completed_length + 50
251
+ if completed_length + 50 < aln_length
252
+ else aln_length
253
+ ),
254
+ line,
255
+ )
256
+ )
257
+ line = handle.readline()
258
+ words = line.strip().split()
259
+ # print("Still looking for seq for %s in line: %r" % (name, line))
260
+ # Dealt with any coordinate header line, should now be sequence
261
+ if not words:
262
+ # Should be sequence here, but perhaps its a short one?
263
+ if (
264
+ lengths[idx] < aln_length
265
+ and len("".join(seqs[idx])) == lengths[idx]
266
+ ):
267
+ # Is this actually allowed in the format? Personally I would
268
+ # expect a line with name and a block of trailing ~ here.
269
+ pass
270
+ else:
271
+ raise ValueError(f"Expected sequence for {name}, got: {line!r}")
272
+ elif words[0] == name:
273
+ assert len(words) > 1, line
274
+ # print(i, name, repr(words))
275
+ seqs[idx].extend(words[1:])
276
+ else:
277
+ raise ValueError(f"Expected sequence for {name!r}, got: {line!r}")
278
+ # TODO - check the sequence lengths thus far are consistent
279
+ # with blocks of 50?
280
+ completed_length += 50
281
+ line = handle.readline()
282
+ if line.strip():
283
+ raise ValueError(f"Expected blank line, got: {line!r}")
284
+
285
+ # Skip over any whitespace at the end...
286
+ while True:
287
+ line = handle.readline()
288
+ if not line:
289
+ # End of file, no more alignments
290
+ break
291
+ elif not line.strip():
292
+ # Blank line, ignore
293
+ pass
294
+ elif line.strip().split()[0] in known_headers:
295
+ # Looks like the start of another alignment:
296
+ self._header = line
297
+ break
298
+ else:
299
+ raise ValueError(f"Unexpected line after GCG MSF alignment: {line!r}")
300
+
301
+ # Combine list of strings into single string, remap gaps
302
+ seqs = ["".join(s).replace("~", "-").replace(".", "-") for s in seqs]
303
+
304
+ # Apply any trailing padding for short sequences
305
+ padded = False
306
+ for idx, (length, s) in enumerate(zip(lengths, seqs)):
307
+ if len(s) < aln_length and len(s) == length:
308
+ padded = True
309
+ seqs[idx] = s + "-" * (aln_length - len(s))
310
+ if padded:
311
+ import warnings
312
+
313
+ from Bio import BiopythonParserWarning
314
+
315
+ warnings.warn(
316
+ "One of more alignment sequences were truncated and have been gap padded",
317
+ BiopythonParserWarning,
318
+ )
319
+
320
+ records = (
321
+ SeqRecord(Seq(s), id=i, name=i, description=i, annotations={"weight": w})
322
+ for (i, s, w) in zip(ids, seqs, weights)
323
+ )
324
+
325
+ # This will check alignment lengths are self-consistent:
326
+ align = MultipleSeqAlignment(records)
327
+ # Check matches the header:
328
+ if align.get_alignment_length() != aln_length:
329
+ raise ValueError(
330
+ "GCG MSF headers said alignment length %i, but have %i"
331
+ % (aln_length, align.get_alignment_length())
332
+ )
333
+ return align
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/NexusIO.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2008-2010, 2012-2014, 2016-2017 by Peter Cock. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Bio.AlignIO support for the "nexus" file format.
8
+
9
+ You are expected to use this module via the Bio.AlignIO functions (or the
10
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
11
+
12
+ See also the Bio.Nexus module (which this code calls internally),
13
+ as this offers more than just accessing the alignment or its
14
+ sequences as SeqRecord objects.
15
+ """
16
+
17
+ from typing import IO
18
+ from collections.abc import Iterator
19
+ from typing import Optional
20
+
21
+ from Bio.Align import MultipleSeqAlignment
22
+ from Bio.AlignIO.Interfaces import AlignmentWriter
23
+ from Bio.Nexus import Nexus
24
+ from Bio.SeqRecord import SeqRecord
25
+
26
+ # You can get a couple of example files here:
27
+ # http://www.molecularevolution.org/resources/fileformats/
28
+
29
+
30
+ # This is a generator function!
31
+ def NexusIterator(
32
+ handle: IO[str], seq_count: int | None = None
33
+ ) -> Iterator[MultipleSeqAlignment]:
34
+ """Return SeqRecord objects from a Nexus file.
35
+
36
+ Thus uses the Bio.Nexus module to do the hard work.
37
+
38
+ You are expected to call this function via Bio.SeqIO or Bio.AlignIO
39
+ (and not use it directly).
40
+
41
+ NOTE - We only expect ONE alignment matrix per Nexus file,
42
+ meaning this iterator will only yield one MultipleSeqAlignment.
43
+ """
44
+ n = Nexus.Nexus(handle)
45
+ if not n.matrix:
46
+ # No alignment found
47
+ return
48
+
49
+ # Bio.Nexus deals with duplicated names by adding a '.copy' suffix.
50
+ # The original names and the modified names are kept in these two lists:
51
+ assert len(n.unaltered_taxlabels) == len(n.taxlabels)
52
+
53
+ if seq_count and seq_count != len(n.unaltered_taxlabels):
54
+ raise ValueError(
55
+ "Found %i sequences, but seq_count=%i"
56
+ % (len(n.unaltered_taxlabels), seq_count)
57
+ )
58
+
59
+ # TODO - Can we extract any annotation too?
60
+ annotations: SeqRecord._AnnotationsDict | None
61
+ if n.datatype in ("dna", "nucleotide"):
62
+ annotations = {"molecule_type": "DNA"}
63
+ elif n.datatype == "rna":
64
+ annotations = {"molecule_type": "RNA"}
65
+ elif n.datatype == "protein":
66
+ annotations = {"molecule_type": "protein"}
67
+ else:
68
+ annotations = None
69
+ records = (
70
+ SeqRecord(
71
+ n.matrix[new_name],
72
+ id=new_name,
73
+ name=old_name,
74
+ description="",
75
+ annotations=annotations,
76
+ )
77
+ for old_name, new_name in zip(n.unaltered_taxlabels, n.taxlabels)
78
+ )
79
+ # All done
80
+ yield MultipleSeqAlignment(records)
81
+
82
+
83
+ class NexusWriter(AlignmentWriter):
84
+ """Nexus alignment writer.
85
+
86
+ Note that Nexus files are only expected to hold ONE alignment
87
+ matrix.
88
+
89
+ You are expected to call this class via the Bio.AlignIO.write() or
90
+ Bio.SeqIO.write() functions.
91
+ """
92
+
93
+ def write_file(self, alignments):
94
+ """Use this to write an entire file containing the given alignments.
95
+
96
+ Arguments:
97
+ - alignments - A list or iterator returning MultipleSeqAlignment objects.
98
+ This should hold ONE and only one alignment.
99
+
100
+ """
101
+ align_iter = iter(alignments) # Could have been a list
102
+ try:
103
+ alignment = next(align_iter)
104
+ except StopIteration:
105
+ # Nothing to write!
106
+ return 0
107
+
108
+ # Check there is only one alignment...
109
+ try:
110
+ next(align_iter)
111
+ raise ValueError("We can only write one Alignment to a Nexus file.")
112
+ except StopIteration:
113
+ pass
114
+
115
+ # Good. Actually write the single alignment,
116
+ self.write_alignment(alignment)
117
+ return 1 # we only support writing one alignment!
118
+
119
+ def write_alignment(self, alignment, interleave=None):
120
+ """Write an alignment to file.
121
+
122
+ Creates an empty Nexus object, adds the sequences
123
+ and then gets Nexus to prepare the output.
124
+ Default interleave behaviour: Interleave if columns > 1000
125
+ --> Override with interleave=[True/False]
126
+ """
127
+ if len(alignment) == 0:
128
+ raise ValueError("Must have at least one sequence")
129
+ columns = alignment.get_alignment_length()
130
+ if columns == 0:
131
+ raise ValueError("Non-empty sequences are required")
132
+ datatype = self._classify_mol_type_for_nexus(alignment)
133
+ minimal_record = (
134
+ "#NEXUS\nbegin data; dimensions ntax=0 nchar=0; format datatype=%s; end;"
135
+ % datatype
136
+ )
137
+ n = Nexus.Nexus(minimal_record)
138
+ for record in alignment:
139
+ # Sanity test sequences (should this be even stricter?)
140
+ if datatype == "dna" and "U" in record.seq:
141
+ raise ValueError(f"{record.id} contains U, but DNA alignment")
142
+ elif datatype == "rna" and "T" in record.seq:
143
+ raise ValueError(f"{record.id} contains T, but RNA alignment")
144
+ n.add_sequence(record.id, str(record.seq))
145
+
146
+ # Note: MrBayes may choke on large alignments if not interleaved
147
+ if interleave is None:
148
+ interleave = columns > 1000
149
+ n.write_nexus_data(self.handle, interleave=interleave)
150
+
151
+ def _classify_mol_type_for_nexus(self, alignment):
152
+ """Return 'protein', 'dna', or 'rna' based on records' molecule type (PRIVATE).
153
+
154
+ All the records must have a molecule_type annotation, and they must
155
+ agree.
156
+
157
+ Raises an exception if this is not possible.
158
+ """
159
+ values = {_.annotations.get("molecule_type", None) for _ in alignment}
160
+ if all(_ and "DNA" in _ for _ in values):
161
+ return "dna" # could have been a mix of "DNA" and "gDNA"
162
+ elif all(_ and "RNA" in _ for _ in values):
163
+ return "rna" # could have been a mix of "RNA" and "mRNA"
164
+ elif all(_ and "protein" in _ for _ in values):
165
+ return "protein"
166
+ else:
167
+ raise ValueError("Need the molecule type to be defined")
168
+
169
+
170
+ if __name__ == "__main__":
171
+ from Bio._utils import run_doctest
172
+
173
+ run_doctest(verbose=0)
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/PhylipIO.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006-2016 by Peter Cock. All rights reserved.
2
+ # Revisions copyright 2011 Brandon Invergo. All rights reserved.
3
+ #
4
+ # This file is part of the Biopython distribution and governed by your
5
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
6
+ # Please see the LICENSE file that should have been included as part of this
7
+ # package.
8
+ """AlignIO support for "phylip" format from Joe Felsenstein's PHYLIP tools.
9
+
10
+ You are expected to use this module via the Bio.AlignIO functions (or the
11
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
12
+
13
+ Support for "relaxed phylip" format is also provided. Relaxed phylip differs
14
+ from standard phylip format in the following ways:
15
+
16
+ - No whitespace is allowed in the sequence ID.
17
+ - No truncation is performed. Instead, sequence IDs are padded to the longest
18
+ ID length, rather than 10 characters. A space separates the sequence
19
+ identifier from the sequence.
20
+
21
+ Relaxed phylip is supported by RAxML and PHYML.
22
+
23
+ Note
24
+ ====
25
+
26
+ In TREE_PUZZLE (Schmidt et al. 2003) and PHYML (Guindon and Gascuel 2003)
27
+ a dot/period (".") in a sequence is interpreted as meaning the same
28
+ character as in the first sequence. The PHYLIP documentation from 3.3 to 3.69
29
+ http://evolution.genetics.washington.edu/phylip/doc/sequence.html says:
30
+
31
+ "a period was also previously allowed but it is no longer allowed,
32
+ because it sometimes is used in different senses in other programs"
33
+
34
+ Biopython 1.58 or later treats dots/periods in the sequence as invalid, both
35
+ for reading and writing. Older versions did nothing special with a dot/period.
36
+ """
37
+
38
+ import string
39
+
40
+ from Bio.Align import MultipleSeqAlignment
41
+ from Bio.Seq import Seq
42
+ from Bio.SeqRecord import SeqRecord
43
+
44
+ from .Interfaces import AlignmentIterator
45
+ from .Interfaces import SequentialAlignmentWriter
46
+
47
+ _PHYLIP_ID_WIDTH = 10
48
+ _NO_DOTS = "PHYLIP format no longer allows dots in sequence"
49
+
50
+
51
+ class PhylipWriter(SequentialAlignmentWriter):
52
+ """Phylip alignment writer."""
53
+
54
+ def write_alignment(self, alignment, id_width=_PHYLIP_ID_WIDTH):
55
+ """Use this to write (another) single alignment to an open file.
56
+
57
+ This code will write interlaced alignments (when the sequences are
58
+ longer than 50 characters).
59
+
60
+ Note that record identifiers are strictly truncated to id_width,
61
+ defaulting to the value required to comply with the PHYLIP standard.
62
+
63
+ For more information on the file format, please see:
64
+ http://evolution.genetics.washington.edu/phylip/doc/sequence.html
65
+ http://evolution.genetics.washington.edu/phylip/doc/main.html#inputfiles
66
+ """
67
+ handle = self.handle
68
+
69
+ if len(alignment) == 0:
70
+ raise ValueError("Must have at least one sequence")
71
+ length_of_seqs = alignment.get_alignment_length()
72
+ for record in alignment:
73
+ if length_of_seqs != len(record.seq):
74
+ raise ValueError("Sequences must all be the same length")
75
+ if length_of_seqs <= 0:
76
+ raise ValueError("Non-empty sequences are required")
77
+
78
+ # Check for repeated identifiers...
79
+ # Apply this test *after* cleaning the identifiers
80
+ names = []
81
+ seqs = []
82
+ for record in alignment:
83
+ """
84
+ Quoting the PHYLIP version 3.6 documentation:
85
+
86
+ The name should be ten characters in length, filled out to
87
+ the full ten characters by blanks if shorter. Any printable
88
+ ASCII/ISO character is allowed in the name, except for
89
+ parentheses ("(" and ")"), square brackets ("[" and "]"),
90
+ colon (":"), semicolon (";") and comma (","). If you forget
91
+ to extend the names to ten characters in length by blanks,
92
+ the program [i.e. PHYLIP] will get out of synchronization
93
+ with the contents of the data file, and an error message will
94
+ result.
95
+
96
+ Note that Tab characters count as only one character in the
97
+ species names. Their inclusion can cause trouble.
98
+ """
99
+ name = sanitize_name(record.id, id_width)
100
+ if name in names:
101
+ raise ValueError(
102
+ "Repeated name %r (originally %r), possibly due to truncation"
103
+ % (name, record.id)
104
+ )
105
+ names.append(name)
106
+ sequence = str(record.seq)
107
+ if "." in sequence:
108
+ # Do this check here (once per record, not once per block)
109
+ raise ValueError(_NO_DOTS)
110
+ seqs.append(sequence)
111
+
112
+ # From experimentation, the use of tabs is not understood by the
113
+ # EMBOSS suite. The nature of the expected white space is not
114
+ # defined in the PHYLIP documentation, simply "These are in free
115
+ # format, separated by blanks". We'll use spaces to keep EMBOSS
116
+ # happy.
117
+ handle.write(" %i %s\n" % (len(alignment), length_of_seqs))
118
+ block = 0
119
+ while True:
120
+ for name, sequence in zip(names, seqs):
121
+ if block == 0:
122
+ # Write name (truncated/padded to id_width characters)
123
+ # Now truncate and right pad to expected length.
124
+ handle.write(name[:id_width].ljust(id_width))
125
+ else:
126
+ # write indent
127
+ handle.write(" " * id_width)
128
+ # Write five chunks of ten letters per line...
129
+ for chunk in range(5):
130
+ i = block * 50 + chunk * 10
131
+ seq_segment = sequence[i : i + 10]
132
+ # TODO - Force any gaps to be '-' character?
133
+ # TODO - How to cope with '?' or '.' in the sequence?
134
+ handle.write(f" {seq_segment}")
135
+ if i + 10 > length_of_seqs:
136
+ break
137
+ handle.write("\n")
138
+ block += 1
139
+ if block * 50 >= length_of_seqs:
140
+ break
141
+ handle.write("\n")
142
+
143
+
144
+ class PhylipIterator(AlignmentIterator):
145
+ """Reads a Phylip alignment file returning a MultipleSeqAlignment iterator.
146
+
147
+ Record identifiers are limited to at most 10 characters.
148
+
149
+ It only copes with interlaced phylip files! Sequential files won't work
150
+ where the sequences are split over multiple lines.
151
+
152
+ For more information on the file format, please see:
153
+ http://evolution.genetics.washington.edu/phylip/doc/sequence.html
154
+ http://evolution.genetics.washington.edu/phylip/doc/main.html#inputfiles
155
+ """
156
+
157
+ # Default truncation length
158
+ id_width = _PHYLIP_ID_WIDTH
159
+
160
+ _header = None # for caching lines between __next__ calls
161
+
162
+ def _is_header(self, line):
163
+ line = line.strip()
164
+ parts = [x for x in line.split() if x]
165
+ if len(parts) != 2:
166
+ return False # First line should have two integers
167
+ try:
168
+ number_of_seqs = int(parts[0])
169
+ length_of_seqs = int(parts[1])
170
+ return True
171
+ except ValueError:
172
+ return False # First line should have two integers
173
+
174
+ def _split_id(self, line):
175
+ """Extract the sequence ID from a Phylip line (PRIVATE).
176
+
177
+ Returning a tuple containing: (sequence_id, sequence_residues)
178
+
179
+ The first 10 characters in the line are are the sequence id, the
180
+ remainder are sequence data.
181
+ """
182
+ seq_id = line[: self.id_width].strip()
183
+ seq = line[self.id_width :].strip().replace(" ", "")
184
+ return seq_id, seq
185
+
186
+ def __next__(self):
187
+ """Parse the next alignment from the handle."""
188
+ handle = self.handle
189
+
190
+ if self._header is None:
191
+ line = handle.readline()
192
+ else:
193
+ # Header we saved from when we were parsing
194
+ # the previous alignment.
195
+ line = self._header
196
+ self._header = None
197
+
198
+ if not line:
199
+ raise StopIteration
200
+ line = line.strip()
201
+ parts = [x for x in line.split() if x]
202
+ if len(parts) != 2:
203
+ raise ValueError("First line should have two integers")
204
+ try:
205
+ number_of_seqs = int(parts[0])
206
+ length_of_seqs = int(parts[1])
207
+ except ValueError:
208
+ raise ValueError("First line should have two integers") from None
209
+
210
+ assert self._is_header(line)
211
+
212
+ if (
213
+ self.records_per_alignment is not None
214
+ and self.records_per_alignment != number_of_seqs
215
+ ):
216
+ raise ValueError(
217
+ "Found %i records in this alignment, told to expect %i"
218
+ % (number_of_seqs, self.records_per_alignment)
219
+ )
220
+
221
+ ids = []
222
+ seqs = []
223
+
224
+ # By default, expects STRICT truncation / padding to 10 characters.
225
+ # Does not require any whitespace between name and seq.
226
+ for i in range(number_of_seqs):
227
+ line = handle.readline().rstrip()
228
+ sequence_id, s = self._split_id(line)
229
+ ids.append(sequence_id)
230
+ if "." in s:
231
+ raise ValueError(_NO_DOTS)
232
+ seqs.append([s])
233
+
234
+ # Look for further blocks
235
+ line = ""
236
+ while True:
237
+ # Skip any blank lines between blocks...
238
+ while "" == line.strip():
239
+ line = handle.readline()
240
+ if not line:
241
+ break # end of file
242
+ if not line:
243
+ break # end of file
244
+
245
+ if self._is_header(line):
246
+ # Looks like the start of a concatenated alignment
247
+ self._header = line
248
+ break
249
+
250
+ # print("New block...")
251
+ for i in range(number_of_seqs):
252
+ s = line.strip().replace(" ", "")
253
+ if "." in s:
254
+ raise ValueError(_NO_DOTS)
255
+ seqs[i].append(s)
256
+ line = handle.readline()
257
+ if (not line) and i + 1 < number_of_seqs:
258
+ raise ValueError("End of file mid-block")
259
+ if not line:
260
+ break # end of file
261
+
262
+ records = (
263
+ SeqRecord(Seq("".join(s)), id=i, name=i, description=i)
264
+ for (i, s) in zip(ids, seqs)
265
+ )
266
+ return MultipleSeqAlignment(records)
267
+
268
+
269
+ # Relaxed Phylip
270
+ class RelaxedPhylipWriter(PhylipWriter):
271
+ """Relaxed Phylip format writer."""
272
+
273
+ def write_alignment(self, alignment):
274
+ """Write a relaxed phylip alignment."""
275
+ # Check inputs
276
+ for name in (s.id.strip() for s in alignment):
277
+ if any(c in name for c in string.whitespace):
278
+ raise ValueError(f"Whitespace not allowed in identifier: {name}")
279
+
280
+ # Calculate a truncation length - maximum length of sequence ID plus a
281
+ # single character for padding
282
+ # If no sequences, set id_width to 1. super(...) call will raise a
283
+ # ValueError
284
+ if len(alignment) == 0:
285
+ id_width = 1
286
+ else:
287
+ id_width = max(len(s.id.strip()) for s in alignment) + 1
288
+ super().write_alignment(alignment, id_width)
289
+
290
+
291
+ class RelaxedPhylipIterator(PhylipIterator):
292
+ """Relaxed Phylip format Iterator."""
293
+
294
+ def _split_id(self, line):
295
+ """Extract the sequence ID from a Phylip line (PRIVATE).
296
+
297
+ Returns a tuple containing: (sequence_id, sequence_residues)
298
+
299
+ For relaxed format split at the first whitespace character.
300
+ """
301
+ seq_id, sequence = line.split(None, 1)
302
+ sequence = sequence.strip().replace(" ", "")
303
+ return seq_id, sequence
304
+
305
+
306
+ class SequentialPhylipWriter(SequentialAlignmentWriter):
307
+ """Sequential Phylip format Writer."""
308
+
309
+ def write_alignment(self, alignment, id_width=_PHYLIP_ID_WIDTH):
310
+ """Write a Phylip alignment to the handle."""
311
+ handle = self.handle
312
+
313
+ if len(alignment) == 0:
314
+ raise ValueError("Must have at least one sequence")
315
+ length_of_seqs = alignment.get_alignment_length()
316
+ for record in alignment:
317
+ if length_of_seqs != len(record.seq):
318
+ raise ValueError("Sequences must all be the same length")
319
+ if length_of_seqs <= 0:
320
+ raise ValueError("Non-empty sequences are required")
321
+
322
+ # Check for repeated identifiers...
323
+ # Apply this test *after* cleaning the identifiers
324
+ names = []
325
+ for record in alignment:
326
+ # Either remove the banned characters, or map them to something
327
+ # else like an underscore "_" or pipe "|" character...
328
+ name = sanitize_name(record.id, id_width)
329
+ if name in names:
330
+ raise ValueError(
331
+ "Repeated name %r (originally %r), possibly due to truncation"
332
+ % (name, record.id)
333
+ )
334
+ names.append(name)
335
+
336
+ # From experimentation, the use of tabs is not understood by the
337
+ # EMBOSS suite. The nature of the expected white space is not
338
+ # defined in the PHYLIP documentation, simply "These are in free
339
+ # format, separated by blanks". We'll use spaces to keep EMBOSS
340
+ # happy.
341
+ handle.write(" %i %s\n" % (len(alignment), length_of_seqs))
342
+ for name, record in zip(names, alignment):
343
+ sequence = str(record.seq)
344
+ if "." in sequence:
345
+ raise ValueError(_NO_DOTS)
346
+ handle.write(name[:id_width].ljust(id_width))
347
+ # Write the entire sequence to one line (see sequential format
348
+ # notes in the SequentialPhylipIterator docstring
349
+ handle.write(sequence)
350
+ handle.write("\n")
351
+
352
+
353
+ class SequentialPhylipIterator(PhylipIterator):
354
+ """Sequential Phylip format Iterator.
355
+
356
+ The sequential format carries the same restrictions as the normal
357
+ interleaved one, with the difference being that the sequences are listed
358
+ sequentially, each sequence written in its entirety before the start of
359
+ the next. According to the PHYLIP documentation for input file
360
+ formatting, newlines and spaces may optionally be entered at any point
361
+ in the sequences.
362
+ """
363
+
364
+ _header = None # for caching lines between __next__ calls
365
+
366
+ def __next__(self):
367
+ """Parse the next alignment from the handle."""
368
+ handle = self.handle
369
+
370
+ if self._header is None:
371
+ line = handle.readline()
372
+ else:
373
+ # Header we saved from when we were parsing
374
+ # the previous alignment.
375
+ line = self._header
376
+ self._header = None
377
+
378
+ if not line:
379
+ raise StopIteration
380
+ line = line.strip()
381
+ parts = [x for x in line.split() if x]
382
+ if len(parts) != 2:
383
+ raise ValueError("First line should have two integers")
384
+ try:
385
+ number_of_seqs = int(parts[0])
386
+ length_of_seqs = int(parts[1])
387
+ except ValueError:
388
+ raise ValueError("First line should have two integers") from None
389
+
390
+ assert self._is_header(line)
391
+
392
+ if (
393
+ self.records_per_alignment is not None
394
+ and self.records_per_alignment != number_of_seqs
395
+ ):
396
+ raise ValueError(
397
+ "Found %i records in this alignment, told to expect %i"
398
+ % (number_of_seqs, self.records_per_alignment)
399
+ )
400
+
401
+ ids = []
402
+ seqs = []
403
+
404
+ # By default, expects STRICT truncation / padding to 10 characters.
405
+ # Does not require any whitespace between name and seq.
406
+ for i in range(number_of_seqs):
407
+ line = handle.readline().rstrip()
408
+ sequence_id, s = self._split_id(line)
409
+ ids.append(sequence_id)
410
+ while len(s) < length_of_seqs:
411
+ # The sequence may be split into multiple lines
412
+ line = handle.readline().strip()
413
+ if not line:
414
+ break
415
+ if line == "":
416
+ continue
417
+ s = "".join([s, line.strip().replace(" ", "")])
418
+ if len(s) > length_of_seqs:
419
+ raise ValueError(
420
+ "Found a record of length %i, "
421
+ "should be %i" % (len(s), length_of_seqs)
422
+ )
423
+ if "." in s:
424
+ raise ValueError(_NO_DOTS)
425
+ seqs.append(s)
426
+ while True:
427
+ # Find other alignments in the file
428
+ line = handle.readline()
429
+ if not line:
430
+ break
431
+ if self._is_header(line):
432
+ self._header = line
433
+ break
434
+
435
+ records = (
436
+ SeqRecord(Seq(s), id=i, name=i, description=i) for (i, s) in zip(ids, seqs)
437
+ )
438
+ return MultipleSeqAlignment(records)
439
+
440
+
441
+ def sanitize_name(name, width=None):
442
+ """Sanitise sequence identifier for output.
443
+
444
+ Removes the banned characters "[]()" and replaces the characters ":;"
445
+ with "|". The name is truncated to "width" characters if specified.
446
+ """
447
+ name = name.strip()
448
+ for char in "[](),":
449
+ name = name.replace(char, "")
450
+ for char in ":;":
451
+ name = name.replace(char, "|")
452
+ if width is not None:
453
+ name = name[:width]
454
+ return name
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/StockholmIO.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2006-2016 by Peter Cock. All rights reserved.
2
+ # Revisions copyright 2015 by Ben Woodcroft. All rights reserved.
3
+ #
4
+ # This file is part of the Biopython distribution and governed by your
5
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
6
+ # Please see the LICENSE file that should have been included as part of this
7
+ # package.
8
+ """Bio.AlignIO support for "stockholm" format (used in the PFAM database).
9
+
10
+ You are expected to use this module via the Bio.AlignIO functions (or the
11
+ Bio.SeqIO functions if you want to work directly with the gapped sequences).
12
+
13
+ For example, consider a Stockholm alignment file containing the following::
14
+
15
+ # STOCKHOLM 1.0
16
+ #=GC SS_cons .................<<<<<<<<...<<<<<<<........>>>>>>>..
17
+ AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGU
18
+ #=GR AP001509.1 SS -----------------<<<<<<<<---..<<-<<-------->>->>..--
19
+ AE007476.1 AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGU
20
+ #=GR AE007476.1 SS -----------------<<<<<<<<-----<<.<<-------->>.>>----
21
+
22
+ #=GC SS_cons ......<<<<<<<.......>>>>>>>..>>>>>>>>...............
23
+ AP001509.1 CUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
24
+ #=GR AP001509.1 SS -------<<<<<--------->>>>>--->>>>>>>>---------------
25
+ AE007476.1 UUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
26
+ #=GR AE007476.1 SS ------.<<<<<--------->>>>>.-->>>>>>>>---------------
27
+ //
28
+
29
+ This is a single multiple sequence alignment, so you would probably load this
30
+ using the Bio.AlignIO.read() function:
31
+
32
+ >>> from Bio import AlignIO
33
+ >>> align = AlignIO.read("Stockholm/simple.sth", "stockholm")
34
+ >>> print(align)
35
+ Alignment with 2 rows and 104 columns
36
+ UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-G...UGU AP001509.1
37
+ AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-C...GAU AE007476.1
38
+ >>> for record in align:
39
+ ... print("%s %i" % (record.id, len(record)))
40
+ AP001509.1 104
41
+ AE007476.1 104
42
+
43
+ In addition to the sequences themselves, this example alignment also includes
44
+ some GR lines for the secondary structure of the sequences. These are
45
+ strings, with one character for each letter in the associated sequence:
46
+
47
+ >>> for record in align:
48
+ ... print(record.id)
49
+ ... print(record.seq)
50
+ ... print(record.letter_annotations['secondary_structure'])
51
+ AP001509.1
52
+ UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
53
+ -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>---------------
54
+ AE007476.1
55
+ AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
56
+ -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>---------------
57
+
58
+ Any general annotation for each row is recorded in the SeqRecord's annotations
59
+ dictionary. Any per-column annotation for the entire alignment in in the
60
+ alignment's column annotations dictionary, such as the secondary structure
61
+ consensus in this example:
62
+
63
+ >>> sorted(align.column_annotations.keys())
64
+ ['secondary_structure']
65
+ >>> align.column_annotations["secondary_structure"]
66
+ '.................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............'
67
+
68
+ You can output this alignment in many different file formats
69
+ using Bio.AlignIO.write(), or the MultipleSeqAlignment object's format method:
70
+
71
+ >>> print(format(align, "fasta"))
72
+ >AP001509.1
73
+ UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-A
74
+ GGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
75
+ >AE007476.1
76
+ AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAA
77
+ GGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
78
+ <BLANKLINE>
79
+
80
+ Most output formats won't be able to hold the annotation possible in a
81
+ Stockholm file:
82
+
83
+ >>> print(format(align, "stockholm"))
84
+ # STOCKHOLM 1.0
85
+ #=GF SQ 2
86
+ AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
87
+ #=GS AP001509.1 AC AP001509.1
88
+ #=GS AP001509.1 DE AP001509.1
89
+ #=GR AP001509.1 SS -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>---------------
90
+ AE007476.1 AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
91
+ #=GS AE007476.1 AC AE007476.1
92
+ #=GS AE007476.1 DE AE007476.1
93
+ #=GR AE007476.1 SS -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>---------------
94
+ #=GC SS_cons .................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............
95
+ //
96
+ <BLANKLINE>
97
+
98
+ Note that when writing Stockholm files, AlignIO does not break long sequences
99
+ up and interleave them (as in the input file shown above). The standard
100
+ allows this simpler layout, and it is more likely to be understood by other
101
+ tools.
102
+
103
+ Finally, as an aside, it can sometimes be useful to use Bio.SeqIO.parse() to
104
+ iterate over the alignment rows as SeqRecord objects - rather than working
105
+ with Alignnment objects.
106
+
107
+ >>> from Bio import SeqIO
108
+ >>> for record in SeqIO.parse("Stockholm/simple.sth", "stockholm"):
109
+ ... print(record.id)
110
+ ... print(record.seq)
111
+ ... print(record.letter_annotations['secondary_structure'])
112
+ AP001509.1
113
+ UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
114
+ -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>---------------
115
+ AE007476.1
116
+ AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
117
+ -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>---------------
118
+
119
+ Remember that if you slice a SeqRecord, the per-letter-annotations like the
120
+ secondary structure string here, are also sliced:
121
+
122
+ >>> sub_record = record[10:20]
123
+ >>> print(sub_record.seq)
124
+ AUCGUUUUAC
125
+ >>> print(sub_record.letter_annotations['secondary_structure'])
126
+ -------<<<
127
+
128
+ Likewise with the alignment object, as long as you are not dropping any rows,
129
+ slicing specific columns of an alignment will slice any per-column-annotations:
130
+
131
+ >>> align.column_annotations["secondary_structure"]
132
+ '.................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............'
133
+ >>> part_align = align[:,10:20]
134
+ >>> part_align.column_annotations["secondary_structure"]
135
+ '.......<<<'
136
+
137
+ You can also see this in the Stockholm output of this partial-alignment:
138
+
139
+ >>> print(format(part_align, "stockholm"))
140
+ # STOCKHOLM 1.0
141
+ #=GF SQ 2
142
+ AP001509.1 UCAACACUCU
143
+ #=GS AP001509.1 AC AP001509.1
144
+ #=GS AP001509.1 DE AP001509.1
145
+ #=GR AP001509.1 SS -------<<<
146
+ AE007476.1 AUCGUUUUAC
147
+ #=GS AE007476.1 AC AE007476.1
148
+ #=GS AE007476.1 DE AE007476.1
149
+ #=GR AE007476.1 SS -------<<<
150
+ #=GC SS_cons .......<<<
151
+ //
152
+ <BLANKLINE>
153
+
154
+ """
155
+
156
+ from Bio.Align import MultipleSeqAlignment
157
+ from Bio.Seq import Seq
158
+ from Bio.SeqRecord import SeqRecord
159
+
160
+ from .Interfaces import AlignmentIterator
161
+ from .Interfaces import SequentialAlignmentWriter
162
+
163
+
164
+ class StockholmWriter(SequentialAlignmentWriter):
165
+ """Stockholm/PFAM alignment writer."""
166
+
167
+ # These dictionaries should be kept in sync with those
168
+ # defined in the StockholmIterator class.
169
+ pfam_gr_mapping = {
170
+ "secondary_structure": "SS",
171
+ "surface_accessibility": "SA",
172
+ "transmembrane": "TM",
173
+ "posterior_probability": "PP",
174
+ "ligand_binding": "LI",
175
+ "active_site": "AS",
176
+ "intron": "IN",
177
+ }
178
+ # These GC mappings are in addition to *_cons in GR mapping:
179
+ pfam_gc_mapping = {"reference_annotation": "RF", "model_mask": "MM"}
180
+ # Following dictionary deliberately does not cover AC, DE or DR
181
+ pfam_gs_mapping = {"organism": "OS", "organism_classification": "OC", "look": "LO"}
182
+
183
+ def write_alignment(self, alignment):
184
+ """Use this to write (another) single alignment to an open file.
185
+
186
+ Note that sequences and their annotation are recorded
187
+ together (rather than having a block of annotation followed
188
+ by a block of aligned sequences).
189
+ """
190
+ count = len(alignment)
191
+
192
+ self._length_of_sequences = alignment.get_alignment_length()
193
+ self._ids_written = []
194
+
195
+ if count == 0:
196
+ raise ValueError("Must have at least one sequence")
197
+ if self._length_of_sequences == 0:
198
+ raise ValueError("Non-empty sequences are required")
199
+
200
+ self.handle.write("# STOCKHOLM 1.0\n")
201
+ self.handle.write("#=GF SQ %i\n" % count)
202
+ for record in alignment:
203
+ self._write_record(record)
204
+ # This shouldn't be None... but just in case,
205
+ if alignment.column_annotations:
206
+ for k, v in sorted(alignment.column_annotations.items()):
207
+ if k in self.pfam_gc_mapping:
208
+ self.handle.write(f"#=GC {self.pfam_gc_mapping[k]} {v}\n")
209
+ elif k in self.pfam_gr_mapping:
210
+ self.handle.write(f"#=GC {self.pfam_gr_mapping[k]}_cons {v}\n")
211
+ else:
212
+ # It doesn't follow the PFAM standards, but should we record
213
+ # this data anyway?
214
+ pass
215
+ self.handle.write("//\n")
216
+
217
+ def _write_record(self, record):
218
+ """Write a single SeqRecord to the file (PRIVATE)."""
219
+ if self._length_of_sequences != len(record.seq):
220
+ raise ValueError("Sequences must all be the same length")
221
+
222
+ # For the case for stockholm to stockholm, try and use record.name
223
+ seq_name = record.id
224
+ if record.name is not None:
225
+ if "accession" in record.annotations:
226
+ if record.id == record.annotations["accession"]:
227
+ seq_name = record.name
228
+
229
+ # In the Stockholm file format, spaces are not allowed in the id
230
+ seq_name = seq_name.replace(" ", "_")
231
+
232
+ if "start" in record.annotations and "end" in record.annotations:
233
+ suffix = f"/{record.annotations['start']}-{record.annotations['end']}"
234
+ if seq_name[-len(suffix) :] != suffix:
235
+ seq_name = "%s/%s-%s" % (
236
+ seq_name,
237
+ record.annotations["start"],
238
+ record.annotations["end"],
239
+ )
240
+
241
+ if seq_name in self._ids_written:
242
+ raise ValueError(f"Duplicate record identifier: {seq_name}")
243
+ self._ids_written.append(seq_name)
244
+ self.handle.write(f"{seq_name} {record.seq}\n")
245
+
246
+ # The recommended placement for GS lines (per sequence annotation)
247
+ # is above the alignment (as a header block) or just below the
248
+ # corresponding sequence.
249
+ #
250
+ # The recommended placement for GR lines (per sequence per column
251
+ # annotation such as secondary structure) is just below the
252
+ # corresponding sequence.
253
+ #
254
+ # We put both just below the corresponding sequence as this allows
255
+ # us to write the file using a single pass through the records.
256
+
257
+ # AC = Accession
258
+ if "accession" in record.annotations:
259
+ self.handle.write(
260
+ f"#=GS {seq_name} AC {self.clean(record.annotations['accession'])}\n"
261
+ )
262
+ elif record.id:
263
+ self.handle.write(f"#=GS {seq_name} AC {self.clean(record.id)}\n")
264
+
265
+ # DE = description
266
+ if record.description:
267
+ self.handle.write(f"#=GS {seq_name} DE {self.clean(record.description)}\n")
268
+
269
+ # DE = database links
270
+ for xref in record.dbxrefs:
271
+ self.handle.write(f"#=GS {seq_name} DR {self.clean(xref)}\n")
272
+
273
+ # GS = other per sequence annotation
274
+ for key, value in record.annotations.items():
275
+ if key in self.pfam_gs_mapping:
276
+ data = self.clean(str(value))
277
+ if data:
278
+ self.handle.write(
279
+ "#=GS %s %s %s\n"
280
+ % (seq_name, self.clean(self.pfam_gs_mapping[key]), data)
281
+ )
282
+ else:
283
+ # It doesn't follow the PFAM standards, but should we record
284
+ # this data anyway?
285
+ pass
286
+
287
+ # GR = per row per column sequence annotation
288
+ for key, value in record.letter_annotations.items():
289
+ if key in self.pfam_gr_mapping and len(str(value)) == len(record.seq):
290
+ data = self.clean(str(value))
291
+ if data:
292
+ self.handle.write(
293
+ "#=GR %s %s %s\n"
294
+ % (seq_name, self.clean(self.pfam_gr_mapping[key]), data)
295
+ )
296
+ else:
297
+ # It doesn't follow the PFAM standards, but should we record
298
+ # this data anyway?
299
+ pass
300
+
301
+
302
+ class StockholmIterator(AlignmentIterator):
303
+ """Loads a Stockholm file from PFAM into MultipleSeqAlignment objects.
304
+
305
+ The file may contain multiple concatenated alignments, which are loaded
306
+ and returned incrementally.
307
+
308
+ This parser will detect if the Stockholm file follows the PFAM
309
+ conventions for sequence specific meta-data (lines starting #=GS
310
+ and #=GR) and populates the SeqRecord fields accordingly.
311
+
312
+ Any annotation which does not follow the PFAM conventions is currently
313
+ ignored.
314
+
315
+ If an accession is provided for an entry in the meta data, IT WILL NOT
316
+ be used as the record.id (it will be recorded in the record's
317
+ annotations). This is because some files have (sub) sequences from
318
+ different parts of the same accession (differentiated by different
319
+ start-end positions).
320
+
321
+ Wrap-around alignments are not supported - each sequences must be on
322
+ a single line. However, interlaced sequences should work.
323
+
324
+ For more information on the file format, please see:
325
+ http://sonnhammer.sbc.su.se/Stockholm.html
326
+ https://en.wikipedia.org/wiki/Stockholm_format
327
+ http://bioperl.org/formats/alignment_formats/Stockholm_multiple_alignment_format.html
328
+
329
+ For consistency with BioPerl and EMBOSS we call this the "stockholm"
330
+ format.
331
+ """
332
+
333
+ # These dictionaries should be kept in sync with those
334
+ # defined in the PfamStockholmWriter class.
335
+ pfam_gr_mapping = {
336
+ "SS": "secondary_structure",
337
+ "SA": "surface_accessibility",
338
+ "TM": "transmembrane",
339
+ "PP": "posterior_probability",
340
+ "LI": "ligand_binding",
341
+ "AS": "active_site",
342
+ "IN": "intron",
343
+ }
344
+ # These GC mappings are in addition to *_cons in GR mapping:
345
+ pfam_gc_mapping = {"RF": "reference_annotation", "MM": "model_mask"}
346
+ # Following dictionary deliberately does not cover AC, DE or DR
347
+ pfam_gs_mapping = {"OS": "organism", "OC": "organism_classification", "LO": "look"}
348
+
349
+ _header = None # for caching lines between __next__ calls
350
+
351
+ def __next__(self):
352
+ """Parse the next alignment from the handle."""
353
+ handle = self.handle
354
+
355
+ if self._header is None:
356
+ line = handle.readline()
357
+ else:
358
+ # Header we saved from when we were parsing
359
+ # the previous alignment.
360
+ line = self._header
361
+ self._header = None
362
+
363
+ if not line:
364
+ # Empty file - just give up.
365
+ raise StopIteration
366
+ if line.strip() != "# STOCKHOLM 1.0":
367
+ raise ValueError("Did not find STOCKHOLM header")
368
+
369
+ # Note: If this file follows the PFAM conventions, there should be
370
+ # a line containing the number of sequences, e.g. "#=GF SQ 67"
371
+ # We do not check for this - perhaps we should, and verify that
372
+ # if present it agrees with our parsing.
373
+
374
+ seqs = {}
375
+ ids = {} # Really only need an OrderedSet, but python lacks this
376
+ gs = {}
377
+ gr = {}
378
+ gf = {}
379
+ gc = {}
380
+ passed_end_alignment = False
381
+ while True:
382
+ line = handle.readline()
383
+ if not line:
384
+ break # end of file
385
+ line = line.strip() # remove trailing \n
386
+ if line == "# STOCKHOLM 1.0":
387
+ self._header = line
388
+ break
389
+ elif line == "//":
390
+ # The "//" line indicates the end of the alignment.
391
+ # There may still be more meta-data
392
+ passed_end_alignment = True
393
+ elif line == "":
394
+ # blank line, ignore
395
+ pass
396
+ elif line[0] != "#":
397
+ # Sequence
398
+ # Format: "<seqname> <sequence>"
399
+ assert not passed_end_alignment
400
+ parts = [x.strip() for x in line.split(" ", 1)]
401
+ if len(parts) != 2:
402
+ # This might be someone attempting to store a zero length sequence?
403
+ raise ValueError(
404
+ "Could not split line into identifier and sequence:\n" + line
405
+ )
406
+ seq_id, seq = parts
407
+ if seq_id not in ids:
408
+ ids[seq_id] = True
409
+ seqs.setdefault(seq_id, "")
410
+ seqs[seq_id] += seq.replace(".", "-")
411
+ elif len(line) >= 5:
412
+ # Comment line or meta-data
413
+ if line[:5] == "#=GF ":
414
+ # Generic per-File annotation, free text
415
+ # Format: #=GF <feature> <free text>
416
+ feature, text = line[5:].strip().split(None, 1)
417
+ # Each feature key could be used more than once,
418
+ # so store the entries as a list of strings.
419
+ if feature not in gf:
420
+ gf[feature] = [text]
421
+ else:
422
+ gf[feature].append(text)
423
+ elif line[:5] == "#=GC ":
424
+ # Generic per-Column annotation, exactly 1 char per column
425
+ # Format: "#=GC <feature> <exactly 1 char per column>"
426
+ feature, text = line[5:].strip().split(None, 2)
427
+ if feature not in gc:
428
+ gc[feature] = ""
429
+ gc[feature] += text.strip() # append to any previous entry
430
+ # Might be interleaved blocks, so can't check length yet
431
+ elif line[:5] == "#=GS ":
432
+ # Generic per-Sequence annotation, free text
433
+ # Format: "#=GS <seqname> <feature> <free text>"
434
+ try:
435
+ seq_id, feature, text = line[5:].strip().split(None, 2)
436
+ except ValueError:
437
+ # Free text can sometimes be empty, which a one line split throws an error for.
438
+ # See https://github.com/biopython/biopython/issues/2982 for more details
439
+ seq_id, feature = line[5:].strip().split(None, 1)
440
+ text = ""
441
+ # if seq_id not in ids:
442
+ # ids.append(seq_id)
443
+ if seq_id not in gs:
444
+ gs[seq_id] = {}
445
+ if feature not in gs[seq_id]:
446
+ gs[seq_id][feature] = [text]
447
+ else:
448
+ gs[seq_id][feature].append(text)
449
+ elif line[:5] == "#=GR ":
450
+ # Generic per-Sequence AND per-Column markup
451
+ # Format: "#=GR <seqname> <feature> <exactly 1 char per column>"
452
+ seq_id, feature, text = line[5:].strip().split(None, 2)
453
+ # if seq_id not in ids:
454
+ # ids.append(seq_id)
455
+ if seq_id not in gr:
456
+ gr[seq_id] = {}
457
+ if feature not in gr[seq_id]:
458
+ gr[seq_id][feature] = ""
459
+ gr[seq_id][feature] += text.strip() # append to any previous entry
460
+ # Might be interleaved blocks, so can't check length yet
461
+ # Next line...
462
+
463
+ assert len(seqs) <= len(ids)
464
+ # assert len(gs) <= len(ids)
465
+ # assert len(gr) <= len(ids)
466
+
467
+ self.ids = ids.keys()
468
+ self.sequences = seqs
469
+ self.seq_annotation = gs
470
+ self.seq_col_annotation = gr
471
+
472
+ if ids and seqs:
473
+ if (
474
+ self.records_per_alignment is not None
475
+ and self.records_per_alignment != len(ids)
476
+ ):
477
+ raise ValueError(
478
+ "Found %i records in this alignment, told to expect %i"
479
+ % (len(ids), self.records_per_alignment)
480
+ )
481
+
482
+ alignment_length = len(list(seqs.values())[0])
483
+ records = [] # Alignment obj will put them all in a list anyway
484
+ for seq_id in ids:
485
+ seq = seqs[seq_id]
486
+ if alignment_length != len(seq):
487
+ raise ValueError(
488
+ "Sequences have different lengths, or repeated identifier"
489
+ )
490
+ name, start, end = self._identifier_split(seq_id)
491
+ record = SeqRecord(
492
+ Seq(seq),
493
+ id=seq_id,
494
+ name=name,
495
+ description=seq_id,
496
+ annotations={"accession": name},
497
+ )
498
+ # Accession will be overridden by _populate_meta_data if an explicit
499
+ # accession is provided:
500
+ record.annotations["accession"] = name
501
+
502
+ if start is not None:
503
+ record.annotations["start"] = start
504
+ if end is not None:
505
+ record.annotations["end"] = end
506
+
507
+ self._populate_meta_data(seq_id, record)
508
+ records.append(record)
509
+ for k, v in gc.items():
510
+ if len(v) != alignment_length:
511
+ raise ValueError(
512
+ "%s length %i, expected %i" % (k, len(v), alignment_length)
513
+ )
514
+ alignment = MultipleSeqAlignment(records)
515
+
516
+ for k, v in sorted(gc.items()):
517
+ if k in self.pfam_gc_mapping:
518
+ alignment.column_annotations[self.pfam_gc_mapping[k]] = v
519
+ elif k.endswith("_cons") and k[:-5] in self.pfam_gr_mapping:
520
+ alignment.column_annotations[self.pfam_gr_mapping[k[:-5]]] = v
521
+ else:
522
+ # Ignore it?
523
+ alignment.column_annotations["GC:" + k] = v
524
+
525
+ # TODO - Introduce an annotated alignment class?
526
+ # For now, store the annotation a new private property:
527
+ alignment._annotations = gr
528
+
529
+ return alignment
530
+ else:
531
+ raise StopIteration
532
+
533
+ def _identifier_split(self, identifier):
534
+ """Return (name, start, end) string tuple from an identifier (PRIVATE)."""
535
+ if "/" in identifier:
536
+ name, start_end = identifier.rsplit("/", 1)
537
+ if start_end.count("-") == 1:
538
+ try:
539
+ start, end = start_end.split("-")
540
+ return name, int(start), int(end)
541
+ except ValueError:
542
+ # Non-integers after final '/' - fall through
543
+ pass
544
+ return identifier, None, None
545
+
546
+ def _get_meta_data(self, identifier, meta_dict):
547
+ """Take an identifier and returns dict of all meta-data matching it (PRIVATE).
548
+
549
+ For example, given "Q9PN73_CAMJE/149-220" will return all matches to
550
+ this or "Q9PN73_CAMJE" which the identifier without its /start-end
551
+ suffix.
552
+
553
+ In the example below, the suffix is required to match the AC, but must
554
+ be removed to match the OS and OC meta-data::
555
+
556
+ # STOCKHOLM 1.0
557
+ #=GS Q9PN73_CAMJE/149-220 AC Q9PN73
558
+ ...
559
+ Q9PN73_CAMJE/149-220 NKA...
560
+ ...
561
+ #=GS Q9PN73_CAMJE OS Campylobacter jejuni
562
+ #=GS Q9PN73_CAMJE OC Bacteria
563
+
564
+ This function will return an empty dictionary if no data is found.
565
+ """
566
+ name, start, end = self._identifier_split(identifier)
567
+ if name == identifier:
568
+ identifier_keys = [identifier]
569
+ else:
570
+ identifier_keys = [identifier, name]
571
+ answer = {}
572
+ for identifier_key in identifier_keys:
573
+ try:
574
+ for feature_key in meta_dict[identifier_key]:
575
+ answer[feature_key] = meta_dict[identifier_key][feature_key]
576
+ except KeyError:
577
+ pass
578
+ return answer
579
+
580
+ def _populate_meta_data(self, identifier, record):
581
+ """Add meta-date to a SecRecord's annotations dictionary (PRIVATE).
582
+
583
+ This function applies the PFAM conventions.
584
+ """
585
+ seq_data = self._get_meta_data(identifier, self.seq_annotation)
586
+ for feature in seq_data:
587
+ # Note this dictionary contains lists!
588
+ if feature == "AC": # ACcession number
589
+ assert len(seq_data[feature]) == 1
590
+ record.annotations["accession"] = seq_data[feature][0]
591
+ elif feature == "DE": # DEscription
592
+ record.description = "\n".join(seq_data[feature])
593
+ elif feature == "DR": # Database Reference
594
+ # Should we try and parse the strings?
595
+ record.dbxrefs = seq_data[feature]
596
+ elif feature in self.pfam_gs_mapping:
597
+ record.annotations[self.pfam_gs_mapping[feature]] = ", ".join(
598
+ seq_data[feature]
599
+ )
600
+ else:
601
+ # Ignore it?
602
+ record.annotations["GS:" + feature] = ", ".join(seq_data[feature])
603
+
604
+ # Now record the per-letter-annotations
605
+ seq_col_data = self._get_meta_data(identifier, self.seq_col_annotation)
606
+ for feature in seq_col_data:
607
+ # Note this dictionary contains strings!
608
+ if feature in self.pfam_gr_mapping:
609
+ record.letter_annotations[self.pfam_gr_mapping[feature]] = seq_col_data[
610
+ feature
611
+ ]
612
+ else:
613
+ # Ignore it?
614
+ record.letter_annotations["GR:" + feature] = seq_col_data[feature]
615
+
616
+
617
+ if __name__ == "__main__":
618
+ from Bio._utils import run_doctest
619
+
620
+ run_doctest()
.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__init__.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2008-2018 by Peter Cock. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Multiple sequence alignment input/output as alignment objects.
8
+
9
+ The Bio.AlignIO interface is deliberately very similar to Bio.SeqIO, and in
10
+ fact the two are connected internally. Both modules use the same set of file
11
+ format names (lower case strings). From the user's perspective, you can read
12
+ in a PHYLIP file containing one or more alignments using Bio.AlignIO, or you
13
+ can read in the sequences within these alignments using Bio.SeqIO.
14
+
15
+ Bio.AlignIO is also documented at http://biopython.org/wiki/AlignIO and by
16
+ a whole chapter in our Tutorial_:
17
+
18
+ .. _Tutorial: https://biopython.org/docs/latest/Tutorial/index.html
19
+
20
+ Input
21
+ -----
22
+ For the typical special case when your file or handle contains one and only
23
+ one alignment, use the function Bio.AlignIO.read(). This takes an input file
24
+ handle (or in recent versions of Biopython a filename as a string), format
25
+ string and optional number of sequences per alignment. It will return a single
26
+ MultipleSeqAlignment object (or raise an exception if there isn't just one
27
+ alignment):
28
+
29
+ >>> from Bio import AlignIO
30
+ >>> align = AlignIO.read("Phylip/interlaced.phy", "phylip")
31
+ >>> print(align)
32
+ Alignment with 3 rows and 384 columns
33
+ -----MKVILLFVLAVFTVFVSS---------------RGIPPE...I-- CYS1_DICDI
34
+ MAHARVLLLALAVLATAAVAVASSSSFADSNPIRPVTDRAASTL...VAA ALEU_HORVU
35
+ ------MWATLPLLCAGAWLLGV--------PVCGAAELSVNSL...PLV CATH_HUMAN
36
+
37
+ For the general case, when the handle could contain any number of alignments,
38
+ use the function Bio.AlignIO.parse(...) which takes the same arguments, but
39
+ returns an iterator giving MultipleSeqAlignment objects (typically used in a
40
+ for loop). If you want random access to the alignments by number, turn this
41
+ into a list:
42
+
43
+ >>> from Bio import AlignIO
44
+ >>> alignments = list(AlignIO.parse("Emboss/needle.txt", "emboss"))
45
+ >>> print(alignments[2])
46
+ Alignment with 2 rows and 120 columns
47
+ -KILIVDDQYGIRILLNEVFNKEGYQTFQAANGLQALDIVTKER...--- ref_rec
48
+ LHIVVVDDDPGTCVYIESVFAELGHTCKSFVRPEAAEEYILTHP...HKE gi|94967506|receiver
49
+
50
+ Most alignment file formats can be concatenated so as to hold as many
51
+ different multiple sequence alignments as possible. One common example
52
+ is the output of the tool seqboot in the PHLYIP suite. Sometimes there
53
+ can be a file header and footer, as seen in the EMBOSS alignment output.
54
+
55
+ Output
56
+ ------
57
+ Use the function Bio.AlignIO.write(...), which takes a complete set of
58
+ Alignment objects (either as a list, or an iterator), an output file handle
59
+ (or filename in recent versions of Biopython) and of course the file format::
60
+
61
+ from Bio import AlignIO
62
+ alignments = ...
63
+ count = SeqIO.write(alignments, "example.faa", "fasta")
64
+
65
+ If using a handle make sure to close it to flush the data to the disk::
66
+
67
+ from Bio import AlignIO
68
+ alignments = ...
69
+ with open("example.faa", "w") as handle:
70
+ count = SeqIO.write(alignments, handle, "fasta")
71
+
72
+ In general, you are expected to call this function once (with all your
73
+ alignments) and then close the file handle. However, for file formats
74
+ like PHYLIP where multiple alignments are stored sequentially (with no file
75
+ header and footer), then multiple calls to the write function should work as
76
+ expected when using handles.
77
+
78
+ If you are using a filename, the repeated calls to the write functions will
79
+ overwrite the existing file each time.
80
+
81
+ Conversion
82
+ ----------
83
+ The Bio.AlignIO.convert(...) function allows an easy interface for simple
84
+ alignment file format conversions. Additionally, it may use file format
85
+ specific optimisations so this should be the fastest way too.
86
+
87
+ In general however, you can combine the Bio.AlignIO.parse(...) function with
88
+ the Bio.AlignIO.write(...) function for sequence file conversion. Using
89
+ generator expressions provides a memory efficient way to perform filtering or
90
+ other extra operations as part of the process.
91
+
92
+ File Formats
93
+ ------------
94
+ When specifying the file format, use lowercase strings. The same format
95
+ names are also used in Bio.SeqIO and include the following:
96
+
97
+ - clustal - Output from Clustal W or X.
98
+ - emboss - EMBOSS tools' "pairs" and "simple" alignment formats.
99
+ - fasta - The generic sequence file format where each record starts with
100
+ an identifier line starting with a ">" character, followed by
101
+ lines of sequence.
102
+ - fasta-m10 - For the pairwise alignments output by Bill Pearson's FASTA
103
+ tools when used with the -m 10 command line option for machine
104
+ readable output.
105
+ - ig - The IntelliGenetics file format, apparently the same as the
106
+ MASE alignment format.
107
+ - msf - The GCG MSF alignment format, originally from PileUp tool.
108
+ - nexus - Output from NEXUS, see also the module Bio.Nexus which can also
109
+ read any phylogenetic trees in these files.
110
+ - phylip - Interlaced PHYLIP, as used by the PHYLIP tools.
111
+ - phylip-sequential - Sequential PHYLIP.
112
+ - phylip-relaxed - PHYLIP like format allowing longer names.
113
+ - stockholm - A richly annotated alignment file format used by PFAM.
114
+ - mauve - Output from progressiveMauve/Mauve
115
+
116
+ Note that while Bio.AlignIO can read all the above file formats, it cannot
117
+ write to all of them.
118
+
119
+ You can also use any file format supported by Bio.SeqIO, such as "fasta" or
120
+ "ig" (which are listed above), PROVIDED the sequences in your file are all the
121
+ same length.
122
+ """
123
+
124
+ # TODO
125
+ # - define policy on reading aligned sequences with gaps in
126
+ # (e.g. - and . characters)
127
+ #
128
+ # - Can we build the to_alignment(...) functionality
129
+ # into the generic Alignment class instead?
130
+ #
131
+ # - How best to handle unique/non unique record.id when writing.
132
+ # For most file formats reading such files is fine; The stockholm
133
+ # parser would fail.
134
+ #
135
+ # - MSF multiple alignment format, aka GCG, aka PileUp format (*.msf)
136
+ # http://www.bioperl.org/wiki/MSF_multiple_alignment_format
137
+ from Bio.Align import MultipleSeqAlignment
138
+ from Bio.File import as_handle
139
+
140
+ from . import ClustalIO
141
+ from . import EmbossIO
142
+ from . import FastaIO
143
+ from . import MafIO
144
+ from . import MauveIO
145
+ from . import MsfIO
146
+ from . import NexusIO
147
+ from . import PhylipIO
148
+ from . import StockholmIO
149
+
150
+ # Convention for format names is "mainname-subtype" in lower case.
151
+ # Please use the same names as BioPerl and EMBOSS where possible.
152
+
153
+ _FormatToIterator = { # "fasta" is done via Bio.SeqIO
154
+ "clustal": ClustalIO.ClustalIterator,
155
+ "emboss": EmbossIO.EmbossIterator,
156
+ "fasta-m10": FastaIO.FastaM10Iterator,
157
+ "maf": MafIO.MafIterator,
158
+ "mauve": MauveIO.MauveIterator,
159
+ "msf": MsfIO.MsfIterator,
160
+ "nexus": NexusIO.NexusIterator,
161
+ "phylip": PhylipIO.PhylipIterator,
162
+ "phylip-sequential": PhylipIO.SequentialPhylipIterator,
163
+ "phylip-relaxed": PhylipIO.RelaxedPhylipIterator,
164
+ "stockholm": StockholmIO.StockholmIterator,
165
+ }
166
+
167
+ _FormatToWriter = { # "fasta" is done via Bio.SeqIO
168
+ "clustal": ClustalIO.ClustalWriter,
169
+ "maf": MafIO.MafWriter,
170
+ "mauve": MauveIO.MauveWriter,
171
+ "nexus": NexusIO.NexusWriter,
172
+ "phylip": PhylipIO.PhylipWriter,
173
+ "phylip-sequential": PhylipIO.SequentialPhylipWriter,
174
+ "phylip-relaxed": PhylipIO.RelaxedPhylipWriter,
175
+ "stockholm": StockholmIO.StockholmWriter,
176
+ }
177
+
178
+
179
+ def write(alignments, handle, format):
180
+ """Write complete set of alignments to a file.
181
+
182
+ Arguments:
183
+ - alignments - A list (or iterator) of MultipleSeqAlignment objects,
184
+ or a single alignment object.
185
+ - handle - File handle object to write to, or filename as string
186
+ (note older versions of Biopython only took a handle).
187
+ - format - lower case string describing the file format to write.
188
+
189
+ You should close the handle after calling this function.
190
+
191
+ Returns the number of alignments written (as an integer).
192
+ """
193
+ from Bio import SeqIO
194
+
195
+ # Try and give helpful error messages:
196
+ if not isinstance(format, str):
197
+ raise TypeError("Need a string for the file format (lower case)")
198
+ if not format:
199
+ raise ValueError("Format required (lower case string)")
200
+ if format != format.lower():
201
+ raise ValueError(f"Format string '{format}' should be lower case")
202
+
203
+ if isinstance(alignments, MultipleSeqAlignment):
204
+ # This raised an exception in older versions of Biopython
205
+ alignments = [alignments]
206
+
207
+ with as_handle(handle, "w") as fp:
208
+ # Map the file format to a writer class
209
+ if format in _FormatToWriter:
210
+ writer_class = _FormatToWriter[format]
211
+ count = writer_class(fp).write_file(alignments)
212
+ elif format in SeqIO._FormatToWriter:
213
+ # Exploit the existing SeqIO parser to do the dirty work!
214
+ # TODO - Can we make one call to SeqIO.write() and count the alignments?
215
+ count = 0
216
+ for alignment in alignments:
217
+ if not isinstance(alignment, MultipleSeqAlignment):
218
+ raise TypeError(
219
+ "Expect a list or iterator of MultipleSeqAlignment "
220
+ "objects, got: %r" % alignment
221
+ )
222
+ SeqIO.write(alignment, fp, format)
223
+ count += 1
224
+ elif format in _FormatToIterator or format in SeqIO._FormatToIterator:
225
+ raise ValueError(f"Reading format '{format}' is supported, but not writing")
226
+ else:
227
+ raise ValueError(f"Unknown format '{format}'")
228
+
229
+ if not isinstance(count, int):
230
+ raise RuntimeError(
231
+ "Internal error - the underlying %s "
232
+ "writer should have returned the alignment count, not %r" % (format, count)
233
+ )
234
+
235
+ return count
236
+
237
+
238
+ # This is a generator function!
239
+ def _SeqIO_to_alignment_iterator(handle, format, seq_count=None):
240
+ """Use Bio.SeqIO to create an MultipleSeqAlignment iterator (PRIVATE).
241
+
242
+ Arguments:
243
+ - handle - handle to the file.
244
+ - format - string describing the file format.
245
+ - seq_count - Optional integer, number of sequences expected in each
246
+ alignment. Recommended for fasta format files.
247
+
248
+ If count is omitted (default) then all the sequences in the file are
249
+ combined into a single MultipleSeqAlignment.
250
+ """
251
+ from Bio import SeqIO
252
+
253
+ if format not in SeqIO._FormatToIterator:
254
+ raise ValueError(f"Unknown format '{format}'")
255
+
256
+ if seq_count:
257
+ # Use the count to split the records into batches.
258
+ seq_record_iterator = SeqIO.parse(handle, format)
259
+
260
+ records = []
261
+ for record in seq_record_iterator:
262
+ records.append(record)
263
+ if len(records) == seq_count:
264
+ yield MultipleSeqAlignment(records)
265
+ records = []
266
+ if records:
267
+ raise ValueError("Check seq_count argument, not enough sequences?")
268
+ else:
269
+ # Must assume that there is a single alignment using all
270
+ # the SeqRecord objects:
271
+ records = list(SeqIO.parse(handle, format))
272
+ if records:
273
+ yield MultipleSeqAlignment(records)
274
+
275
+
276
+ def parse(handle, format, seq_count=None):
277
+ """Iterate over an alignment file as MultipleSeqAlignment objects.
278
+
279
+ Arguments:
280
+ - handle - handle to the file, or the filename as a string
281
+ (note older versions of Biopython only took a handle).
282
+ - format - string describing the file format.
283
+ - seq_count - Optional integer, number of sequences expected in each
284
+ alignment. Recommended for fasta format files.
285
+
286
+ If you have the file name in a string 'filename', use:
287
+
288
+ >>> from Bio import AlignIO
289
+ >>> filename = "Emboss/needle.txt"
290
+ >>> format = "emboss"
291
+ >>> for alignment in AlignIO.parse(filename, format):
292
+ ... print("Alignment of length %i" % alignment.get_alignment_length())
293
+ Alignment of length 124
294
+ Alignment of length 119
295
+ Alignment of length 120
296
+ Alignment of length 118
297
+ Alignment of length 125
298
+
299
+ If you have a string 'data' containing the file contents, use::
300
+
301
+ from Bio import AlignIO
302
+ from io import StringIO
303
+ my_iterator = AlignIO.parse(StringIO(data), format)
304
+
305
+ Use the Bio.AlignIO.read() function when you expect a single record only.
306
+ """
307
+ from Bio import SeqIO
308
+
309
+ # Try and give helpful error messages:
310
+ if not isinstance(format, str):
311
+ raise TypeError("Need a string for the file format (lower case)")
312
+ if not format:
313
+ raise ValueError("Format required (lower case string)")
314
+ if format != format.lower():
315
+ raise ValueError(f"Format string '{format}' should be lower case")
316
+ if seq_count is not None and not isinstance(seq_count, int):
317
+ raise TypeError("Need integer for seq_count (sequences per alignment)")
318
+
319
+ with as_handle(handle) as fp:
320
+ # Map the file format to a sequence iterator:
321
+ if format in _FormatToIterator:
322
+ iterator_generator = _FormatToIterator[format]
323
+ i = iterator_generator(fp, seq_count)
324
+
325
+ elif format in SeqIO._FormatToIterator:
326
+ # Exploit the existing SeqIO parser to the dirty work!
327
+ i = _SeqIO_to_alignment_iterator(fp, format, seq_count=seq_count)
328
+ else:
329
+ raise ValueError(f"Unknown format '{format}'")
330
+
331
+ yield from i
332
+
333
+
334
+ def read(handle, format, seq_count=None):
335
+ """Turn an alignment file into a single MultipleSeqAlignment object.
336
+
337
+ Arguments:
338
+ - handle - handle to the file, or the filename as a string
339
+ (note older versions of Biopython only took a handle).
340
+ - format - string describing the file format.
341
+ - seq_count - Optional integer, number of sequences expected in each
342
+ alignment. Recommended for fasta format files.
343
+
344
+ If the handle contains no alignments, or more than one alignment,
345
+ an exception is raised. For example, using a PFAM/Stockholm file
346
+ containing one alignment:
347
+
348
+ >>> from Bio import AlignIO
349
+ >>> filename = "Clustalw/protein.aln"
350
+ >>> format = "clustal"
351
+ >>> alignment = AlignIO.read(filename, format)
352
+ >>> print("Alignment of length %i" % alignment.get_alignment_length())
353
+ Alignment of length 411
354
+
355
+ If however you want the first alignment from a file containing
356
+ multiple alignments this function would raise an exception.
357
+
358
+ >>> from Bio import AlignIO
359
+ >>> filename = "Emboss/needle.txt"
360
+ >>> format = "emboss"
361
+ >>> alignment = AlignIO.read(filename, format)
362
+ Traceback (most recent call last):
363
+ ...
364
+ ValueError: More than one record found in handle
365
+
366
+ Instead use:
367
+
368
+ >>> from Bio import AlignIO
369
+ >>> filename = "Emboss/needle.txt"
370
+ >>> format = "emboss"
371
+ >>> alignment = next(AlignIO.parse(filename, format))
372
+ >>> print("First alignment has length %i" % alignment.get_alignment_length())
373
+ First alignment has length 124
374
+
375
+ You must use the Bio.AlignIO.parse() function if you want to read multiple
376
+ records from the handle.
377
+ """
378
+ iterator = parse(handle, format, seq_count)
379
+ try:
380
+ alignment = next(iterator)
381
+ except StopIteration:
382
+ raise ValueError("No records found in handle") from None
383
+ try:
384
+ next(iterator)
385
+ raise ValueError("More than one record found in handle")
386
+ except StopIteration:
387
+ pass
388
+ if seq_count:
389
+ if len(alignment) != seq_count:
390
+ raise RuntimeError(
391
+ "More sequences found in alignment than specified in seq_count: %s."
392
+ % seq_count
393
+ )
394
+ return alignment
395
+
396
+
397
+ def convert(in_file, in_format, out_file, out_format, molecule_type=None):
398
+ """Convert between two alignment files, returns number of alignments.
399
+
400
+ Arguments:
401
+ - in_file - an input handle or filename
402
+ - in_format - input file format, lower case string
403
+ - output - an output handle or filename
404
+ - out_file - output file format, lower case string
405
+ - molecule_type - optional molecule type to apply, string containing
406
+ "DNA", "RNA" or "protein".
407
+
408
+ **NOTE** - If you provide an output filename, it will be opened which will
409
+ overwrite any existing file without warning. This may happen if even the
410
+ conversion is aborted (e.g. an invalid out_format name is given).
411
+
412
+ Some output formats require the molecule type be specified where this
413
+ cannot be determined by the parser. For example, converting to FASTA,
414
+ Clustal, or PHYLIP format to NEXUS:
415
+
416
+ >>> from io import StringIO
417
+ >>> from Bio import AlignIO
418
+ >>> handle = StringIO()
419
+ >>> AlignIO.convert("Phylip/horses.phy", "phylip", handle, "nexus", "DNA")
420
+ 1
421
+ >>> print(handle.getvalue())
422
+ #NEXUS
423
+ begin data;
424
+ dimensions ntax=10 nchar=40;
425
+ format datatype=dna missing=? gap=-;
426
+ matrix
427
+ Mesohippus AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
428
+ Hypohippus AAACCCCCCCAAAAAAAAACAAAAAAAAAAAAAAAAAAAA
429
+ Archaeohip CAAAAAAAAAAAAAAAACACAAAAAAAAAAAAAAAAAAAA
430
+ Parahippus CAAACAACAACAAAAAAAACAAAAAAAAAAAAAAAAAAAA
431
+ Merychippu CCAACCACCACCCCACACCCAAAAAAAAAAAAAAAAAAAA
432
+ 'M. secundu' CCAACCACCACCCACACCCCAAAAAAAAAAAAAAAAAAAA
433
+ Nannipus CCAACCACAACCCCACACCCAAAAAAAAAAAAAAAAAAAA
434
+ Neohippari CCAACCCCCCCCCCACACCCAAAAAAAAAAAAAAAAAAAA
435
+ Calippus CCAACCACAACCCACACCCCAAAAAAAAAAAAAAAAAAAA
436
+ Pliohippus CCCACCCCCCCCCACACCCCAAAAAAAAAAAAAAAAAAAA
437
+ ;
438
+ end;
439
+ <BLANKLINE>
440
+ """
441
+ if molecule_type:
442
+ if not isinstance(molecule_type, str):
443
+ raise TypeError(f"Molecule type should be a string, not {molecule_type!r}")
444
+ elif (
445
+ "DNA" in molecule_type
446
+ or "RNA" in molecule_type
447
+ or "protein" in molecule_type
448
+ ):
449
+ pass
450
+ else:
451
+ raise ValueError(f"Unexpected molecule type, {molecule_type!r}")
452
+
453
+ # TODO - Add optimised versions of important conversions
454
+ # For now just off load the work to SeqIO parse/write
455
+ # Don't open the output file until we've checked the input is OK:
456
+ alignments = parse(in_file, in_format, None)
457
+
458
+ if molecule_type:
459
+ # Edit the records on the fly to set molecule type
460
+
461
+ def over_ride(alignment):
462
+ """Over-ride molecule in-place."""
463
+ for record in alignment:
464
+ record.annotations["molecule_type"] = molecule_type
465
+ return alignment
466
+
467
+ alignments = (over_ride(_) for _ in alignments)
468
+ return write(alignments, out_file, out_format)
469
+
470
+
471
+ if __name__ == "__main__":
472
+ from Bio._utils import run_doctest
473
+
474
+ run_doctest()
.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/.___init__.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/.___pycache__ ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__init__.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2000-2002 by Andrew Dalke.
2
+ # Revisions copyright 2007-2010 by Peter Cock.
3
+ # All rights reserved.
4
+ #
5
+ # This file is part of the Biopython distribution and governed by your
6
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
7
+ # Please see the LICENSE file that should have been included as part of this
8
+ # package.
9
+ """Alphabets were previously used to declare sequence type and letters (OBSOLETE).
10
+
11
+ The design of Bio.Alphabet included a number of historic design choices
12
+ which, with the benefit of hindsight, were regretable. Bio.Alphabet was
13
+ therefore removed from Biopython in release 1.78. Instead, the molecule type is
14
+ included as an annotation on SeqRecords where appropriate.
15
+
16
+ Please see https://biopython.org/wiki/Alphabet for examples showing how to
17
+ transition from Bio.Alphabet to molecule type annotations.
18
+ """
19
+
20
+ raise ImportError(
21
+ "Bio.Alphabet has been removed from Biopython. In many cases, the alphabet can simply be ignored and removed from scripts. In a few cases, you may need to specify the ``molecule_type`` as an annotation on a SeqRecord for your script to work correctly. Please see https://biopython.org/wiki/Alphabet for more information."
22
+ )
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/._NCBIWWW.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/._NCBIXML.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/.___init__.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/.___pycache__ ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/.__parser.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/.__writers.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIWWW.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 1999 by Jeffrey Chang. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ #
8
+ # Patched by Brad Chapman.
9
+ # Chris Wroe added modifications for work in myGrid
10
+
11
+ """Code to invoke the NCBI BLAST server over the internet.
12
+
13
+ This module provides code to work with the WWW version of BLAST
14
+ provided by the NCBI. https://blast.ncbi.nlm.nih.gov/
15
+
16
+ Variables:
17
+
18
+ - email Set the Blast email parameter (default is None).
19
+ - tool Set the Blast tool parameter (default is ``biopython``).
20
+
21
+ """
22
+
23
+ import time
24
+ import warnings
25
+ from io import StringIO
26
+ from urllib.parse import urlencode
27
+ from urllib.request import build_opener
28
+ from urllib.request import HTTPBasicAuthHandler
29
+ from urllib.request import HTTPPasswordMgrWithDefaultRealm
30
+ from urllib.request import install_opener
31
+ from urllib.request import Request
32
+ from urllib.request import urlopen
33
+
34
+ from Bio import BiopythonWarning
35
+ from Bio._utils import function_with_previous
36
+
37
+ email = None
38
+ tool = "biopython"
39
+
40
+
41
+ NCBI_BLAST_URL = "https://blast.ncbi.nlm.nih.gov/Blast.cgi"
42
+
43
+
44
+ @function_with_previous
45
+ def qblast(
46
+ program,
47
+ database,
48
+ sequence,
49
+ url_base=NCBI_BLAST_URL,
50
+ auto_format=None,
51
+ composition_based_statistics=None,
52
+ db_genetic_code=None,
53
+ endpoints=None,
54
+ entrez_query="(none)",
55
+ expect=10.0,
56
+ filter=None,
57
+ gapcosts=None,
58
+ genetic_code=None,
59
+ hitlist_size=50,
60
+ i_thresh=None,
61
+ layout=None,
62
+ lcase_mask=None,
63
+ matrix_name=None,
64
+ nucl_penalty=None,
65
+ nucl_reward=None,
66
+ other_advanced=None,
67
+ perc_ident=None,
68
+ phi_pattern=None,
69
+ query_file=None,
70
+ query_believe_defline=None,
71
+ query_from=None,
72
+ query_to=None,
73
+ searchsp_eff=None,
74
+ service=None,
75
+ threshold=None,
76
+ ungapped_alignment=None,
77
+ word_size=None,
78
+ short_query=None,
79
+ alignments=500,
80
+ alignment_view=None,
81
+ descriptions=500,
82
+ entrez_links_new_window=None,
83
+ expect_low=None,
84
+ expect_high=None,
85
+ format_entrez_query=None,
86
+ format_object=None,
87
+ format_type="XML",
88
+ ncbi_gi=None,
89
+ results_file=None,
90
+ show_overview=None,
91
+ megablast=None,
92
+ template_type=None,
93
+ template_length=None,
94
+ username="blast",
95
+ password=None,
96
+ ):
97
+ """BLAST search using NCBI's QBLAST server.
98
+
99
+ Supports all parameters of the old qblast API for Put and Get.
100
+
101
+ Please note that NCBI uses the new Common URL API for BLAST searches
102
+ on the internet (https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html).
103
+ Thus, some of the parameters used by this function are not (or are no longer)
104
+ officially supported by NCBI. Although they are still functioning, this
105
+ may change in the future.
106
+
107
+ Some useful parameters:
108
+
109
+ - program blastn, blastp, blastx, tblastn, or tblastx (lower case)
110
+ - database Which database to search against (e.g. "nr").
111
+ - sequence The sequence to search.
112
+ - ncbi_gi TRUE/FALSE whether to give 'gi' identifier.
113
+ - descriptions Number of descriptions to show. Def 500.
114
+ - alignments Number of alignments to show. Def 500.
115
+ - expect An expect value cutoff. Def 10.0.
116
+ - matrix_name Specify an alt. matrix (PAM30, PAM70, BLOSUM80, BLOSUM45).
117
+ - filter "none" turns off filtering. Default no filtering
118
+ - format_type "HTML", "Text", "ASN.1", or "XML". Def. "XML".
119
+ - entrez_query Entrez query to limit Blast search - only applies when searching nucleotide BLASTDBs
120
+ - hitlist_size Number of hits to return. Default 50
121
+ - megablast TRUE/FALSE whether to use MEga BLAST algorithm (blastn only)
122
+ - short_query TRUE/FALSE whether to adjust the search parameters for a
123
+ short query sequence. Note that this will override
124
+ manually set parameters like word size and e value. Turns
125
+ off when sequence length is > 30 residues. Default: None.
126
+ - service plain, psi, phi, rpsblast, megablast (lower case)
127
+
128
+ This function does no checking of the validity of the parameters
129
+ and passes the values to the server as is. More help is available at:
130
+ https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html
131
+
132
+ """
133
+ programs = ["blastn", "blastp", "blastx", "tblastn", "tblastx"]
134
+ if program not in programs:
135
+ raise ValueError(
136
+ f"Program specified is {program}. Expected one of {', '.join(programs)}"
137
+ )
138
+
139
+ # SHORT_QUERY_ADJUST throws an error when using blastn (wrong parameter
140
+ # assignment from NCBIs side).
141
+ # Thus we set the (known) parameters directly:
142
+ if short_query and program == "blastn":
143
+ short_query = None
144
+ # We only use the 'short-query' parameters for short sequences:
145
+ if len(sequence) < 31:
146
+ expect = 1000
147
+ word_size = 7
148
+ nucl_reward = 1
149
+ filter = None
150
+ lcase_mask = None
151
+ warnings.warn(
152
+ '"SHORT_QUERY_ADJUST" is incorrectly implemented (by NCBI) for blastn.'
153
+ " We bypass the problem by manually adjusting the search parameters."
154
+ " Thus, results may slightly differ from web page searches.",
155
+ BiopythonWarning,
156
+ )
157
+
158
+ # Format the "Put" command, which sends search requests to qblast.
159
+ # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node5.html on 9 July 2007
160
+ # Additional parameters are taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node9.html on 8 Oct 2010
161
+ # To perform a PSI-BLAST or PHI-BLAST search the service ("Put" and "Get" commands) must be specified
162
+ # (e.g. psi_blast = NCBIWWW.qblast("blastp", "refseq_protein", input_sequence, service="psi"))
163
+ parameters = {
164
+ "AUTO_FORMAT": auto_format,
165
+ "COMPOSITION_BASED_STATISTICS": composition_based_statistics,
166
+ "DATABASE": database,
167
+ "DB_GENETIC_CODE": db_genetic_code,
168
+ "ENDPOINTS": endpoints,
169
+ "ENTREZ_QUERY": entrez_query,
170
+ "EXPECT": expect,
171
+ "FILTER": filter,
172
+ "GAPCOSTS": gapcosts,
173
+ "GENETIC_CODE": genetic_code,
174
+ "HITLIST_SIZE": hitlist_size,
175
+ "I_THRESH": i_thresh,
176
+ "LAYOUT": layout,
177
+ "LCASE_MASK": lcase_mask,
178
+ "MEGABLAST": megablast,
179
+ "MATRIX_NAME": matrix_name,
180
+ "NUCL_PENALTY": nucl_penalty,
181
+ "NUCL_REWARD": nucl_reward,
182
+ "OTHER_ADVANCED": other_advanced,
183
+ "PERC_IDENT": perc_ident,
184
+ "PHI_PATTERN": phi_pattern,
185
+ "PROGRAM": program,
186
+ # ('PSSM': pssm: - It is possible to use PSI-BLAST via this API?
187
+ "QUERY": sequence,
188
+ "QUERY_FILE": query_file,
189
+ "QUERY_BELIEVE_DEFLINE": query_believe_defline,
190
+ "QUERY_FROM": query_from,
191
+ "QUERY_TO": query_to,
192
+ # 'RESULTS_FILE': ...: - Can we use this parameter?
193
+ "SEARCHSP_EFF": searchsp_eff,
194
+ "SERVICE": service,
195
+ "SHORT_QUERY_ADJUST": short_query,
196
+ "TEMPLATE_TYPE": template_type,
197
+ "TEMPLATE_LENGTH": template_length,
198
+ "THRESHOLD": threshold,
199
+ "UNGAPPED_ALIGNMENT": ungapped_alignment,
200
+ "WORD_SIZE": word_size,
201
+ "CMD": "Put",
202
+ }
203
+
204
+ if password is not None:
205
+ # handle authentication for BLAST cloud
206
+ password_mgr = HTTPPasswordMgrWithDefaultRealm()
207
+ password_mgr.add_password(None, url_base, username, password)
208
+ handler = HTTPBasicAuthHandler(password_mgr)
209
+ opener = build_opener(handler)
210
+ install_opener(opener)
211
+
212
+ if url_base == NCBI_BLAST_URL:
213
+ parameters.update({"email": email, "tool": tool})
214
+ parameters = {key: value for key, value in parameters.items() if value is not None}
215
+ message = urlencode(parameters).encode()
216
+ request = Request(url_base, message, {"User-Agent": "BiopythonClient"})
217
+ # Send off the initial query to qblast.
218
+ # Note the NCBI do not currently impose a rate limit here, other
219
+ # than the request not to make say 50 queries at once using multiple
220
+ # threads.
221
+ handle = urlopen(request)
222
+
223
+ # Format the "Get" command, which gets the formatted results from qblast
224
+ # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node6.html on 9 July 2007
225
+ rid, rtoe = _parse_qblast_ref_page(handle)
226
+ parameters = {
227
+ "ALIGNMENTS": alignments,
228
+ "ALIGNMENT_VIEW": alignment_view,
229
+ "DESCRIPTIONS": descriptions,
230
+ "ENTREZ_LINKS_NEW_WINDOW": entrez_links_new_window,
231
+ "EXPECT_LOW": expect_low,
232
+ "EXPECT_HIGH": expect_high,
233
+ "FORMAT_ENTREZ_QUERY": format_entrez_query,
234
+ "FORMAT_OBJECT": format_object,
235
+ "FORMAT_TYPE": format_type,
236
+ "NCBI_GI": ncbi_gi,
237
+ "RID": rid,
238
+ "RESULTS_FILE": results_file,
239
+ "SERVICE": service,
240
+ "SHOW_OVERVIEW": show_overview,
241
+ "CMD": "Get",
242
+ }
243
+ parameters = {key: value for key, value in parameters.items() if value is not None}
244
+ message = urlencode(parameters).encode()
245
+
246
+ # Poll NCBI until the results are ready.
247
+ # https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=DeveloperInfo
248
+ # 1. Do not contact the server more often than once every 10 seconds.
249
+ # 2. Do not poll for any single RID more often than once a minute.
250
+ # 3. Use the URL parameter email and tool, so that the NCBI
251
+ # can contact you if there is a problem.
252
+ # 4. Run scripts weekends or between 9 pm and 5 am Eastern time
253
+ # on weekdays if more than 50 searches will be submitted.
254
+ # --
255
+ # Could start with a 10s delay, but expect most short queries
256
+ # will take longer thus at least 70s with delay. Therefore,
257
+ # start with 20s delay, thereafter once a minute.
258
+ delay = 20 # seconds
259
+ start_time = time.time()
260
+ while True:
261
+ current = time.time()
262
+ wait = qblast.previous + delay - current
263
+ if wait > 0:
264
+ time.sleep(wait)
265
+ qblast.previous = current + wait
266
+ else:
267
+ qblast.previous = current
268
+ # delay by at least 60 seconds only if running the request against the public NCBI API
269
+ if delay < 60 and url_base == NCBI_BLAST_URL:
270
+ # Wasn't a quick return, must wait at least a minute
271
+ delay = 60
272
+ elapsed = time.time() - start_time
273
+ # Throw a warning if search takes longer than ten minutes
274
+ if elapsed >= 600:
275
+ warnings.warn(
276
+ f"BLAST request {rid} is taking longer than 10 minutes, consider re-issuing it",
277
+ BiopythonWarning,
278
+ )
279
+
280
+ request = Request(url_base, message, {"User-Agent": "BiopythonClient"})
281
+ handle = urlopen(request)
282
+ results = handle.read().decode()
283
+
284
+ # Can see an "\n\n" page while results are in progress,
285
+ # if so just wait a bit longer...
286
+ if results == "\n\n":
287
+ continue
288
+ # XML results don't have the Status tag when finished
289
+ if "Status=" not in results:
290
+ break
291
+ i = results.index("Status=")
292
+ j = results.index("\n", i)
293
+ status = results[i + len("Status=") : j].strip()
294
+ if status.upper() == "READY":
295
+ break
296
+ return StringIO(results)
297
+
298
+
299
+ qblast.previous = 0
300
+
301
+
302
+ def _parse_qblast_ref_page(handle):
303
+ """Extract a tuple of RID, RTOE from the 'please wait' page (PRIVATE).
304
+
305
+ The NCBI FAQ pages use TOE for 'Time of Execution', so RTOE is probably
306
+ 'Request Time of Execution' and RID would be 'Request Identifier'.
307
+ """
308
+ s = handle.read().decode()
309
+ i = s.find("RID =")
310
+ if i == -1:
311
+ rid = None
312
+ else:
313
+ j = s.find("\n", i)
314
+ rid = s[i + len("RID =") : j].strip()
315
+
316
+ i = s.find("RTOE =")
317
+ if i == -1:
318
+ rtoe = None
319
+ else:
320
+ j = s.find("\n", i)
321
+ rtoe = s[i + len("RTOE =") : j].strip()
322
+
323
+ if not rid and not rtoe:
324
+ # Can we reliably extract the error message from the HTML page?
325
+ # e.g. "Message ID#24 Error: Failed to read the Blast query:
326
+ # Nucleotide FASTA provided for protein sequence"
327
+ # or "Message ID#32 Error: Query contains no data: Query
328
+ # contains no sequence data"
329
+ #
330
+ # This used to occur inside a <div class="error msInf"> entry:
331
+ i = s.find('<div class="error msInf">')
332
+ if i != -1:
333
+ msg = s[i + len('<div class="error msInf">') :].strip()
334
+ msg = msg.split("</div>", 1)[0].split("\n", 1)[0].strip()
335
+ if msg:
336
+ raise ValueError(f"Error message from NCBI: {msg}")
337
+ # In spring 2010 the markup was like this:
338
+ i = s.find('<p class="error">')
339
+ if i != -1:
340
+ msg = s[i + len('<p class="error">') :].strip()
341
+ msg = msg.split("</p>", 1)[0].split("\n", 1)[0].strip()
342
+ if msg:
343
+ raise ValueError(f"Error message from NCBI: {msg}")
344
+ # Generic search based on the way the error messages start:
345
+ i = s.find("Message ID#")
346
+ if i != -1:
347
+ # Break the message at the first HTML tag
348
+ msg = s[i:].split("<", 1)[0].split("\n", 1)[0].strip()
349
+ raise ValueError(f"Error message from NCBI: {msg}")
350
+ # We didn't recognise the error layout :(
351
+ # print(s)
352
+ raise ValueError(
353
+ "No RID and no RTOE found in the 'please wait' page, "
354
+ "there was probably an error in your request but we "
355
+ "could not extract a helpful error message."
356
+ )
357
+ elif not rid:
358
+ # Can this happen?
359
+ raise ValueError(
360
+ f"No RID found in the 'please wait' page. (although RTOE = {rtoe!r})"
361
+ )
362
+ elif not rtoe:
363
+ # Can this happen?
364
+ raise ValueError(
365
+ f"No RTOE found in the 'please wait' page. (although RID = {rid!r})"
366
+ )
367
+
368
+ try:
369
+ return rid, int(rtoe)
370
+ except ValueError:
371
+ raise ValueError(
372
+ f"A non-integer RTOE found in the 'please wait' page, {rtoe!r}"
373
+ ) from None
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIXML.py ADDED
@@ -0,0 +1,1331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 1999-2000 by Jeffrey Chang. All rights reserved.
2
+ # Copyright 2000 by Bertrand Frottier. All rights reserved.
3
+ # Revisions 2005-2006 copyright Michiel de Hoon
4
+ # Revisions 2006-2009 copyright Peter Cock
5
+ #
6
+ # This file is part of the Biopython distribution and governed by your
7
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
8
+ # Please see the LICENSE file that should have been included as part of this
9
+ # package.
10
+ """Code to work with the BLAST XML output.
11
+
12
+ The BLAST XML DTD file is available on the NCBI site at:
13
+ https://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd
14
+
15
+ Record classes to hold BLAST output are:
16
+
17
+ Classes:
18
+ Blast Holds all the information from a blast search.
19
+ PSIBlast Holds all the information from a psi-blast search.
20
+
21
+ Header Holds information from the header.
22
+ Description Holds information about one hit description.
23
+ Alignment Holds information about one alignment hit.
24
+ HSP Holds information about one HSP.
25
+ MultipleAlignment Holds information about a multiple alignment.
26
+ DatabaseReport Holds information from the database report.
27
+ Parameters Holds information from the parameters.
28
+
29
+ """
30
+ # XXX finish printable BLAST output
31
+
32
+ import sys
33
+ import warnings
34
+ import xml.sax
35
+ from xml.sax.handler import ContentHandler
36
+
37
+ from Bio import BiopythonParserWarning
38
+
39
+ from Bio.Align import MultipleSeqAlignment
40
+ from Bio.Seq import Seq
41
+ from Bio.SeqRecord import SeqRecord
42
+
43
+
44
+ def fmt_(value, format_spec="%s", default_str="<unknown>"):
45
+ """Ensure the given value formats to a string correctly."""
46
+ if value is None:
47
+ return default_str
48
+ return format_spec % value
49
+
50
+
51
+ class Header:
52
+ """Saves information from a blast header.
53
+
54
+ Members:
55
+ application The name of the BLAST flavor that generated this data.
56
+ version Version of blast used.
57
+ date Date this data was generated.
58
+ reference Reference for blast.
59
+
60
+ query Name of query sequence.
61
+ query_letters Number of letters in the query sequence. (int)
62
+
63
+ database Name of the database.
64
+ database_sequences Number of sequences in the database. (int)
65
+ database_letters Number of letters in the database. (int)
66
+
67
+ """
68
+
69
+ def __init__(self):
70
+ """Initialize the class."""
71
+ self.application = ""
72
+ self.version = ""
73
+ self.date = ""
74
+ self.reference = ""
75
+
76
+ self.query = ""
77
+ self.query_letters = None
78
+
79
+ self.database = ""
80
+ self.database_sequences = None
81
+ self.database_letters = None
82
+
83
+
84
+ class Description:
85
+ """Stores information about one hit in the descriptions section.
86
+
87
+ Members:
88
+ title Title of the hit.
89
+ score Number of bits. (int)
90
+ bits Bit score. (float)
91
+ e E value. (float)
92
+ num_alignments Number of alignments for the same subject. (int)
93
+ """
94
+
95
+ def __init__(self):
96
+ """Initialize the class."""
97
+ self.title = ""
98
+ self.score = None
99
+ self.bits = None
100
+ self.e = None
101
+ self.num_alignments = None
102
+
103
+ def __str__(self):
104
+ """Return the description as a string."""
105
+ return f"{self.title:<66} {self.score:>5} {self.e}"
106
+
107
+
108
+ class DescriptionExt(Description):
109
+ """Extended description record for BLASTXML version 2.
110
+
111
+ Members:
112
+ items List of DescriptionExtItem
113
+ """
114
+
115
+ def __init__(self):
116
+ """Initialize the class."""
117
+ super().__init__()
118
+
119
+ self.items = []
120
+
121
+ def append_item(self, item):
122
+ """Add a description extended record."""
123
+ if len(self.items) == 0:
124
+ self.title = str(item)
125
+ self.items.append(item)
126
+
127
+
128
+ class DescriptionExtItem:
129
+ """Stores information about one record in hit description for BLASTXML version 2.
130
+
131
+ Members:
132
+ id Database identifier
133
+ title Title of the hit.
134
+ """
135
+
136
+ def __init__(self):
137
+ """Initialize the class."""
138
+ self.id = None
139
+ self.title = None
140
+ self.accession = None
141
+ self.taxid = None
142
+ self.sciname = None
143
+
144
+ def __str__(self):
145
+ """Return the description identifier and title as a string."""
146
+ return f"{self.id} {self.title}"
147
+
148
+
149
+ class Alignment:
150
+ """Stores information about one hit in the alignments section.
151
+
152
+ Members:
153
+ title Name.
154
+ hit_id Hit identifier. (str)
155
+ hit_def Hit definition. (str)
156
+ length Length. (int)
157
+ hsps A list of HSP objects.
158
+
159
+ """
160
+
161
+ def __init__(self):
162
+ """Initialize the class."""
163
+ self.title = ""
164
+ self.hit_id = ""
165
+ self.hit_def = ""
166
+ self.length = None
167
+ self.hsps = []
168
+
169
+ def __str__(self):
170
+ """Return the BLAST alignment as a formatted string."""
171
+ lines = self.title.split("\n")
172
+ lines.append(f"Length = {self.length}\n")
173
+ return "\n ".join(lines)
174
+
175
+
176
+ class HSP:
177
+ """Stores information about one hsp in an alignment hit.
178
+
179
+ Members:
180
+ - score BLAST score of hit. (float)
181
+ - bits Number of bits for that score. (float)
182
+ - expect Expect value. (float)
183
+ - num_alignments Number of alignments for same subject. (int)
184
+ - identities Number of identities (int) if using the XML parser.
185
+ Tuple of number of identities/total aligned (int, int)
186
+ if using the (obsolete) plain text parser.
187
+ - positives Number of positives (int) if using the XML parser.
188
+ Tuple of number of positives/total aligned (int, int)
189
+ if using the (obsolete) plain text parser.
190
+ - gaps Number of gaps (int) if using the XML parser.
191
+ Tuple of number of gaps/total aligned (int, int) if
192
+ using the (obsolete) plain text parser.
193
+ - align_length Length of the alignment. (int)
194
+ - strand Tuple of (query, target) strand.
195
+ - frame Tuple of 1 or 2 frame shifts, depending on the flavor.
196
+
197
+ - query The query sequence.
198
+ - query_start The start residue for the query sequence. (1-based)
199
+ - query_end The end residue for the query sequence. (1-based)
200
+ - match The match sequence.
201
+ - sbjct The sbjct sequence.
202
+ - sbjct_start The start residue for the sbjct sequence. (1-based)
203
+ - sbjct_end The end residue for the sbjct sequence. (1-based)
204
+
205
+ Not all flavors of BLAST return values for every attribute::
206
+
207
+ score expect identities positives strand frame
208
+ BLASTP X X X X
209
+ BLASTN X X X X X
210
+ BLASTX X X X X X
211
+ TBLASTN X X X X X
212
+ TBLASTX X X X X X/X
213
+
214
+ Note: for BLASTX, the query sequence is shown as a protein sequence,
215
+ but the numbering is based on the nucleotides. Thus, the numbering
216
+ is 3x larger than the number of amino acid residues. A similar effect
217
+ can be seen for the sbjct sequence in TBLASTN, and for both sequences
218
+ in TBLASTX.
219
+
220
+ Also, for negative frames, the sequence numbering starts from
221
+ query_start and counts down.
222
+
223
+ """
224
+
225
+ def __init__(self):
226
+ """Initialize the class."""
227
+ self.score = None
228
+ self.bits = None
229
+ self.expect = None
230
+ self.num_alignments = None
231
+ self.identities = (None, None)
232
+ self.positives = (None, None)
233
+ self.gaps = (None, None)
234
+ self.align_length = None
235
+ self.strand = (None, None)
236
+ self.frame = ()
237
+
238
+ self.query = ""
239
+ self.query_start = None
240
+ self.query_end = None
241
+ self.match = ""
242
+ self.sbjct = ""
243
+ self.sbjct_start = None
244
+ self.sbjct_end = None
245
+
246
+ def __str__(self):
247
+ """Return the BLAST HSP as a formatted string."""
248
+ lines = [
249
+ "Score %s (%s bits), expectation %s, alignment length %s"
250
+ % (
251
+ fmt_(self.score, "%i"),
252
+ fmt_(self.bits, "%i"),
253
+ fmt_(self.expect, "%0.1e"),
254
+ fmt_(self.align_length, "%i"),
255
+ )
256
+ ]
257
+ if self.align_length is None:
258
+ return "\n".join(lines)
259
+ if self.align_length < 50:
260
+ lines.append(
261
+ "Query:%8s %s %s" % (self.query_start, self.query, self.query_end)
262
+ )
263
+ lines.append(f" {self.match}")
264
+ lines.append(
265
+ "Sbjct:%8s %s %s" % (self.sbjct_start, self.sbjct, self.sbjct_end)
266
+ )
267
+ else:
268
+ lines.append(
269
+ "Query:%8s %s...%s %s"
270
+ % (self.query_start, self.query[:45], self.query[-3:], self.query_end)
271
+ )
272
+ lines.append(f" {self.match[:45]}...{self.match[-3:]}")
273
+ lines.append(
274
+ "Sbjct:%8s %s...%s %s"
275
+ % (self.sbjct_start, self.sbjct[:45], self.sbjct[-3:], self.sbjct_end)
276
+ )
277
+ return "\n".join(lines)
278
+
279
+
280
+ class MultipleAlignment:
281
+ """Holds information about a multiple alignment.
282
+
283
+ Members:
284
+ alignment A list of tuples (name, start residue, sequence, end residue).
285
+
286
+ The start residue is 1-based. It may be blank, if that sequence is
287
+ not aligned in the multiple alignment.
288
+
289
+ """
290
+
291
+ def __init__(self):
292
+ """Initialize the class."""
293
+ self.alignment = []
294
+
295
+ def to_generic(self):
296
+ """Retrieve generic alignment object for the given alignment.
297
+
298
+ Instead of the tuples, this returns a MultipleSeqAlignment object
299
+ from Bio.Align, through which you can manipulate and query
300
+ the object.
301
+
302
+ Thanks to James Casbon for the code.
303
+ """
304
+ seq_parts = []
305
+ seq_names = []
306
+ parse_number = 0
307
+ n = 0
308
+ for name, start, seq, end in self.alignment:
309
+ if name == "QUERY": # QUERY is the first in each alignment block
310
+ parse_number += 1
311
+ n = 0
312
+
313
+ if parse_number == 1: # create on first_parse, append on all others
314
+ seq_parts.append(seq)
315
+ seq_names.append(name)
316
+ else:
317
+ seq_parts[n] += seq
318
+ n += 1
319
+
320
+ records = (
321
+ SeqRecord(Seq(seq), name) for (name, seq) in zip(seq_names, seq_parts)
322
+ )
323
+ return MultipleSeqAlignment(records)
324
+
325
+
326
+ class Round:
327
+ """Holds information from a PSI-BLAST round.
328
+
329
+ Members:
330
+ number Round number. (int)
331
+ reused_seqs Sequences in model, found again. List of Description objects.
332
+ new_seqs Sequences not found, or below threshold. List of Description.
333
+ alignments A list of Alignment objects.
334
+ multiple_alignment A MultipleAlignment object.
335
+ """
336
+
337
+ def __init__(self):
338
+ """Initialize the class."""
339
+ self.number = None
340
+ self.reused_seqs = []
341
+ self.new_seqs = []
342
+ self.alignments = []
343
+ self.multiple_alignment = None
344
+
345
+
346
+ class DatabaseReport:
347
+ """Holds information about a database report.
348
+
349
+ Members:
350
+ database_name List of database names. (can have multiple dbs)
351
+ num_letters_in_database Number of letters in the database. (int)
352
+ num_sequences_in_database List of number of sequences in the database.
353
+ posted_date List of the dates the databases were posted.
354
+ ka_params A tuple of (lambda, k, h) values. (floats)
355
+ gapped # XXX this isn't set right!
356
+ ka_params_gap A tuple of (lambda, k, h) values. (floats)
357
+
358
+ """
359
+
360
+ def __init__(self):
361
+ """Initialize the class."""
362
+ self.database_name = []
363
+ self.posted_date = []
364
+ self.num_letters_in_database = []
365
+ self.num_sequences_in_database = []
366
+ self.ka_params = (None, None, None)
367
+ self.gapped = 0
368
+ self.ka_params_gap = (None, None, None)
369
+
370
+
371
+ class Parameters:
372
+ """Holds information about the parameters.
373
+
374
+ Members:
375
+ matrix Name of the matrix.
376
+ gap_penalties Tuple of (open, extend) penalties. (floats)
377
+ sc_match Match score for nucleotide-nucleotide comparison
378
+ sc_mismatch Mismatch penalty for nucleotide-nucleotide comparison
379
+ num_hits Number of hits to the database. (int)
380
+ num_sequences Number of sequences. (int)
381
+ num_good_extends Number of extensions. (int)
382
+ num_seqs_better_e Number of sequences better than e-value. (int)
383
+ hsps_no_gap Number of HSP's better, without gapping. (int)
384
+ hsps_prelim_gapped Number of HSP's gapped in prelim test. (int)
385
+ hsps_prelim_gapped_attemped Number of HSP's attempted in prelim. (int)
386
+ hsps_gapped Total number of HSP's gapped. (int)
387
+ query_length Length of the query. (int)
388
+ query_id Identifier of the query sequence. (str)
389
+ database_length Number of letters in the database. (int)
390
+ effective_hsp_length Effective HSP length. (int)
391
+ effective_query_length Effective length of query. (int)
392
+ effective_database_length Effective length of database. (int)
393
+ effective_search_space Effective search space. (int)
394
+ effective_search_space_used Effective search space used. (int)
395
+ frameshift Frameshift window. Tuple of (int, float)
396
+ threshold Threshold. (int)
397
+ window_size Window size. (int)
398
+ dropoff_1st_pass Tuple of (score, bits). (int, float)
399
+ gap_x_dropoff Tuple of (score, bits). (int, float)
400
+ gap_x_dropoff_final Tuple of (score, bits). (int, float)
401
+ gap_trigger Tuple of (score, bits). (int, float)
402
+ blast_cutoff Tuple of (score, bits). (int, float)
403
+ """
404
+
405
+ def __init__(self):
406
+ """Initialize the class."""
407
+ self.matrix = ""
408
+ self.gap_penalties = (None, None)
409
+ self.sc_match = None
410
+ self.sc_mismatch = None
411
+ self.num_hits = None
412
+ self.num_sequences = None
413
+ self.num_good_extends = None
414
+ self.num_seqs_better_e = None
415
+ self.hsps_no_gap = None
416
+ self.hsps_prelim_gapped = None
417
+ self.hsps_prelim_gapped_attemped = None
418
+ self.hsps_gapped = None
419
+ self.query_id = None
420
+ self.query_length = None
421
+ self.database_length = None
422
+ self.effective_hsp_length = None
423
+ self.effective_query_length = None
424
+ self.effective_database_length = None
425
+ self.effective_search_space = None
426
+ self.effective_search_space_used = None
427
+ self.frameshift = (None, None)
428
+ self.threshold = None
429
+ self.window_size = None
430
+ self.dropoff_1st_pass = (None, None)
431
+ self.gap_x_dropoff = (None, None)
432
+ self.gap_x_dropoff_final = (None, None)
433
+ self.gap_trigger = (None, None)
434
+ self.blast_cutoff = (None, None)
435
+
436
+
437
+ # TODO - Add a friendly __str__ method to BLAST results
438
+ class Blast(Header, DatabaseReport, Parameters):
439
+ """Saves the results from a blast search.
440
+
441
+ Members:
442
+ descriptions A list of Description objects.
443
+ alignments A list of Alignment objects.
444
+ multiple_alignment A MultipleAlignment object.
445
+ + members inherited from base classes
446
+
447
+ """
448
+
449
+ def __init__(self):
450
+ """Initialize the class."""
451
+ Header.__init__(self)
452
+ DatabaseReport.__init__(self)
453
+ Parameters.__init__(self)
454
+ self.descriptions = []
455
+ self.alignments = []
456
+ self.multiple_alignment = None
457
+
458
+
459
+ class PSIBlast(Header, DatabaseReport, Parameters):
460
+ """Saves the results from a blastpgp search.
461
+
462
+ Members:
463
+ rounds A list of Round objects.
464
+ converged Whether the search converged.
465
+ + members inherited from base classes
466
+
467
+ """
468
+
469
+ def __init__(self):
470
+ """Initialize the class."""
471
+ Header.__init__(self)
472
+ DatabaseReport.__init__(self)
473
+ Parameters.__init__(self)
474
+ self.rounds = []
475
+ self.converged = 0
476
+
477
+
478
+ class _XMLparser(ContentHandler):
479
+ """Generic SAX Parser (PRIVATE).
480
+
481
+ Just a very basic SAX parser.
482
+
483
+ Redefine the methods startElement, characters and endElement.
484
+ """
485
+
486
+ def __init__(self, debug=0):
487
+ """Initialize the parser.
488
+
489
+ Arguments:
490
+ - debug - integer, amount of debug information to print
491
+
492
+ """
493
+ self._tag = []
494
+ self._value = ""
495
+ self._debug = debug
496
+ self._debug_ignore_list = []
497
+ self._method_name_level = 1
498
+ self._method_map = None
499
+
500
+ def startElement(self, name, attr):
501
+ """Found XML start tag.
502
+
503
+ No real need of attr, BLAST DTD doesn't use them
504
+
505
+ Arguments:
506
+ - name -- name of the tag
507
+ - attr -- tag attributes
508
+
509
+ """
510
+ self._tag.append(name)
511
+
512
+ if len(self._tag) == 1:
513
+ # root node
514
+ self._on_root_node(name)
515
+ return
516
+
517
+ # Try to call a method (defined in subclasses)
518
+ method = "start_" + self._node_method_name(name)
519
+
520
+ # Note could use try / except AttributeError
521
+ # BUT I found often triggered by nested errors...
522
+ if method in self._method_map:
523
+ self._method_map[method]()
524
+ if self._debug > 4:
525
+ sys.stderr.write("NCBIXML: Parsed: " + method + "\n")
526
+ elif self._debug > 3:
527
+ # Doesn't exist (yet) and may want to warn about it
528
+ if method not in self._debug_ignore_list:
529
+ sys.stderr.write("NCBIXML: Ignored: " + method + "\n")
530
+ self._debug_ignore_list.append(method)
531
+
532
+ # We don't care about white space in parent tags like Hsp,
533
+ # but that white space doesn't belong to child tags like Hsp_midline
534
+ if self._value.strip():
535
+ raise ValueError(
536
+ f"What should we do with {self._value} before the {name!r} tag?"
537
+ )
538
+ self._value = ""
539
+
540
+ def characters(self, ch):
541
+ """Found some text.
542
+
543
+ Arguments:
544
+ - ch -- characters read
545
+
546
+ """
547
+ self._value += ch # You don't ever get the whole string
548
+
549
+ def endElement(self, name):
550
+ """Found XML end tag.
551
+
552
+ Arguments:
553
+ - name -- tag name
554
+
555
+ """
556
+ # DON'T strip any white space, we may need it e.g. the hsp-midline
557
+
558
+ # Try to call a method (defined in subclasses)
559
+ method = "end_" + self._node_method_name(name)
560
+
561
+ # Note could use try / except AttributeError
562
+ # BUT I found often triggered by nested errors...
563
+ if method in self._method_map:
564
+ self._method_map[method]()
565
+ if self._debug > 2:
566
+ sys.stderr.write(f"NCBIXML: Parsed: {method} {self._value}\n")
567
+ elif self._debug > 1:
568
+ # Doesn't exist (yet) and may want to warn about it
569
+ if method not in self._debug_ignore_list:
570
+ sys.stderr.write(f"NCBIXML: Ignored: {method} {self._value}\n")
571
+ self._debug_ignore_list.append(method)
572
+
573
+ # Reset character buffer
574
+ self._value = ""
575
+
576
+ self._tag.pop()
577
+
578
+ def _node_method_name(self, name):
579
+ if self._method_name_level == 1:
580
+ return name
581
+ return "/".join(self._tag[-self._method_name_level :])
582
+
583
+
584
+ class BlastParser(_XMLparser):
585
+ """Parse XML BLAST data into a Blast object.
586
+
587
+ Parses XML output from BLAST (direct use discouraged).
588
+ This (now) returns a list of Blast records.
589
+ Historically it returned a single Blast record.
590
+ You are expected to use this via the parse or read functions.
591
+
592
+ All XML 'action' methods are private methods and may be:
593
+
594
+ - ``_start_TAG`` called when the start tag is found
595
+ - ``_end_TAG`` called when the end tag is found
596
+
597
+ """
598
+
599
+ def __init__(self, debug=0):
600
+ """Initialize the parser.
601
+
602
+ Arguments:
603
+ - debug - integer, amount of debug information to print
604
+
605
+ """
606
+ # Calling superclass method
607
+ _XMLparser.__init__(self, debug)
608
+
609
+ self._parser = xml.sax.make_parser()
610
+ self._parser.setContentHandler(self)
611
+
612
+ # To avoid ValueError: unknown url type: NCBI_BlastOutput.dtd
613
+ self._parser.setFeature(xml.sax.handler.feature_validation, 0)
614
+ self._parser.setFeature(xml.sax.handler.feature_namespaces, 0)
615
+ self._parser.setFeature(xml.sax.handler.feature_external_pes, 0)
616
+ self._parser.setFeature(xml.sax.handler.feature_external_ges, 0)
617
+
618
+ self._xml_version = 1
619
+
620
+ self.reset()
621
+
622
+ def reset(self):
623
+ """Reset all the data allowing reuse of the BlastParser() object."""
624
+ self._records = []
625
+ self._header = Header()
626
+ self._parameters = Parameters()
627
+ self._parameters.filter = None # Maybe I should update the class?
628
+
629
+ def _on_root_node(self, name):
630
+ if name == "BlastOutput":
631
+ self._setup_blast_v1()
632
+ elif name == "BlastXML2":
633
+ self._setup_blast_v2()
634
+ else:
635
+ raise ValueError(
636
+ "Invalid root node name: %s. Root node should be either"
637
+ " BlastOutput or BlastXML2" % name
638
+ )
639
+
640
+ def _setup_blast_v1(self):
641
+ self._method_map = {
642
+ "start_Iteration": self._start_blast_record,
643
+ "end_Iteration": self._end_blast_record,
644
+ "end_BlastOutput_program": self._set_header_application,
645
+ "end_BlastOutput_version": self._set_header_version,
646
+ "end_BlastOutput_reference": self._set_header_reference,
647
+ "end_BlastOutput_db": self._set_header_database,
648
+ "end_BlastOutput_query-ID": self._set_header_query_id,
649
+ "end_BlastOutput_query-def": self._set_header_query,
650
+ "end_BlastOutput_query-len": self._set_header_query_letters,
651
+ "end_Iteration_query-ID": self._set_record_query_id,
652
+ "end_Iteration_query-def": self._set_record_query_def,
653
+ "end_Iteration_query-len": self._set_record_query_letters,
654
+ "end_BlastOutput_hits": self._set_record_hits,
655
+ "end_Parameters_matrix": self._set_parameters_matrix,
656
+ "end_Parameters_expect": self._set_parameters_expect,
657
+ "end_Parameters_sc-match": self._set_parameters_sc_match,
658
+ "end_Parameters_sc-mismatch": self._set_parameters_sc_mismatch,
659
+ "end_Parameters_gap-open": self._set_parameters_gap_penalties,
660
+ "end_Parameters_gap-extend": self._set_parameters_gap_extend,
661
+ "end_Parameters_filter": self._set_parameters_filter,
662
+ "start_Hit": self._start_hit,
663
+ "end_Hit": self._end_hit,
664
+ "end_Hit_id": self.set_hit_id,
665
+ "end_Hit_def": self.set_hit_def,
666
+ "end_Hit_accession": self.set_hit_accession,
667
+ "end_Hit_len": self.set_hit_len,
668
+ "start_Hsp": self._start_hsp,
669
+ "end_Hsp_score": self._set_hsp_score,
670
+ "end_Hsp_bit-score": self._set_hsp_bit_score,
671
+ "end_Hsp_evalue": self._set_hsp_e_value,
672
+ "end_Hsp_query-from": self._set_hsp_query_start,
673
+ "end_Hsp_query-to": self._set_hsp_query_end,
674
+ "end_Hsp_hit-from": self._set_hsp_hit_from,
675
+ "end_Hsp_hit-to": self._set_hsp_hit_to,
676
+ "end_Hsp_query-frame": self._set_hsp_query_frame,
677
+ "end_Hsp_hit-frame": self._set_hsp_hit_frame,
678
+ "end_Hsp_identity": self._set_hsp_identity,
679
+ "end_Hsp_positive": self._set_hsp_positive,
680
+ "end_Hsp_gaps": self._set_hsp_gaps,
681
+ "end_Hsp_align-len": self._set_hsp_align_len,
682
+ "end_Hsp_qseq": self._set_hsp_query_seq,
683
+ "end_Hsp_hseq": self._set_hsp_subject_seq,
684
+ "end_Hsp_midline": self._set_hsp_midline,
685
+ "end_Statistics_db-num": self._set_statistics_db_num,
686
+ "end_Statistics_db-len": self._set_statistics_db_len,
687
+ "end_Statistics_hsp-len": self._set_statistics_hsp_len,
688
+ "end_Statistics_eff-space": self._set_statistics_eff_space,
689
+ "end_Statistics_kappa": self._set_statistics_kappa,
690
+ "end_Statistics_lambda": self._set_statistics_lambda,
691
+ "end_Statistics_entropy": self._set_statistics_entropy,
692
+ }
693
+
694
+ def _setup_blast_v2(self):
695
+ self._method_name_level = 2
696
+ self._xml_version = 2
697
+ self._method_map = {
698
+ "start_report/Report": self._start_blast_record,
699
+ "end_report/Report": self._end_blast_record,
700
+ "end_Report/program": self._set_header_application,
701
+ "end_Report/version": self._set_header_version,
702
+ "end_Report/reference": self._set_header_reference,
703
+ "end_Target/db": self._set_header_database,
704
+ "end_Search/query-id": self._set_record_query_id,
705
+ "end_Search/query-title": self._set_record_query_def,
706
+ "end_Search/query-len": self._set_record_query_letters,
707
+ "end_BlastOutput_hits": self._set_record_hits,
708
+ "end_Parameters/matrix": self._set_parameters_matrix,
709
+ "end_Parameters/expect": self._set_parameters_expect,
710
+ "end_Parameters/sc-match": self._set_parameters_sc_match,
711
+ "end_Parameters/sc-mismatch": self._set_parameters_sc_mismatch,
712
+ "end_Parameters/gap-open": self._set_parameters_gap_penalties,
713
+ "end_Parameters/gap-extend": self._set_parameters_gap_extend,
714
+ "end_Parameters/filter": self._set_parameters_filter,
715
+ "start_hits/Hit": self._start_hit,
716
+ "end_hits/Hit": self._end_hit,
717
+ "start_description/HitDescr": self._start_hit_descr_item,
718
+ "end_description/HitDescr": self._end_hit_descr_item,
719
+ "end_HitDescr/id": self._end_description_id,
720
+ "end_HitDescr/accession": self._end_description_accession,
721
+ "end_HitDescr/title": self._end_description_title,
722
+ "end_HitDescr/taxid": self._end_description_taxid,
723
+ "end_HitDescr/sciname": self._end_description_sciname,
724
+ "end_Hit/len": self.set_hit_len,
725
+ "start_hsps/Hsp": self._start_hsp,
726
+ "end_hsps/Hsp": self._end_hsp,
727
+ "end_Hsp/score": self._set_hsp_score,
728
+ "end_Hsp/bit-score": self._set_hsp_bit_score,
729
+ "end_Hsp/evalue": self._set_hsp_e_value,
730
+ "end_Hsp/query-from": self._set_hsp_query_start,
731
+ "end_Hsp/query-to": self._set_hsp_query_end,
732
+ "end_Hsp/hit-from": self._set_hsp_hit_from,
733
+ "end_Hsp/hit-to": self._set_hsp_hit_to,
734
+ "end_Hsp/query-frame": self._set_hsp_query_frame,
735
+ "end_Hsp/hit-frame": self._set_hsp_hit_frame,
736
+ "end_Hsp/query-strand": self._set_hsp_query_strand,
737
+ "end_Hsp/hit-strand": self._set_hsp_hit_strand,
738
+ "end_Hsp/identity": self._set_hsp_identity,
739
+ "end_Hsp/positive": self._set_hsp_positive,
740
+ "end_Hsp/gaps": self._set_hsp_gaps,
741
+ "end_Hsp/align-len": self._set_hsp_align_len,
742
+ "end_Hsp/qseq": self._set_hsp_query_seq,
743
+ "end_Hsp/hseq": self._set_hsp_subject_seq,
744
+ "end_Hsp/midline": self._set_hsp_midline,
745
+ "end_Statistics/db-num": self._set_statistics_db_num,
746
+ "end_Statistics/db-len": self._set_statistics_db_len,
747
+ "end_Statistics/hsp-len": self._set_statistics_hsp_len,
748
+ "end_Statistics/eff-space": self._set_statistics_eff_space,
749
+ "end_Statistics/kappa": self._set_statistics_kappa,
750
+ "end_Statistics/lambda": self._set_statistics_lambda,
751
+ "end_Statistics/entropy": self._set_statistics_entropy,
752
+ }
753
+
754
+ def _start_blast_record(self):
755
+ """Start interaction (PRIVATE)."""
756
+ self._blast = Blast()
757
+
758
+ def _end_blast_record(self):
759
+ """End interaction (PRIVATE)."""
760
+ # We stored a lot of generic "top level" information
761
+ # in self._header (an object of type Header)
762
+ self._blast.reference = self._header.reference
763
+ self._blast.date = self._header.date
764
+ self._blast.version = self._header.version
765
+ self._blast.database = self._header.database
766
+ self._blast.application = self._header.application
767
+
768
+ # These are required for "old" pre 2.2.14 files
769
+ # where only <BlastOutput_query-ID>, <BlastOutput_query-def>
770
+ # and <BlastOutput_query-len> were used. Now they
771
+ # are supplemented/replaced by <Iteration_query-ID>,
772
+ # <Iteration_query-def> and <Iteration_query-len>
773
+ if not hasattr(self._blast, "query") or not self._blast.query:
774
+ self._blast.query = self._header.query
775
+ if not hasattr(self._blast, "query_id") or not self._blast.query_id:
776
+ self._blast.query_id = self._header.query_id
777
+ if not hasattr(self._blast, "query_letters") or not self._blast.query_letters:
778
+ self._blast.query_letters = self._header.query_letters
779
+
780
+ # Hack to record the query length as both the query_letters and
781
+ # query_length properties (as in the plain text parser, see
782
+ # Bug 2176 comment 12):
783
+ self._blast.query_length = self._blast.query_letters
784
+ # Perhaps in the long term we should deprecate one, but I would
785
+ # prefer to drop query_letters - so we need a transition period
786
+ # with both.
787
+
788
+ # Hack to record the claimed database size as database_length
789
+ # (as well as in num_letters_in_database, see Bug 2176 comment 13):
790
+ self._blast.database_length = self._blast.num_letters_in_database
791
+ # TODO? Deprecate database_letters next?
792
+
793
+ # Hack to record the claimed database sequence count as database_sequences
794
+ self._blast.database_sequences = self._blast.num_sequences_in_database
795
+
796
+ # Apply the "top level" parameter information
797
+ self._blast.matrix = self._parameters.matrix
798
+ self._blast.num_seqs_better_e = self._parameters.num_seqs_better_e
799
+ self._blast.gap_penalties = self._parameters.gap_penalties
800
+ self._blast.filter = self._parameters.filter
801
+ self._blast.expect = self._parameters.expect
802
+ self._blast.sc_match = self._parameters.sc_match
803
+ self._blast.sc_mismatch = self._parameters.sc_mismatch
804
+
805
+ # Add to the list
806
+ self._records.append(self._blast)
807
+ # Clear the object (a new empty one is create in _start_Iteration)
808
+ self._blast = None
809
+
810
+ if self._debug:
811
+ sys.stderr.write("NCBIXML: Added Blast record to results\n")
812
+
813
+ # Header
814
+ def _set_header_application(self):
815
+ """BLAST program, e.g., blastp, blastn, etc. (PRIVATE).
816
+
817
+ Save this to put on each blast record object
818
+ """
819
+ self._header.application = self._value.upper()
820
+
821
+ def _set_header_version(self):
822
+ """Version number and date of the BLAST engine (PRIVATE).
823
+
824
+ e.g. "BLASTX 2.2.12 [Aug-07-2005]" but there can also be
825
+ variants like "BLASTP 2.2.18+" without the date.
826
+
827
+ Save this to put on each blast record object
828
+ """
829
+ parts = self._value.split()
830
+ # TODO - Check the first word starts with BLAST?
831
+
832
+ # The version is the second word (field one)
833
+ self._header.version = parts[1]
834
+
835
+ # Check there is a third word (the date)
836
+ if len(parts) >= 3:
837
+ if parts[2][0] == "[" and parts[2][-1] == "]":
838
+ self._header.date = parts[2][1:-1]
839
+ else:
840
+ # Assume this is still a date, but without the
841
+ # square brackets
842
+ self._header.date = parts[2]
843
+
844
+ def _set_header_reference(self):
845
+ """Record any article reference describing the algorithm (PRIVATE).
846
+
847
+ Save this to put on each blast record object
848
+ """
849
+ self._header.reference = self._value
850
+
851
+ def _set_header_database(self):
852
+ """Record the database(s) searched (PRIVATE).
853
+
854
+ Save this to put on each blast record object
855
+ """
856
+ self._header.database = self._value
857
+
858
+ def _set_header_query_id(self):
859
+ """Record the identifier of the query (PRIVATE).
860
+
861
+ Important in old pre 2.2.14 BLAST, for recent versions
862
+ <Iteration_query-ID> is enough
863
+ """
864
+ self._header.query_id = self._value
865
+
866
+ def _set_header_query(self):
867
+ """Record the definition line of the query (PRIVATE).
868
+
869
+ Important in old pre 2.2.14 BLAST, for recent versions
870
+ <Iteration_query-def> is enough
871
+ """
872
+ self._header.query = self._value
873
+
874
+ def _set_header_query_letters(self):
875
+ """Record the length of the query (PRIVATE).
876
+
877
+ Important in old pre 2.2.14 BLAST, for recent versions
878
+ <Iteration_query-len> is enough
879
+ """
880
+ self._header.query_letters = int(self._value)
881
+
882
+ def _set_record_query_id(self):
883
+ """Record the identifier of the query (PRIVATE)."""
884
+ self._blast.query_id = self._value
885
+
886
+ def _set_record_query_def(self):
887
+ """Record the definition line of the query (PRIVATE)."""
888
+ self._blast.query = self._value
889
+
890
+ def _set_record_query_letters(self):
891
+ """Record the length of the query (PRIVATE)."""
892
+ self._blast.query_letters = int(self._value)
893
+
894
+ # def _end_BlastOutput_query_seq(self):
895
+ # """The query sequence (PRIVATE)."""
896
+ # pass # XXX Missing in Blast ?
897
+
898
+ # def _end_BlastOutput_iter_num(self):
899
+ # """The psi-blast iteration number (PRIVATE)."""
900
+ # pass # XXX TODO PSI
901
+
902
+ def _set_record_hits(self):
903
+ """Hits to the database sequences, one for every sequence (PRIVATE)."""
904
+ self._blast.num_hits = int(self._value)
905
+
906
+ # def _end_BlastOutput_message(self):
907
+ # """error messages (PRIVATE)."""
908
+ # pass # XXX What to do ?
909
+
910
+ # Parameters
911
+ def _set_parameters_matrix(self):
912
+ """Matrix used (-M on legacy BLAST) (PRIVATE)."""
913
+ self._parameters.matrix = self._value
914
+
915
+ def _set_parameters_expect(self):
916
+ """Expect values cutoff (PRIVATE)."""
917
+ # NOTE: In old text output there was a line:
918
+ # Number of sequences better than 1.0e-004: 1
919
+ # As far as I can see, parameters.num_seqs_better_e
920
+ # would take the value of 1, and the expectation
921
+ # value was not recorded.
922
+ #
923
+ # Anyway we should NOT record this against num_seqs_better_e
924
+ self._parameters.expect = self._value
925
+
926
+ # def _end_Parameters_include(self):
927
+ # """Inclusion threshold for a psi-blast iteration (-h) (PRIVATE)."""
928
+ # pass # XXX TODO PSI
929
+
930
+ def _set_parameters_sc_match(self):
931
+ """Match score for nucleotide-nucleotide comparison (-r) (PRIVATE)."""
932
+ self._parameters.sc_match = int(self._value)
933
+
934
+ def _set_parameters_sc_mismatch(self):
935
+ """Mismatch penalty for nucleotide-nucleotide comparison (-r) (PRIVATE)."""
936
+ self._parameters.sc_mismatch = int(self._value)
937
+
938
+ def _set_parameters_gap_penalties(self):
939
+ """Gap existence cost (-G) (PRIVATE)."""
940
+ self._parameters.gap_penalties = int(self._value)
941
+
942
+ def _set_parameters_gap_extend(self):
943
+ """Gap extension cose (-E) (PRIVATE)."""
944
+ self._parameters.gap_penalties = (
945
+ self._parameters.gap_penalties,
946
+ int(self._value),
947
+ )
948
+
949
+ def _set_parameters_filter(self):
950
+ """Record filtering options (-F) (PRIVATE)."""
951
+ self._parameters.filter = self._value
952
+
953
+ # def _end_Parameters_pattern(self):
954
+ # """Pattern used for phi-blast search (PRIVATE).
955
+ # """
956
+ # pass # XXX TODO PSI
957
+
958
+ # def _end_Parameters_entrez_query(self):
959
+ # """Entrez query used to limit search (PRIVATE).
960
+ # """
961
+ # pass # XXX TODO PSI
962
+
963
+ # Hits
964
+ def _start_hit(self):
965
+ """Start filling records (PRIVATE)."""
966
+ self._blast.alignments.append(Alignment())
967
+ self._descr = Description() if self._xml_version == 1 else DescriptionExt()
968
+ self._blast.descriptions.append(self._descr)
969
+ self._blast.multiple_alignment = []
970
+ self._hit = self._blast.alignments[-1]
971
+
972
+ self._descr.num_alignments = 0
973
+ # Specifically ignore CREATE_VIEW statements that sometimes
974
+ # exist between <Hit> tags, as a result of very large remote
975
+ # BLAST searches.
976
+ if self._value.strip() == "CREATE_VIEW":
977
+ warnings.warn(
978
+ f"NCBIXML: Ignored: {self._value!r}",
979
+ BiopythonParserWarning,
980
+ )
981
+ self._value = ""
982
+
983
+ def _end_hit(self):
984
+ """Clear variables (PRIVATE)."""
985
+ # Cleanup
986
+ self._blast.multiple_alignment = None
987
+ self._hit = None
988
+ self._descr = None
989
+
990
+ def set_hit_id(self):
991
+ """Record the identifier of the database sequence (PRIVATE)."""
992
+ self._hit.hit_id = self._value
993
+ self._hit.title = self._value + " "
994
+
995
+ def set_hit_def(self):
996
+ """Record the definition line of the database sequence (PRIVATE)."""
997
+ self._hit.hit_def = self._value
998
+ self._hit.title += self._value
999
+ self._descr.title = self._hit.title
1000
+
1001
+ def set_hit_accession(self):
1002
+ """Record the accession value of the database sequence (PRIVATE)."""
1003
+ self._hit.accession = self._value
1004
+ self._descr.accession = self._value
1005
+
1006
+ def set_hit_len(self):
1007
+ """Record the length of the hit."""
1008
+ self._hit.length = int(self._value)
1009
+
1010
+ # HSPs
1011
+ def _start_hsp(self):
1012
+ # Note that self._start_Hit() should have been called
1013
+ # to setup things like self._blast.multiple_alignment
1014
+ self._hsp = HSP()
1015
+ self._hsp.positives = None
1016
+ self._hit.hsps.append(self._hsp)
1017
+ self._descr.num_alignments += 1
1018
+ self._blast.multiple_alignment.append(MultipleAlignment())
1019
+ self._mult_al = self._blast.multiple_alignment[-1]
1020
+
1021
+ def _end_hsp(self):
1022
+ if self._hsp.frame and len(self._hsp.frame) == 1:
1023
+ self._hsp.frame += (0,)
1024
+
1025
+ # Hsp_num is useless
1026
+ def _set_hsp_score(self):
1027
+ """Record the raw score of HSP (PRIVATE)."""
1028
+ self._hsp.score = float(self._value)
1029
+ if self._descr.score is None:
1030
+ self._descr.score = float(self._value)
1031
+
1032
+ def _set_hsp_bit_score(self):
1033
+ """Record the Bit score of HSP (PRIVATE)."""
1034
+ self._hsp.bits = float(self._value)
1035
+ if self._descr.bits is None:
1036
+ self._descr.bits = float(self._value)
1037
+
1038
+ def _set_hsp_e_value(self):
1039
+ """Record the expect value of the HSP (PRIVATE)."""
1040
+ self._hsp.expect = float(self._value)
1041
+ if self._descr.e is None:
1042
+ self._descr.e = float(self._value)
1043
+
1044
+ def _set_hsp_query_start(self):
1045
+ """Offset of query at the start of the alignment (one-offset) (PRIVATE)."""
1046
+ self._hsp.query_start = int(self._value)
1047
+
1048
+ def _set_hsp_query_end(self):
1049
+ """Offset of query at the end of the alignment (one-offset) (PRIVATE)."""
1050
+ self._hsp.query_end = int(self._value)
1051
+
1052
+ def _set_hsp_hit_from(self):
1053
+ """Offset of the database at the start of the alignment (one-offset) (PRIVATE)."""
1054
+ self._hsp.sbjct_start = int(self._value)
1055
+
1056
+ def _set_hsp_hit_to(self):
1057
+ """Offset of the database at the end of the alignment (one-offset) (PRIVATE)."""
1058
+ self._hsp.sbjct_end = int(self._value)
1059
+
1060
+ # def _end_Hsp_pattern_from(self):
1061
+ # """Start of phi-blast pattern on the query (one-offset) (PRIVATE)."""
1062
+ # pass # XXX TODO PSI
1063
+
1064
+ # def _end_Hsp_pattern_to(self):
1065
+ # """End of phi-blast pattern on the query (one-offset) (PRIVATE)."""
1066
+ # pass # XXX TODO PSI
1067
+
1068
+ def _set_hsp_query_frame(self):
1069
+ """Frame of the query if applicable (PRIVATE)."""
1070
+ v = int(self._value)
1071
+ self._hsp.frame = (v,)
1072
+ if self._header.application == "BLASTN":
1073
+ self._hsp.strand = ("Plus" if v > 0 else "Minus",)
1074
+
1075
+ def _set_hsp_hit_frame(self):
1076
+ """Frame of the database sequence if applicable (PRIVATE)."""
1077
+ v = int(self._value)
1078
+ if len(self._hsp.frame) == 0:
1079
+ self._hsp.frame = (0, v)
1080
+ else:
1081
+ self._hsp.frame += (v,)
1082
+ if self._header.application == "BLASTN":
1083
+ self._hsp.strand += ("Plus" if v > 0 else "Minus",)
1084
+
1085
+ def _set_hsp_query_strand(self):
1086
+ """Frame of the query if applicable (PRIVATE)."""
1087
+ self._hsp.strand = (self._value,)
1088
+ if self._header.application == "BLASTN":
1089
+ self._hsp.frame = (1 if self._value == "Plus" else -1,)
1090
+
1091
+ def _set_hsp_hit_strand(self):
1092
+ """Frame of the database sequence if applicable (PRIVATE)."""
1093
+ self._hsp.strand += (self._value,)
1094
+ if self._header.application == "BLASTN":
1095
+ self._hsp.frame += (1 if self._value == "Plus" else -1,)
1096
+
1097
+ def _set_hsp_identity(self):
1098
+ """Record the number of identities in the alignment (PRIVATE)."""
1099
+ v = int(self._value)
1100
+ self._hsp.identities = v
1101
+ if self._hsp.positives is None:
1102
+ self._hsp.positives = v
1103
+
1104
+ def _set_hsp_positive(self):
1105
+ """Record the number of positive (conservative) substitutions in the alignment (PRIVATE)."""
1106
+ self._hsp.positives = int(self._value)
1107
+
1108
+ def _set_hsp_gaps(self):
1109
+ """Record the number of gaps in the alignment (PRIVATE)."""
1110
+ self._hsp.gaps = int(self._value)
1111
+
1112
+ def _set_hsp_align_len(self):
1113
+ """Record the length of the alignment (PRIVATE)."""
1114
+ self._hsp.align_length = int(self._value)
1115
+
1116
+ # def _en_Hsp_density(self):
1117
+ # """Score density (PRIVATE)."""
1118
+ # pass # XXX ???
1119
+
1120
+ def _set_hsp_query_seq(self):
1121
+ """Record the alignment string for the query (PRIVATE)."""
1122
+ self._hsp.query = self._value
1123
+
1124
+ def _set_hsp_subject_seq(self):
1125
+ """Record the alignment string for the database (PRIVATE)."""
1126
+ self._hsp.sbjct = self._value
1127
+
1128
+ def _set_hsp_midline(self):
1129
+ """Record the middle line as normally seen in BLAST report (PRIVATE)."""
1130
+ self._hsp.match = self._value # do NOT strip spaces!
1131
+ assert len(self._hsp.match) == len(self._hsp.query)
1132
+ assert len(self._hsp.match) == len(self._hsp.sbjct)
1133
+
1134
+ # Statistics
1135
+ def _set_statistics_db_num(self):
1136
+ """Record the number of sequences in the database (PRIVATE)."""
1137
+ self._blast.num_sequences_in_database = int(self._value)
1138
+
1139
+ def _set_statistics_db_len(self):
1140
+ """Record the number of letters in the database (PRIVATE)."""
1141
+ self._blast.num_letters_in_database = int(self._value)
1142
+
1143
+ def _set_statistics_hsp_len(self):
1144
+ """Record the effective HSP length (PRIVATE)."""
1145
+ self._blast.effective_hsp_length = int(self._value)
1146
+
1147
+ def _set_statistics_eff_space(self):
1148
+ """Record the effective search space (PRIVATE)."""
1149
+ self._blast.effective_search_space = float(self._value)
1150
+
1151
+ def _set_statistics_kappa(self):
1152
+ """Karlin-Altschul parameter K (PRIVATE)."""
1153
+ self._blast.ka_params = float(self._value)
1154
+
1155
+ def _set_statistics_lambda(self):
1156
+ """Karlin-Altschul parameter Lambda (PRIVATE)."""
1157
+ self._blast.ka_params = (float(self._value), self._blast.ka_params)
1158
+
1159
+ def _set_statistics_entropy(self):
1160
+ """Karlin-Altschul parameter H (PRIVATE)."""
1161
+ self._blast.ka_params = self._blast.ka_params + (float(self._value),)
1162
+
1163
+ def _start_hit_descr_item(self):
1164
+ """XML v2. Start hit description item."""
1165
+ self._hit_descr_item = DescriptionExtItem()
1166
+
1167
+ def _end_hit_descr_item(self):
1168
+ """XML v2. Start hit description item."""
1169
+ self._descr.append_item(self._hit_descr_item)
1170
+ if not self._hit.title:
1171
+ self._hit.title = str(self._hit_descr_item)
1172
+ self._hit_descr_item = None
1173
+
1174
+ def _end_description_id(self):
1175
+ """XML v2. The identifier of the database sequence(PRIVATE)."""
1176
+ self._hit_descr_item.id = self._value
1177
+ if not self._hit.hit_id:
1178
+ self._hit.hit_id = self._value
1179
+
1180
+ def _end_description_accession(self):
1181
+ """XML v2. The accession value of the database sequence (PRIVATE)."""
1182
+ self._hit_descr_item.accession = self._value
1183
+ if not getattr(self._hit, "accession", None):
1184
+ self._hit.accession = self._value
1185
+
1186
+ def _end_description_title(self):
1187
+ """XML v2. The hit description title (PRIVATE)."""
1188
+ self._hit_descr_item.title = self._value
1189
+
1190
+ def _end_description_taxid(self):
1191
+ try:
1192
+ self._hit_descr_item.taxid = int(self._value)
1193
+ except ValueError:
1194
+ pass
1195
+
1196
+ def _end_description_sciname(self):
1197
+ self._hit_descr_item.sciname = self._value
1198
+
1199
+
1200
+ def read(handle, debug=0):
1201
+ """Return a single Blast record (assumes just one query).
1202
+
1203
+ Uses the BlastParser internally.
1204
+
1205
+ This function is for use when there is one and only one BLAST
1206
+ result in your XML file.
1207
+
1208
+ Use the Bio.Blast.NCBIXML.parse() function if you expect more than
1209
+ one BLAST record (i.e. if you have more than one query sequence).
1210
+ """
1211
+ iterator = parse(handle, debug)
1212
+ try:
1213
+ record = next(iterator)
1214
+ except StopIteration:
1215
+ raise ValueError("No records found in handle") from None
1216
+ try:
1217
+ next(iterator)
1218
+ raise ValueError("More than one record found in handle")
1219
+ except StopIteration:
1220
+ pass
1221
+ return record
1222
+
1223
+
1224
+ def parse(handle, debug=0):
1225
+ """Return an iterator a Blast record for each query.
1226
+
1227
+ Incremental parser, this is an iterator that returns
1228
+ Blast records. It uses the BlastParser internally.
1229
+
1230
+ handle - file handle to and XML file to parse
1231
+ debug - integer, amount of debug information to print
1232
+
1233
+ This is a generator function that returns multiple Blast records
1234
+ objects - one for each query sequence given to blast. The file
1235
+ is read incrementally, returning complete records as they are read
1236
+ in.
1237
+
1238
+ Should cope with new BLAST 2.2.14+ which gives a single XML file
1239
+ for multiple query records.
1240
+
1241
+ Should also cope with XML output from older versions BLAST which
1242
+ gave multiple XML files concatenated together (giving a single file
1243
+ which strictly speaking wasn't valid XML).
1244
+ """
1245
+ from xml.parsers import expat
1246
+
1247
+ BLOCK = 1024
1248
+ MARGIN = 10 # must be at least length of newline + XML start
1249
+ XML_START = "<?xml"
1250
+ NEW_LINE = "\n"
1251
+ NULL = ""
1252
+
1253
+ pending = ""
1254
+ text = handle.read(BLOCK)
1255
+ if isinstance(text, bytes):
1256
+ # Not a text handle, raw bytes mode
1257
+ XML_START = b"<?xml"
1258
+ NEW_LINE = b"\n"
1259
+ NULL = b""
1260
+ pending = b""
1261
+
1262
+ if not text:
1263
+ # NO DATA FOUND!
1264
+ raise ValueError("Your XML file was empty")
1265
+
1266
+ try:
1267
+ while text:
1268
+ # We are now starting a new XML file
1269
+ if not text.startswith(XML_START):
1270
+ raise ValueError(
1271
+ "Your XML file did not start with %r... but instead %r"
1272
+ % (XML_START, text[:20])
1273
+ )
1274
+
1275
+ expat_parser = expat.ParserCreate()
1276
+ blast_parser = BlastParser(debug)
1277
+ expat_parser.StartElementHandler = blast_parser.startElement
1278
+ expat_parser.EndElementHandler = blast_parser.endElement
1279
+ expat_parser.CharacterDataHandler = blast_parser.characters
1280
+
1281
+ expat_parser.Parse(text, False)
1282
+ while blast_parser._records:
1283
+ record = blast_parser._records[0]
1284
+ blast_parser._records = blast_parser._records[1:]
1285
+ yield record
1286
+
1287
+ while True:
1288
+ # Read in another block of the file...
1289
+ text, pending = pending + handle.read(BLOCK), ""
1290
+ if not text:
1291
+ # End of the file!
1292
+ break
1293
+
1294
+ # Now read a little bit more so we can check for the
1295
+ # start of another XML file...
1296
+ pending = handle.read(MARGIN)
1297
+
1298
+ if (NEW_LINE + XML_START) not in (text + pending):
1299
+ # Good - still dealing with the same XML file
1300
+ expat_parser.Parse(text, False)
1301
+ while blast_parser._records:
1302
+ yield blast_parser._records.pop(0)
1303
+ else:
1304
+ # This is output from pre 2.2.14 BLAST,
1305
+ # one XML file for each query!
1306
+
1307
+ # Finish the old file:
1308
+ text, pending = (text + pending).split(NEW_LINE + XML_START, 1)
1309
+ pending = XML_START + pending
1310
+
1311
+ expat_parser.Parse(text, True) # End of XML record
1312
+ while blast_parser._records:
1313
+ yield blast_parser._records.pop(0)
1314
+
1315
+ # Now we are going to re-loop, reset the
1316
+ # parsers and start reading the next XML file
1317
+ text, pending = pending, NULL
1318
+ break
1319
+
1320
+ # At this point we have finished the first XML record.
1321
+ # If the file is from an old version of blast, it may
1322
+ # contain more XML records (check if text=="").
1323
+ assert not pending, pending
1324
+ assert len(blast_parser._records) == 0, len(blast_parser._records)
1325
+ finally:
1326
+ expat_parser.Parse(NULL, True)
1327
+
1328
+ # We should have finished the file!
1329
+ assert not text, text
1330
+ assert not pending, pending
1331
+ assert len(blast_parser._records) == 0, len(blast_parser._records)
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/__init__.py ADDED
@@ -0,0 +1,1352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 1999 by Jeffrey Chang. All rights reserved.
2
+ # Revisions 2023 by Michiel de Hoon. All rights reserved.
3
+ #
4
+ # This file is part of the Biopython distribution and governed by your
5
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
6
+ # Please see the LICENSE file that should have been included as part of this
7
+ # package.
8
+
9
+ """Code to parse and store BLAST XML output, and to invoke the NCBI BLAST web server.
10
+
11
+ This module provides code to parse and store BLAST XML output, following its
12
+ definition in the associated BLAST XML DTD file:
13
+ https://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd
14
+
15
+ This module also provides code to invoke the BLAST web server provided by NCBI.
16
+ https://blast.ncbi.nlm.nih.gov/
17
+
18
+ Variables:
19
+
20
+ - email Set the Blast email parameter (default is None).
21
+ - tool Set the Blast tool parameter (default is ``biopython``).
22
+
23
+ """
24
+
25
+ import io
26
+ import textwrap
27
+ import time
28
+ import warnings
29
+ from collections import UserList
30
+ from urllib.parse import urlencode
31
+ from urllib.request import build_opener
32
+ from urllib.request import HTTPBasicAuthHandler
33
+ from urllib.request import HTTPPasswordMgrWithDefaultRealm
34
+ from urllib.request import install_opener
35
+ from urllib.request import Request
36
+ from urllib.request import urlopen
37
+ from xml.parsers import expat
38
+
39
+ import numpy as np
40
+
41
+ from Bio import BiopythonWarning
42
+ from Bio import StreamModeError
43
+ from Bio._utils import function_with_previous
44
+ from Bio.Align import Alignment
45
+ from Bio.Align import Alignments
46
+ from Bio.Blast import _writers
47
+
48
+ email = None
49
+ tool = "biopython"
50
+
51
+
52
+ NCBI_BLAST_URL = "https://blast.ncbi.nlm.nih.gov/Blast.cgi"
53
+
54
+ BLOCK = 2048 # default block size from expat
55
+
56
+
57
+ class NotXMLError(ValueError):
58
+ """Failed to parse file as XML."""
59
+
60
+ def __init__(self, message):
61
+ """Initialize the class."""
62
+ self.msg = message
63
+
64
+ def __str__(self):
65
+ """Return a string summary of the exception."""
66
+ return (
67
+ "Failed to parse the XML data (%s). Please make sure that the input data "
68
+ "are in XML format." % self.msg
69
+ )
70
+
71
+
72
+ class CorruptedXMLError(ValueError):
73
+ """Corrupted XML."""
74
+
75
+ def __init__(self, message):
76
+ """Initialize the class."""
77
+ self.msg = message
78
+
79
+ def __str__(self):
80
+ """Return a string summary of the exception."""
81
+ return (
82
+ "Failed to parse the XML data (%s). Please make sure that the input data "
83
+ "are not corrupted." % self.msg
84
+ )
85
+
86
+
87
+ class HSP(Alignment):
88
+ """Stores an alignment of one query sequence against a target sequence.
89
+
90
+ An HSP (High-scoring Segment Pair) stores the alignment of one query
91
+ sequence segment against one target (hit) sequence segment. The
92
+ ``Bio.Blast.HSP`` class inherits from the ``Bio.Align.Alignment`` class.
93
+
94
+ In addition to the ``target`` and ``query`` attributes of a
95
+ ``Bio.Align.Alignment``, a ``Bio.Blast.HSP`` object has the following
96
+ attributes:
97
+
98
+ - score: score of HSP;
99
+ - annotations: a dictionary that may contain the following keys:
100
+ - 'bit score': score (in bits) of HSP (float);
101
+ - 'evalue': e-value of HSP (float);
102
+ - 'identity': number of identities in HSP (integer);
103
+ - 'positive': number of positives in HSP (integer);
104
+ - 'gaps': number of gaps in HSP (integer);
105
+ - 'midline': formatting middle line.
106
+
107
+ A ``Bio.Blast.HSP`` object behaves the same as a `Bio.Align.Alignment``
108
+ object and can be used as such. However, when printing a ``Bio.Blast.HSP``
109
+ object, the BLAST e-value and bit score are included in the output (in
110
+ addition to the alignment itself).
111
+
112
+ See the documentation of ``Bio.Blast.Record`` for a more detailed
113
+ explanation of how the information in BLAST records is stored in
114
+ Biopython.
115
+ """
116
+
117
+ def __repr__(self):
118
+ query = self.query
119
+ target = self.target
120
+ n, m = self.shape
121
+ return f"<Bio.Blast.HSP target.id={target.id!r} query.id={query.id!r}; {n} rows x {m} columns>"
122
+
123
+ def __str__(self):
124
+ alignment_text = super().__str__()
125
+ query = self.query
126
+ target = self.target
127
+ query_strand = (
128
+ "Plus" if self.coordinates[1, 0] <= self.coordinates[1, -1] else "Minus"
129
+ )
130
+ target_strand = (
131
+ "Plus" if self.coordinates[0, 0] <= self.coordinates[0, -1] else "Minus"
132
+ )
133
+ indent = " " * 8
134
+ query_description = textwrap.fill(
135
+ query.description,
136
+ width=80,
137
+ initial_indent=indent,
138
+ subsequent_indent=indent,
139
+ )
140
+ target_description = textwrap.fill(
141
+ target.description,
142
+ width=80,
143
+ initial_indent=indent,
144
+ subsequent_indent=indent,
145
+ )
146
+ evalue = self.annotations["evalue"]
147
+ bitscore = self.annotations["bit score"]
148
+ score = self.score
149
+ steps = np.diff(self.coordinates, 1)
150
+ aln_span = sum(abs(steps).max(0))
151
+ terms = []
152
+ identity = self.annotations["identity"]
153
+ identity_percentage = round(100.0 * identity / aln_span)
154
+ identity_text = "Identities:%d/%d(%d%%)" % (
155
+ identity,
156
+ aln_span,
157
+ identity_percentage,
158
+ )
159
+ terms.append(identity_text)
160
+ positive = self.annotations.get("positive")
161
+ if positive is not None:
162
+ positive_percentage = round(100.0 * positive / aln_span)
163
+ positive_text = "Positives:%d/%d(%d%%)" % (
164
+ positive,
165
+ aln_span,
166
+ positive_percentage,
167
+ )
168
+ terms.append(positive_text)
169
+ try:
170
+ gaps = self.annotations["gaps"]
171
+ except KeyError:
172
+ pass
173
+ else:
174
+ gaps_percentage = round(100.0 * gaps / aln_span)
175
+ gaps_text = "Gaps:%d.%d(%d%%)" % (gaps, aln_span, gaps_percentage)
176
+ terms.append(gaps_text)
177
+ counts_line = ", ".join(terms)
178
+ return """\
179
+ Query : %s Length: %d Strand: %s
180
+ %s
181
+ Target: %s Length: %d Strand: %s
182
+ %s
183
+
184
+ Score:%d bits(%d), Expect:%.1g,
185
+ %s
186
+
187
+ %s
188
+ """ % (
189
+ query.id,
190
+ len(query),
191
+ query_strand,
192
+ query_description,
193
+ target.id,
194
+ len(target),
195
+ target_strand,
196
+ target_description,
197
+ bitscore,
198
+ score,
199
+ evalue,
200
+ counts_line,
201
+ alignment_text,
202
+ )
203
+
204
+
205
+ class Hit(Alignments):
206
+ """Stores a single BLAST hit of one single query against one target.
207
+
208
+ The ``Bio.Blast.Hit`` class inherits from the ``Bio.Align.Alignments``
209
+ class, which is a subclass of a Python list. The ``Bio.Blast.Hit`` class
210
+ stores ``Bio.Blast.HSP`` objwcts, which inherit from
211
+ ``Bio.Align.Alignment``. A ``Bio.Blast.Hit`` object is therefore
212
+ effectively a list of ``Bio.Align.Alignment`` objects. Most hits consist of
213
+ only 1 or a few Alignment objects.
214
+
215
+ Each ``Bio.Blast.Hit`` object has a ``target`` attribute containing the
216
+ following information:
217
+
218
+ - target.id: seqId of subject;
219
+ - target.description: definition line of subject;
220
+ - target.name: accession of subject;
221
+ - len(target.seq): sequence length of subject.
222
+
223
+ See the documentation of ``Bio.Blast.Record`` for a more detailed
224
+ explanation of the information stored in the alignments contained in the
225
+ ``Bio.Blast.Hit`` object.
226
+ """
227
+
228
+ def __getitem__(self, key):
229
+ try:
230
+ value = super().__getitem__(key)
231
+ except IndexError:
232
+ raise IndexError("index out of range") from None
233
+ if isinstance(key, slice):
234
+ hit = Hit(value)
235
+ hit.target = self.target
236
+ return hit
237
+ else:
238
+ return value
239
+
240
+ def __repr__(self):
241
+ target = self.target
242
+ try:
243
+ alignment = self[0]
244
+ except IndexError:
245
+ return f"<Bio.Blast.Hit target.id={target.id!r}; no hits>"
246
+ query = alignment.query
247
+ nhsps = len(self)
248
+ if nhsps == 1:
249
+ unit = "HSP"
250
+ else: # nhsps > 1
251
+ unit = "HSPs"
252
+ return f"<Bio.Blast.Hit target.id={target.id!r} query.id={query.id!r}; {nhsps} {unit}>"
253
+
254
+ def __str__(self):
255
+ """Return a human readable summary of the Hit object."""
256
+ lines = []
257
+
258
+ # set query id line
259
+ query = self[0].query
260
+ qid_line = "Query: %s" % query.id
261
+ lines.append(qid_line)
262
+ indent = " " * 7
263
+ description_lines = textwrap.wrap(
264
+ query.description,
265
+ width=80,
266
+ initial_indent=indent,
267
+ subsequent_indent=indent,
268
+ )
269
+ lines.extend(description_lines)
270
+
271
+ # set hit id line
272
+ target = self.target
273
+ hid_line = " Hit: %s (length=%i)" % (target.id, len(target))
274
+ lines.append(hid_line)
275
+ description_lines = textwrap.wrap(
276
+ target.description,
277
+ width=80,
278
+ initial_indent=indent,
279
+ subsequent_indent=indent,
280
+ )
281
+ lines.extend(description_lines)
282
+
283
+ # set hsp line and table
284
+ lines.append(
285
+ " HSPs: %s %s %s %s %s %s"
286
+ % ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21)
287
+ )
288
+ pattern = "%11s %8s %9s %6s %15s %21s"
289
+ lines.append(
290
+ pattern % ("#", "E-value", "Bit score", "Span", "Query range", "Hit range")
291
+ )
292
+ lines.append(pattern % ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21))
293
+ for idx, hsp in enumerate(self):
294
+ # evalue
295
+ evalue = format(hsp.annotations["evalue"], ".2g")
296
+ # bit score
297
+ bitscore = format(hsp.annotations["bit score"], ".2f")
298
+ # alignment length
299
+ steps = np.diff(hsp.coordinates, 1)
300
+ aln_span = sum(abs(steps).max(0))
301
+ # query region
302
+ query_start = hsp.coordinates[1, 0]
303
+ query_end = hsp.coordinates[1, -1]
304
+ query_range = f"[{query_start}:{query_end}]"
305
+ # max column length is 18
306
+ query_range = (
307
+ query_range[:13] + "~]" if len(query_range) > 15 else query_range
308
+ )
309
+ # hit region
310
+ hit_start = hsp.coordinates[0, 0]
311
+ hit_end = hsp.coordinates[0, -1]
312
+ hit_range = f"[{hit_start}:{hit_end}]"
313
+ hit_range = hit_range[:19] + "~]" if len(hit_range) > 21 else hit_range
314
+ # append the hsp row
315
+ lines.append(
316
+ pattern % (idx, evalue, bitscore, aln_span, query_range, hit_range)
317
+ )
318
+
319
+ return "\n".join(lines)
320
+
321
+
322
+ class Record(list):
323
+ """Stores the BLAST results for a single query.
324
+
325
+ A ``Bio.Blast.Record`` object is a list of ``Bio.Blast.Hit`` objects, each
326
+ corresponding to one hit for the query in the BLAST output.
327
+
328
+ The ``Bio.Blast.Record`` object may have the following attributes:
329
+ - query: A ``SeqRecord`` object which may contain some or all of the
330
+ following information:
331
+ - query.id: SeqId of query;
332
+ - query.description: Definition line of query;
333
+ - len(query.seq): Length of the query sequence.
334
+ - stat: A dictionary with summary statistics of the BLAST run. It may
335
+ contain the following keys:
336
+ - 'db-num': number of sequences in BLAST db (integer);
337
+ - 'db-len': length of BLAST db (integer);
338
+ - 'hsp-len': effective HSP length (integer);
339
+ - 'eff-space': effective search space (float);
340
+ - 'kappa': Karlin-Altschul parameter K (float);
341
+ - 'lambda': Karlin-Altschul parameter Lambda (float);
342
+ - 'entropy': Karlin-Altschul parameter H (float).
343
+ - message: Some (error?) information.
344
+
345
+ Each ``Bio.Blast.Hit`` object has a ``target`` attribute containing the
346
+ following information:
347
+
348
+ - target.id: seqId of subject;
349
+ - target.description: definition line of subject;
350
+ - target.name: accession of subject;
351
+ - len(target.seq): sequence length of subject.
352
+
353
+ The ``Bio.Blast.Hit`` class inherits from the ``Bio.Align.Alignments``
354
+ class, which inherits from a Python list. In this list, the
355
+ ``Bio.Blast.Hit`` object stores ``Bio.Blast.HSP`` objects, which inherit
356
+ from the ``Bio.Align.Alignment`` class. A ``Bio.Blast.Hit`` object is
357
+ therefore effectively a list of alignment objects.
358
+
359
+ Each HSP in a ``Bio.Blast.Hit`` object has the attributes ``target`` and
360
+ ``query`` attributes, as usual for of a ``Bio.Align.Alignment`` object
361
+ storing a pairwise alignment, pointing to a ``SeqRecord`` object
362
+ representing the target and query, respectively. For translated BLAST
363
+ searches, the ``features`` attribute of the target or query may contain a
364
+ ``SeqFeature`` of type CDS that stores the amino acid sequence region. The
365
+ ``qualifiers`` attribute of such a feature is a dictionary with a single
366
+ key 'coded_by'; the corresponding value specifies the nucleotide sequence
367
+ region, in a GenBank-style string with 1-based coordinates, that encodes
368
+ the amino acid sequence.
369
+
370
+ Each ``Bio.Blast.HSP`` object has the following additional attributes:
371
+
372
+ - score: score of HSP;
373
+ - annotations: a dictionary that may contain the following keys:
374
+ - 'bit score': score (in bits) of HSP (float);
375
+ - 'evalue': e-value of HSP (float);
376
+ - 'identity': number of identities in HSP (integer);
377
+ - 'positive': number of positives in HSP (integer);
378
+ - 'gaps': number of gaps in HSP (integer);
379
+ - 'midline': formatting middle line.
380
+
381
+ >>> from Bio import Blast
382
+ >>> record = Blast.read("Blast/xml_2212L_blastx_001.xml")
383
+ >>> record.query
384
+ SeqRecord(seq=Seq(None, length=556), id='gi|1347369|gb|G25137.1|G25137', name='<unknown name>', description='human STS EST48004, sequence tagged site', dbxrefs=[])
385
+ >>> record.stat
386
+ {'db-num': 2934173, 'db-len': 1011751523, 'hsp-len': 0, 'eff-space': 0, 'kappa': 0.041, 'lambda': 0.267, 'entropy': 0.14}
387
+ >>> len(record)
388
+ 78
389
+ >>> hit = record[0]
390
+ >>> type(hit)
391
+ <class 'Bio.Blast.Hit'>
392
+ >>> from Bio.Align import Alignments
393
+ >>> isinstance(hit, Alignments)
394
+ True
395
+ >>> hit.target
396
+ SeqRecord(seq=Seq(None, length=319), id='gi|12654095|gb|AAH00859.1|', name='AAH00859', description='Unknown (protein for IMAGE:3459481) [Homo sapiens]', dbxrefs=[])
397
+
398
+ Most hits consist of only 1 or a few Alignment objects:
399
+
400
+ >>> len(hit)
401
+ 1
402
+ >>> alignment = hit[0]
403
+ >>> type(alignment)
404
+ <class 'Bio.Blast.HSP'>
405
+ >>> alignment.score
406
+ 630.0
407
+ >>> alignment.annotations
408
+ {'bit score': 247.284, 'evalue': 1.69599e-64, 'identity': 122, 'positive': 123, 'gaps': 0, 'midline': 'DLQLLIKAVNLFPAGTNSRWEVIANYMNIHSSSGVKRTAKDVIGKAKSLQKLDPHQKDDINKKAFDKFKKEHGVVPQADNATPSERF GPYTDFTP TTE QKL EQAL TYPVNT ERW IA AVPGR K+'}
409
+
410
+ Target and query information are stored in the respective attributes of the
411
+ alignment:
412
+
413
+ >>> alignment.target
414
+ SeqRecord(seq=Seq({155: 'DLQLLIKAVNLFPAGTNSRWEVIANYMNIHSSSGVKRTAKDVIGKAKSLQKLDP...TKK'}, length=319), id='gi|12654095|gb|AAH00859.1|', name='AAH00859', description='Unknown (protein for IMAGE:3459481) [Homo sapiens]', dbxrefs=[])
415
+ >>> alignment.query
416
+ SeqRecord(seq=Seq('DLQLLIKAVNLFPAGTNSRWEVIANYMNIHSSSGVKRTAKDVIGKAKSLQKLDP...XKE'), id='gi|1347369|gb|G25137.1|G25137', name='<unknown name>', description='human STS EST48004, sequence tagged site', dbxrefs=[])
417
+
418
+ This was a BLASTX run, so the query sequence was translated:
419
+
420
+ >>> len(alignment.target.features)
421
+ 0
422
+ >>> len(alignment.query.features)
423
+ 1
424
+ >>> feature = alignment.query.features[0]
425
+ >>> feature
426
+ SeqFeature(SimpleLocation(ExactPosition(0), ExactPosition(133)), type='CDS', qualifiers=...)
427
+ >>> feature.qualifiers
428
+ {'coded_by': 'gi|1347369|gb|G25137.1|G25137:1..399'}
429
+
430
+ i.e., nucleotides 0:399 (in zero-based coordinates) encode the amino acids
431
+ of the query in the alignment.
432
+
433
+ For an alignment against the reverse strand, the location in the qualifier
434
+ is shown as in this example:
435
+
436
+ >>> record[72][0].query.features[0].qualifiers
437
+ {'coded_by': 'complement(gi|1347369|gb|G25137.1|G25137:345..530)'}
438
+
439
+ """
440
+
441
+ def __init__(self):
442
+ """Initialize the Record object."""
443
+ self.query = None
444
+
445
+ def __repr__(self):
446
+ query = self.query
447
+ try:
448
+ query_id = query.id
449
+ except AttributeError:
450
+ query_id = "unknown"
451
+ nhits = len(self)
452
+ if nhits == 0:
453
+ return f"<Bio.Blast.Record query.id={query_id!r}; no hits>"
454
+ elif nhits == 1:
455
+ return f"<Bio.Blast.Record query.id={query_id!r}; 1 hit>"
456
+ else:
457
+ return f"<Bio.Blast.Record query.id={query_id!r}; {nhits} hits>"
458
+
459
+ def __str__(self):
460
+ lines = []
461
+ try:
462
+ version = self.version
463
+ except AttributeError:
464
+ pass
465
+ else:
466
+ lines.append(f"Program: {version}")
467
+ try:
468
+ db = self.db
469
+ except AttributeError:
470
+ pass
471
+ else:
472
+ lines.append(f" db: {db}")
473
+ if self.query is not None:
474
+ # self.query may be None with legacy Blast if there are no hits
475
+ lines.append(" Query: %s (length=%d)" % (self.query.id, len(self.query)))
476
+ indent = " " * 9
477
+ description_lines = textwrap.wrap(
478
+ self.query.description,
479
+ width=80,
480
+ initial_indent=indent,
481
+ subsequent_indent=indent,
482
+ )
483
+ lines.extend(description_lines)
484
+ if len(self) == 0:
485
+ lines.append(" Hits: No hits found")
486
+ else:
487
+ lines.append(" Hits: %s %s %s" % ("-" * 4, "-" * 5, "-" * 58))
488
+ pattern = "%13s %5s %s"
489
+ lines.append(pattern % ("#", "# HSP", "ID + description"))
490
+ lines.append(pattern % ("-" * 4, "-" * 5, "-" * 58))
491
+ for idx, hit in enumerate(self):
492
+ n = len(hit) # Number of HSPs
493
+ if idx < 30:
494
+ hid_line = "%s %s" % (hit.target.id, hit.target.description)
495
+ if len(hid_line) > 58:
496
+ hid_line = hid_line[:55] + "..."
497
+ lines.append(pattern % (idx, len(hit), hid_line))
498
+ elif idx > len(self) - 4:
499
+ hid_line = "%s %s" % (hit.target.id, hit.target.description)
500
+ if len(hid_line) > 58:
501
+ hid_line = hid_line[:55] + "..."
502
+ lines.append(pattern % (idx, len(hit), hid_line))
503
+ elif idx == 30:
504
+ lines.append("%14s" % "~~~")
505
+ return "\n".join(lines)
506
+
507
+ def __getitem__(self, key):
508
+ try:
509
+ value = super().__getitem__(key)
510
+ except IndexError:
511
+ raise IndexError("index out of range") from None
512
+ except TypeError:
513
+ if not isinstance(key, str):
514
+ raise TypeError("key must be an integer, slice, or str") from None
515
+ for hit in self:
516
+ if hit.target.id == key:
517
+ return hit
518
+ raise KeyError(key)
519
+ else:
520
+ if isinstance(key, slice):
521
+ record = Record()
522
+ record.extend(value)
523
+ # Only store the query attribute, as the other attributes
524
+ # pertain to the complete Blast record:
525
+ try:
526
+ query = self.query
527
+ except AttributeError:
528
+ pass
529
+ else:
530
+ record.query = query
531
+ # The following keys may be present if the record was created
532
+ # by Blast.read:
533
+ keys = (
534
+ "source",
535
+ "program",
536
+ "version",
537
+ "reference",
538
+ "db",
539
+ "param",
540
+ "mbstat",
541
+ )
542
+ for key in keys:
543
+ try:
544
+ value = getattr(self, key)
545
+ except AttributeError:
546
+ pass
547
+ else:
548
+ setattr(record, key, value)
549
+ return record
550
+ return value
551
+
552
+ def keys(self):
553
+ """Return a list of the target.id of each hit."""
554
+ return [hit.target.id for hit in self]
555
+
556
+ def __contains__(self, key):
557
+ for hit in self:
558
+ if hit.target.id == key:
559
+ return True
560
+ return False
561
+
562
+ def index(self, key):
563
+ """Return the index of the hit for which the target.id is equal to the key."""
564
+ for i, hit in enumerate(self):
565
+ if hit.target.id == key:
566
+ return i
567
+ raise ValueError(f"'{key}' not found")
568
+
569
+
570
+ class Records(UserList):
571
+ """Stores the BLAST results of a single BLAST run.
572
+
573
+ A ``Bio.Blast.Records`` object is an iterator. Iterating over it returns
574
+ returns ``Bio.Blast.Record`` objects, each of which corresponds to one
575
+ BLAST query.
576
+
577
+ Common attributes of a ``Bio.Blast.Records`` object are
578
+
579
+ - source: The input data from which the ``Bio.Blast.Records`` object
580
+ was constructed.
581
+ - program: The specific BLAST program that was used (e.g., 'blastn').
582
+ - version: The version of the BLAST program (e.g., 'BLASTN 2.2.27+').
583
+ - reference: The literature reference to the BLAST publication.
584
+ - db: The BLAST database against which the query was run
585
+ (e.g., 'nr').
586
+ - query: A ``SeqRecord`` object which may contain some or all of the
587
+ following information:
588
+ - query.id: SeqId of the query;
589
+ - query.description: Definition line of the query;
590
+ - query.seq: The query sequence. The query sequence.
591
+ The query sequence.
592
+ - param: A dictionary with the parameters used for the BLAST run.
593
+ You may find the following keys in this dictionary:
594
+ - 'matrix': the scoring matrix used in the BLAST run
595
+ (e.g., 'BLOSUM62') (string);
596
+ - 'expect': threshold on the expected number of chance
597
+ matches (float);
598
+ - 'include': e-value threshold for inclusion in
599
+ multipass model in psiblast (float);
600
+ - 'sc-match': score for matching nucleotides (integer);
601
+ - 'sc-mismatch': score for mismatched nucleotides
602
+ (integer);
603
+ - 'gap-open': gap opening cost (integer);
604
+ - 'gap-extend': gap extension cost (integer);
605
+ - 'filter': filtering options applied in the BLAST
606
+ run (string);
607
+ - 'pattern': PHI-BLAST pattern (string);
608
+ - 'entrez-query': Limit of request to Entrez query (string).
609
+ - mbstat: A dictionary with Mega BLAST search statistics. As this
610
+ information is stored near the end of the XML file, this
611
+ attribute can only be accessed after the file has been read
612
+ completely (by iterating over the records until a
613
+ ``StopIteration`` is issued. This dictionary can contain the
614
+ same keys as the dictionary stored under the ``stat``
615
+ attribute of a ``Record`` object.
616
+
617
+ >>> from Bio import Blast
618
+ >>> path = "Blast/xml_2218_blastp_002.xml"
619
+
620
+ In a script, you would use a ``with`` block, as in
621
+
622
+ >>> with Blast.parse(path) as records:
623
+ ... print(records.source)
624
+ ...
625
+ Blast/xml_2218_blastp_002.xml
626
+
627
+ to ensure that the file is closed at the end of the block.
628
+ Here, we will simply do
629
+
630
+ >>> records = Blast.parse("Blast/xml_2218_blastp_002.xml")
631
+
632
+ so we can see the output of each command right away.
633
+
634
+ >>> type(records)
635
+ <class 'Bio.Blast.Records'>
636
+ >>> records.source
637
+ 'Blast/xml_2218_blastp_002.xml'
638
+ >>> records.program
639
+ 'blastp'
640
+ >>> records.version
641
+ 'BLASTP 2.2.18+'
642
+ >>> records.reference
643
+ 'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Schäffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.'
644
+ >>> records.db
645
+ 'gpipe/9606/Previous/protein'
646
+ >>> records.param
647
+ {'matrix': 'BLOSUM62', 'expect': 0.01, 'gap-open': 11, 'gap-extend': 1, 'filter': 'm L; R -d repeat/repeat_9606;'}
648
+
649
+ Iterating over the records returns Bio.Blast.Record objects:
650
+
651
+ >>> record = next(records)
652
+ >>> type(record)
653
+ <class 'Bio.Blast.Record'>
654
+ >>> record.query.id
655
+ 'gi|585505|sp|Q08386|MOPB_RHOCA'
656
+ >>> record = next(records)
657
+ >>> type(record)
658
+ <class 'Bio.Blast.Record'>
659
+ >>> record.query.id
660
+ 'gi|129628|sp|P07175.1|PARA_AGRTU'
661
+ >>> record = next(records) # doctest:+ELLIPSIS
662
+ Traceback (most recent call last):
663
+ ...
664
+ StopIteration
665
+
666
+ You can also use the records as a list, for example by extracting a record
667
+ by index, or by calling ``len`` or ``print`` on the records. The parser
668
+ will then automatically iterate over the records and store them:
669
+
670
+ >>> records = Blast.parse("Blast/wnts.xml")
671
+ >>> record = records[3] # this causes all records to be read in and stored
672
+ >>> record.query.id
673
+ 'Query_4'
674
+ >>> len(records)
675
+ 5
676
+
677
+ After the records have been read in, you can still iterate over them:
678
+
679
+ >>> for i, record in enumerate(records):
680
+ ... print(i, record.query.id)
681
+ ...
682
+ 0 Query_1
683
+ 1 Query_2
684
+ 2 Query_3
685
+ 3 Query_4
686
+ 4 Query_5
687
+
688
+ """ # noqa: RST201, RST203, RST301
689
+
690
+ def __init__(self, source):
691
+ """Initialize the Records object."""
692
+ if isinstance(source, list): # UserList API requirement
693
+ self._records = source
694
+ self._loaded = True
695
+ self._index = 0
696
+ return
697
+
698
+ self.source = source
699
+ try:
700
+ stream = open(source, "rb")
701
+ except TypeError: # not a path, assume we received a stream
702
+ if source.read(0) != b"":
703
+ raise StreamModeError(
704
+ "BLAST output files must be opened in binary mode."
705
+ ) from None
706
+ stream = source
707
+ self._stream = stream
708
+ self._read_header()
709
+ self._records = [] # for when we want to use Records as a list
710
+ self._loaded = False
711
+
712
+ def _read_header(self):
713
+ from Bio.Blast._parser import XMLHandler
714
+
715
+ stream = self._stream
716
+ source = self.source
717
+ try: # context manager won't kick in until after parse returns
718
+ parser = expat.ParserCreate(namespace_separator=" ")
719
+ self._parser = parser
720
+
721
+ handler = XMLHandler(parser)
722
+ handler._records = self
723
+
724
+ while True:
725
+ data = stream.read(BLOCK)
726
+ if data == b"":
727
+ try:
728
+ handler._parser
729
+ except AttributeError:
730
+ break
731
+ else:
732
+ try:
733
+ parser.Parse(b"", True)
734
+ except expat.ExpatError as e:
735
+ if parser.StartElementHandler is not None:
736
+ raise ValueError(
737
+ f"premature end of XML file: line {e.lineno}, column {e.offset}"
738
+ )
739
+ raise e
740
+ try:
741
+ parser.Parse(data, False)
742
+ except expat.ExpatError as e:
743
+ try:
744
+ parser.Parse(b"", True)
745
+ except expat.ExpatError:
746
+ pass
747
+ if parser.StartElementHandler:
748
+ # We saw the initial <!xml declaration, so we can be
749
+ # sure that we are parsing XML data. Most likely, the
750
+ # XML file is corrupted.
751
+ raise CorruptedXMLError(e) from None
752
+ else:
753
+ # We have not seen the initial <!xml declaration, so
754
+ # probably the input data is not in XML format.
755
+ raise NotXMLError(e) from None
756
+ try:
757
+ self._cache
758
+ except AttributeError:
759
+ pass
760
+ else:
761
+ # We have finished reading the header
762
+ break
763
+ except Exception:
764
+ if stream is not source:
765
+ stream.close()
766
+ raise
767
+ self._index = 0
768
+
769
+ def __enter__(self):
770
+ return self
771
+
772
+ def __exit__(self, exc_type, exc_value, exc_traceback):
773
+ try:
774
+ self._parser.Parse(b"", True)
775
+ del self._parser
776
+ except (AttributeError, expat.ExpatError):
777
+ pass
778
+
779
+ try:
780
+ del self._cache
781
+ except AttributeError:
782
+ pass
783
+
784
+ try:
785
+ stream = self._stream
786
+ except AttributeError:
787
+ return
788
+ if stream is not self.source:
789
+ stream.close()
790
+ del self._stream
791
+
792
+ def __iter__(self):
793
+ return self
794
+
795
+ def __next__(self):
796
+ if self._loaded is True:
797
+ try:
798
+ record = self._records[self._index]
799
+ except IndexError:
800
+ raise StopIteration from None
801
+ self._index += 1
802
+ return record
803
+ try:
804
+ cache = self._cache
805
+ except AttributeError:
806
+ raise StopIteration from None
807
+ parser = self._parser
808
+ stream = self._stream
809
+ while True:
810
+ try:
811
+ record = self._cache.popleft()
812
+ except IndexError: # no record ready to be returned
813
+ pass
814
+ else:
815
+ self._index += 1
816
+ return record
817
+ # Read in another block of data from the file.
818
+ data = stream.read(BLOCK)
819
+ if data == b"":
820
+ try:
821
+ del self._parser
822
+ try:
823
+ parser.Parse(b"", True)
824
+ except expat.ExpatError as e:
825
+ if parser.StartElementHandler is not None:
826
+ raise ValueError(
827
+ f"premature end of XML file: line {e.lineno}, column {e.offset}"
828
+ )
829
+ raise e
830
+ except AttributeError:
831
+ pass
832
+ raise StopIteration
833
+ try:
834
+ parser.Parse(data, False)
835
+ except expat.ExpatError as e:
836
+ raise CorruptedXMLError(e) from None
837
+
838
+ def __getitem__(self, index):
839
+ item = super().__getitem__(index)
840
+ if index == slice(None, None, None):
841
+ for key, value in self.__dict__.items():
842
+ if key not in ("_stream", "_parser", "_cache"):
843
+ item.__dict__[key] = value
844
+ return item
845
+
846
+ @property
847
+ def data(self):
848
+ """Overrides the data attribute of UserList."""
849
+ if self._loaded is False:
850
+ # Read all records and store them
851
+ index = self._index
852
+ if index > 0:
853
+ try:
854
+ self._stream.seek(0)
855
+ except io.UnsupportedOperation:
856
+ raise ValueError(
857
+ "list-like access after iterating is supported only if the input data is seekable."
858
+ )
859
+ self._read_header()
860
+ self._index = 0
861
+ for record in self:
862
+ self._records.append(record)
863
+ stream = self._stream
864
+ if stream is not self.source:
865
+ stream.close()
866
+ del self._stream
867
+ self._loaded = True
868
+ self._index = index
869
+ return self._records
870
+
871
+ def __repr__(self):
872
+ return f"<Bio.Blast.Records source={self.source!r} program={self.program!r} version={self.version!r} db={self.db!r}>"
873
+
874
+ def __str__(self):
875
+ text = """\
876
+ Program: %s
877
+ db: %s""" % (
878
+ self.version,
879
+ self.db,
880
+ )
881
+ records = self[:] # to ensure that the records are read in
882
+ for record in self._records:
883
+ text += "\n\n" + str(record)
884
+ return text
885
+
886
+
887
+ def parse(source):
888
+ """Parse an XML file containing BLAST output and return a Bio.Blast.Records object.
889
+
890
+ This returns an iterator object; iterating over it returns Bio.Blast.Record
891
+ objects one by one.
892
+
893
+ The source can be a file stream or the path to an XML file containing the
894
+ BLAST output. If a file stream, source must be in binary mode. This allows
895
+ the parser to detect the encoding from the XML file,and to use it to convert
896
+ any text in the XML to the correct Unicode string. The qblast function in
897
+ Bio.Blast returns a file stream in binary mode. For files, please use mode
898
+ "rb" when opening the file, as in
899
+
900
+ >>> from Bio import Blast
901
+ >>> stream = open("Blast/wnts.xml", "rb") # opened in binary mode
902
+ >>> records = Blast.parse(stream)
903
+ >>> for record in records:
904
+ ... print(record.query.id, record.query.description)
905
+ ...
906
+ Query_1 gi|195230749:301-1383 Homo sapiens wingless-type MMTV integration site family member 2 (WNT2), transcript variant 1, mRNA
907
+ Query_2 gi|325053704:108-1166 Homo sapiens wingless-type MMTV integration site family, member 3A (WNT3A), mRNA
908
+ Query_3 gi|156630997:105-1160 Homo sapiens wingless-type MMTV integration site family, member 4 (WNT4), mRNA
909
+ Query_4 gi|371502086:108-1205 Homo sapiens wingless-type MMTV integration site family, member 5A (WNT5A), transcript variant 2, mRNA
910
+ Query_5 gi|53729353:216-1313 Homo sapiens wingless-type MMTV integration site family, member 6 (WNT6), mRNA
911
+ >>> stream.close()
912
+
913
+ """
914
+ return Records(source)
915
+
916
+
917
+ def read(source):
918
+ """Parse an XML file containing BLAST output for a single query and return it.
919
+
920
+ Internally, this function uses Bio.Blast.parse to obtain an iterator over
921
+ BLAST records. The function then reads one record from the iterator,
922
+ ensures that there are no further records, and returns the record it found
923
+ as a Bio.Blast.Record object. An exception is raised if no records are
924
+ found, or more than one record is found.
925
+
926
+ The source can be a file stream or the path to an XML file containing the
927
+ BLAST output. If a file stream, source must be in binary mode. This allows
928
+ the parser to detect the encoding from the XML file,and to use it to convert
929
+ any text in the XML to the correct Unicode string. The qblast function in
930
+ Bio.Blast returns a file stream in binary mode. For files, please use mode
931
+ "rb" when opening the file, as in
932
+
933
+ >>> from Bio import Blast
934
+ >>> stream = open("Blast/xml_21500_blastn_001.xml", "rb") # opened in binary mode
935
+ >>> record = Blast.read(stream)
936
+ >>> record.query.id
937
+ 'Query_78041'
938
+ >>> record.query.description
939
+ 'G26684.1 human STS STS_D11570, sequence tagged site'
940
+ >>> len(record)
941
+ 11
942
+ >>> stream.close()
943
+
944
+ Use the Bio.Blast.parse function if you want to read a file containing
945
+ BLAST output for more than one query.
946
+ """
947
+ with parse(source) as records:
948
+ try:
949
+ record = next(records)
950
+ except StopIteration:
951
+ raise ValueError("No BLAST output found.") from None
952
+ try:
953
+ next(records)
954
+ raise ValueError("BLAST output for more than one query found.")
955
+ except StopIteration:
956
+ pass
957
+ for key in ("source", "program", "version", "reference", "db", "param", "mbstat"):
958
+ try:
959
+ value = getattr(records, key)
960
+ except AttributeError:
961
+ pass
962
+ else:
963
+ setattr(record, key, value)
964
+ return record
965
+
966
+
967
+ def write(records, destination, fmt="XML"):
968
+ """Write BLAST records as an XML file, and return the number of records.
969
+
970
+ Arguments:
971
+ - records - A ``Bio.Blast.Records`` object.
972
+ - destination - File or file-like object to write to, or filename as
973
+ string.
974
+ The File object must have been opened for writing in
975
+ binary mode, and must be closed (or flushed) by the caller
976
+ after this function returns to ensure that all records are
977
+ written.
978
+ - fmt - string describing the file format to write
979
+ (case-insensitive).
980
+ Currently, only "XML" and "XML2" are accepted.
981
+
982
+ Returns the number of records written (as an integer).
983
+ """
984
+ fmt = fmt.upper()
985
+ if fmt == "XML":
986
+ Writer = _writers.XMLWriter
987
+ elif fmt == "XML2":
988
+ Writer = _writers.XML2Writer
989
+ else:
990
+ raise ValueError(f"Unknown format {fmt}; expected 'XML' or 'XML2'")
991
+ try:
992
+ stream = open(destination, "wb")
993
+ except TypeError: # not a path, assume we received a stream
994
+ try:
995
+ destination.write(b"")
996
+ except TypeError:
997
+ # destination was opened in text mode
998
+ raise StreamModeError(
999
+ "File must be opened in binary mode for writing."
1000
+ ) from None
1001
+ stream = destination
1002
+ writer = Writer(stream)
1003
+ try:
1004
+ count = writer.write(records)
1005
+ finally:
1006
+ if stream is not destination:
1007
+ stream.close()
1008
+ return count
1009
+
1010
+
1011
+ @function_with_previous
1012
+ def qblast(
1013
+ program,
1014
+ database,
1015
+ sequence,
1016
+ url_base=NCBI_BLAST_URL,
1017
+ auto_format=None,
1018
+ composition_based_statistics=None,
1019
+ db_genetic_code=None,
1020
+ endpoints=None,
1021
+ entrez_query="(none)",
1022
+ expect=10.0,
1023
+ filter=None,
1024
+ gapcosts=None,
1025
+ genetic_code=None,
1026
+ hitlist_size=50,
1027
+ i_thresh=None,
1028
+ layout=None,
1029
+ lcase_mask=None,
1030
+ matrix_name=None,
1031
+ nucl_penalty=None,
1032
+ nucl_reward=None,
1033
+ other_advanced=None,
1034
+ perc_ident=None,
1035
+ phi_pattern=None,
1036
+ query_file=None,
1037
+ query_believe_defline=None,
1038
+ query_from=None,
1039
+ query_to=None,
1040
+ searchsp_eff=None,
1041
+ service=None,
1042
+ threshold=None,
1043
+ ungapped_alignment=None,
1044
+ word_size=None,
1045
+ short_query=None,
1046
+ alignments=500,
1047
+ alignment_view=None,
1048
+ descriptions=500,
1049
+ entrez_links_new_window=None,
1050
+ expect_low=None,
1051
+ expect_high=None,
1052
+ format_entrez_query=None,
1053
+ format_object=None,
1054
+ format_type="XML",
1055
+ ncbi_gi=None,
1056
+ results_file=None,
1057
+ show_overview=None,
1058
+ megablast=None,
1059
+ template_type=None,
1060
+ template_length=None,
1061
+ username="blast",
1062
+ password=None,
1063
+ ):
1064
+ """BLAST search using NCBI's QBLAST server.
1065
+
1066
+ Supports all parameters of the old qblast API for Put and Get.
1067
+
1068
+ Please note that NCBI uses the new Common URL API for BLAST searches on
1069
+ the internet (https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html).
1070
+ Thus, some of the parameters used by this function are not (or are no
1071
+ longer) officially supported by NCBI. Although they are still functioning,
1072
+ this may change in the future.
1073
+
1074
+ Some useful parameters:
1075
+
1076
+ - program blastn, blastp, blastx, tblastn, or tblastx (lower case)
1077
+ - database Which database to search against (e.g. "nr").
1078
+ - sequence The sequence to search.
1079
+ - ncbi_gi TRUE/FALSE whether to give 'gi' identifier.
1080
+ - descriptions Number of descriptions to show. Def 500.
1081
+ - alignments Number of alignments to show. Def 500.
1082
+ - expect An expect value cutoff. Def 10.0.
1083
+ - matrix_name Specify an alt. matrix (PAM30, PAM70, BLOSUM80, BLOSUM45).
1084
+ - filter "none" turns off filtering. Default no filtering
1085
+ - format_type "XML" (default), "HTML", "Text", "XML2", "JSON2",
1086
+ or "Tabular".
1087
+ - entrez_query Entrez query to limit Blast search - only applies when searching nucleotide BLASTDBs
1088
+ - hitlist_size Number of hits to return. Default 50
1089
+ - megablast TRUE/FALSE whether to use MEga BLAST algorithm (blastn only)
1090
+ - short_query TRUE/FALSE whether to adjust the search parameters for a
1091
+ short query sequence. Note that this will override
1092
+ manually set parameters like word size and e value. Turns
1093
+ off when sequence length is > 30 residues. Default: None.
1094
+ - service plain, psi, phi, rpsblast, megablast (lower case)
1095
+
1096
+ This function does no checking of the validity of the parameters
1097
+ and passes the values to the server as is. More help is available at:
1098
+ https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html
1099
+
1100
+ The http.client.HTTPResponse object returned by this function has the
1101
+ additional attributes rid and rtoe with the Request ID and Request Time Of
1102
+ Execution for this BLAST search.
1103
+
1104
+ """
1105
+ programs = ["blastn", "blastp", "blastx", "tblastn", "tblastx"]
1106
+ if program not in programs:
1107
+ raise ValueError(
1108
+ f"Program specified is {program}. Expected one of {', '.join(programs)}"
1109
+ )
1110
+
1111
+ # SHORT_QUERY_ADJUST throws an error when using blastn (wrong parameter
1112
+ # assignment from NCBIs side).
1113
+ # Thus we set the (known) parameters directly:
1114
+ if short_query and program == "blastn":
1115
+ short_query = None
1116
+ # We only use the 'short-query' parameters for short sequences:
1117
+ if len(sequence) < 31:
1118
+ expect = 1000
1119
+ word_size = 7
1120
+ nucl_reward = 1
1121
+ filter = None
1122
+ lcase_mask = None
1123
+ warnings.warn(
1124
+ '"SHORT_QUERY_ADJUST" is incorrectly implemented (by NCBI) for blastn.'
1125
+ " We bypass the problem by manually adjusting the search parameters."
1126
+ " Thus, results may slightly differ from web page searches.",
1127
+ BiopythonWarning,
1128
+ )
1129
+
1130
+ # Format the "Put" command, which sends search requests to qblast.
1131
+ # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node5.html on 9 July 2007
1132
+ # Additional parameters are taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node9.html on 8 Oct 2010
1133
+ # To perform a PSI-BLAST or PHI-BLAST search the service ("Put" and "Get" commands) must be specified
1134
+ # (e.g. psi_blast = NCBIWWW.qblast("blastp", "refseq_protein", input_sequence, service="psi"))
1135
+ parameters = {
1136
+ "AUTO_FORMAT": auto_format,
1137
+ "COMPOSITION_BASED_STATISTICS": composition_based_statistics,
1138
+ "DATABASE": database,
1139
+ "DB_GENETIC_CODE": db_genetic_code,
1140
+ "ENDPOINTS": endpoints,
1141
+ "ENTREZ_QUERY": entrez_query,
1142
+ "EXPECT": expect,
1143
+ "FILTER": filter,
1144
+ "GAPCOSTS": gapcosts,
1145
+ "GENETIC_CODE": genetic_code,
1146
+ "HITLIST_SIZE": hitlist_size,
1147
+ "I_THRESH": i_thresh,
1148
+ "LAYOUT": layout,
1149
+ "LCASE_MASK": lcase_mask,
1150
+ "MEGABLAST": megablast,
1151
+ "MATRIX_NAME": matrix_name,
1152
+ "NUCL_PENALTY": nucl_penalty,
1153
+ "NUCL_REWARD": nucl_reward,
1154
+ "OTHER_ADVANCED": other_advanced,
1155
+ "PERC_IDENT": perc_ident,
1156
+ "PHI_PATTERN": phi_pattern,
1157
+ "PROGRAM": program,
1158
+ # ('PSSM': pssm: - It is possible to use PSI-BLAST via this API?
1159
+ "QUERY": sequence,
1160
+ "QUERY_FILE": query_file,
1161
+ "QUERY_BELIEVE_DEFLINE": query_believe_defline,
1162
+ "QUERY_FROM": query_from,
1163
+ "QUERY_TO": query_to,
1164
+ # 'RESULTS_FILE': ...: - Can we use this parameter?
1165
+ "SEARCHSP_EFF": searchsp_eff,
1166
+ "SERVICE": service,
1167
+ "SHORT_QUERY_ADJUST": short_query,
1168
+ "TEMPLATE_TYPE": template_type,
1169
+ "TEMPLATE_LENGTH": template_length,
1170
+ "THRESHOLD": threshold,
1171
+ "UNGAPPED_ALIGNMENT": ungapped_alignment,
1172
+ "WORD_SIZE": word_size,
1173
+ "CMD": "Put",
1174
+ }
1175
+
1176
+ if password is not None:
1177
+ # handle authentication for BLAST cloud
1178
+ password_mgr = HTTPPasswordMgrWithDefaultRealm()
1179
+ password_mgr.add_password(None, url_base, username, password)
1180
+ handler = HTTPBasicAuthHandler(password_mgr)
1181
+ opener = build_opener(handler)
1182
+ install_opener(opener)
1183
+
1184
+ if url_base == NCBI_BLAST_URL:
1185
+ parameters.update({"email": email, "tool": tool})
1186
+ parameters = {key: value for key, value in parameters.items() if value is not None}
1187
+ message = urlencode(parameters).encode()
1188
+ request = Request(url_base, message, {"User-Agent": "BiopythonClient"})
1189
+ # Send off the initial query to qblast.
1190
+ # Note the NCBI do not currently impose a rate limit here, other
1191
+ # than the request not to make say 50 queries at once using multiple
1192
+ # threads.
1193
+ stream = urlopen(request)
1194
+
1195
+ # Format the "Get" command, which gets the formatted results from qblast
1196
+ # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node6.html on 9 July 2007
1197
+ rid, rtoe = _parse_qblast_ref_page(stream)
1198
+ parameters = {
1199
+ "ALIGNMENTS": alignments,
1200
+ "ALIGNMENT_VIEW": alignment_view,
1201
+ "DESCRIPTIONS": descriptions,
1202
+ "ENTREZ_LINKS_NEW_WINDOW": entrez_links_new_window,
1203
+ "EXPECT_LOW": expect_low,
1204
+ "EXPECT_HIGH": expect_high,
1205
+ "FORMAT_ENTREZ_QUERY": format_entrez_query,
1206
+ "FORMAT_OBJECT": format_object,
1207
+ "FORMAT_TYPE": format_type,
1208
+ "NCBI_GI": ncbi_gi,
1209
+ "RID": rid,
1210
+ "RESULTS_FILE": results_file,
1211
+ "SERVICE": service,
1212
+ "SHOW_OVERVIEW": show_overview,
1213
+ "CMD": "Get",
1214
+ }
1215
+ parameters = {key: value for key, value in parameters.items() if value is not None}
1216
+ message = urlencode(parameters).encode()
1217
+
1218
+ # Poll NCBI until the results are ready.
1219
+ # https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=DeveloperInfo
1220
+ # 1. Do not contact the server more often than once every 10 seconds.
1221
+ # 2. Do not poll for any single RID more often than once a minute.
1222
+ # 3. Use the URL parameter email and tool, so that the NCBI
1223
+ # can contact you if there is a problem.
1224
+ # 4. Run scripts weekends or between 9 pm and 5 am Eastern time
1225
+ # on weekdays if more than 50 searches will be submitted.
1226
+ # --
1227
+ # Could start with a 10s delay, but expect most short queries
1228
+ # will take longer thus at least 70s with delay. Therefore,
1229
+ # start with 20s delay, thereafter once a minute.
1230
+ delay = 20 # seconds
1231
+ start_time = time.time()
1232
+ while True:
1233
+ current = time.time()
1234
+ wait = qblast.previous + delay - current
1235
+ if wait > 0:
1236
+ time.sleep(wait)
1237
+ qblast.previous = current + wait
1238
+ else:
1239
+ qblast.previous = current
1240
+ # delay by at least 60 seconds only if running the request against the public NCBI API
1241
+ if delay < 60 and url_base == NCBI_BLAST_URL:
1242
+ # Wasn't a quick return, must wait at least a minute
1243
+ delay = 60
1244
+ elapsed = time.time() - start_time
1245
+ if elapsed >= 600:
1246
+ warnings.warn(
1247
+ f"BLAST request {rid} is taking longer than 10 minutes, consider re-issuing it",
1248
+ BiopythonWarning,
1249
+ )
1250
+ request = Request(url_base, message, {"User-Agent": "BiopythonClient"})
1251
+ stream = urlopen(request)
1252
+ data = stream.peek()
1253
+ if format_type == "HTML" and b"<title>NCBI Blast:</title>" in data:
1254
+ continue
1255
+ elif data.startswith(b"<!DOCTYPE html"):
1256
+ continue
1257
+ else:
1258
+ break
1259
+ if format_type == "XML":
1260
+ assert data.startswith(b"<?xml ")
1261
+ elif format_type == "HTML":
1262
+ assert data.startswith(b"<!DOCTYPE html ")
1263
+ elif format_type in ("Text", "Tabular"):
1264
+ assert data.startswith(b"<p><!--\nQBlastInfoBegin")
1265
+ elif format_type in ("XML2", "JSON2"):
1266
+ assert data.startswith(b"PK\x03\x04") # zipped file
1267
+ stream.rid = rid
1268
+ stream.rtoe = rtoe
1269
+ return stream
1270
+
1271
+
1272
+ qblast.previous = 0
1273
+
1274
+
1275
+ def _parse_qblast_ref_page(handle):
1276
+ """Extract a tuple of RID, RTOE from the 'please wait' page (PRIVATE).
1277
+
1278
+ The NCBI FAQ pages use TOE for 'Time of Execution', so RTOE is probably
1279
+ 'Request Time of Execution' and RID would be 'Request Identifier'.
1280
+ """
1281
+ s = handle.read().decode()
1282
+ i = s.find("RID =")
1283
+ if i == -1:
1284
+ rid = None
1285
+ else:
1286
+ j = s.find("\n", i)
1287
+ rid = s[i + len("RID =") : j].strip()
1288
+
1289
+ i = s.find("RTOE =")
1290
+ if i == -1:
1291
+ rtoe = None
1292
+ else:
1293
+ j = s.find("\n", i)
1294
+ rtoe = s[i + len("RTOE =") : j].strip()
1295
+
1296
+ if not rid and not rtoe:
1297
+ # Can we reliably extract the error message from the HTML page?
1298
+ # e.g. "Message ID#24 Error: Failed to read the Blast query:
1299
+ # Nucleotide FASTA provided for protein sequence"
1300
+ # or "Message ID#32 Error: Query contains no data: Query
1301
+ # contains no sequence data"
1302
+ #
1303
+ # This used to occur inside a <div class="error msInf"> entry:
1304
+ i = s.find('<div class="error msInf">')
1305
+ if i != -1:
1306
+ msg = s[i + len('<div class="error msInf">') :].strip()
1307
+ msg = msg.split("</div>", 1)[0].split("\n", 1)[0].strip()
1308
+ if msg:
1309
+ raise ValueError(f"Error message from NCBI: {msg}")
1310
+ # In spring 2010 the markup was like this:
1311
+ i = s.find('<p class="error">')
1312
+ if i != -1:
1313
+ msg = s[i + len('<p class="error">') :].strip()
1314
+ msg = msg.split("</p>", 1)[0].split("\n", 1)[0].strip()
1315
+ if msg:
1316
+ raise ValueError(f"Error message from NCBI: {msg}")
1317
+ # Generic search based on the way the error messages start:
1318
+ i = s.find("Message ID#")
1319
+ if i != -1:
1320
+ # Break the message at the first HTML tag
1321
+ msg = s[i:].split("<", 1)[0].split("\n", 1)[0].strip()
1322
+ raise ValueError(f"Error message from NCBI: {msg}")
1323
+ # We didn't recognise the error layout :(
1324
+ # print(s)
1325
+ raise ValueError(
1326
+ "No RID and no RTOE found in the 'please wait' page, "
1327
+ "there was probably an error in your request but we "
1328
+ "could not extract a helpful error message."
1329
+ )
1330
+ elif not rid:
1331
+ # Can this happen?
1332
+ raise ValueError(
1333
+ f"No RID found in the 'please wait' page. (although RTOE = {rtoe!r})"
1334
+ )
1335
+ elif not rtoe:
1336
+ # Can this happen?
1337
+ raise ValueError(
1338
+ f"No RTOE found in the 'please wait' page. (although RID = {rid!r})"
1339
+ )
1340
+
1341
+ try:
1342
+ return rid, int(rtoe)
1343
+ except ValueError:
1344
+ raise ValueError(
1345
+ f"A non-integer RTOE found in the 'please wait' page, {rtoe!r}"
1346
+ ) from None
1347
+
1348
+
1349
+ if __name__ == "__main__":
1350
+ from Bio._utils import run_doctest
1351
+
1352
+ run_doctest()
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/_parser.py ADDED
@@ -0,0 +1,1226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 1999 by Jeffrey Chang. All rights reserved.
2
+ # Copyright 2000 by Bertrand Frottier. All rights reserved.
3
+ # Revisions 2005-2006 copyright Michiel de Hoon
4
+ # Revisions 2006-2009 copyright Peter Cock
5
+ # Revisions 2023 by Michiel de Hoon. All rights reserved.
6
+ #
7
+ # This file is part of the Biopython distribution and governed by your
8
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
9
+ # Please see the LICENSE file that should have been included as part of this
10
+ # package.
11
+ """Code to parse BLAST XML output, and to parse the BLAST DTD file defining the XML.
12
+
13
+ The BLAST XML DTD file is available on the NCBI site at:
14
+ https://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd
15
+ """
16
+
17
+ import html
18
+ import os.path
19
+ from collections import deque
20
+ from xml.parsers import expat
21
+
22
+ from Bio import Entrez
23
+ from Bio.Align import Alignment
24
+ from Bio.Blast import Hit
25
+ from Bio.Blast import HSP
26
+ from Bio.Blast import Record
27
+ from Bio.Seq import reverse_complement
28
+ from Bio.Seq import Seq
29
+ from Bio.SeqFeature import SeqFeature
30
+ from Bio.SeqFeature import SimpleLocation
31
+ from Bio.SeqRecord import SeqRecord
32
+
33
+ import numpy as np
34
+
35
+
36
+ class DTDHandler:
37
+ """Parser for the BLAST XML DTD file."""
38
+
39
+ def __init__(self):
40
+ """Initialize the parser and parse the BLAST XML DTD file."""
41
+ parser = expat.ParserCreate()
42
+ parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
43
+ parser.ExternalEntityRefHandler = self._externalEntityRefHandler
44
+ self.parser = parser
45
+ self.start_methods = {}
46
+ self.end_methods = {}
47
+ XMLHandler._dtd_methods = self.start_methods, self.end_methods
48
+
49
+ def _elementDeclHandler(self, name, model):
50
+ method_name = name
51
+ if name not in (
52
+ "BlastOutput_query-ID",
53
+ "BlastOutput_query-def",
54
+ "BlastOutput_query-len",
55
+ ):
56
+ # Note that NCBI_BlastOutput.dtd defines both BlastOutput_query-ID
57
+ # and Iteration_query-ID, while NCBI_BlastOutput2.xsd defines
58
+ # query-id only, which corresponds to Iteration_query-ID.
59
+ # Same for BlastOutput_query-def and BlastOutput_query-len.
60
+ for prefix in (
61
+ "BlastOutput_",
62
+ "Iteration_",
63
+ "Parameters_",
64
+ "Statistics_",
65
+ "Hit_",
66
+ "Hsp_",
67
+ ):
68
+ method_name = method_name.replace(prefix, "")
69
+ method_name = method_name.lower().replace("-", "_")
70
+ start_method = "_start_" + method_name
71
+ end_method = "_end_" + method_name
72
+ self.start_methods[name] = getattr(XMLHandler, start_method)
73
+ self.end_methods[name] = getattr(XMLHandler, end_method)
74
+
75
+ def _externalEntityRefHandler(self, context, base, systemId, publicId):
76
+ assert context is None
77
+ assert base is None
78
+ self.parseFile(systemId)
79
+ return 1
80
+
81
+ def parseFile(self, filename):
82
+ """Parse a DTD file."""
83
+ directory = Entrez.__path__[0]
84
+ path = os.path.join(directory, "DTDs", filename)
85
+ parser = self.parser.ExternalEntityParserCreate(None)
86
+ parser.ElementDeclHandler = self._elementDeclHandler
87
+ with open(path, "rb") as stream:
88
+ parser.ParseFile(stream)
89
+
90
+
91
+ class SchemaHandler:
92
+ """XML Schema parser used to parse NCBI_BlastOutput2.xsd.
93
+
94
+ The XML Schema for Blast XML2 is available from
95
+ https://www.ncbi.nlm.nih.gov/data_specs/schema_alt/NCBI_BlastOutput2.xsd
96
+ """
97
+
98
+ def __init__(self, parser):
99
+ """Initialize the XML Schema parser."""
100
+ self.parser = parser
101
+ self.start_methods = {}
102
+ self.end_methods = {}
103
+ XMLHandler._schema_methods = self.start_methods, self.end_methods
104
+
105
+ def _startElementHandler(self, name, attributes):
106
+ """Found XML start tag.
107
+
108
+ Arguments:
109
+ - name -- name of the tag
110
+ - attributes -- tag attributes
111
+
112
+ """
113
+ if name == "http://www.w3.org/2001/XMLSchema include":
114
+ filename = attributes["schemaLocation"]
115
+ directory = Entrez.__path__[0]
116
+ path = os.path.join(directory, "XSDs", filename)
117
+ parser = expat.ParserCreate(namespace_separator=" ")
118
+ parser.StartElementHandler = self._startElementHandler
119
+ with open(path, "rb") as stream:
120
+ parser.ParseFile(stream)
121
+ elif name == "http://www.w3.org/2001/XMLSchema element":
122
+ tag = attributes.get("name")
123
+ if tag is None:
124
+ return
125
+ namespace = "http://www.ncbi.nlm.nih.gov"
126
+ key = f"{namespace} {tag}"
127
+ if tag == "BlastOutput2":
128
+ self.start_methods[key] = XMLHandler._start_blastoutput
129
+ self.end_methods[key] = XMLHandler._end_blastoutput_xml2
130
+ elif tag in (
131
+ "error",
132
+ "Err",
133
+ "code",
134
+ "message",
135
+ "subjects",
136
+ "bl2seq",
137
+ ):
138
+ pass # TBD
139
+ else:
140
+ if tag == "params":
141
+ tag = "param"
142
+ elif tag == "search":
143
+ tag = "iterations"
144
+ elif tag == "Search":
145
+ tag = "Iteration"
146
+ elif tag == "query-title":
147
+ tag = "query-def"
148
+ elif tag == "title":
149
+ tag = "def"
150
+ method_name = tag.lower().replace("-", "_")
151
+ start_method = "_start_" + method_name
152
+ end_method = "_end_" + method_name
153
+ if tag == "eff-space":
154
+ end_method += "_xml2"
155
+ self.start_methods[key] = getattr(XMLHandler, start_method)
156
+ self.end_methods[key] = getattr(XMLHandler, end_method)
157
+
158
+
159
+ class _HSP_cache:
160
+ __slots__ = (
161
+ "num",
162
+ "bit_score",
163
+ "score",
164
+ "evalue",
165
+ "identity",
166
+ "positive",
167
+ "query_from",
168
+ "query_to",
169
+ "query_frame",
170
+ "query_strand",
171
+ "hit_from",
172
+ "hit_to",
173
+ "hit_frame",
174
+ "hit_strand",
175
+ "qseq",
176
+ "hseq",
177
+ "gaps",
178
+ "align_len",
179
+ "density",
180
+ "midline",
181
+ )
182
+
183
+
184
+ class XMLHandler:
185
+ """Handler for BLAST XML data."""
186
+
187
+ schema_namespace = "http://www.w3.org/2001/XMLSchema-instance"
188
+ _schema_methods = None
189
+ _dtd_methods = None
190
+
191
+ def __init__(self, parser):
192
+ """Initialize the expat parser."""
193
+ parser.XmlDeclHandler = self._xmlDeclHandler
194
+ parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
195
+ self._parser = parser
196
+
197
+ def _startNamespaceDeclHandler(self, prefix, uri):
198
+ parser = self._parser
199
+ if uri == XMLHandler.schema_namespace:
200
+ # This is an xml schema
201
+ parser.StartElementHandler = self._start_blastxml2
202
+
203
+ def _endNamespaceDeclHandler(self, prefix):
204
+ return
205
+
206
+ def _start_blastxml2(self, name, attributes):
207
+ """Process the XML schema (before processing the element)."""
208
+ uri, localname = name.split(" ")
209
+ assert uri == "http://www.ncbi.nlm.nih.gov"
210
+ assert localname in ("BlastXML2", "BlastOutput2")
211
+ key = "%s schemaLocation" % XMLHandler.schema_namespace
212
+ domain, url = attributes[key].split()
213
+ assert domain == "http://www.ncbi.nlm.nih.gov"
214
+ if XMLHandler._schema_methods is None:
215
+ filename = os.path.basename(url)
216
+ directory = Entrez.__path__[0]
217
+ path = os.path.join(directory, "XSDs", filename)
218
+ parser = expat.ParserCreate(namespace_separator=" ")
219
+ handler = SchemaHandler(parser)
220
+ parser.StartElementHandler = handler._startElementHandler
221
+ with open(path, "rb") as stream:
222
+ parser.ParseFile(stream)
223
+ self._start_methods, self._end_methods = XMLHandler._schema_methods
224
+ parser = self._parser
225
+ parser.StartElementHandler = self._startElementHandler
226
+ parser.EndElementHandler = self._endElementHandler
227
+ parser.CharacterDataHandler = self._characterDataHandler
228
+ self._characters = ""
229
+
230
+ def _start_blastoutput(self, name, attributes):
231
+ assert self._characters.strip() == ""
232
+ self._characters = ""
233
+
234
+ def _start_program(self, name, attributes):
235
+ assert self._characters.strip() == ""
236
+ self._characters = ""
237
+
238
+ def _start_version(self, name, attributes):
239
+ assert self._characters.strip() == ""
240
+ self._characters = ""
241
+
242
+ def _start_reference(self, name, attributes):
243
+ assert self._characters.strip() == ""
244
+ self._characters = ""
245
+
246
+ def _start_db(self, name, attributes):
247
+ assert self._characters.strip() == ""
248
+ self._characters = ""
249
+
250
+ def _start_blastoutput_query_id(self, name, attributes):
251
+ assert self._characters.strip() == ""
252
+ self._characters = ""
253
+
254
+ def _start_blastoutput_query_def(self, name, attributes):
255
+ assert self._characters.strip() == ""
256
+ self._characters = ""
257
+
258
+ def _start_mbstat(self, name, attributes):
259
+ assert self._characters.strip() == ""
260
+ self._characters = ""
261
+
262
+ def _start_param(self, name, attributes):
263
+ assert self._characters.strip() == ""
264
+ self._characters = ""
265
+
266
+ def _start_parameters(self, name, attributes):
267
+ assert self._characters.strip() == ""
268
+ self._characters = ""
269
+ self._records.param = {}
270
+
271
+ def _start_matrix(self, name, attributes):
272
+ assert self._characters.strip() == ""
273
+ self._characters = ""
274
+
275
+ def _start_expect(self, name, attributes):
276
+ assert self._characters.strip() == ""
277
+ self._characters = ""
278
+
279
+ def _start_sc_match(self, name, attributes):
280
+ assert self._characters.strip() == ""
281
+ self._characters = ""
282
+
283
+ def _start_sc_mismatch(self, name, attributes):
284
+ assert self._characters.strip() == ""
285
+ self._characters = ""
286
+
287
+ def _start_include(self, name, attributes):
288
+ assert self._characters.strip() == ""
289
+ self._characters = ""
290
+
291
+ def _start_gap_open(self, name, attributes):
292
+ assert self._characters.strip() == ""
293
+ self._characters = ""
294
+
295
+ def _start_gap_extend(self, name, attributes):
296
+ assert self._characters.strip() == ""
297
+ self._characters = ""
298
+
299
+ def _start_filter(self, name, attributes):
300
+ assert self._characters.strip() == ""
301
+ self._characters = ""
302
+
303
+ def _start_cbs(self, name, attributes):
304
+ assert self._characters.strip() == ""
305
+ self._characters = ""
306
+
307
+ def _start_db_gencode(self, name, attributes):
308
+ assert self._characters.strip() == ""
309
+ self._characters = ""
310
+
311
+ def _start_query_gencode(self, name, attributes):
312
+ assert self._characters.strip() == ""
313
+ self._characters = ""
314
+
315
+ def _start_bl2seq_mode(self, name, attributes):
316
+ assert self._characters.strip() == ""
317
+ self._characters = ""
318
+
319
+ def _start_query_masking(self, name, attributes):
320
+ assert self._characters.strip() == ""
321
+ self._characters = ""
322
+
323
+ def _start_range(self, name, attributes):
324
+ assert self._characters.strip() == ""
325
+ self._characters = ""
326
+
327
+ def _start_from(self, name, attributes):
328
+ assert self._characters.strip() == ""
329
+ self._characters = ""
330
+
331
+ def _start_to(self, name, attributes):
332
+ assert self._characters.strip() == ""
333
+ self._characters = ""
334
+
335
+ def _start_pattern(self, name, attributes):
336
+ assert self._characters.strip() == ""
337
+ self._characters = ""
338
+
339
+ def _start_entrez_query(self, name, attributes):
340
+ assert self._characters.strip() == ""
341
+ self._characters = ""
342
+
343
+ def _start_iterations(self, name, attributes):
344
+ self._records._cache = deque()
345
+ assert self._characters.strip() == ""
346
+ self._characters = ""
347
+
348
+ def _start_blastoutput_query_len(self, name, attributes):
349
+ assert self._characters.strip() == ""
350
+ self._characters = ""
351
+
352
+ def _start_query_seq(self, name, attributes):
353
+ assert self._characters.strip() == ""
354
+ self._characters = ""
355
+
356
+ def _start_iteration(self, name, attributes):
357
+ if self._program == "psiblast" and name == "http://www.ncbi.nlm.nih.gov Search":
358
+ # PSIBLAST XML2 uses both <Iteration> and <Search>; ignore one
359
+ return
360
+ record = Record()
361
+ self._record = record
362
+
363
+ def _start_iter_num(self, name, attributes):
364
+ assert self._characters.strip() == ""
365
+ self._characters = ""
366
+
367
+ def _start_query_id(self, name, attributes):
368
+ assert self._characters.strip() == ""
369
+ self._characters = ""
370
+
371
+ def _start_query_def(self, name, attributes):
372
+ assert self._characters.strip() == ""
373
+ self._characters = ""
374
+
375
+ def _start_query_len(self, name, attributes):
376
+ assert self._characters.strip() == ""
377
+ self._characters = ""
378
+
379
+ def _start_hits(self, name, attributes):
380
+ assert self._characters.strip() == ""
381
+ self._characters = ""
382
+
383
+ def _start_hit(self, name, attributes):
384
+ assert self._characters.strip() == ""
385
+ self._characters = ""
386
+ self._alignments = Hit()
387
+
388
+ def _start_num(self, name, attributes):
389
+ assert self._characters.strip() == ""
390
+ self._characters = ""
391
+
392
+ def _start_description(self, name, attributes):
393
+ self._alignments.targets = []
394
+
395
+ def _start_hitdescr(self, name, attributes):
396
+ return
397
+
398
+ def _start_id(self, name, attributes):
399
+ assert self._characters.strip() == ""
400
+ self._characters = ""
401
+
402
+ def _start_def(self, name, attributes):
403
+ assert self._characters.strip() == ""
404
+ self._characters = ""
405
+
406
+ def _start_taxid(self, name, attributes):
407
+ assert self._characters.strip() == ""
408
+ self._characters = ""
409
+
410
+ def _start_sciname(self, name, attributes):
411
+ assert self._characters.strip() == ""
412
+ self._characters = ""
413
+
414
+ def _start_hsps(self, name, attributes):
415
+ assert self._characters.strip() == ""
416
+ self._characters = ""
417
+
418
+ def _start_len(self, name, attributes):
419
+ assert self._characters.strip() == ""
420
+ self._characters = ""
421
+
422
+ def _start_accession(self, name, attributes):
423
+ assert self._characters.strip() == ""
424
+ self._characters = ""
425
+
426
+ def _start_hsp(self, name, attributes):
427
+ assert self._characters.strip() == ""
428
+ self._characters = ""
429
+ self._hsp = _HSP_cache()
430
+
431
+ def _start_bit_score(self, name, attributes):
432
+ assert self._characters.strip() == ""
433
+ self._characters = ""
434
+
435
+ def _start_score(self, name, attributes):
436
+ assert self._characters.strip() == ""
437
+ self._characters = ""
438
+
439
+ def _start_evalue(self, name, attributes):
440
+ assert self._characters.strip() == ""
441
+ self._characters = ""
442
+
443
+ def _start_query_from(self, name, attributes):
444
+ assert self._characters.strip() == ""
445
+ self._characters = ""
446
+
447
+ def _start_query_to(self, name, attributes):
448
+ assert self._characters.strip() == ""
449
+ self._characters = ""
450
+
451
+ def _start_query_strand(self, name, attributes):
452
+ assert self._characters.strip() == ""
453
+ self._characters = ""
454
+
455
+ def _start_hit_from(self, name, attributes):
456
+ assert self._characters.strip() == ""
457
+ self._characters = ""
458
+
459
+ def _start_hit_to(self, name, attributes):
460
+ assert self._characters.strip() == ""
461
+ self._characters = ""
462
+
463
+ def _start_hit_strand(self, name, attributes):
464
+ assert self._characters.strip() == ""
465
+ self._characters = ""
466
+
467
+ def _start_pattern_from(self, name, attributes):
468
+ assert self._characters.strip() == ""
469
+ self._characters = ""
470
+
471
+ def _start_pattern_to(self, name, attributes):
472
+ assert self._characters.strip() == ""
473
+ self._characters = ""
474
+
475
+ def _start_query_frame(self, name, attributes):
476
+ assert self._characters.strip() == ""
477
+ self._characters = ""
478
+
479
+ def _start_hit_frame(self, name, attributes):
480
+ assert self._characters.strip() == ""
481
+ self._characters = ""
482
+
483
+ def _start_identity(self, name, attributes):
484
+ assert self._characters.strip() == ""
485
+ self._characters = ""
486
+
487
+ def _start_positive(self, name, attributes):
488
+ assert self._characters.strip() == ""
489
+ self._characters = ""
490
+
491
+ def _start_gaps(self, name, attributes):
492
+ assert self._characters.strip() == ""
493
+ self._characters = ""
494
+
495
+ def _start_align_len(self, name, attributes):
496
+ assert self._characters.strip() == ""
497
+ self._characters = ""
498
+
499
+ def _start_density(self, name, attributes):
500
+ assert self._characters.strip() == ""
501
+ self._characters = ""
502
+
503
+ def _start_qseq(self, name, attributes):
504
+ assert self._characters.strip() == ""
505
+ self._characters = ""
506
+
507
+ def _start_hseq(self, name, attributes):
508
+ assert self._characters.strip() == ""
509
+ self._characters = ""
510
+
511
+ def _start_midline(self, name, attributes):
512
+ assert self._characters.strip() == ""
513
+ self._characters = ""
514
+
515
+ def _start_stat(self, name, attributes):
516
+ assert self._characters.strip() == ""
517
+ self._characters = ""
518
+
519
+ def _start_message(self, name, attributes):
520
+ assert self._characters.strip() == ""
521
+ self._characters = ""
522
+
523
+ def _start_statistics(self, name, attributes):
524
+ assert self._characters.strip() == ""
525
+ self._characters = ""
526
+ self._stat = {}
527
+
528
+ def _start_db_num(self, name, attributes):
529
+ assert self._characters.strip() == ""
530
+ self._characters = ""
531
+
532
+ def _start_db_len(self, name, attributes):
533
+ assert self._characters.strip() == ""
534
+ self._characters = ""
535
+
536
+ def _start_hsp_len(self, name, attributes):
537
+ assert self._characters.strip() == ""
538
+ self._characters = ""
539
+
540
+ def _start_eff_space(self, name, attributes):
541
+ assert self._characters.strip() == ""
542
+ self._characters = ""
543
+
544
+ def _start_kappa(self, name, attributes):
545
+ assert self._characters.strip() == ""
546
+ self._characters = ""
547
+
548
+ def _start_lambda(self, name, attributes):
549
+ assert self._characters.strip() == ""
550
+ self._characters = ""
551
+
552
+ def _start_entropy(self, name, attributes):
553
+ assert self._characters.strip() == ""
554
+ self._characters = ""
555
+
556
+ def _start_report(self, name, attributes):
557
+ return
558
+
559
+ def _start_search_target(self, name, attributes):
560
+ return
561
+
562
+ def _start_target(self, name, attributes):
563
+ return
564
+
565
+ def _start_results(self, name, attributes):
566
+ return
567
+
568
+ def _end_blastoutput(self, name):
569
+ assert self._characters.strip() == ""
570
+ parser = self._parser
571
+ parser.StartElementHandler = None
572
+ parser.EndElementHandler = None
573
+ parser.CharacterDataHandler = None
574
+ del self._characters
575
+ del self._records
576
+ del self._parser
577
+
578
+ def _end_blastoutput_xml2(self, name):
579
+ assert self._characters.strip() == ""
580
+
581
+ def _end_blastxml2(self, name):
582
+ self._end_blastoutput(name)
583
+
584
+ def _end_program(self, name):
585
+ program = self._characters
586
+ self._program = program
587
+ self._records.program = program
588
+ self._characters = ""
589
+
590
+ def _end_version(self, name):
591
+ self._records.version = self._characters
592
+ self._characters = ""
593
+
594
+ def _end_reference(self, name):
595
+ self._records.reference = html.unescape(self._characters)
596
+ self._characters = ""
597
+
598
+ def _end_db(self, name):
599
+ self._records.db = self._characters
600
+ self._characters = ""
601
+
602
+ def _end_blastoutput_query_id(self, name):
603
+ query_id = self._characters
604
+ self._records.query = SeqRecord(None, query_id)
605
+ self._characters = ""
606
+
607
+ def _end_blastoutput_query_def(self, name):
608
+ query_def = self._characters
609
+ self._records.query.description = query_def
610
+ self._characters = ""
611
+
612
+ def _end_blastoutput_query_len(self, name):
613
+ length = int(self._characters)
614
+ self._records.query.seq = Seq(None, length=length)
615
+ self._characters = ""
616
+
617
+ def _end_query_seq(self, name):
618
+ seq = Seq(self._characters)
619
+ self._characters = ""
620
+ assert len(seq) == len(self._records.query.seq)
621
+ self._records.query.seq = seq
622
+
623
+ def _end_mbstat(self, name):
624
+ assert self._characters.strip() == ""
625
+ self._characters = ""
626
+ self._records.mbstat = self._stat
627
+ del self._stat
628
+
629
+ def _end_param(self, name):
630
+ assert self._characters.strip() == ""
631
+ self._characters = ""
632
+
633
+ def _end_parameters(self, name):
634
+ assert self._characters.strip() == ""
635
+ self._characters = ""
636
+
637
+ def _end_matrix(self, name):
638
+ self._records.param["matrix"] = self._characters
639
+ self._characters = ""
640
+
641
+ def _end_expect(self, name):
642
+ self._records.param["expect"] = float(self._characters)
643
+ self._characters = ""
644
+
645
+ def _end_sc_match(self, name):
646
+ self._records.param["sc-match"] = int(self._characters)
647
+ self._characters = ""
648
+
649
+ def _end_sc_mismatch(self, name):
650
+ self._records.param["sc-mismatch"] = int(self._characters)
651
+ self._characters = ""
652
+
653
+ def _end_include(self, name):
654
+ self._records.param["include"] = float(self._characters)
655
+ self._characters = ""
656
+
657
+ def _end_gap_open(self, name):
658
+ self._records.param["gap-open"] = int(self._characters)
659
+ self._characters = ""
660
+
661
+ def _end_gap_extend(self, name):
662
+ self._records.param["gap-extend"] = int(self._characters)
663
+ self._characters = ""
664
+
665
+ def _end_filter(self, name):
666
+ self._records.param["filter"] = self._characters
667
+ self._characters = ""
668
+
669
+ def _end_cbs(self, name):
670
+ self._records.param["cbs"] = int(self._characters)
671
+ self._characters = ""
672
+
673
+ def _end_db_gencode(self, name):
674
+ self._records.param["db-gencode"] = int(self._characters)
675
+ self._characters = ""
676
+
677
+ def _end_bl2seq_mode(self, name):
678
+ self._records.param["bl2seq-mode"] = int(self._characters)
679
+ self._characters = ""
680
+
681
+ def _end_query_masking(self, name):
682
+ assert self._characters.strip() == ""
683
+ self._characters = ""
684
+ location = self._location
685
+ del self._location
686
+ feature = SeqFeature(location, type="masking")
687
+ self._record.query.features.append(feature)
688
+
689
+ def _end_range(self, name):
690
+ start = self._from - 1
691
+ del self._from
692
+ end = self._to
693
+ del self._to
694
+ self._location = SimpleLocation(start, end)
695
+
696
+ def _end_from(self, name):
697
+ self._from = int(self._characters)
698
+ self._characters = ""
699
+
700
+ def _end_to(self, name):
701
+ self._to = int(self._characters)
702
+ self._characters = ""
703
+
704
+ def _end_query_gencode(self, name):
705
+ self._records.param["query-gencode"] = int(self._characters)
706
+ self._characters = ""
707
+
708
+ def _end_pattern(self, name):
709
+ self._records.param["pattern"] = self._characters
710
+ self._characters = ""
711
+
712
+ def _end_entrez_query(self, name):
713
+ self._records.param["entrez-query"] = self._characters
714
+ self._characters = ""
715
+
716
+ def _end_iterations(self, name):
717
+ assert self._characters.strip() == ""
718
+ self._characters = ""
719
+
720
+ def _end_iteration(self, name):
721
+ assert self._characters.strip() == ""
722
+ self._characters = ""
723
+ if self._program == "psiblast" and name == "http://www.ncbi.nlm.nih.gov Search":
724
+ # PSIBLAST XML2 uses both <Iteration> and <Search>; ignore one
725
+ return
726
+ self._records._cache.append(self._record)
727
+ del self._record
728
+
729
+ def _end_iter_num(self, name):
730
+ self._record.num = int(self._characters)
731
+ self._characters = ""
732
+
733
+ def _end_query_id(self, name):
734
+ query_id = self._characters
735
+ self._record.query = SeqRecord(None, query_id)
736
+ self._characters = ""
737
+
738
+ def _end_query_def(self, name):
739
+ query_def = self._characters
740
+ self._record.query.description = query_def
741
+ self._characters = ""
742
+
743
+ def _end_query_len(self, name):
744
+ length = int(self._characters)
745
+ self._record.query.seq = Seq(None, length=length)
746
+ self._characters = ""
747
+
748
+ def _end_hits(self, name):
749
+ assert self._characters.strip() == ""
750
+ self._characters = ""
751
+
752
+ def _end_hit(self, name):
753
+ assert self._characters.strip() == ""
754
+ self._characters = ""
755
+ hit = self._alignments
756
+ del self._alignments
757
+ self._record.append(hit)
758
+
759
+ def _end_description(self, name):
760
+ self._alignments.target = self._alignments.targets[0]
761
+
762
+ def _end_hitdescr(self, name):
763
+ self._alignments.targets.append(self._alignments.target)
764
+
765
+ def _end_id(self, name):
766
+ hit_id = self._characters
767
+ self._alignments.target = SeqRecord(None, hit_id)
768
+ self._characters = ""
769
+
770
+ def _end_def(self, name):
771
+ description = self._characters
772
+ self._alignments.target.description = description
773
+ self._characters = ""
774
+
775
+ def _end_taxid(self, name):
776
+ taxid = self._characters
777
+ self._alignments.target.annotations["taxid"] = int(taxid)
778
+ self._characters = ""
779
+
780
+ def _end_sciname(self, name):
781
+ sciname = self._characters
782
+ self._alignments.target.annotations["sciname"] = sciname
783
+ self._characters = ""
784
+
785
+ def _end_accession(self, name):
786
+ accession = self._characters
787
+ self._alignments.target.name = accession
788
+ self._characters = ""
789
+
790
+ def _end_len(self, name):
791
+ length = int(self._characters)
792
+ seq = Seq(None, length=length)
793
+ alignments = self._alignments
794
+ try:
795
+ targets = alignments.targets
796
+ except AttributeError:
797
+ # XML
798
+ alignments.target.seq = seq
799
+ else:
800
+ # XML2
801
+ for target in alignments.targets:
802
+ target.seq = seq
803
+ self._characters = ""
804
+
805
+ def _end_hsps(self, name):
806
+ assert self._characters.strip() == ""
807
+ self._characters = ""
808
+
809
+ def _end_num(self, name):
810
+ try:
811
+ element = self._hsp
812
+ except AttributeError:
813
+ element = self._alignments
814
+ element.num = int(self._characters)
815
+ self._characters = ""
816
+
817
+ def _end_bit_score(self, name):
818
+ self._hsp.bit_score = float(self._characters)
819
+ self._characters = ""
820
+
821
+ def _end_score(self, name):
822
+ self._hsp.score = float(self._characters)
823
+ self._characters = ""
824
+
825
+ def _end_evalue(self, name):
826
+ self._hsp.evalue = float(self._characters)
827
+ self._characters = ""
828
+
829
+ def _end_query_from(self, name):
830
+ self._hsp.query_from = int(self._characters)
831
+ self._characters = ""
832
+
833
+ def _end_query_to(self, name):
834
+ self._hsp.query_to = int(self._characters)
835
+ self._characters = ""
836
+
837
+ def _end_query_strand(self, name):
838
+ query_strand = self._characters
839
+ assert query_strand == "Plus"
840
+ self._hsp.query_strand = query_strand
841
+ self._characters = ""
842
+
843
+ def _end_hit_from(self, name):
844
+ self._hsp.hit_from = int(self._characters)
845
+ self._characters = ""
846
+
847
+ def _end_hit_to(self, name):
848
+ self._hsp.hit_to = int(self._characters)
849
+ self._characters = ""
850
+
851
+ def _end_hit_strand(self, name):
852
+ hit_strand = self._characters
853
+ assert hit_strand in ("Plus", "Minus")
854
+ self._hsp.hit_strand = hit_strand
855
+ self._characters = ""
856
+
857
+ def _end_pattern_from(self, name):
858
+ self._hsp.pattern_from = int(self._characters)
859
+ self._characters = ""
860
+
861
+ def _end_pattern_to(self, name):
862
+ self._hsp.pattern_to = int(self._characters)
863
+ self._characters = ""
864
+
865
+ def _end_query_frame(self, name):
866
+ query_frame = int(self._characters)
867
+ program = self._program
868
+ if program in ("blastn", "megablast") and query_frame == 1:
869
+ pass
870
+ elif program in ("blastx", "tblastx") and query_frame in (-3, -2, -1, 1, 2, 3):
871
+ pass
872
+ elif (
873
+ program in ("blastp", "tblastn", "rpsblast", "psiblast")
874
+ and query_frame == 0
875
+ ):
876
+ pass
877
+ else:
878
+ raise ValueError(
879
+ f"unexpected value {query_frame} in tag <Hsp_query-frame> for program {program}"
880
+ )
881
+ self._hsp.query_frame = query_frame
882
+ self._characters = ""
883
+
884
+ def _end_hit_frame(self, name):
885
+ hit_frame = int(self._characters)
886
+ program = self._program
887
+ if program in ("blastn", "megablast") and hit_frame in (-1, 1):
888
+ pass
889
+ elif program in ("blastp", "blastx", "rpsblast", "psiblast") and hit_frame == 0:
890
+ pass
891
+ elif program in ("tblastn", "tblastx") and hit_frame in (-3, -2, -1, 1, 2, 3):
892
+ pass
893
+ else:
894
+ raise ValueError(
895
+ f"unexpected value {hit_frame} in tag <Hsp_hit-frame> for program {program}"
896
+ )
897
+ self._hsp.hit_frame = hit_frame
898
+ self._characters = ""
899
+
900
+ def _end_identity(self, name):
901
+ self._hsp.identity = int(self._characters)
902
+ self._characters = ""
903
+
904
+ def _end_positive(self, name):
905
+ self._hsp.positive = int(self._characters)
906
+ self._characters = ""
907
+
908
+ def _end_gaps(self, name):
909
+ self._hsp.gaps = int(self._characters)
910
+ self._characters = ""
911
+
912
+ def _end_align_len(self, name):
913
+ self._hsp.align_len = int(self._characters)
914
+ self._characters = ""
915
+
916
+ def _end_density(self, name):
917
+ self._hsp.density = int(self._characters)
918
+ self._characters = ""
919
+
920
+ def _end_qseq(self, name):
921
+ self._hsp.qseq = self._characters
922
+ self._characters = ""
923
+
924
+ def _end_hseq(self, name):
925
+ self._hsp.hseq = self._characters
926
+ self._characters = ""
927
+
928
+ def _end_midline(self, name):
929
+ self._hsp.midline = self._characters
930
+ self._characters = ""
931
+
932
+ def _end_hsp(self, name):
933
+ assert self._characters.strip() == ""
934
+ self._characters = ""
935
+ hsp = self._hsp
936
+ del self._hsp
937
+ program = self._program
938
+ query = self._record.query
939
+ if query is None:
940
+ query = self._records.query
941
+ query_id = query.id
942
+ query_description = query.description
943
+ query_length = len(query.seq)
944
+ query = SeqRecord(None, query_id, description=query_description)
945
+ target = self._alignments.target
946
+ target_id = target.id
947
+ target_name = target.name
948
+ target_description = target.description
949
+ target_length = len(target.seq)
950
+ target = SeqRecord(None, target_id, target_name, description=target_description)
951
+ query_seq_aligned = hsp.qseq.encode()
952
+ target_seq_aligned = hsp.hseq.encode()
953
+ try:
954
+ align_len = hsp.align_len
955
+ except AttributeError: # PSIBLAST XML2
956
+ assert len(query_seq_aligned) == 0
957
+ assert len(target_seq_aligned) == 0
958
+ query_seq_data = None
959
+ target.seq = Seq(None, target_length)
960
+ coordinates = np.empty((2, 0), dtype=int)
961
+ else:
962
+ assert len(query_seq_aligned) == align_len
963
+ assert len(target_seq_aligned) == align_len
964
+ (
965
+ (
966
+ target_seq_data,
967
+ query_seq_data,
968
+ ),
969
+ coordinates,
970
+ ) = Alignment.parse_printed_alignment(
971
+ [target_seq_aligned, query_seq_aligned]
972
+ )
973
+ query_start = hsp.query_from - 1
974
+ query_end = hsp.query_to
975
+ if program in ("blastx", "tblastx"):
976
+ assert query_end - query_start == 3 * len(query_seq_data)
977
+ location = SimpleLocation(0, len(query_seq_data))
978
+ coded_by = f"{query_id}:{hsp.query_from}..{hsp.query_to}"
979
+ query_frame = hsp.query_frame
980
+ if query_frame > 0:
981
+ assert query_start % 3 == query_frame - 1
982
+ elif query_frame < 0:
983
+ assert (query_length - query_end) % 3 == -query_frame - 1
984
+ coded_by = f"complement({coded_by})"
985
+ qualifiers = {"coded_by": coded_by}
986
+ feature = SeqFeature(location, type="CDS", qualifiers=qualifiers)
987
+ query.features.append(feature)
988
+ else:
989
+ coordinates[1, :] += query_start
990
+ assert query_end - query_start == len(query_seq_data)
991
+ query_seq_data = {query_start: query_seq_data}
992
+ if program == "blastn":
993
+ try:
994
+ query_strand = hsp.query_strand
995
+ except AttributeError:
996
+ # v1 XML
997
+ pass
998
+ else:
999
+ # v2 XML
1000
+ assert query_strand == "Plus"
1001
+ if program in ("blastn", "megablast"):
1002
+ try:
1003
+ target_strand = hsp.hit_strand
1004
+ except AttributeError:
1005
+ # v1 XML
1006
+ target_frame = hsp.hit_frame
1007
+ if target_frame == +1:
1008
+ target_strand = "Plus"
1009
+ elif target_frame == -1:
1010
+ target_strand = "Minus"
1011
+ if target_strand == "Plus":
1012
+ target_start = hsp.hit_from - 1
1013
+ target_end = hsp.hit_to
1014
+ coordinates[0, :] += target_start
1015
+ assert target_end - target_start == len(target_seq_data)
1016
+ target_seq_data = {target_start: target_seq_data}
1017
+ target.seq = Seq(target_seq_data, target_length)
1018
+ elif target_strand == "Minus":
1019
+ target_start = hsp.hit_to - 1
1020
+ target_end = hsp.hit_from
1021
+ coordinates[0, :] = target_end - coordinates[0, :]
1022
+ assert target_end - target_start == len(target_seq_data)
1023
+ target_seq_data = {target_length - target_end: target_seq_data}
1024
+ seq = Seq(target_seq_data, target_length)
1025
+ target.seq = seq.reverse_complement()
1026
+ elif program in ("blastp", "blastx", "rpsblast", "psiblast"):
1027
+ target_start = hsp.hit_from - 1
1028
+ target_end = hsp.hit_to
1029
+ coordinates[0, :] += target_start
1030
+ assert target_end - target_start == len(target_seq_data)
1031
+ target_seq_data = {target_start: target_seq_data}
1032
+ target.seq = Seq(target_seq_data, target_length)
1033
+ elif program in ("tblastn", "tblastx"):
1034
+ target_start = hsp.hit_from - 1
1035
+ target_end = hsp.hit_to
1036
+ assert target_end - target_start == 3 * len(target_seq_data)
1037
+ location = SimpleLocation(0, target_length)
1038
+ coded_by = f"{target_id}:{hsp.hit_from}..{hsp.hit_to}"
1039
+ target_frame = hsp.hit_frame
1040
+ if target_frame >= 0:
1041
+ assert target_start % 3 == target_frame - 1
1042
+ elif target_frame < 0:
1043
+ assert (target_length - target_end) % 3 == -target_frame - 1
1044
+ coded_by = f"complement({coded_by})"
1045
+ qualifiers = {"coded_by": coded_by}
1046
+ feature = SeqFeature(location, type="CDS", qualifiers=qualifiers)
1047
+ target.features.append(feature)
1048
+ target.seq = Seq(target_seq_data, target_length)
1049
+ else:
1050
+ raise RuntimeError("Unexpected program name '%s'" % program)
1051
+ query.seq = Seq(query_seq_data, query_length)
1052
+ sequences = [target, query]
1053
+ alignment = HSP(sequences, coordinates)
1054
+ alignment.num = hsp.num
1055
+ alignment.score = hsp.score
1056
+ annotations = {}
1057
+ annotations["bit score"] = hsp.bit_score
1058
+ annotations["evalue"] = hsp.evalue
1059
+ annotations["identity"] = hsp.identity
1060
+ try:
1061
+ annotations["positive"] = hsp.positive
1062
+ except AttributeError:
1063
+ # missing in blastn for XML1
1064
+ pass
1065
+ try:
1066
+ annotations["gaps"] = hsp.gaps
1067
+ except AttributeError:
1068
+ # missing in legacy megablast
1069
+ pass
1070
+ try:
1071
+ annotations["midline"] = hsp.midline
1072
+ except AttributeError:
1073
+ # missing in psiblast for XML2
1074
+ pass
1075
+ alignment.annotations = annotations
1076
+ self._alignments.append(alignment)
1077
+
1078
+ def _end_stat(self, name):
1079
+ assert self._characters.strip() == ""
1080
+ self._characters = ""
1081
+ self._record.stat = self._stat
1082
+ del self._stat
1083
+
1084
+ def _end_message(self, name):
1085
+ self._record.message = self._characters
1086
+ self._characters = ""
1087
+
1088
+ def _end_statistics(self, name):
1089
+ assert self._characters.strip() == ""
1090
+ self._characters = ""
1091
+
1092
+ def _end_db_num(self, name):
1093
+ self._stat["db-num"] = int(self._characters)
1094
+ self._characters = ""
1095
+
1096
+ def _end_db_len(self, name):
1097
+ self._stat["db-len"] = int(self._characters)
1098
+ self._characters = ""
1099
+
1100
+ def _end_hsp_len(self, name):
1101
+ self._stat["hsp-len"] = int(self._characters)
1102
+ self._characters = ""
1103
+
1104
+ def _end_eff_space(self, name):
1105
+ characters = self._characters
1106
+ if characters.isdigit():
1107
+ value = int(characters)
1108
+ else:
1109
+ value = float(characters)
1110
+ self._stat["eff-space"] = value
1111
+ self._characters = ""
1112
+
1113
+ def _end_eff_space_xml2(self, name):
1114
+ self._stat["eff-space"] = int(self._characters)
1115
+ self._characters = ""
1116
+
1117
+ def _end_kappa(self, name):
1118
+ self._stat["kappa"] = float(self._characters)
1119
+ self._characters = ""
1120
+
1121
+ def _end_lambda(self, name):
1122
+ self._stat["lambda"] = float(self._characters)
1123
+ self._characters = ""
1124
+
1125
+ def _end_entropy(self, name):
1126
+ self._stat["entropy"] = float(self._characters)
1127
+ self._characters = ""
1128
+
1129
+ def _end_report(self, name):
1130
+ return
1131
+
1132
+ def _end_search_target(self, name):
1133
+ return
1134
+
1135
+ def _end_target(self, name):
1136
+ return
1137
+
1138
+ def _end_results(self, name):
1139
+ return
1140
+
1141
+ def _xmlDeclHandler(self, version, encoding, standalone):
1142
+ parser = self._parser
1143
+ parser.ExternalEntityRefHandler = self._externalEntityRefHandler
1144
+ parser.StartNamespaceDeclHandler = self._startNamespaceDeclHandler
1145
+ parser.EndNamespaceDeclHandler = self._endNamespaceDeclHandler
1146
+ parser.StartElementHandler = self._startElementHandler
1147
+ parser.EndElementHandler = self._endElementHandler
1148
+ parser.CharacterDataHandler = self._characterDataHandler
1149
+ self._characters = ""
1150
+ parser.XmlDeclHandler = None
1151
+
1152
+ def _externalEntityRefHandler(self, context, base, systemId, publicId):
1153
+ """Handle the DTD declaration."""
1154
+ assert context is None
1155
+ assert base is None
1156
+ if systemId not in (
1157
+ "NCBI_BlastOutput.dtd",
1158
+ "http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd",
1159
+ "https://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd",
1160
+ ):
1161
+ raise ValueError("output from legacy BLAST program")
1162
+ assert publicId == "-//NCBI//NCBI BlastOutput/EN"
1163
+ if XMLHandler._dtd_methods is None:
1164
+ handler = DTDHandler()
1165
+ handler.parseFile("NCBI_BlastOutput.dtd")
1166
+ self._parser.ExternalEntityRefHandler = None
1167
+ self._start_methods, self._end_methods = XMLHandler._dtd_methods
1168
+ return 1
1169
+
1170
+ def _startElementHandler(self, name, attributes):
1171
+ """Found XML start tag.
1172
+
1173
+ Arguments:
1174
+ - name -- name of the tag
1175
+ - attributes -- tag attributes
1176
+
1177
+ """
1178
+ method = self._start_methods.get(name)
1179
+ if method is None:
1180
+ raise ValueError(
1181
+ "Failed to find method for %s (%s)" % (name, self._start_methods.keys())
1182
+ )
1183
+ method(self, name, attributes)
1184
+
1185
+ def _endElementHandler(self, name):
1186
+ """Found XML end tag.
1187
+
1188
+ Arguments:
1189
+ - name -- tag name
1190
+
1191
+ """
1192
+ method = self._end_methods.get(name)
1193
+ if method is None:
1194
+ raise ValueError("Failed to find method for %s" % name)
1195
+ method(self, name)
1196
+
1197
+ def _characterDataHandler(self, characters):
1198
+ """Found some text.
1199
+
1200
+ Arguments:
1201
+ - characters -- characters read
1202
+
1203
+ """
1204
+ self._characters += characters
1205
+
1206
+ def __iter__(self):
1207
+ return self
1208
+
1209
+ def __repr__(self):
1210
+ try:
1211
+ stream = self._stream
1212
+ except AttributeError:
1213
+ stream = None
1214
+ try:
1215
+ parser = self._parser
1216
+ except AttributeError:
1217
+ parser = None
1218
+ address = hex(id(self))
1219
+ if stream is None and parser is None:
1220
+ return f"<Bio.Blast._parser.XMLHandler object at {address} with no stream or parser>"
1221
+ elif stream is None:
1222
+ return f"<Bio.Blast._parser.XMLHandler object at {address} with parser {parser} and no stream>"
1223
+ elif parser is None:
1224
+ return f"<Bio.Blast._parser.XMLHandler object at {address} with stream {stream} and no parser>"
1225
+ else:
1226
+ return f"<Bio.Blast._parser.XMLHandler object at {address} with stream {stream} and parser {parser}>"
.venv_haddock/lib/python3.12/site-packages/Bio/Blast/_writers.py ADDED
@@ -0,0 +1,1520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import codecs
2
+ import html
3
+ from abc import ABC
4
+ from abc import abstractmethod
5
+
6
+ from Bio.Seq import UndefinedSequenceError
7
+
8
+
9
+ def _html_entity_replace(error):
10
+ start = error.start
11
+ end = error.end
12
+ character = error.object[start:end]
13
+ codepoint = ord(character)
14
+ entity = f"&amp;{html.entities.codepoint2name[codepoint]};"
15
+ return entity, end
16
+
17
+
18
+ codecs.register_error("htmlentityreplace", _html_entity_replace)
19
+
20
+
21
+ class BaseXMLWriter(ABC):
22
+ """XML Writer, abstract base class."""
23
+
24
+ def __init__(self, stream):
25
+ """Init the stuff."""
26
+ self.stream = stream
27
+
28
+ def write(self, records):
29
+ """Write the records."""
30
+ stream = self.stream
31
+ program = records.program
32
+ self._program = program
33
+ self._write_xml_declaration()
34
+ self._write_definition()
35
+ self._start_blastoutput()
36
+ self._write_program(program.encode())
37
+ self._write_version(records.version.encode())
38
+ reference = html.escape(records.reference).encode("ASCII", "htmlentityreplace")
39
+ self._write_reference(reference)
40
+ self._write_db(records.db.encode())
41
+ try:
42
+ query = records.query
43
+ except AttributeError: # XML2
44
+ pass
45
+ else:
46
+ self._write_query_id(query.id.encode())
47
+ self._write_query_def(query.description.encode())
48
+ self._write_query_len(len(query))
49
+ try:
50
+ query_seq = bytes(query.seq)
51
+ except UndefinedSequenceError:
52
+ pass
53
+ else:
54
+ self._write_query_seq(query_seq)
55
+ self._write_params(records.param)
56
+ count = self._write_records(records)
57
+ try:
58
+ mbstat = records.mbstat
59
+ except AttributeError:
60
+ pass
61
+ else:
62
+ self._start_mbstat()
63
+ self._write_statistics(mbstat)
64
+ self._end_mbstat()
65
+ self._end_blastoutput()
66
+ return count
67
+
68
+ def _write_xml_declaration(self):
69
+ self.stream.write(b'<?xml version="1.0"?>\n')
70
+
71
+ def _write_params(self, param):
72
+ self._start_param()
73
+ value = param.get("matrix")
74
+ if value is not None:
75
+ self._write_parameters_matrix(value.encode())
76
+ self._write_parameters_expect(param["expect"])
77
+ value = param.get("include")
78
+ if value is not None:
79
+ self._write_parameters_include(value)
80
+ value = param.get("sc-match")
81
+ if value is not None:
82
+ self._write_parameters_sc_match(value)
83
+ value = param.get("sc-mismatch")
84
+ if value is not None:
85
+ self._write_parameters_sc_mismatch(value)
86
+ value = param.get("gap-open")
87
+ if value is not None:
88
+ self._write_parameters_gap_open(value)
89
+ value = param.get("gap-extend")
90
+ if value is not None:
91
+ self._write_parameters_gap_extend(value)
92
+ value = param.get("filter")
93
+ if value is not None:
94
+ self._write_parameters_filter(value.encode())
95
+ value = param.get("pattern")
96
+ if value is not None:
97
+ self._write_parameters_pattern(value.encode())
98
+ value = param.get("entrez-query")
99
+ if value is not None:
100
+ self._write_parameters_entrez_query(value.encode())
101
+ value = param.get("cbs")
102
+ if value is not None:
103
+ self._write_parameters_cbs(value)
104
+ value = param.get("query-gencode")
105
+ if value is not None:
106
+ self._write_parameters_query_gencode(value)
107
+ value = param.get("db-gencode")
108
+ if value is not None:
109
+ self._write_parameters_db_gencode(value)
110
+ value = param.get("bl2seq-mode")
111
+ if value is not None:
112
+ self._write_parameters_bl2seq_mode(value.encode())
113
+ self._end_param()
114
+
115
+ def _write_records(self, records):
116
+ count = 0
117
+ self._start_iterations()
118
+ for record in records:
119
+ self._write_record(record)
120
+ count += 1
121
+ self._end_iterations()
122
+ return count
123
+
124
+ def _write_record(self, record):
125
+ stream = self.stream
126
+ self._start_iteration(record)
127
+ query = record.query
128
+ if query is None:
129
+ query_length = None
130
+ else:
131
+ query_length = len(query.seq)
132
+ self._write_iteration_query_id(query.id.encode())
133
+ description = query.description
134
+ if description != "<unknown description>":
135
+ self._write_iteration_query_def(description.encode())
136
+ self._write_iteration_query_len(query_length)
137
+ for feature in query.features:
138
+ if feature.type == "masking":
139
+ self._write_iteration_query_masking(feature.location)
140
+ self._start_iteration_hits()
141
+ for hit in record:
142
+ self._write_hit(hit, query_length)
143
+ self._end_iteration_hits()
144
+ try:
145
+ stat = record.stat
146
+ except AttributeError:
147
+ pass
148
+ else:
149
+ self._start_iteration_stat()
150
+ self._write_statistics(stat)
151
+ self._end_iteration_stat()
152
+ self._end_iteration()
153
+
154
+ def _write_hit(self, hit, query_length):
155
+ stream = self.stream
156
+ program = self._program
157
+ target = hit.target
158
+ target_length = len(target.seq)
159
+ self._start_iteration_hit()
160
+ self._write_hit_num(hit.num)
161
+ try:
162
+ targets = hit.targets
163
+ except AttributeError: # XML
164
+ self._write_hit_id(target.id.encode())
165
+ self._write_hit_def(target.description.encode())
166
+ self._write_hit_accession(target.name.encode())
167
+ else: # XML2
168
+ self._start_hit_targets()
169
+ for target in targets:
170
+ self._start_hitdescr()
171
+ self._write_hit_id(target.id.encode())
172
+ self._write_hit_accession(target.name.encode())
173
+ self._write_hit_def(target.description.encode())
174
+ taxid = target.annotations.get("taxid")
175
+ if taxid is not None:
176
+ self._write_hit_taxid(taxid)
177
+ sciname = target.annotations.get("sciname")
178
+ if sciname is not None:
179
+ self._write_hit_sciname(sciname.encode())
180
+ self._end_hitdescr()
181
+ self._end_hit_targets()
182
+ self._write_hit_len(target_length)
183
+ self._start_hit_hsps()
184
+ for hsp in hit:
185
+ self._write_hsp(hsp, query_length, target_length)
186
+ self._end_hit_hsps()
187
+ self._end_iteration_hit()
188
+
189
+ def _write_hsp(self, hsp, query_length, target_length):
190
+ stream = self.stream
191
+ program = self._program
192
+ query = hsp.query
193
+ target = hsp.target
194
+ coordinates = hsp.coordinates
195
+ if coordinates.shape[1] > 0:
196
+ hit_from, query_from = coordinates[:, 0]
197
+ hit_to, query_to = coordinates[:, -1]
198
+ if program in ("blastn", "megablast"):
199
+ if hit_from <= hit_to:
200
+ hit_frame = 1
201
+ hit_from += 1
202
+ else:
203
+ hit_frame = -1
204
+ hit_to += 1
205
+ elif program in ("blastp", "blastx", "rpsblast", "psiblast"):
206
+ hit_from += 1
207
+ hit_frame = 0
208
+ elif program in ("tblastn", "tblastx"):
209
+ feature = target.features[0]
210
+ coded_by = feature.qualifiers["coded_by"]
211
+ if coded_by.startswith("complement("):
212
+ assert coded_by.endswith(")")
213
+ coded_by = coded_by[11:-1]
214
+ strand = -1
215
+ else:
216
+ strand = +1
217
+ hit_id, hit_from_to = coded_by.split(":")
218
+ hit_from, hit_to = hit_from_to.split("..")
219
+ hit_from = int(hit_from)
220
+ hit_to = int(hit_to)
221
+ hit_start = hit_from - 1
222
+ hit_end = hit_to
223
+ if strand == +1:
224
+ hit_frame = hit_start % 3 + 1
225
+ else:
226
+ hit_frame = (hit_end - target_length) % -3 - 1
227
+ if program in ("blastn", "megablast"):
228
+ if query_from <= query_to:
229
+ query_from += 1
230
+ query_frame = 1
231
+ else:
232
+ query_to += 1
233
+ query_frame = -1
234
+ elif program in ("blastp", "tblastn", "rpsblast", "psiblast"):
235
+ query_from += 1
236
+ query_frame = 0
237
+ elif program in ("blastx", "tblastx"):
238
+ feature = query.features[0]
239
+ coded_by = feature.qualifiers["coded_by"]
240
+ if coded_by.startswith("complement("):
241
+ assert coded_by.endswith(")")
242
+ coded_by = coded_by[11:-1]
243
+ strand = -1
244
+ else:
245
+ strand = +1
246
+ query_id, query_from_to = coded_by.split(":")
247
+ query_from, query_to = query_from_to.split("..")
248
+ query_from = int(query_from)
249
+ query_to = int(query_to)
250
+ query_start = query_from - 1
251
+ query_end = query_to
252
+ if strand == +1:
253
+ query_frame = query_start % 3 + 1
254
+ else:
255
+ query_frame = (query_end - query_length) % -3 - 1
256
+ hseq = hsp[0]
257
+ qseq = hsp[1]
258
+ align_len = len(hseq)
259
+ else:
260
+ # PSIBLAST XML2
261
+ query_from = 0
262
+ query_to = 0
263
+ hit_from = 0
264
+ hit_to = 0
265
+ hseq = ""
266
+ qseq = ""
267
+ query_frame = None
268
+ hit_frame = None
269
+ align_len = None
270
+ annotations = hsp.annotations
271
+ bit_score = annotations["bit score"]
272
+ evalue = annotations["evalue"]
273
+ identity = annotations["identity"]
274
+ positive = annotations.get("positive")
275
+ gaps = annotations.get("gaps")
276
+ midline = annotations.get("midline")
277
+ self._start_hsp()
278
+ self._write_hsp_num(hsp.num)
279
+ self._write_hsp_bit_score(str(bit_score).encode())
280
+ self._write_hsp_score(hsp.score)
281
+ self._write_hsp_evalue(str(evalue).encode())
282
+ self._write_hsp_query_from(query_from)
283
+ self._write_hsp_query_to(query_to)
284
+ self._write_hsp_hit_from(hit_from)
285
+ self._write_hsp_hit_to(hit_to)
286
+ if query_frame is not None:
287
+ self._write_hsp_query_frame(query_frame)
288
+ if hit_frame is not None:
289
+ self._write_hsp_hit_frame(hit_frame)
290
+ self._write_hsp_identity(identity)
291
+ if positive is not None:
292
+ self._write_hsp_positive(positive)
293
+ if gaps is not None:
294
+ self._write_hsp_gaps(gaps)
295
+ if align_len is not None:
296
+ self._write_hsp_align_len(align_len)
297
+ self._write_hsp_qseq(qseq.encode())
298
+ self._write_hsp_hseq(hseq.encode())
299
+ if midline is not None:
300
+ self._write_hsp_midline(midline.encode())
301
+ self._end_hsp()
302
+
303
+ def _write_statistics(self, stat):
304
+ self.stream.write(b" <Statistics>\n")
305
+ self._write_statistics_db_num(stat["db-num"])
306
+ self._write_statistics_db_len(stat["db-len"])
307
+ self._write_statistics_hsp_len(stat["hsp-len"])
308
+ self._write_statistics_eff_space(str(stat["eff-space"]).encode())
309
+ self._write_statistics_kappa(stat["kappa"])
310
+ self._write_statistics_lambda(stat["lambda"])
311
+ self._write_statistics_entropy(stat["entropy"])
312
+ self.stream.write(b" </Statistics>\n")
313
+
314
+ def _write_definition(self):
315
+ return
316
+
317
+ @abstractmethod
318
+ def _start_blastoutput(self):
319
+ return
320
+
321
+ @abstractmethod
322
+ def _end_blastoutput(self):
323
+ return
324
+
325
+ @abstractmethod
326
+ def _write_program(self, program):
327
+ return
328
+
329
+ @abstractmethod
330
+ def _write_version(self, version):
331
+ return
332
+
333
+ @abstractmethod
334
+ def _write_reference(self, reference):
335
+ return
336
+
337
+ @abstractmethod
338
+ def _write_db(self, db):
339
+ return
340
+
341
+ @abstractmethod
342
+ def _start_param(self):
343
+ return
344
+
345
+ @abstractmethod
346
+ def _end_param(self):
347
+ return
348
+
349
+ @abstractmethod
350
+ def _start_iterations(self):
351
+ return
352
+
353
+ @abstractmethod
354
+ def _end_iterations(self):
355
+ return
356
+
357
+ @abstractmethod
358
+ def _start_iteration(self):
359
+ return
360
+
361
+ @abstractmethod
362
+ def _end_iteration(self):
363
+ return
364
+
365
+ @abstractmethod
366
+ def _write_iteration_query_id(self, query_id):
367
+ return
368
+
369
+ @abstractmethod
370
+ def _write_iteration_query_def(self, query_def):
371
+ return
372
+
373
+ @abstractmethod
374
+ def _write_iteration_query_len(self, query_len):
375
+ return
376
+
377
+ def _write_iteration_query_masking(self, location):
378
+ return
379
+
380
+ @abstractmethod
381
+ def _start_iteration_hits(self):
382
+ return
383
+
384
+ @abstractmethod
385
+ def _end_iteration_hits(self):
386
+ return
387
+
388
+ @abstractmethod
389
+ def _start_iteration_stat(self):
390
+ return
391
+
392
+ @abstractmethod
393
+ def _end_iteration_stat(self):
394
+ return
395
+
396
+ @abstractmethod
397
+ def _write_parameters_matrix(self, value):
398
+ return
399
+
400
+ @abstractmethod
401
+ def _write_parameters_expect(self, value):
402
+ return
403
+
404
+ @abstractmethod
405
+ def _write_parameters_include(self, value):
406
+ return
407
+
408
+ @abstractmethod
409
+ def _write_parameters_sc_match(self, value):
410
+ return
411
+
412
+ @abstractmethod
413
+ def _write_parameters_sc_mismatch(self, value):
414
+ return
415
+
416
+ @abstractmethod
417
+ def _write_parameters_gap_open(self, value):
418
+ return
419
+
420
+ @abstractmethod
421
+ def _write_parameters_gap_extend(self, value):
422
+ return
423
+
424
+ @abstractmethod
425
+ def _write_parameters_filter(self, value):
426
+ return
427
+
428
+ @abstractmethod
429
+ def _write_parameters_pattern(self, value):
430
+ return
431
+
432
+ @abstractmethod
433
+ def _write_parameters_entrez_query(self, value):
434
+ return
435
+
436
+ def _write_parameters_cbs(self, value):
437
+ return
438
+
439
+ def _write_parameters_query_gencode(self, value):
440
+ return
441
+
442
+ def _write_parameters_db_gencode(self, value):
443
+ return
444
+
445
+ def _write_parameters_bl2seq_mode(self, value):
446
+ return
447
+
448
+ @abstractmethod
449
+ def _write_statistics_db_num(self, db_num):
450
+ return
451
+
452
+ @abstractmethod
453
+ def _write_statistics_db_len(self, db_len):
454
+ return
455
+
456
+ @abstractmethod
457
+ def _write_statistics_hsp_len(self, hsp_len):
458
+ return
459
+
460
+ @abstractmethod
461
+ def _write_statistics_eff_space(self, value):
462
+ return
463
+
464
+ @abstractmethod
465
+ def _write_statistics_kappa(self, value):
466
+ return
467
+
468
+ @abstractmethod
469
+ def _write_statistics_lambda(self, value):
470
+ return
471
+
472
+ @abstractmethod
473
+ def _write_statistics_entropy(self, value):
474
+ return
475
+
476
+ @abstractmethod
477
+ def _start_iteration_hit(self):
478
+ return
479
+
480
+ @abstractmethod
481
+ def _end_iteration_hit(self):
482
+ return
483
+
484
+ @abstractmethod
485
+ def _write_hit_num(self, num):
486
+ return
487
+
488
+ @abstractmethod
489
+ def _write_hit_id(self, hit_id):
490
+ return
491
+
492
+ @abstractmethod
493
+ def _write_hit_def(self, hit_def):
494
+ return
495
+
496
+ @abstractmethod
497
+ def _write_hit_accession(self, hit_accession):
498
+ return
499
+
500
+ def _write_hit_taxid(self, taxid):
501
+ return
502
+
503
+ def _write_hit_sciname(self, sciname):
504
+ return
505
+
506
+ @abstractmethod
507
+ def _write_hit_len(self, hit_length):
508
+ return
509
+
510
+ @abstractmethod
511
+ def _start_hit_hsps(self):
512
+ return
513
+
514
+ @abstractmethod
515
+ def _end_hit_hsps(self):
516
+ return
517
+
518
+ @abstractmethod
519
+ def _start_hsp(self):
520
+ return
521
+
522
+ @abstractmethod
523
+ def _end_hsp(self):
524
+ return
525
+
526
+ @abstractmethod
527
+ def _write_hsp_num(self, num):
528
+ return
529
+
530
+ @abstractmethod
531
+ def _write_hsp_bit_score(self, bit_score):
532
+ return
533
+
534
+ @abstractmethod
535
+ def _write_hsp_score(self, score):
536
+ return
537
+
538
+ @abstractmethod
539
+ def _write_hsp_evalue(self, evalue):
540
+ return
541
+
542
+ @abstractmethod
543
+ def _write_hsp_query_from(self, query_from):
544
+ return
545
+
546
+ @abstractmethod
547
+ def _write_hsp_query_to(self, query_to):
548
+ return
549
+
550
+ @abstractmethod
551
+ def _write_hsp_hit_from(self, hit_from):
552
+ return
553
+
554
+ @abstractmethod
555
+ def _write_hsp_hit_to(self, hit_to):
556
+ return
557
+
558
+ @abstractmethod
559
+ def _write_hsp_pattern_from(self, hit_from):
560
+ return
561
+
562
+ @abstractmethod
563
+ def _write_hsp_pattern_to(self, hit_to):
564
+ return
565
+
566
+ @abstractmethod
567
+ def _write_hsp_query_frame(self, query_frame):
568
+ return
569
+
570
+ @abstractmethod
571
+ def _write_hsp_hit_frame(self, hit_frame):
572
+ return
573
+
574
+ @abstractmethod
575
+ def _write_hsp_identity(self, identity):
576
+ return
577
+
578
+ @abstractmethod
579
+ def _write_hsp_positive(self, positive):
580
+ return
581
+
582
+ @abstractmethod
583
+ def _write_hsp_gaps(self, gaps):
584
+ return
585
+
586
+ @abstractmethod
587
+ def _write_hsp_align_len(self, align_len):
588
+ return
589
+
590
+ @abstractmethod
591
+ def _write_hsp_density(self, density):
592
+ return
593
+
594
+ @abstractmethod
595
+ def _write_hsp_qseq(self, qseq):
596
+ return
597
+
598
+ @abstractmethod
599
+ def _write_hsp_hseq(self, hseq):
600
+ return
601
+
602
+ @abstractmethod
603
+ def _write_hsp_midline(self, midline):
604
+ return
605
+
606
+
607
+ class XMLWriter(BaseXMLWriter):
608
+ """XML Writer."""
609
+
610
+ def _write_definition(self):
611
+ self.stream.write(
612
+ b"""\
613
+ <!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" "https://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">
614
+ """
615
+ )
616
+
617
+ def _start_blastoutput(self):
618
+ self.stream.write(b"<BlastOutput>\n")
619
+
620
+ def _end_blastoutput(self):
621
+ self.stream.write(b"</BlastOutput>\n")
622
+
623
+ def _write_program(self, program):
624
+ self.stream.write(b"<BlastOutput_program>%b</BlastOutput_program>\n" % program)
625
+
626
+ def _write_version(self, version):
627
+ self.stream.write(b"<BlastOutput_version>%b</BlastOutput_version>\n" % version)
628
+
629
+ def _write_reference(self, reference):
630
+ self.stream.write(
631
+ b"<BlastOutput_reference>%b</BlastOutput_reference>\n" % reference
632
+ )
633
+
634
+ def _write_db(self, db):
635
+ self.stream.write(b"<BlastOutput_db>%b</BlastOutput_db>\n" % db)
636
+
637
+ def _write_query_id(self, query_id):
638
+ self.stream.write(
639
+ b"<BlastOutput_query-ID>%b</BlastOutput_query-ID>\n" % query_id
640
+ )
641
+
642
+ def _write_query_def(self, query_def):
643
+ self.stream.write(
644
+ b"<BlastOutput_query-def>%b</BlastOutput_query-def>\n" % query_def
645
+ )
646
+
647
+ def _write_query_len(self, query_len):
648
+ self.stream.write(
649
+ b"<BlastOutput_query-len>%d</BlastOutput_query-len>\n" % query_len
650
+ )
651
+
652
+ def _write_query_seq(self, query_seq):
653
+ self.stream.write(
654
+ b"<BlastOutput_query-seq>%b</BlastOutput_query-seq>\n" % query_seq
655
+ )
656
+
657
+ def _start_param(self):
658
+ self.stream.write(
659
+ b"""\
660
+ <BlastOutput_param>
661
+ <Parameters>
662
+ """
663
+ )
664
+
665
+ def _end_param(self):
666
+ self.stream.write(
667
+ b"""\
668
+ </Parameters>
669
+ </BlastOutput_param>
670
+ """
671
+ )
672
+
673
+ def _start_iterations(self):
674
+ self.stream.write(b"<BlastOutput_iterations>\n")
675
+
676
+ def _end_iterations(self):
677
+ self.stream.write(b"</BlastOutput_iterations>\n")
678
+
679
+ def _start_mbstat(self):
680
+ self.stream.write(b" <BlastOutput_mbstat>\n")
681
+
682
+ def _end_mbstat(self):
683
+ self.stream.write(b" </BlastOutput_mbstat>\n")
684
+
685
+ def _start_iteration(self, record):
686
+ self.stream.write(b"<Iteration>\n")
687
+ self._write_iteration_num(record.num)
688
+
689
+ def _end_iteration(self):
690
+ self.stream.write(b"</Iteration>\n")
691
+
692
+ def _write_iteration_num(self, num):
693
+ self.stream.write(b" <Iteration_iter-num>%d</Iteration_iter-num>\n" % num)
694
+
695
+ def _write_iteration_query_id(self, query_id):
696
+ self.stream.write(b"<Iteration_query-ID>%b</Iteration_query-ID>\n" % query_id)
697
+
698
+ def _write_iteration_query_def(self, query_def):
699
+ self.stream.write(
700
+ b"<Iteration_query-def>%b</Iteration_query-def>\n" % query_def
701
+ )
702
+
703
+ def _write_iteration_query_len(self, query_len):
704
+ self.stream.write(
705
+ b"<Iteration_query-len>%d</Iteration_query-len>\n" % query_len
706
+ )
707
+
708
+ def _start_iteration_hits(self):
709
+ self.stream.write(b"<Iteration_hits>\n")
710
+
711
+ def _end_iteration_hits(self):
712
+ self.stream.write(b"</Iteration_hits>\n")
713
+
714
+ def _start_iteration_stat(self):
715
+ self.stream.write(b" <Iteration_stat>\n")
716
+
717
+ def _end_iteration_stat(self):
718
+ self.stream.write(b" </Iteration_stat>\n")
719
+
720
+ def _write_parameters_matrix(self, value):
721
+ self.stream.write(b" <Parameters_matrix>%b</Parameters_matrix>\n" % value)
722
+
723
+ def _write_parameters_expect(self, value):
724
+ self.stream.write(b" <Parameters_expect>%g</Parameters_expect>\n" % value)
725
+
726
+ def _write_parameters_include(self, value):
727
+ self.stream.write(
728
+ b" <Parameters_include>%g</Parameters_include>\n" % value
729
+ )
730
+
731
+ def _write_parameters_sc_match(self, value):
732
+ self.stream.write(
733
+ b" <Parameters_sc-match>%d</Parameters_sc-match>\n" % value
734
+ )
735
+
736
+ def _write_parameters_sc_mismatch(self, value):
737
+ self.stream.write(
738
+ b" <Parameters_sc-mismatch>%d</Parameters_sc-mismatch>\n" % value
739
+ )
740
+
741
+ def _write_parameters_gap_open(self, value):
742
+ self.stream.write(
743
+ b" <Parameters_gap-open>%d</Parameters_gap-open>\n" % value
744
+ )
745
+
746
+ def _write_parameters_gap_extend(self, value):
747
+ self.stream.write(
748
+ b" <Parameters_gap-extend>%d</Parameters_gap-extend>\n" % value
749
+ )
750
+
751
+ def _write_parameters_filter(self, value):
752
+ self.stream.write(b" <Parameters_filter>%b</Parameters_filter>\n" % value)
753
+
754
+ def _write_parameters_pattern(self, value):
755
+ self.stream.write(
756
+ b" <Parameters_pattern>%b</Parameters_pattern>\n" % value
757
+ )
758
+
759
+ def _write_parameters_entrez_query(self, value):
760
+ self.stream.write(
761
+ b" <Parameters_entrez-query>%b</Parameters_entrez-query>\n" % value
762
+ )
763
+
764
+ def _write_statistics_db_num(self, db_num):
765
+ self.stream.write(b" <Statistics_db-num>%d</Statistics_db-num>\n" % db_num)
766
+
767
+ def _write_statistics_db_len(self, db_len):
768
+ self.stream.write(b" <Statistics_db-len>%d</Statistics_db-len>\n" % db_len)
769
+
770
+ def _write_statistics_hsp_len(self, hsp_len):
771
+ self.stream.write(
772
+ b" <Statistics_hsp-len>%d</Statistics_hsp-len>\n" % hsp_len
773
+ )
774
+
775
+ def _write_statistics_eff_space(self, value):
776
+ self.stream.write(
777
+ b" <Statistics_eff-space>%s</Statistics_eff-space>\n" % value
778
+ )
779
+
780
+ def _write_statistics_kappa(self, value):
781
+ self.stream.write(b" <Statistics_kappa>%r</Statistics_kappa>\n" % value)
782
+
783
+ def _write_statistics_lambda(self, value):
784
+ self.stream.write(b" <Statistics_lambda>%r</Statistics_lambda>\n" % value)
785
+
786
+ def _write_statistics_entropy(self, value):
787
+ self.stream.write(
788
+ b" <Statistics_entropy>%r</Statistics_entropy>\n" % value
789
+ )
790
+
791
+ def _start_iteration_hit(self):
792
+ self.stream.write(b"<Hit>\n")
793
+
794
+ def _end_iteration_hit(self):
795
+ self.stream.write(b"</Hit>\n")
796
+
797
+ def _write_hit_num(self, num):
798
+ self.stream.write(b" <Hit_num>%d</Hit_num>\n" % num)
799
+
800
+ def _write_hit_id(self, hit_id):
801
+ self.stream.write(b" <Hit_id>%b</Hit_id>\n" % hit_id)
802
+
803
+ def _write_hit_def(self, hit_def):
804
+ self.stream.write(b" <Hit_def>%b</Hit_def>\n" % hit_def)
805
+
806
+ def _write_hit_accession(self, hit_accession):
807
+ self.stream.write(b" <Hit_accession>%b</Hit_accession>\n" % hit_accession)
808
+
809
+ def _write_hit_len(self, hit_length):
810
+ self.stream.write(b" <Hit_len>%d</Hit_len>\n" % hit_length)
811
+
812
+ def _start_hit_hsps(self):
813
+ self.stream.write(b" <Hit_hsps>\n")
814
+
815
+ def _end_hit_hsps(self):
816
+ self.stream.write(b" </Hit_hsps>\n")
817
+
818
+ def _start_hsp(self):
819
+ self.stream.write(b" <Hsp>\n")
820
+
821
+ def _end_hsp(self):
822
+ self.stream.write(b" </Hsp>\n")
823
+
824
+ def _write_hsp_num(self, num):
825
+ self.stream.write(b" <Hsp_num>%d</Hsp_num>\n" % num)
826
+
827
+ def _write_hsp_bit_score(self, bit_score):
828
+ self.stream.write(b" <Hsp_bit-score>%b</Hsp_bit-score>\n" % bit_score)
829
+
830
+ def _write_hsp_score(self, score):
831
+ self.stream.write(b" <Hsp_score>%d</Hsp_score>\n" % score)
832
+
833
+ def _write_hsp_evalue(self, evalue):
834
+ self.stream.write(b" <Hsp_evalue>%b</Hsp_evalue>\n" % evalue)
835
+
836
+ def _write_hsp_query_from(self, query_from):
837
+ self.stream.write(b" <Hsp_query-from>%d</Hsp_query-from>\n" % query_from)
838
+
839
+ def _write_hsp_query_to(self, query_to):
840
+ self.stream.write(b" <Hsp_query-to>%d</Hsp_query-to>\n" % query_to)
841
+
842
+ def _write_hsp_hit_from(self, hit_from):
843
+ self.stream.write(b" <Hsp_hit-from>%d</Hsp_hit-from>\n" % hit_from)
844
+
845
+ def _write_hsp_hit_to(self, hit_to):
846
+ self.stream.write(b" <Hsp_hit-to>%d</Hsp_hit-to>\n" % hit_to)
847
+
848
+ def _write_hsp_pattern_from(self, pattern_from):
849
+ self.stream.write(
850
+ b" <Hsp_pattern-from>%d</Hsp_pattern-from>\n" % pattern_from
851
+ )
852
+
853
+ def _write_hsp_pattern_to(self, pattern_to):
854
+ self.stream.write(b" <Hsp_pattern-to>%d</Hsp_pattern-to>\n" % pattern_to)
855
+
856
+ def _write_hsp_query_frame(self, query_frame):
857
+ self.stream.write(b" <Hsp_query-frame>%d</Hsp_query-frame>\n" % query_frame)
858
+
859
+ def _write_hsp_hit_frame(self, hit_frame):
860
+ self.stream.write(b" <Hsp_hit-frame>%d</Hsp_hit-frame>\n" % hit_frame)
861
+
862
+ def _write_hsp_identity(self, identity):
863
+ self.stream.write(b" <Hsp_identity>%d</Hsp_identity>\n" % identity)
864
+
865
+ def _write_hsp_positive(self, positive):
866
+ self.stream.write(b" <Hsp_positive>%d</Hsp_positive>\n" % positive)
867
+
868
+ def _write_hsp_gaps(self, gaps):
869
+ self.stream.write(b" <Hsp_gaps>%d</Hsp_gaps>\n" % gaps)
870
+
871
+ def _write_hsp_align_len(self, align_len):
872
+ self.stream.write(b" <Hsp_align-len>%d</Hsp_align-len>\n" % align_len)
873
+
874
+ def _write_hsp_density(self, density):
875
+ self.stream.write(b" <Hsp_density>%d</Hsp_density>\n" % density)
876
+
877
+ def _write_hsp_qseq(self, qseq):
878
+ self.stream.write(b" <Hsp_qseq>%b</Hsp_qseq>\n" % qseq)
879
+
880
+ def _write_hsp_hseq(self, hseq):
881
+ self.stream.write(b" <Hsp_hseq>%b</Hsp_hseq>\n" % hseq)
882
+
883
+ def _write_hsp_midline(self, midline):
884
+ self.stream.write(b" <Hsp_midline>%b</Hsp_midline>\n" % midline)
885
+
886
+
887
+ class XML2Writer(BaseXMLWriter):
888
+ """XML2 Writer."""
889
+
890
+ def _start_blastoutput(self):
891
+ self.stream.write(
892
+ b"""\
893
+ <BlastXML2
894
+ xmlns="http://www.ncbi.nlm.nih.gov"
895
+ xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
896
+ xs:schemaLocation="http://www.ncbi.nlm.nih.gov http://www.ncbi.nlm.nih.gov/data_specs/schema_alt/NCBI_BlastOutput2.xsd"
897
+ >
898
+ <BlastOutput2>
899
+ <report>
900
+ <Report>
901
+ """
902
+ )
903
+
904
+ def _end_blastoutput(self):
905
+ self.stream.write(
906
+ b"""\
907
+ </Report>
908
+ </report>
909
+ </BlastOutput2>
910
+ </BlastXML2>
911
+ """
912
+ )
913
+
914
+ def _write_program(self, program):
915
+ self.stream.write(b" <program>%b</program>\n" % program)
916
+
917
+ def _write_version(self, version):
918
+ self.stream.write(b" <version>%b</version>\n" % version)
919
+
920
+ def _write_reference(self, reference):
921
+ self.stream.write(b" <reference>%b</reference>\n" % reference)
922
+
923
+ def _write_db(self, db):
924
+ self.stream.write(
925
+ b"""\
926
+ <search-target>
927
+ <Target>
928
+ <db>%b</db>
929
+ </Target>
930
+ </search-target>
931
+ """
932
+ % db
933
+ )
934
+
935
+ def _start_param(self):
936
+ self.stream.write(
937
+ b"""\
938
+ <params>
939
+ <Parameters>
940
+ """
941
+ )
942
+
943
+ def _end_param(self):
944
+ self.stream.write(
945
+ b"""\
946
+ </Parameters>
947
+ </params>
948
+ """
949
+ )
950
+
951
+ def _start_iterations(self):
952
+ self.stream.write(
953
+ b"""\
954
+ <results>
955
+ <Results>
956
+ """
957
+ )
958
+
959
+ def _end_iterations(self):
960
+ self.stream.write(
961
+ b"""\
962
+ </Results>
963
+ </results>
964
+ """
965
+ )
966
+
967
+ def _start_iteration(self, record):
968
+ try:
969
+ num = record.num
970
+ except AttributeError:
971
+ pass
972
+ else: # PSIBLAST
973
+ self.stream.write(
974
+ b"""\
975
+ <Iteration>
976
+ """
977
+ )
978
+ self._write_iteration_num(num)
979
+ self.stream.write(
980
+ b"""\
981
+ <search>
982
+ <Search>
983
+ """
984
+ )
985
+
986
+ def _end_iteration(self):
987
+ self.stream.write(
988
+ b"""\
989
+ </Search>
990
+ </search>
991
+ """
992
+ )
993
+ if self._program == "psiblast":
994
+ self.stream.write(
995
+ b"""\
996
+ </Iteration>
997
+ """
998
+ )
999
+
1000
+ def _write_iteration_num(self, num):
1001
+ self.stream.write(b" <iter-num>%d</iter-num>\n" % num)
1002
+
1003
+ def _write_iteration_query_id(self, query_id):
1004
+ self.stream.write(
1005
+ b"""\
1006
+ <query-id>%b</query-id>
1007
+ """
1008
+ % query_id
1009
+ )
1010
+
1011
+ def _write_iteration_query_def(self, query_def):
1012
+ self.stream.write(
1013
+ b"""\
1014
+ <query-title>%b</query-title>
1015
+ """
1016
+ % query_def
1017
+ )
1018
+
1019
+ def _write_iteration_query_len(self, query_len):
1020
+ self.stream.write(
1021
+ b"""\
1022
+ <query-len>%d</query-len>
1023
+ """
1024
+ % query_len
1025
+ )
1026
+
1027
+ def _write_iteration_query_masking(self, location):
1028
+ self.stream.write(
1029
+ b"""\
1030
+ <query-masking>
1031
+ <Range>
1032
+ <from>%d</from>
1033
+ <to>%d</to>
1034
+ </Range>
1035
+ </query-masking>
1036
+ """
1037
+ % (location.start + 1, location.end)
1038
+ )
1039
+
1040
+ def _start_iteration_hits(self):
1041
+ self.stream.write(
1042
+ b"""\
1043
+ <hits>
1044
+ """
1045
+ )
1046
+
1047
+ def _end_iteration_hits(self):
1048
+ self.stream.write(
1049
+ b"""\
1050
+ </hits>
1051
+ """
1052
+ )
1053
+
1054
+ def _start_iteration_stat(self):
1055
+ self.stream.write(
1056
+ b"""\
1057
+ <stat>
1058
+ """
1059
+ )
1060
+
1061
+ def _end_iteration_stat(self):
1062
+ self.stream.write(
1063
+ b"""\
1064
+ </stat>
1065
+ """
1066
+ )
1067
+
1068
+ def _write_parameters_matrix(self, value):
1069
+ self.stream.write(
1070
+ b"""\
1071
+ <matrix>%b</matrix>
1072
+ """
1073
+ % value
1074
+ )
1075
+
1076
+ def _write_parameters_expect(self, value):
1077
+ self.stream.write(
1078
+ b"""\
1079
+ <expect>%g</expect>
1080
+ """
1081
+ % value
1082
+ )
1083
+
1084
+ def _write_parameters_include(self, value):
1085
+ self.stream.write(
1086
+ b"""\
1087
+ <include>%g</include>
1088
+ """
1089
+ % value
1090
+ )
1091
+
1092
+ def _write_parameters_sc_match(self, value):
1093
+ self.stream.write(
1094
+ b"""\
1095
+ <sc-match>%d</sc-match>
1096
+ """
1097
+ % value
1098
+ )
1099
+
1100
+ def _write_parameters_sc_mismatch(self, value):
1101
+ self.stream.write(
1102
+ b"""\
1103
+ <sc-mismatch>%d</sc-mismatch>
1104
+ """
1105
+ % value
1106
+ )
1107
+
1108
+ def _write_parameters_gap_open(self, value):
1109
+ self.stream.write(
1110
+ b"""\
1111
+ <gap-open>%d</gap-open>
1112
+ """
1113
+ % value
1114
+ )
1115
+
1116
+ def _write_parameters_gap_extend(self, value):
1117
+ self.stream.write(
1118
+ b"""\
1119
+ <gap-extend>%d</gap-extend>
1120
+ """
1121
+ % value
1122
+ )
1123
+
1124
+ def _write_parameters_filter(self, value):
1125
+ self.stream.write(
1126
+ b"""\
1127
+ <filter>%b</filter>
1128
+ """
1129
+ % value
1130
+ )
1131
+
1132
+ def _write_parameters_pattern(self, value):
1133
+ self.stream.write(
1134
+ b"""\
1135
+ <pattern>%b</pattern>
1136
+ """
1137
+ % value
1138
+ )
1139
+
1140
+ def _write_parameters_entrez_query(self, value):
1141
+ self.stream.write(
1142
+ b"""\
1143
+ <entrez-query>%b</entrez-query>
1144
+ """
1145
+ % value
1146
+ )
1147
+
1148
+ def _write_parameters_cbs(self, value):
1149
+ self.stream.write(
1150
+ b"""\
1151
+ <cbs>%d</cbs>
1152
+ """
1153
+ % value
1154
+ )
1155
+
1156
+ def _write_parameters_query_gencode(self, value):
1157
+ self.stream.write(
1158
+ b"""\
1159
+ <query-gencode>%d</query-gencode>
1160
+ """
1161
+ % value
1162
+ )
1163
+
1164
+ def _write_parameters_db_gencode(self, value):
1165
+ self.stream.write(
1166
+ b"""\
1167
+ <db-gencode>%d</db-gencode>
1168
+ """
1169
+ % value
1170
+ )
1171
+
1172
+ def _write_parameters_bl2seq_mode(self, value):
1173
+ self.stream.write(
1174
+ b"""\
1175
+ <bl2seq-mode>%b</bl2seq-mode>
1176
+ """
1177
+ % value
1178
+ )
1179
+
1180
+ def _write_statistics_db_num(self, db_num):
1181
+ self.stream.write(
1182
+ b"""\
1183
+ <db-num>%d</db-num>
1184
+ """
1185
+ % db_num
1186
+ )
1187
+
1188
+ def _write_statistics_db_len(self, db_len):
1189
+ self.stream.write(
1190
+ b"""\
1191
+ <db-len>%d</db-len>
1192
+ """
1193
+ % db_len
1194
+ )
1195
+
1196
+ def _write_statistics_hsp_len(self, hsp_len):
1197
+ self.stream.write(
1198
+ b"""\
1199
+ <hsp-len>%d</hsp-len>
1200
+ """
1201
+ % hsp_len
1202
+ )
1203
+
1204
+ def _write_statistics_eff_space(self, value):
1205
+ self.stream.write(
1206
+ b"""\
1207
+ <eff-space>%s</eff-space>
1208
+ """
1209
+ % value
1210
+ )
1211
+
1212
+ def _write_statistics_kappa(self, value):
1213
+ self.stream.write(
1214
+ b"""\
1215
+ <kappa>%r</kappa>
1216
+ """
1217
+ % value
1218
+ )
1219
+
1220
+ def _write_statistics_lambda(self, value):
1221
+ self.stream.write(
1222
+ b"""\
1223
+ <lambda>%r</lambda>
1224
+ """
1225
+ % value
1226
+ )
1227
+
1228
+ def _write_statistics_entropy(self, value):
1229
+ self.stream.write(
1230
+ b"""\
1231
+ <entropy>%r</entropy>
1232
+ """
1233
+ % value
1234
+ )
1235
+
1236
+ def _start_iteration_hit(self):
1237
+ self.stream.write(
1238
+ b"""\
1239
+ <Hit>
1240
+ """
1241
+ )
1242
+
1243
+ def _end_iteration_hit(self):
1244
+ self.stream.write(
1245
+ b"""\
1246
+ </Hit>
1247
+ """
1248
+ )
1249
+
1250
+ def _write_hit_num(self, num):
1251
+ self.stream.write(
1252
+ b"""\
1253
+ <num>%d</num>
1254
+ """
1255
+ % num
1256
+ )
1257
+
1258
+ def _start_hit_targets(self):
1259
+ self.stream.write(
1260
+ b"""\
1261
+ <description>
1262
+ """
1263
+ )
1264
+
1265
+ def _end_hit_targets(self):
1266
+ self.stream.write(
1267
+ b"""\
1268
+ </description>
1269
+ """
1270
+ )
1271
+
1272
+ def _start_hitdescr(self):
1273
+ self.stream.write(
1274
+ b"""\
1275
+ <HitDescr>
1276
+ """
1277
+ )
1278
+
1279
+ def _end_hitdescr(self):
1280
+ self.stream.write(
1281
+ b"""\
1282
+ </HitDescr>
1283
+ """
1284
+ )
1285
+
1286
+ def _write_hit_id(self, hit_id):
1287
+ self.stream.write(
1288
+ b"""\
1289
+ <id>%b</id>
1290
+ """
1291
+ % hit_id
1292
+ )
1293
+
1294
+ def _write_hit_def(self, hit_def):
1295
+ self.stream.write(
1296
+ b"""\
1297
+ <title>%b</title>
1298
+ """
1299
+ % hit_def
1300
+ )
1301
+
1302
+ def _write_hit_accession(self, hit_accession):
1303
+ self.stream.write(
1304
+ b"""\
1305
+ <accession>%b</accession>
1306
+ """
1307
+ % hit_accession
1308
+ )
1309
+
1310
+ def _write_hit_len(self, hit_length):
1311
+ self.stream.write(
1312
+ b"""\
1313
+ <len>%d</len>
1314
+ """
1315
+ % hit_length
1316
+ )
1317
+
1318
+ def _write_hit_taxid(self, taxid):
1319
+ self.stream.write(
1320
+ b"""\
1321
+ <taxid>%d</taxid>
1322
+ """
1323
+ % taxid
1324
+ )
1325
+
1326
+ def _write_hit_sciname(self, sciname):
1327
+ self.stream.write(
1328
+ b"""\
1329
+ <sciname>%b</sciname>
1330
+ """
1331
+ % sciname
1332
+ )
1333
+
1334
+ def _start_hit_hsps(self):
1335
+ self.stream.write(
1336
+ b"""\
1337
+ <hsps>
1338
+ """
1339
+ )
1340
+
1341
+ def _end_hit_hsps(self):
1342
+ self.stream.write(
1343
+ b"""\
1344
+ </hsps>
1345
+ """
1346
+ )
1347
+
1348
+ def _start_hsp(self):
1349
+ self.stream.write(
1350
+ b"""\
1351
+ <Hsp>
1352
+ """
1353
+ )
1354
+
1355
+ def _end_hsp(self):
1356
+ self.stream.write(
1357
+ b"""\
1358
+ </Hsp>
1359
+ """
1360
+ )
1361
+
1362
+ def _write_hsp_num(self, num):
1363
+ self.stream.write(
1364
+ b"""\
1365
+ <num>%d</num>
1366
+ """
1367
+ % num
1368
+ )
1369
+
1370
+ def _write_hsp_bit_score(self, bit_score):
1371
+ self.stream.write(
1372
+ b"""\
1373
+ <bit-score>%b</bit-score>
1374
+ """
1375
+ % bit_score
1376
+ )
1377
+
1378
+ def _write_hsp_score(self, score):
1379
+ self.stream.write(
1380
+ b"""\
1381
+ <score>%d</score>
1382
+ """
1383
+ % score
1384
+ )
1385
+
1386
+ def _write_hsp_evalue(self, evalue):
1387
+ self.stream.write(
1388
+ b"""\
1389
+ <evalue>%b</evalue>
1390
+ """
1391
+ % evalue
1392
+ )
1393
+
1394
+ def _write_hsp_query_from(self, query_from):
1395
+ self.stream.write(
1396
+ b"""\
1397
+ <query-from>%d</query-from>
1398
+ """
1399
+ % query_from
1400
+ )
1401
+
1402
+ def _write_hsp_query_to(self, query_to):
1403
+ self.stream.write(
1404
+ b"""\
1405
+ <query-to>%d</query-to>
1406
+ """
1407
+ % query_to
1408
+ )
1409
+
1410
+ def _write_hsp_hit_from(self, hit_from):
1411
+ self.stream.write(
1412
+ b"""\
1413
+ <hit-from>%d</hit-from>
1414
+ """
1415
+ % hit_from
1416
+ )
1417
+
1418
+ def _write_hsp_hit_to(self, hit_to):
1419
+ self.stream.write(
1420
+ b"""\
1421
+ <hit-to>%d</hit-to>
1422
+ """
1423
+ % hit_to
1424
+ )
1425
+
1426
+ def _write_hsp_pattern_from(self, pattern_from):
1427
+ self.stream.write(
1428
+ b"""\
1429
+ <pattern-from>%d</pattern-from>
1430
+ """
1431
+ % pattern_from
1432
+ )
1433
+
1434
+ def _write_hsp_pattern_to(self, pattern_to):
1435
+ self.stream.write(
1436
+ b"""\
1437
+ <pattern-to>%d</pattern-to>
1438
+ """
1439
+ % pattern_to
1440
+ )
1441
+
1442
+ def _write_hsp_query_frame(self, query_frame):
1443
+ self.stream.write(
1444
+ b"""\
1445
+ <query-frame>%d</query-frame>
1446
+ """
1447
+ % query_frame
1448
+ )
1449
+
1450
+ def _write_hsp_hit_frame(self, hit_frame):
1451
+ self.stream.write(
1452
+ b"""\
1453
+ <hit-frame>%d</hit-frame>
1454
+ """
1455
+ % hit_frame
1456
+ )
1457
+
1458
+ def _write_hsp_identity(self, identity):
1459
+ self.stream.write(
1460
+ b"""\
1461
+ <identity>%d</identity>
1462
+ """
1463
+ % identity
1464
+ )
1465
+
1466
+ def _write_hsp_positive(self, positive):
1467
+ self.stream.write(
1468
+ b"""\
1469
+ <positive>%d</positive>
1470
+ """
1471
+ % positive
1472
+ )
1473
+
1474
+ def _write_hsp_gaps(self, gaps):
1475
+ self.stream.write(
1476
+ b"""\
1477
+ <gaps>%d</gaps>
1478
+ """
1479
+ % gaps
1480
+ )
1481
+
1482
+ def _write_hsp_align_len(self, align_len):
1483
+ self.stream.write(
1484
+ b"""\
1485
+ <align-len>%d</align-len>
1486
+ """
1487
+ % align_len
1488
+ )
1489
+
1490
+ def _write_hsp_density(self, density):
1491
+ self.stream.write(
1492
+ b"""\
1493
+ <density>%d</density>
1494
+ """
1495
+ % density
1496
+ )
1497
+
1498
+ def _write_hsp_qseq(self, qseq):
1499
+ self.stream.write(
1500
+ b"""\
1501
+ <qseq>%b</qseq>
1502
+ """
1503
+ % qseq
1504
+ )
1505
+
1506
+ def _write_hsp_hseq(self, hseq):
1507
+ self.stream.write(
1508
+ b"""\
1509
+ <hseq>%b</hseq>
1510
+ """
1511
+ % hseq
1512
+ )
1513
+
1514
+ def _write_hsp_midline(self, midline):
1515
+ self.stream.write(
1516
+ b"""\
1517
+ <midline>%b</midline>
1518
+ """
1519
+ % midline
1520
+ )
.venv_haddock/lib/python3.12/site-packages/Bio/CAPS/.___init__.py ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/CAPS/.___pycache__ ADDED
Binary file (4.1 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/CAPS/__init__.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2005 by Jonathan Taylor.
2
+ # All rights reserved.
3
+ # This code is part of the Biopython distribution and governed by its
4
+ # license. Please see the LICENSE file that should have been included
5
+ # as part of this package.
6
+ """Cleaved amplified polymorphic sequence (CAPS) markers.
7
+
8
+ A CAPS marker is a location a DifferentialCutsite as described below and a
9
+ set of primers that can be used to visualize this. More information can
10
+ be found in the paper `Konieczny and Ausubel (1993)`_ (PMID 8106085).
11
+
12
+ .. _`Konieczny and Ausubel (1993)`: https://doi.org/10.1046/j.1365-313X.1993.04020403.x
13
+
14
+ """
15
+
16
+ from Bio.Align import MultipleSeqAlignment
17
+ from Bio.Seq import Seq
18
+
19
+
20
+ class DifferentialCutsite:
21
+ """Differential enzyme cutsite in an alignment.
22
+
23
+ A differential cutsite is a location in an alignment where an enzyme cuts
24
+ at least one sequence and also cannot cut at least one other sequence.
25
+
26
+ Members:
27
+ - start - Where it lives in the alignment.
28
+ - enzyme - The enzyme that causes this.
29
+ - cuts_in - A list of sequences (as indexes into the alignment) the
30
+ enzyme cuts in.
31
+ - blocked_in - A list of sequences (as indexes into the alignment) the
32
+ enzyme is blocked in.
33
+
34
+ """
35
+
36
+ def __init__(self, **kwds):
37
+ """Initialize a DifferentialCutsite.
38
+
39
+ Each member (as listed in the class description) should be included as a
40
+ keyword.
41
+ """
42
+ self.start = int(kwds["start"])
43
+ self.enzyme = kwds["enzyme"]
44
+ self.cuts_in = kwds["cuts_in"]
45
+ self.blocked_in = kwds["blocked_in"]
46
+
47
+
48
+ class AlignmentHasDifferentLengthsError(Exception):
49
+ """Exception where sequences in alignment have different lengths."""
50
+
51
+
52
+ class CAPSMap:
53
+ """A map of an alignment showing all possible dcuts.
54
+
55
+ Members:
56
+ - alignment - The alignment that is mapped.
57
+ - dcuts - A list of possible CAPS markers in the form of
58
+ DifferentialCutsites.
59
+
60
+ """
61
+
62
+ def __init__(self, alignment, enzymes=None):
63
+ """Initialize the CAPSMap.
64
+
65
+ Required:
66
+ - alignment - The alignment to be mapped.
67
+
68
+ Optional:
69
+ - enzymes - List of enzymes to be used to create the map.
70
+ Defaults to an empty list.
71
+
72
+ """
73
+ if enzymes is None:
74
+ enzymes = []
75
+ if isinstance(alignment, MultipleSeqAlignment):
76
+ self.sequences = [rec.seq for rec in alignment]
77
+ self.size = len(self.sequences)
78
+ self.length = len(self.sequences[0])
79
+ for seq in self.sequences:
80
+ if len(seq) != self.length:
81
+ raise AlignmentHasDifferentLengthsError
82
+ else: # Alignment object
83
+ self.sequences = [Seq(s) for s in alignment]
84
+ self.size, self.length = alignment.shape
85
+
86
+ self.alignment = alignment
87
+ self.enzymes = enzymes
88
+
89
+ # look for dcuts
90
+ self._digest()
91
+
92
+ def _digest_with(self, enzyme):
93
+ cuts = [] # list of lists, one per sequence
94
+ all_seq_cuts = []
95
+
96
+ # go through each sequence
97
+ for seq in self.sequences:
98
+ # grab all the cuts in the sequence
99
+ seq_cuts = [cut - enzyme.fst5 for cut in enzyme.search(seq)]
100
+ # maintain a list of all cuts in all sequences
101
+ all_seq_cuts.extend(seq_cuts)
102
+ cuts.append(seq_cuts)
103
+
104
+ # we sort the all list and remove duplicates
105
+ all_seq_cuts = sorted(set(all_seq_cuts))
106
+
107
+ for cut in all_seq_cuts:
108
+ # test for dcuts
109
+
110
+ cuts_in = []
111
+ blocked_in = []
112
+
113
+ for i, seq in enumerate(self.sequences):
114
+ if cut in cuts[i]:
115
+ cuts_in.append(i)
116
+ else:
117
+ blocked_in.append(i)
118
+
119
+ if cuts_in and blocked_in:
120
+ self.dcuts.append(
121
+ DifferentialCutsite(
122
+ start=cut, enzyme=enzyme, cuts_in=cuts_in, blocked_in=blocked_in
123
+ )
124
+ )
125
+
126
+ def _digest(self):
127
+ self.dcuts = []
128
+
129
+ for enzyme in self.enzymes:
130
+ self._digest_with(enzyme)
.venv_haddock/lib/python3.12/site-packages/Bio/Cluster/.___init__.py ADDED
Binary file (4.1 kB). View file