bioalign 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bioalign/__init__.py +35 -0
- bioalign/cli.py +183 -0
- bioalign/core.py +442 -0
- bioalign/export.py +146 -0
- bioalign/phylo.py +268 -0
- bioalign/remote.py +148 -0
- bioalign-0.1.0.dist-info/METADATA +108 -0
- bioalign-0.1.0.dist-info/RECORD +12 -0
- bioalign-0.1.0.dist-info/WHEEL +5 -0
- bioalign-0.1.0.dist-info/entry_points.txt +2 -0
- bioalign-0.1.0.dist-info/licenses/LICENSE +21 -0
- bioalign-0.1.0.dist-info/top_level.txt +1 -0
bioalign/export.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import Sequence, Union
|
|
5
|
+
|
|
6
|
+
from .core import BioAlignError, SequenceRecord, compute_alignment_stats, detect_sequence_type
|
|
7
|
+
|
|
8
|
+
SUPPORTED_FORMATS = ("fasta", "clustal", "phylip", "stockholm", "msf", "nexus")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _wrap(seq: str, width: int = 60) -> str:
|
|
12
|
+
return "\n".join(seq[i : i + width] for i in range(0, len(seq), width))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _clustal_conservation_line(records: Sequence[SequenceRecord], start: int, end: int) -> str:
|
|
16
|
+
strong_groups = (
|
|
17
|
+
set("STA"),
|
|
18
|
+
set("NEQK"),
|
|
19
|
+
set("NHQK"),
|
|
20
|
+
set("NDEQ"),
|
|
21
|
+
set("QHRK"),
|
|
22
|
+
set("MILV"),
|
|
23
|
+
set("MILF"),
|
|
24
|
+
set("HY"),
|
|
25
|
+
set("FYW"),
|
|
26
|
+
)
|
|
27
|
+
weak_groups = (
|
|
28
|
+
set("CSA"),
|
|
29
|
+
set("ATV"),
|
|
30
|
+
set("SAG"),
|
|
31
|
+
set("STNK"),
|
|
32
|
+
set("STPA"),
|
|
33
|
+
set("SGND"),
|
|
34
|
+
set("SNDEQK"),
|
|
35
|
+
set("NDEQHK"),
|
|
36
|
+
set("NEQHRK"),
|
|
37
|
+
set("FVLIM"),
|
|
38
|
+
set("HFY"),
|
|
39
|
+
)
|
|
40
|
+
marks = []
|
|
41
|
+
for col in range(start, end):
|
|
42
|
+
chars = [r.seq[col].upper() for r in records]
|
|
43
|
+
if any(c in ("-", ".") for c in chars):
|
|
44
|
+
marks.append(" ")
|
|
45
|
+
continue
|
|
46
|
+
uniq = set(chars)
|
|
47
|
+
if len(uniq) == 1:
|
|
48
|
+
marks.append("*")
|
|
49
|
+
elif any(uniq.issubset(g) for g in strong_groups):
|
|
50
|
+
marks.append(":")
|
|
51
|
+
elif any(uniq.issubset(g) for g in weak_groups):
|
|
52
|
+
marks.append(".")
|
|
53
|
+
else:
|
|
54
|
+
marks.append(" ")
|
|
55
|
+
return "".join(marks)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def format_alignment(
|
|
59
|
+
records: Sequence[SequenceRecord],
|
|
60
|
+
fmt: str = "fasta",
|
|
61
|
+
sequence_type: Union[str, None] = None,
|
|
62
|
+
) -> str:
|
|
63
|
+
"""Format an aligned sequence collection into FASTA, Clustal, PHYLIP, Stockholm, MSF, or NEXUS."""
|
|
64
|
+
if not records:
|
|
65
|
+
raise BioAlignError("No aligned records supplied.")
|
|
66
|
+
lengths = {len(r.seq) for r in records}
|
|
67
|
+
if len(lengths) != 1:
|
|
68
|
+
raise BioAlignError("All sequences must have equal aligned length before formatting.")
|
|
69
|
+
|
|
70
|
+
f = fmt.lower().strip()
|
|
71
|
+
if f not in SUPPORTED_FORMATS:
|
|
72
|
+
raise BioAlignError(f"Unsupported format '{fmt}'; choose from {', '.join(SUPPORTED_FORMATS)}.")
|
|
73
|
+
|
|
74
|
+
aln_len = len(records[0].seq)
|
|
75
|
+
seq_type = sequence_type or detect_sequence_type(records)
|
|
76
|
+
|
|
77
|
+
if f == "fasta":
|
|
78
|
+
blocks = []
|
|
79
|
+
for r in records:
|
|
80
|
+
hdr = f">{r.id}" + (f" {r.description}" if r.description else "")
|
|
81
|
+
blocks.append(f"{hdr}\n{_wrap(r.seq, 60)}")
|
|
82
|
+
return "\n".join(blocks) + "\n"
|
|
83
|
+
|
|
84
|
+
if f == "clustal":
|
|
85
|
+
pad = min(28, max(12, *(len(r.id) for r in records)))
|
|
86
|
+
out = ["CLUSTAL W (1.83) multiple sequence alignment\n"]
|
|
87
|
+
for pos in range(0, aln_len, 60):
|
|
88
|
+
end = min(aln_len, pos + 60)
|
|
89
|
+
for r in records:
|
|
90
|
+
clean = re.sub(r"\s+", "_", r.id)[:pad]
|
|
91
|
+
out.append(f"{clean.ljust(pad + 4)}{r.seq[pos:end]}")
|
|
92
|
+
out.append(f"{' ' * (pad + 4)}{_clustal_conservation_line(records, pos, end)}\n")
|
|
93
|
+
return "\n".join(out)
|
|
94
|
+
|
|
95
|
+
if f == "phylip":
|
|
96
|
+
lines = [f" {len(records)} {aln_len}"]
|
|
97
|
+
for idx, r in enumerate(records):
|
|
98
|
+
short = re.sub(r"\s+", "_", r.id)[:9] or f"Seq_{idx + 1}"
|
|
99
|
+
lines.append(f"{short.ljust(10)} {r.seq}")
|
|
100
|
+
return "\n".join(lines) + "\n"
|
|
101
|
+
|
|
102
|
+
if f == "stockholm":
|
|
103
|
+
pad = min(30, max(14, *(len(r.id) for r in records)))
|
|
104
|
+
stats = compute_alignment_stats(records)
|
|
105
|
+
cons = str(stats["consensus"])
|
|
106
|
+
lines = ["# STOCKHOLM 1.0", "#=GF ID BioAlign_MSA", ""]
|
|
107
|
+
for r in records:
|
|
108
|
+
clean = re.sub(r"\s+", "_", r.id)[:pad]
|
|
109
|
+
lines.append(f"{clean.ljust(pad + 2)}{r.seq}")
|
|
110
|
+
lines.append(f"{'#=GC seq_cons'.ljust(pad + 2)}{cons}")
|
|
111
|
+
lines.append("//\n")
|
|
112
|
+
return "\n".join(lines)
|
|
113
|
+
|
|
114
|
+
if f == "msf":
|
|
115
|
+
pad = min(20, max(10, *(len(r.id) for r in records)))
|
|
116
|
+
mol_flag = "P" if seq_type == "protein" else "N"
|
|
117
|
+
lines = ["PileUp", "", f" MSF: {aln_len} Type: {mol_flag} Check: 0000 ..", ""]
|
|
118
|
+
for r in records:
|
|
119
|
+
clean = re.sub(r"\s+", "_", r.id)[:pad]
|
|
120
|
+
lines.append(f" Name: {clean.ljust(pad + 2)} Len: {aln_len} Check: 0000 Weight: 1.00")
|
|
121
|
+
lines.append("\n//\n")
|
|
122
|
+
for pos in range(0, aln_len, 50):
|
|
123
|
+
for r in records:
|
|
124
|
+
clean = re.sub(r"\s+", "_", r.id)[:pad]
|
|
125
|
+
chunk = r.seq[pos : pos + 50]
|
|
126
|
+
grouped = " ".join(chunk[k : k + 10] for k in range(0, len(chunk), 10))
|
|
127
|
+
lines.append(f"{clean.ljust(pad + 3)}{grouped}")
|
|
128
|
+
lines.append("")
|
|
129
|
+
return "\n".join(lines) + "\n"
|
|
130
|
+
|
|
131
|
+
datatype = "DNA" if seq_type == "dna" else ("RNA" if seq_type == "rna" else "PROTEIN")
|
|
132
|
+
pad = min(24, max(12, *(len(r.id) for r in records)))
|
|
133
|
+
lines = [
|
|
134
|
+
"#NEXUS",
|
|
135
|
+
"",
|
|
136
|
+
"BEGIN DATA;",
|
|
137
|
+
f" DIMENSIONS NTAX={len(records)} NCHAR={aln_len};",
|
|
138
|
+
f" FORMAT DATATYPE={datatype} GAP=- MISSING=?;",
|
|
139
|
+
" MATRIX",
|
|
140
|
+
]
|
|
141
|
+
for r in records:
|
|
142
|
+
clean = re.sub(r"[^A-Za-z0-9_.-]", "_", r.id)[:pad]
|
|
143
|
+
lines.append(f" {clean.ljust(pad + 2)}{r.seq}")
|
|
144
|
+
lines.append(" ;")
|
|
145
|
+
lines.append("END;\n")
|
|
146
|
+
return "\n".join(lines)
|
bioalign/phylo.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Dict, List, Optional, Sequence, Tuple
|
|
7
|
+
|
|
8
|
+
from .core import BioAlignError, poisson_distance_matrix
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class PhyloNode:
|
|
13
|
+
id: str
|
|
14
|
+
name: str = ""
|
|
15
|
+
branch_length: float = 0.0
|
|
16
|
+
children: List["PhyloNode"] = field(default_factory=list)
|
|
17
|
+
is_leaf: bool = True
|
|
18
|
+
leaf_count: int = 1
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _build_upgma(names: Sequence[str], dist_mat: Sequence[Sequence[float]]) -> PhyloNode:
|
|
22
|
+
n = len(names)
|
|
23
|
+
if n == 0:
|
|
24
|
+
raise BioAlignError("Cannot construct tree from zero sequences.")
|
|
25
|
+
if n == 1:
|
|
26
|
+
return PhyloNode(id="leaf_0", name=names[0], branch_length=0.05, is_leaf=True, leaf_count=1)
|
|
27
|
+
|
|
28
|
+
clusters: Dict[int, Tuple[PhyloNode, float, int, Dict[int, float]]] = {}
|
|
29
|
+
for i in range(n):
|
|
30
|
+
dmap = {j: float(dist_mat[i][j]) for j in range(n) if j != i}
|
|
31
|
+
node = PhyloNode(id=f"leaf_{i}", name=names[i], branch_length=0.0, is_leaf=True, leaf_count=1)
|
|
32
|
+
clusters[i] = (node, 0.0, 1, dmap)
|
|
33
|
+
|
|
34
|
+
next_id = n
|
|
35
|
+
while len(clusters) > 1:
|
|
36
|
+
keys = list(clusters.keys())
|
|
37
|
+
best_a, best_b = keys[0], keys[1]
|
|
38
|
+
min_d = float("inf")
|
|
39
|
+
for ia in range(len(keys)):
|
|
40
|
+
for ib in range(ia + 1, len(keys)):
|
|
41
|
+
ka, kb = keys[ia], keys[ib]
|
|
42
|
+
d = clusters[ka][3].get(kb, float("inf"))
|
|
43
|
+
if d < min_d:
|
|
44
|
+
min_d = d
|
|
45
|
+
best_a, best_b = ka, kb
|
|
46
|
+
|
|
47
|
+
node_a, h_a, sz_a, d_a = clusters[best_a]
|
|
48
|
+
node_b, h_b, sz_b, d_b = clusters[best_b]
|
|
49
|
+
new_h = max(min_d / 2.0, max(h_a, h_b) + 0.002)
|
|
50
|
+
node_a.branch_length = max(0.002, round(new_h - h_a, 4))
|
|
51
|
+
node_b.branch_length = max(0.002, round(new_h - h_b, 4))
|
|
52
|
+
|
|
53
|
+
merged_node = PhyloNode(
|
|
54
|
+
id=f"node_{next_id}",
|
|
55
|
+
name="",
|
|
56
|
+
branch_length=0.0,
|
|
57
|
+
children=[node_a, node_b],
|
|
58
|
+
is_leaf=False,
|
|
59
|
+
leaf_count=node_a.leaf_count + node_b.leaf_count,
|
|
60
|
+
)
|
|
61
|
+
new_sz = sz_a + sz_b
|
|
62
|
+
new_dmap: Dict[int, float] = {}
|
|
63
|
+
for k, (_, _, _, dk) in clusters.items():
|
|
64
|
+
if k in (best_a, best_b):
|
|
65
|
+
continue
|
|
66
|
+
val = (d_a.get(k, 0.0) * sz_a + d_b.get(k, 0.0) * sz_b) / new_sz
|
|
67
|
+
new_dmap[k] = val
|
|
68
|
+
dk.pop(best_a, None)
|
|
69
|
+
dk.pop(best_b, None)
|
|
70
|
+
dk[next_id] = val
|
|
71
|
+
|
|
72
|
+
del clusters[best_a]
|
|
73
|
+
del clusters[best_b]
|
|
74
|
+
clusters[next_id] = (merged_node, new_h, new_sz, new_dmap)
|
|
75
|
+
next_id += 1
|
|
76
|
+
|
|
77
|
+
return next(iter(clusters.values()))[0]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _build_nj(names: Sequence[str], dist_mat: Sequence[Sequence[float]]) -> PhyloNode:
|
|
81
|
+
n = len(names)
|
|
82
|
+
if n <= 2:
|
|
83
|
+
return _build_upgma(names, dist_mat)
|
|
84
|
+
|
|
85
|
+
nodes: Dict[int, PhyloNode] = {}
|
|
86
|
+
dists: Dict[int, Dict[int, float]] = {}
|
|
87
|
+
for i in range(n):
|
|
88
|
+
nodes[i] = PhyloNode(id=f"leaf_{i}", name=names[i], branch_length=0.0, is_leaf=True, leaf_count=1)
|
|
89
|
+
dists[i] = {j: float(dist_mat[i][j]) for j in range(n) if j != i}
|
|
90
|
+
|
|
91
|
+
next_id = n
|
|
92
|
+
while len(nodes) > 2:
|
|
93
|
+
keys = list(nodes.keys())
|
|
94
|
+
m = len(keys)
|
|
95
|
+
row_sums = {k: sum(dists[k].get(other, 0.0) for other in keys if other != k) for k in keys}
|
|
96
|
+
|
|
97
|
+
best_a, best_b = keys[0], keys[1]
|
|
98
|
+
min_q = float("inf")
|
|
99
|
+
for ia in range(m):
|
|
100
|
+
for ib in range(ia + 1, len(keys)):
|
|
101
|
+
ka, kb = keys[ia], keys[ib]
|
|
102
|
+
q = (m - 2) * dists[ka].get(kb, 0.0) - row_sums[ka] - row_sums[kb]
|
|
103
|
+
if q < min_q:
|
|
104
|
+
min_q = q
|
|
105
|
+
best_a, best_b = ka, kb
|
|
106
|
+
|
|
107
|
+
d_ab = dists[best_a].get(best_b, 0.0)
|
|
108
|
+
limb_a = 0.5 * d_ab + (row_sums[best_a] - row_sums[best_b]) / (2.0 * (m - 2))
|
|
109
|
+
limb_b = d_ab - limb_a
|
|
110
|
+
if limb_a < 0.002:
|
|
111
|
+
limb_b = max(0.002, limb_b + limb_a)
|
|
112
|
+
limb_a = 0.002
|
|
113
|
+
if limb_b < 0.002:
|
|
114
|
+
limb_a = max(0.002, limb_a + limb_b)
|
|
115
|
+
limb_b = 0.002
|
|
116
|
+
|
|
117
|
+
na_node = nodes[best_a]
|
|
118
|
+
nb_node = nodes[best_b]
|
|
119
|
+
na_node.branch_length = round(limb_a, 4)
|
|
120
|
+
nb_node.branch_length = round(limb_b, 4)
|
|
121
|
+
|
|
122
|
+
parent = PhyloNode(
|
|
123
|
+
id=f"node_{next_id}",
|
|
124
|
+
name="",
|
|
125
|
+
branch_length=0.0,
|
|
126
|
+
children=[na_node, nb_node],
|
|
127
|
+
is_leaf=False,
|
|
128
|
+
leaf_count=na_node.leaf_count + nb_node.leaf_count,
|
|
129
|
+
)
|
|
130
|
+
new_d: Dict[int, float] = {}
|
|
131
|
+
for k in keys:
|
|
132
|
+
if k in (best_a, best_b):
|
|
133
|
+
continue
|
|
134
|
+
dk = max(0.0, 0.5 * (dists[best_a].get(k, 0.0) + dists[best_b].get(k, 0.0) - d_ab))
|
|
135
|
+
new_d[k] = dk
|
|
136
|
+
dists[k].pop(best_a, None)
|
|
137
|
+
dists[k].pop(best_b, None)
|
|
138
|
+
dists[k][next_id] = dk
|
|
139
|
+
|
|
140
|
+
del nodes[best_a]
|
|
141
|
+
del nodes[best_b]
|
|
142
|
+
del dists[best_a]
|
|
143
|
+
del dists[best_b]
|
|
144
|
+
nodes[next_id] = parent
|
|
145
|
+
dists[next_id] = new_d
|
|
146
|
+
next_id += 1
|
|
147
|
+
|
|
148
|
+
ka, kb = list(nodes.keys())
|
|
149
|
+
rem = max(0.004, dists[ka].get(kb, 0.05))
|
|
150
|
+
na_node = nodes[ka]
|
|
151
|
+
nb_node = nodes[kb]
|
|
152
|
+
na_node.branch_length = round(rem / 2.0, 4)
|
|
153
|
+
nb_node.branch_length = round(rem / 2.0, 4)
|
|
154
|
+
return PhyloNode(
|
|
155
|
+
id=f"root_{next_id}",
|
|
156
|
+
name="",
|
|
157
|
+
branch_length=0.0,
|
|
158
|
+
children=[na_node, nb_node],
|
|
159
|
+
is_leaf=False,
|
|
160
|
+
leaf_count=na_node.leaf_count + nb_node.leaf_count,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def build_tree(
|
|
165
|
+
names: Sequence[str],
|
|
166
|
+
identity_matrix_pct: Sequence[Sequence[float]],
|
|
167
|
+
method: str = "nj",
|
|
168
|
+
) -> PhyloNode:
|
|
169
|
+
"""Construct a Neighbor-Joining ('nj') or UPGMA ('upgma') tree from pairwise identity (%)."""
|
|
170
|
+
m = method.lower().strip()
|
|
171
|
+
if m not in ("nj", "upgma"):
|
|
172
|
+
raise BioAlignError(f"Unsupported tree method '{method}'; choose 'nj' or 'upgma'.")
|
|
173
|
+
dist_mat = poisson_distance_matrix(identity_matrix_pct)
|
|
174
|
+
if m == "upgma":
|
|
175
|
+
return _build_upgma(names, dist_mat)
|
|
176
|
+
return _build_nj(names, dist_mat)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def to_newick(root: PhyloNode) -> str:
|
|
180
|
+
"""Serialize a PhyloNode tree to standard Newick format."""
|
|
181
|
+
def _fmt(node: PhyloNode, is_root: bool) -> str:
|
|
182
|
+
clean_name = re.sub(r"[:;,()\s]+", "_", node.name)
|
|
183
|
+
bl = "" if is_root else f":{node.branch_length:.4f}"
|
|
184
|
+
if node.is_leaf or not node.children:
|
|
185
|
+
return f"{clean_name}{bl}"
|
|
186
|
+
inner = ",".join(_fmt(ch, False) for ch in node.children)
|
|
187
|
+
return f"({inner}){clean_name}{bl}"
|
|
188
|
+
|
|
189
|
+
return f"{_fmt(root, True)};"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def render_tree_svg(
|
|
193
|
+
root: PhyloNode,
|
|
194
|
+
method_label: str = "Neighbor-Joining",
|
|
195
|
+
cladogram: bool = False,
|
|
196
|
+
width: int = 860,
|
|
197
|
+
row_height: int = 28,
|
|
198
|
+
) -> str:
|
|
199
|
+
"""Render a publication-grade rectangular phylogram or cladogram as SVG."""
|
|
200
|
+
pad_top = 52
|
|
201
|
+
pad_left = 40
|
|
202
|
+
label_space = 250
|
|
203
|
+
plot_w = max(220, width - pad_left - label_space)
|
|
204
|
+
|
|
205
|
+
def _max_path(node: PhyloNode, acc: float) -> float:
|
|
206
|
+
nxt = acc + (0.0 if node is root else (1.0 if cladogram else node.branch_length))
|
|
207
|
+
if node.is_leaf or not node.children:
|
|
208
|
+
return nxt
|
|
209
|
+
return max(_max_path(c, nxt) for c in node.children)
|
|
210
|
+
|
|
211
|
+
def _depth(node: PhyloNode) -> int:
|
|
212
|
+
if node.is_leaf or not node.children:
|
|
213
|
+
return 0
|
|
214
|
+
return 1 + max(_depth(c) for c in node.children)
|
|
215
|
+
|
|
216
|
+
max_depth = max(0.01, _max_path(root, 0.0))
|
|
217
|
+
total_levels = max(1, _depth(root))
|
|
218
|
+
placed: List[Dict[str, object]] = []
|
|
219
|
+
leaf_idx = 0
|
|
220
|
+
|
|
221
|
+
def _layout(node: PhyloNode, acc: float, px: Optional[float]) -> float:
|
|
222
|
+
nonlocal leaf_idx
|
|
223
|
+
cur_acc = acc + (0.0 if node is root else node.branch_length)
|
|
224
|
+
if cladogram:
|
|
225
|
+
x = pad_left + ((total_levels - _depth(node)) / total_levels) * plot_w
|
|
226
|
+
else:
|
|
227
|
+
x = pad_left + (cur_acc / max_depth) * plot_w
|
|
228
|
+
if node.is_leaf or not node.children:
|
|
229
|
+
y = float(pad_top + leaf_idx * row_height)
|
|
230
|
+
leaf_idx += 1
|
|
231
|
+
placed.append({"node": node, "x": x, "y": y, "px": px, "py": None})
|
|
232
|
+
return y
|
|
233
|
+
child_ys = [_layout(c, cur_acc, x) for c in node.children]
|
|
234
|
+
y = (min(child_ys) + max(child_ys)) / 2.0
|
|
235
|
+
for item in placed:
|
|
236
|
+
if item["node"] in node.children:
|
|
237
|
+
item["py"] = y
|
|
238
|
+
placed.append({"node": node, "x": x, "y": y, "px": px, "py": None})
|
|
239
|
+
return y
|
|
240
|
+
|
|
241
|
+
_layout(root, 0.0, None)
|
|
242
|
+
height = max(220, 2 * pad_top + max(1, leaf_idx - 1) * row_height + 36)
|
|
243
|
+
mode_txt = "Cladogram" if cladogram else "Phylogram"
|
|
244
|
+
|
|
245
|
+
lines = [
|
|
246
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
|
|
247
|
+
' <rect width="100%" height="100%" fill="#ffffff"/>',
|
|
248
|
+
' <style>text{font-family:Arial,Helvetica,sans-serif;}</style>',
|
|
249
|
+
f' <text x="{pad_left}" y="26" font-size="13" font-weight="700" fill="#0f172a">BioAlign Phylogenetic Tree ({html.escape(method_label)}, {mode_txt})</text>',
|
|
250
|
+
]
|
|
251
|
+
for item in placed:
|
|
252
|
+
px = item["px"]
|
|
253
|
+
py = item["py"]
|
|
254
|
+
x = float(item["x"])
|
|
255
|
+
y = float(item["y"])
|
|
256
|
+
node = item["node"]
|
|
257
|
+
assert isinstance(node, PhyloNode)
|
|
258
|
+
if px is not None and py is not None:
|
|
259
|
+
lines.append(
|
|
260
|
+
f' <path d="M {px:.2f} {float(py):.2f} L {px:.2f} {y:.2f} L {x:.2f} {y:.2f}" fill="none" stroke="#1d5c6b" stroke-width="1.6"/>'
|
|
261
|
+
)
|
|
262
|
+
if node.is_leaf:
|
|
263
|
+
lines.append(f' <circle cx="{x:.2f}" cy="{y:.2f}" r="2.8" fill="#8b303f"/>')
|
|
264
|
+
lines.append(
|
|
265
|
+
f' <text x="{x + 8:.2f}" y="{y + 4:.2f}" font-size="11.5" fill="#0f172a">{html.escape(node.name)}</text>'
|
|
266
|
+
)
|
|
267
|
+
lines.append("</svg>\n")
|
|
268
|
+
return "\n".join(lines)
|
bioalign/remote.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
import urllib.error
|
|
5
|
+
import urllib.parse
|
|
6
|
+
import urllib.request
|
|
7
|
+
import xml.etree.ElementTree as ET
|
|
8
|
+
from typing import Dict, List, Sequence
|
|
9
|
+
|
|
10
|
+
from .core import BioAlignError, SequenceRecord, align_sequences, detect_sequence_type, parse_fasta
|
|
11
|
+
|
|
12
|
+
EBI_BASE = "https://www.ebi.ac.uk/Tools/services/rest"
|
|
13
|
+
EBI_MSA_ENGINES = ("clustalo", "muscle", "mafft", "tcoffee", "kalign")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _http_post(url: str, params: Dict[str, str], timeout: float = 30.0) -> str:
|
|
17
|
+
data = urllib.parse.urlencode(params).encode("utf-8")
|
|
18
|
+
req = urllib.request.Request(url, data=data, method="POST")
|
|
19
|
+
req.add_header("User-Agent", "bioalign-python/0.1.0")
|
|
20
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
21
|
+
return resp.read().decode("utf-8", "replace").strip()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _http_get(url: str, timeout: float = 30.0) -> str:
|
|
25
|
+
req = urllib.request.Request(url, method="GET")
|
|
26
|
+
req.add_header("User-Agent", "bioalign-python/0.1.0")
|
|
27
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
28
|
+
return resp.read().decode("utf-8", "replace")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _poll_ebi_job(service: str, job_id: str, poll_interval: float = 3.0, max_wait: float = 300.0) -> None:
|
|
32
|
+
deadline = time.monotonic() + max_wait
|
|
33
|
+
status_url = f"{EBI_BASE}/{service}/status/{job_id}"
|
|
34
|
+
while time.monotonic() < deadline:
|
|
35
|
+
status = _http_get(status_url).strip()
|
|
36
|
+
if status == "FINISHED":
|
|
37
|
+
return
|
|
38
|
+
if status in ("ERROR", "FAILURE", "NOT_FOUND"):
|
|
39
|
+
raise BioAlignError(f"EMBL-EBI {service} job {job_id} terminated with status {status}.")
|
|
40
|
+
time.sleep(poll_interval)
|
|
41
|
+
raise BioAlignError(f"Timed out waiting for EMBL-EBI {service} job {job_id}.")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def run_ebi_msa(
|
|
45
|
+
records: Sequence[SequenceRecord],
|
|
46
|
+
engine: str = "clustalo",
|
|
47
|
+
email: str = "",
|
|
48
|
+
fallback_local: bool = True,
|
|
49
|
+
max_wait: float = 300.0,
|
|
50
|
+
) -> List[SequenceRecord]:
|
|
51
|
+
"""Run multiple sequence alignment via EMBL-EBI Job Dispatcher, with optional local fallback."""
|
|
52
|
+
eng = engine.lower().strip()
|
|
53
|
+
if eng not in EBI_MSA_ENGINES:
|
|
54
|
+
raise BioAlignError(f"Unsupported EBI MSA engine '{engine}'; choose from {', '.join(EBI_MSA_ENGINES)}.")
|
|
55
|
+
if not email:
|
|
56
|
+
raise BioAlignError("EMBL-EBI Job Dispatcher requires a contact --email address.")
|
|
57
|
+
|
|
58
|
+
fasta_str = "".join(f">{r.id}\n{r.seq.replace('-', '')}\n" for r in records)
|
|
59
|
+
seq_type = detect_sequence_type(records)
|
|
60
|
+
params: Dict[str, str] = {"email": email, "sequence": fasta_str}
|
|
61
|
+
if eng == "clustalo":
|
|
62
|
+
params["stype"] = "protein" if seq_type == "protein" else ("rna" if seq_type == "rna" else "dna")
|
|
63
|
+
params["outfmt"] = "fa"
|
|
64
|
+
elif eng in ("muscle", "mafft", "kalign"):
|
|
65
|
+
params["format"] = "fasta"
|
|
66
|
+
params["stype"] = "protein" if seq_type == "protein" else "dna"
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
job_id = _http_post(f"{EBI_BASE}/{eng}/run", params)
|
|
70
|
+
_poll_ebi_job(eng, job_id, max_wait=max_wait)
|
|
71
|
+
for rtype in ("aln-fasta", "fa", "out"):
|
|
72
|
+
try:
|
|
73
|
+
out_text = _http_get(f"{EBI_BASE}/{eng}/result/{job_id}/{rtype}")
|
|
74
|
+
if ">" in out_text:
|
|
75
|
+
return parse_fasta(out_text)
|
|
76
|
+
except urllib.error.HTTPError:
|
|
77
|
+
continue
|
|
78
|
+
raise BioAlignError(f"Could not retrieve FASTA alignment from EMBL-EBI job {job_id}.")
|
|
79
|
+
except (urllib.error.URLError, TimeoutError, BioAlignError):
|
|
80
|
+
if fallback_local:
|
|
81
|
+
return align_sequences(records, sequence_type=seq_type)
|
|
82
|
+
raise
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def run_ebi_blast(
|
|
86
|
+
query: SequenceRecord,
|
|
87
|
+
email: str,
|
|
88
|
+
program: str = "blastp",
|
|
89
|
+
database: str = "uniprotkb_swissprot",
|
|
90
|
+
max_hits: int = 25,
|
|
91
|
+
max_wait: float = 300.0,
|
|
92
|
+
) -> List[Dict[str, object]]:
|
|
93
|
+
"""Run NCBI BLAST+ homolog search via EMBL-EBI Job Dispatcher and return parsed hits + sequences."""
|
|
94
|
+
if not email:
|
|
95
|
+
raise BioAlignError("EMBL-EBI NCBI BLAST+ requires a contact --email address.")
|
|
96
|
+
seq_type = detect_sequence_type([query])
|
|
97
|
+
stype = "protein" if program == "blastp" or seq_type == "protein" else "dna"
|
|
98
|
+
params = {
|
|
99
|
+
"email": email,
|
|
100
|
+
"program": program,
|
|
101
|
+
"stype": stype,
|
|
102
|
+
"database": database,
|
|
103
|
+
"sequence": f">{query.id}\n{query.seq.replace('-', '')}\n",
|
|
104
|
+
"alignments": str(max_hits),
|
|
105
|
+
"scores": str(max_hits),
|
|
106
|
+
}
|
|
107
|
+
job_id = _http_post(f"{EBI_BASE}/ncbiblast/run", params)
|
|
108
|
+
_poll_ebi_job("ncbiblast", job_id, max_wait=max_wait)
|
|
109
|
+
xml_text = _http_get(f"{EBI_BASE}/ncbiblast/result/{job_id}/xml")
|
|
110
|
+
root = ET.fromstring(xml_text)
|
|
111
|
+
|
|
112
|
+
hits: List[Dict[str, object]] = []
|
|
113
|
+
for hit_el in root.iter():
|
|
114
|
+
if not hit_el.tag.endswith("hit"):
|
|
115
|
+
continue
|
|
116
|
+
hit_id = hit_el.attrib.get("id", "")
|
|
117
|
+
hit_ac = hit_el.attrib.get("ac", hit_id)
|
|
118
|
+
desc = hit_el.attrib.get("description", "")
|
|
119
|
+
best_evalue = None
|
|
120
|
+
best_ident = None
|
|
121
|
+
hseq_clean = ""
|
|
122
|
+
for hsp in hit_el.iter():
|
|
123
|
+
if hsp.tag.endswith("expectation"):
|
|
124
|
+
try:
|
|
125
|
+
best_evalue = float(hsp.text or "nan")
|
|
126
|
+
except ValueError:
|
|
127
|
+
pass
|
|
128
|
+
elif hsp.tag.endswith("identity"):
|
|
129
|
+
try:
|
|
130
|
+
best_ident = float(hsp.text or "nan")
|
|
131
|
+
except ValueError:
|
|
132
|
+
pass
|
|
133
|
+
elif hsp.tag.endswith("matchSeq") and not hseq_clean:
|
|
134
|
+
hseq_clean = (hsp.text or "").replace("-", "").strip().upper()
|
|
135
|
+
if hseq_clean:
|
|
136
|
+
hits.append(
|
|
137
|
+
{
|
|
138
|
+
"id": hit_id or hit_ac,
|
|
139
|
+
"accession": hit_ac,
|
|
140
|
+
"description": desc,
|
|
141
|
+
"identity_pct": best_ident,
|
|
142
|
+
"evalue": best_evalue,
|
|
143
|
+
"sequence": hseq_clean,
|
|
144
|
+
}
|
|
145
|
+
)
|
|
146
|
+
if len(hits) >= max_hits:
|
|
147
|
+
break
|
|
148
|
+
return hits
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bioalign
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Homology search, multiple sequence alignment, Shannon conservation analytics, Neighbor-Joining phylogenetics, and multi-format MSA conversion
|
|
5
|
+
Author-email: Alper Karagöl <akaragol@mit.edu>, Taner Karagöl <karagolt@mit.edu>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.karagolresearch.com/bioalign
|
|
8
|
+
Project-URL: Documentation, https://www.karagolresearch.com/bioalign
|
|
9
|
+
Project-URL: Preprint, https://doi.org/10.1101/2024.08.01.606148
|
|
10
|
+
Keywords: bioinformatics,multiple-sequence-alignment,phylo,neighbor-joining,conservation,blast,clustal-omega,mafft
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
21
|
+
Requires-Python: >=3.8
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: numpy>=1.20.0
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# bioalign
|
|
28
|
+
|
|
29
|
+
[](https://pypi.org/project/bioalign/) [](https://opensource.org/licenses/MIT)
|
|
30
|
+
|
|
31
|
+
`bioalign` is the standalone Python library and command-line interface for the [BioAlign](https://www.karagolresearch.com/bioalign) workbench. It combines local affine-gap progressive alignment (BLOSUM62 and nucleotide scoring), optional EMBL-EBI Job Dispatcher remote search and alignment (`ncbiblast`, `clustalo`, `muscle`, `mafft`, `tcoffee`, `kalign`), per-column Shannon entropy and conservation profiling, Poisson-corrected distance matrices, Neighbor-Joining and UPGMA tree reconstruction, and multi-format alignment conversion (`FASTA`, `Clustal`, `PHYLIP`, `Stockholm`, `MSF`, `NEXUS`, `Newick`, `SVG`, `CSV`, and `JSON`).
|
|
32
|
+
|
|
33
|
+
## Installation
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install bioalign
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Command-Line Usage
|
|
40
|
+
|
|
41
|
+
### 1. Align Unaligned Sequences (Offline Progressive Needleman-Wunsch or Remote EMBL-EBI)
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
bioalign align unaligned.fasta -o aligned.fasta
|
|
45
|
+
bioalign align unaligned.fasta --engine clustalo --email researcher@institute.edu -o aligned.fasta
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### 2. Compute Conservation, Shannon Entropy, Consensus, and Pairwise Identity
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
bioalign stats aligned.fasta -o alignment_summary.json --csv per_column_metrics.csv
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 3. Reconstruct Neighbor-Joining or UPGMA Trees (Newick + Publication SVG)
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
bioalign tree aligned.fasta --method nj -o tree.nwk --svg tree.svg
|
|
58
|
+
bioalign tree aligned.fasta --method upgma --cladogram --svg cladogram.svg
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### 4. Convert Alignments Across Standard Formats
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
bioalign convert aligned.fasta --to clustal -o aligned.aln
|
|
65
|
+
bioalign convert aligned.fasta --to stockholm -o aligned.sto
|
|
66
|
+
bioalign convert aligned.fasta --to phylip -o aligned.phy
|
|
67
|
+
bioalign convert aligned.fasta --to nexus -o aligned.nex
|
|
68
|
+
bioalign convert aligned.fasta --to msf -o aligned.msf
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### 5. Run Homolog Search + Alignment Pipeline via EMBL-EBI Job Dispatcher
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
bioalign search query.fasta --email researcher@institute.edu --align clustalo -o results_dir
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Python API
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from bioalign import (
|
|
81
|
+
align_sequences,
|
|
82
|
+
build_tree,
|
|
83
|
+
compute_alignment_stats,
|
|
84
|
+
format_alignment,
|
|
85
|
+
parse_fasta,
|
|
86
|
+
to_newick,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
records = parse_fasta("unaligned.fasta")
|
|
90
|
+
aligned = align_sequences(records)
|
|
91
|
+
stats = compute_alignment_stats(aligned)
|
|
92
|
+
tree = build_tree(
|
|
93
|
+
[r.id for r in aligned],
|
|
94
|
+
stats["identity_matrix"],
|
|
95
|
+
method="nj",
|
|
96
|
+
)
|
|
97
|
+
print("Consensus:", stats["consensus"])
|
|
98
|
+
print("Newick:", to_newick(tree))
|
|
99
|
+
print(format_alignment(aligned, fmt="clustal"))
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Citation
|
|
103
|
+
|
|
104
|
+
Karagöl, A., Karagöl, T. An Evolutionary Statistics Toolkit for Simplified Sequence Analysis on Web with Client-Side Processing. *bioRxiv* (2024). https://doi.org/10.1101/2024.08.01.606148
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
Released under the MIT License.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
bioalign/__init__.py,sha256=n10a89t032LBKt8OP1Dukw9GmB72QDe8PD3rpqNLP-s,787
|
|
2
|
+
bioalign/cli.py,sha256=ExbYtKrnnf5I04Y7YDuCrVr0Pw_fyeH6xnNeCNzYtaM,9078
|
|
3
|
+
bioalign/core.py,sha256=tixQrTEX_jJxO74ODyeWQhNtk4K6ffQJVdC2X5i-OaI,16089
|
|
4
|
+
bioalign/export.py,sha256=HbHJKRiQ0ULAl9vJ1HU-P46dbsj_YQVJ2mmZe8nZHRs,5191
|
|
5
|
+
bioalign/phylo.py,sha256=6drlpD9utALOXM_X3NnEd-LEP21yUoq04pPWV_heXtE,9713
|
|
6
|
+
bioalign/remote.py,sha256=RdpbM4n32Lkum6onFDdM2z0SODlDTiFS-5Cfo2_7bgQ,5886
|
|
7
|
+
bioalign-0.1.0.dist-info/licenses/LICENSE,sha256=9SB5TBHmbLzDVJFERQNrSSjz7q4FcbxBIqHDIwvEkMM,1090
|
|
8
|
+
bioalign-0.1.0.dist-info/METADATA,sha256=33w93qyCpOoHsJcz3VQW2L7Pne-ipLJuddPxLnWTvt8,4146
|
|
9
|
+
bioalign-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
bioalign-0.1.0.dist-info/entry_points.txt,sha256=Dd0JApvAcIbT6VLuvs6cYSHgmvcyh1-jzHwyEkHg8KA,47
|
|
11
|
+
bioalign-0.1.0.dist-info/top_level.txt,sha256=j9f0e505ZPMNNWhT5wNuAnPJXOvGnl_WCLQx_nqa1aE,9
|
|
12
|
+
bioalign-0.1.0.dist-info/RECORD,,
|