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 ADDED
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .core import (
6
+ BioAlignError,
7
+ SequenceRecord,
8
+ align_sequences,
9
+ compute_alignment_stats,
10
+ detect_sequence_type,
11
+ parse_fasta,
12
+ poisson_distance_matrix,
13
+ )
14
+ from .export import SUPPORTED_FORMATS, format_alignment
15
+ from .phylo import PhyloNode, build_tree, render_tree_svg, to_newick
16
+ from .remote import run_ebi_blast, run_ebi_msa
17
+
18
+ __all__ = [
19
+ "__version__",
20
+ "BioAlignError",
21
+ "SequenceRecord",
22
+ "PhyloNode",
23
+ "SUPPORTED_FORMATS",
24
+ "parse_fasta",
25
+ "detect_sequence_type",
26
+ "align_sequences",
27
+ "compute_alignment_stats",
28
+ "poisson_distance_matrix",
29
+ "build_tree",
30
+ "to_newick",
31
+ "render_tree_svg",
32
+ "format_alignment",
33
+ "run_ebi_msa",
34
+ "run_ebi_blast",
35
+ ]
bioalign/cli.py ADDED
@@ -0,0 +1,183 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Optional, Sequence
9
+
10
+ from . import __version__
11
+ from .core import (
12
+ BioAlignError,
13
+ SequenceRecord,
14
+ align_sequences,
15
+ compute_alignment_stats,
16
+ parse_fasta,
17
+ )
18
+ from .export import SUPPORTED_FORMATS, format_alignment
19
+ from .phylo import build_tree, render_tree_svg, to_newick
20
+ from .remote import EBI_MSA_ENGINES, run_ebi_blast, run_ebi_msa
21
+
22
+
23
+ def build_parser() -> argparse.ArgumentParser:
24
+ ap = argparse.ArgumentParser(
25
+ prog="bioalign",
26
+ description="Homology search, multiple sequence alignment, Shannon conservation analytics, and Neighbor-Joining phylogenetics.",
27
+ )
28
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
29
+ sub = ap.add_subparsers(dest="cmd", required=True)
30
+
31
+ p_aln = sub.add_parser("align", help="Align unaligned FASTA sequences locally or via EMBL-EBI")
32
+ p_aln.add_argument("input", help="Input unaligned FASTA path")
33
+ p_aln.add_argument(
34
+ "--engine",
35
+ choices=("local", *EBI_MSA_ENGINES),
36
+ default="local",
37
+ help="Alignment engine [default: local progressive affine-gap Needleman-Wunsch]",
38
+ )
39
+ p_aln.add_argument("--email", default="", help="Contact email (required for remote EMBL-EBI engines)")
40
+ p_aln.add_argument("--format", choices=SUPPORTED_FORMATS, default="fasta", help="Output alignment format [default: fasta]")
41
+ p_aln.add_argument("-o", "--output", default="", help="Output file path (prints to stdout if omitted)")
42
+
43
+ p_st = sub.add_parser("stats", help="Compute conservation (%), Shannon entropy (bits), consensus, and identity matrix")
44
+ p_st.add_argument("input", help="Aligned FASTA path")
45
+ p_st.add_argument("-o", "--output", default="", help="Output summary JSON path (prints to stdout if omitted)")
46
+ p_st.add_argument("--csv", default="", help="Optional per-column CSV output path")
47
+
48
+ p_tr = sub.add_parser("tree", help="Build Neighbor-Joining or UPGMA phylogenetic tree from aligned FASTA")
49
+ p_tr.add_argument("input", help="Aligned FASTA path")
50
+ p_tr.add_argument("--method", choices=("nj", "upgma"), default="nj", help="Tree algorithm [default: nj]")
51
+ p_tr.add_argument("-o", "--output", default="", help="Output Newick (.nwk) path (prints to stdout if omitted)")
52
+ p_tr.add_argument("--svg", default="", help="Optional publication SVG tree path")
53
+ p_tr.add_argument("--cladogram", action="store_true", help="Render equal-step cladogram branch layout in SVG")
54
+
55
+ p_cv = sub.add_parser("convert", help="Convert aligned FASTA into Clustal, PHYLIP, Stockholm, MSF, NEXUS, or FASTA")
56
+ p_cv.add_argument("input", help="Aligned FASTA path")
57
+ p_cv.add_argument("--to", required=True, choices=SUPPORTED_FORMATS, help="Target MSA format")
58
+ p_cv.add_argument("-o", "--output", default="", help="Output file path (prints to stdout if omitted)")
59
+
60
+ p_sr = sub.add_parser("search", help="Run NCBI BLAST+ homolog search via EMBL-EBI and align retrieved homologs")
61
+ p_sr.add_argument("input", help="Query FASTA path (first sequence is used as query)")
62
+ p_sr.add_argument("--email", required=True, help="Contact email required by EMBL-EBI Job Dispatcher")
63
+ p_sr.add_argument("--program", choices=("blastp", "blastn"), default="blastp", help="BLAST program [default: blastp]")
64
+ p_sr.add_argument("--database", default="uniprotkb_swissprot", help="Target database [default: uniprotkb_swissprot]")
65
+ p_sr.add_argument("--max-hits", type=int, default=20, help="Maximum homologs to retrieve [default: 20]")
66
+ p_sr.add_argument("--align", choices=("local", *EBI_MSA_ENGINES), default="clustalo", help="MSA engine [default: clustalo]")
67
+ p_sr.add_argument("-o", "--outdir", required=True, help="Output directory for hits CSV, aligned FASTA, Newick tree, and stats JSON")
68
+ return ap
69
+
70
+
71
+ def main(argv: Optional[Sequence[str]] = None) -> None:
72
+ ap = build_parser()
73
+ args = ap.parse_args(argv)
74
+ try:
75
+ if args.cmd == "align":
76
+ recs = parse_fasta(Path(args.input))
77
+ if args.engine == "local":
78
+ aligned = align_sequences(recs)
79
+ else:
80
+ aligned = run_ebi_msa(recs, engine=args.engine, email=args.email)
81
+ rendered = format_alignment(aligned, fmt=args.format)
82
+ if args.output:
83
+ Path(args.output).write_text(rendered, encoding="utf-8")
84
+ print(f"Aligned {len(aligned)} sequences ({len(aligned[0].seq)} columns) -> {args.output}")
85
+ else:
86
+ sys.stdout.write(rendered)
87
+
88
+ elif args.cmd == "stats":
89
+ recs = parse_fasta(Path(args.input))
90
+ stats = compute_alignment_stats(recs)
91
+ if args.csv:
92
+ cons = stats["conservation_pct"]
93
+ ent = stats["shannon_entropy_bits"]
94
+ gaps = stats["column_gap_pct"]
95
+ consensus = str(stats["consensus"])
96
+ with open(args.csv, "w", newline="", encoding="utf-8") as fh:
97
+ w = csv.writer(fh)
98
+ w.writerow(["column", "consensus_residue", "conservation_pct", "shannon_entropy_bits", "gap_pct"])
99
+ for idx in range(int(stats["alignment_length"])):
100
+ w.writerow([idx + 1, consensus[idx], cons[idx], ent[idx], gaps[idx]])
101
+ payload = json.dumps(stats, indent=2)
102
+ if args.output:
103
+ Path(args.output).write_text(payload + "\n", encoding="utf-8")
104
+ print(f"Wrote alignment statistics -> {args.output}")
105
+ else:
106
+ print(payload)
107
+
108
+ elif args.cmd == "tree":
109
+ recs = parse_fasta(Path(args.input))
110
+ stats = compute_alignment_stats(recs)
111
+ tree = build_tree(
112
+ [r.id for r in recs],
113
+ stats["identity_matrix"], # type: ignore[arg-type]
114
+ method=args.method,
115
+ )
116
+ nwk = to_newick(tree)
117
+ if args.svg:
118
+ label = "Neighbor-Joining" if args.method == "nj" else "UPGMA"
119
+ svg = render_tree_svg(tree, method_label=label, cladogram=args.cladogram)
120
+ Path(args.svg).write_text(svg, encoding="utf-8")
121
+ if args.output:
122
+ Path(args.output).write_text(nwk + "\n", encoding="utf-8")
123
+ print(f"Wrote {args.method.upper()} Newick tree -> {args.output}")
124
+ else:
125
+ print(nwk)
126
+
127
+ elif args.cmd == "convert":
128
+ recs = parse_fasta(Path(args.input))
129
+ out_txt = format_alignment(recs, fmt=args.to)
130
+ if args.output:
131
+ Path(args.output).write_text(out_txt, encoding="utf-8")
132
+ print(f"Converted {len(recs)} sequences to {args.to} -> {args.output}")
133
+ else:
134
+ sys.stdout.write(out_txt)
135
+
136
+ elif args.cmd == "search":
137
+ queries = parse_fasta(Path(args.input))
138
+ query = queries[0]
139
+ hits = run_ebi_blast(
140
+ query=query,
141
+ email=args.email,
142
+ program=args.program,
143
+ database=args.database,
144
+ max_hits=args.max_hits,
145
+ )
146
+ outdir = Path(args.outdir)
147
+ outdir.mkdir(parents=True, exist_ok=True)
148
+ with open(outdir / "blast_homolog_hits.csv", "w", newline="", encoding="utf-8") as fh:
149
+ w = csv.DictWriter(
150
+ fh,
151
+ fieldnames=["id", "accession", "description", "identity_pct", "evalue", "sequence"],
152
+ )
153
+ w.writeheader()
154
+ w.writerows(hits)
155
+
156
+ pool = [query]
157
+ seen = {query.id}
158
+ for h in hits:
159
+ hid = str(h["id"])
160
+ if hid not in seen:
161
+ seen.add(hid)
162
+ pool.append(SequenceRecord(id=hid, seq=str(h["sequence"]), description=str(h["description"])))
163
+
164
+ if len(pool) >= 2:
165
+ if args.align == "local":
166
+ aligned = align_sequences(pool)
167
+ else:
168
+ aligned = run_ebi_msa(pool, engine=args.align, email=args.email)
169
+ (outdir / "aligned.fasta").write_text(format_alignment(aligned, "fasta"), encoding="utf-8")
170
+ stats = compute_alignment_stats(aligned)
171
+ (outdir / "alignment_stats.json").write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8")
172
+ tree = build_tree([r.id for r in aligned], stats["identity_matrix"], method="nj") # type: ignore[arg-type]
173
+ (outdir / "tree_nj.nwk").write_text(to_newick(tree) + "\n", encoding="utf-8")
174
+ (outdir / "tree_nj.svg").write_text(render_tree_svg(tree), encoding="utf-8")
175
+ print(f"Completed BioAlign homolog pipeline ({len(hits)} hits) -> {outdir}")
176
+
177
+ except (BioAlignError, OSError) as exc:
178
+ print(f"[bioalign] Error: {exc}", file=sys.stderr)
179
+ sys.exit(1)
180
+
181
+
182
+ if __name__ == "__main__":
183
+ main()
bioalign/core.py ADDED
@@ -0,0 +1,442 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import Dict, List, Sequence, Tuple, Union
7
+
8
+ import numpy as np
9
+
10
+
11
+ class BioAlignError(ValueError):
12
+ """Raised when input sequences, alignments, or parameters are invalid."""
13
+
14
+
15
+ @dataclass
16
+ class SequenceRecord:
17
+ id: str
18
+ seq: str
19
+ description: str = ""
20
+
21
+
22
+ AA_ORDER = "ARNDCQEGHILKMFPSTWYV"
23
+ _BLOSUM62_ROWS: Dict[str, List[int]] = {
24
+ "A": [4, -1, -2, -2, 0, -1, -1, 0, -2, -1, -1, -1, -1, -2, -1, 1, 0, -3, -2, 0],
25
+ "R": [-1, 5, 0, -2, -3, 1, 0, -2, 0, -3, -2, 2, -1, -3, -2, -1, -1, -3, -2, -3],
26
+ "N": [-2, 0, 6, 1, -3, 0, 0, 0, 1, -3, -3, 0, -2, -3, -2, 1, 0, -4, -2, -3],
27
+ "D": [-2, -2, 1, 6, -3, 0, 2, -1, -1, -3, -4, -1, -3, -3, -1, 0, -1, -4, -3, -3],
28
+ "C": [0, -3, -3, -3, 9, -3, -4, -3, -3, -1, -1, -3, -1, -2, -3, -1, -1, -2, -2, -1],
29
+ "Q": [-1, 1, 0, 0, -3, 5, 2, -2, 0, -3, -2, 1, 0, -3, -1, 0, -1, -2, -1, -2],
30
+ "E": [-1, 0, 0, 2, -4, 2, 5, -2, 0, -3, -3, 1, -2, -3, -1, 0, -1, -3, -2, -2],
31
+ "G": [0, -2, 0, -1, -3, -2, -2, 6, -2, -4, -4, -2, -3, -3, -2, 0, -2, -2, -3, -3],
32
+ "H": [-2, 0, 1, -1, -3, 0, 0, -2, 8, -3, -3, -1, -2, -1, -2, -1, -2, -2, 2, -3],
33
+ "I": [-1, -3, -3, -3, -1, -3, -3, -4, -3, 4, 2, -3, 1, 0, -3, -2, -1, -3, -1, 3],
34
+ "L": [-1, -2, -3, -4, -1, -2, -3, -4, -3, 2, 4, -2, 2, 0, -3, -2, -1, -2, -1, 1],
35
+ "K": [-1, 2, 0, -1, -3, 1, 1, -2, -1, -3, -2, 5, -1, -3, -1, 0, -1, -3, -2, -2],
36
+ "M": [-1, -1, -2, -3, -1, 0, -2, -3, -2, 1, 2, -1, 5, 0, -2, -1, -1, -1, -1, 1],
37
+ "F": [-2, -3, -3, -3, -2, -3, -3, -3, -1, 0, 0, -3, 0, 6, -4, -2, -2, 1, 3, -1],
38
+ "P": [-1, -2, -2, -1, -3, -1, -1, -2, -2, -3, -3, -1, -2, -4, 7, -1, -1, -4, -3, -2],
39
+ "S": [1, -1, 1, 0, -1, 0, 0, 0, -1, -2, -2, 0, -1, -2, -1, 4, 1, -3, -2, -2],
40
+ "T": [0, -1, 0, -1, -1, -1, -1, -2, -2, -1, -1, -1, -1, -2, -1, 1, 5, -2, -2, 0],
41
+ "W": [-3, -3, -4, -4, -2, -2, -3, -2, -2, -3, -2, -3, -1, 1, -4, -3, -2, 11, 2, -3],
42
+ "Y": [-2, -2, -2, -3, -2, -1, -2, -3, 2, -1, -1, -2, -1, 3, -3, -2, -2, 2, 7, -1],
43
+ "V": [0, -3, -3, -3, -1, -2, -2, -3, -3, 3, 1, -2, 1, -1, -2, -2, 0, -3, -1, 4],
44
+ }
45
+ BLOSUM62: Dict[Tuple[str, str], int] = {}
46
+ for _r_aa, _vals in _BLOSUM62_ROWS.items():
47
+ for _c_idx, _val in enumerate(_vals):
48
+ BLOSUM62[(_r_aa, AA_ORDER[_c_idx])] = _val
49
+
50
+
51
+ def parse_fasta(source: Union[str, Path]) -> List[SequenceRecord]:
52
+ """Parse FASTA records from a file path or raw FASTA string."""
53
+ if isinstance(source, Path):
54
+ text = source.read_text(encoding="utf-8")
55
+ else:
56
+ s = str(source)
57
+ p = Path(s)
58
+ if "\n" not in s and len(s) < 1024 and p.exists() and p.is_file():
59
+ text = p.read_text(encoding="utf-8")
60
+ else:
61
+ text = s
62
+
63
+ records: List[SequenceRecord] = []
64
+ cur_id: Union[str, None] = None
65
+ cur_desc = ""
66
+ chunks: List[str] = []
67
+
68
+ for raw in text.splitlines():
69
+ line = raw.strip()
70
+ if not line:
71
+ continue
72
+ if line.startswith(">"):
73
+ if cur_id is not None:
74
+ seq = "".join(chunks).replace(" ", "").upper()
75
+ if not seq:
76
+ raise BioAlignError(f"Empty sequence for record '{cur_id}'.")
77
+ records.append(SequenceRecord(id=cur_id, seq=seq, description=cur_desc))
78
+ header = line[1:].strip()
79
+ parts = header.split(None, 1)
80
+ cur_id = parts[0] if parts else f"Seq_{len(records) + 1}"
81
+ cur_desc = parts[1] if len(parts) > 1 else ""
82
+ chunks = []
83
+ else:
84
+ if cur_id is None:
85
+ cur_id = "Seq_1"
86
+ cur_desc = ""
87
+ chunks.append(line)
88
+
89
+ if cur_id is not None:
90
+ seq = "".join(chunks).replace(" ", "").upper()
91
+ if not seq:
92
+ raise BioAlignError(f"Empty sequence for record '{cur_id}'.")
93
+ records.append(SequenceRecord(id=cur_id, seq=seq, description=cur_desc))
94
+
95
+ if not records:
96
+ raise BioAlignError("No valid FASTA records found.")
97
+ return records
98
+
99
+
100
+ def detect_sequence_type(records: Sequence[SequenceRecord]) -> str:
101
+ """Detect whether sequences represent 'dna', 'rna', or 'protein'."""
102
+ joined = "".join(ch for r in records for ch in r.seq.upper() if ch not in "-.?*")
103
+ if not joined:
104
+ return "protein"
105
+ dna_chars = set("ACGTN")
106
+ rna_chars = set("ACGUN")
107
+ frac_dna = sum(1 for c in joined if c in dna_chars) / len(joined)
108
+ frac_rna = sum(1 for c in joined if c in rna_chars) / len(joined)
109
+ if "U" in joined and frac_rna >= 0.90:
110
+ return "rna"
111
+ if frac_dna >= 0.92:
112
+ return "dna"
113
+ return "protein"
114
+
115
+
116
+ def _pair_score(a: str, b: str, seq_type: str) -> float:
117
+ if a == "-" and b == "-":
118
+ return 0.0
119
+ if a == "-" or b == "-":
120
+ return -4.0
121
+ if seq_type in ("dna", "rna"):
122
+ return 5.0 if a == b else -4.0
123
+ return float(BLOSUM62.get((a, b), 4 if a == b else -1))
124
+
125
+
126
+ def _align_profiles(
127
+ prof_a: List[SequenceRecord],
128
+ prof_b: List[SequenceRecord],
129
+ seq_type: str,
130
+ gap_open: float = -10.0,
131
+ gap_extend: float = -1.0,
132
+ ) -> List[SequenceRecord]:
133
+ """Affine-gap Gotoh global profile-profile alignment."""
134
+ la = len(prof_a[0].seq)
135
+ lb = len(prof_b[0].seq)
136
+ na = len(prof_a)
137
+ nb = len(prof_b)
138
+
139
+ col_a = [[r.seq[i] for r in prof_a] for i in range(la)]
140
+ col_b = [[r.seq[j] for r in prof_b] for j in range(lb)]
141
+
142
+ neg_inf = -1e15
143
+ m_mat = np.full((la + 1, lb + 1), neg_inf, dtype=float)
144
+ x_mat = np.full((la + 1, lb + 1), neg_inf, dtype=float)
145
+ y_mat = np.full((la + 1, lb + 1), neg_inf, dtype=float)
146
+ tb_m = np.zeros((la + 1, lb + 1), dtype=np.int8)
147
+ tb_x = np.zeros((la + 1, lb + 1), dtype=np.int8)
148
+ tb_y = np.zeros((la + 1, lb + 1), dtype=np.int8)
149
+
150
+ m_mat[0, 0] = 0.0
151
+ for i in range(1, la + 1):
152
+ x_mat[i, 0] = gap_open + (i - 1) * gap_extend
153
+ tb_x[i, 0] = 1
154
+ for j in range(1, lb + 1):
155
+ y_mat[0, j] = gap_open + (j - 1) * gap_extend
156
+ tb_y[0, j] = 2
157
+
158
+ norm = float(na * nb)
159
+ for i in range(1, la + 1):
160
+ ca = col_a[i - 1]
161
+ for j in range(1, lb + 1):
162
+ cb = col_b[j - 1]
163
+ s = 0.0
164
+ for a_ch in ca:
165
+ for b_ch in cb:
166
+ s += _pair_score(a_ch, b_ch, seq_type)
167
+ s /= norm
168
+
169
+ open_x = m_mat[i - 1, j] + gap_open
170
+ ext_x = x_mat[i - 1, j] + gap_extend
171
+ if open_x >= ext_x:
172
+ x_mat[i, j] = open_x
173
+ tb_x[i, j] = 0
174
+ else:
175
+ x_mat[i, j] = ext_x
176
+ tb_x[i, j] = 1
177
+
178
+ open_y = m_mat[i, j - 1] + gap_open
179
+ ext_y = y_mat[i, j - 1] + gap_extend
180
+ if open_y >= ext_y:
181
+ y_mat[i, j] = open_y
182
+ tb_y[i, j] = 0
183
+ else:
184
+ y_mat[i, j] = ext_y
185
+ tb_y[i, j] = 2
186
+
187
+ prev_vals = (m_mat[i - 1, j - 1], x_mat[i - 1, j - 1], y_mat[i - 1, j - 1])
188
+ best_state = int(np.argmax(prev_vals))
189
+ m_mat[i, j] = prev_vals[best_state] + s
190
+ tb_m[i, j] = best_state
191
+
192
+ end_vals = (m_mat[la, lb], x_mat[la, lb], y_mat[la, lb])
193
+ state = int(np.argmax(end_vals))
194
+ i, j = la, lb
195
+ ops: List[int] = []
196
+ while i > 0 or j > 0:
197
+ if i > 0 and j == 0:
198
+ ops.append(1)
199
+ i -= 1
200
+ continue
201
+ if j > 0 and i == 0:
202
+ ops.append(2)
203
+ j -= 1
204
+ continue
205
+ if state == 0:
206
+ prev = int(tb_m[i, j])
207
+ ops.append(0)
208
+ i -= 1
209
+ j -= 1
210
+ state = prev
211
+ elif state == 1:
212
+ prev = int(tb_x[i, j])
213
+ ops.append(1)
214
+ i -= 1
215
+ state = prev
216
+ else:
217
+ prev = int(tb_y[i, j])
218
+ ops.append(2)
219
+ j -= 1
220
+ state = prev
221
+ ops.reverse()
222
+
223
+ out_a: List[List[str]] = [[] for _ in range(na)]
224
+ out_b: List[List[str]] = [[] for _ in range(nb)]
225
+ ia, ib = 0, 0
226
+ for op in ops:
227
+ if op == 0:
228
+ for k in range(na):
229
+ out_a[k].append(prof_a[k].seq[ia])
230
+ for k in range(nb):
231
+ out_b[k].append(prof_b[k].seq[ib])
232
+ ia += 1
233
+ ib += 1
234
+ elif op == 1:
235
+ for k in range(na):
236
+ out_a[k].append(prof_a[k].seq[ia])
237
+ for k in range(nb):
238
+ out_b[k].append("-")
239
+ ia += 1
240
+ else:
241
+ for k in range(na):
242
+ out_a[k].append("-")
243
+ for k in range(nb):
244
+ out_b[k].append(prof_b[k].seq[ib])
245
+ ib += 1
246
+
247
+ merged: List[SequenceRecord] = []
248
+ for k, rec in enumerate(prof_a):
249
+ merged.append(SequenceRecord(id=rec.id, seq="".join(out_a[k]), description=rec.description))
250
+ for k, rec in enumerate(prof_b):
251
+ merged.append(SequenceRecord(id=rec.id, seq="".join(out_b[k]), description=rec.description))
252
+ return merged
253
+
254
+
255
+ def align_sequences(
256
+ records: Sequence[SequenceRecord],
257
+ sequence_type: Union[str, None] = None,
258
+ gap_open: float = -10.0,
259
+ gap_extend: float = -1.0,
260
+ ) -> List[SequenceRecord]:
261
+ """Progressive UPGMA-guided affine-gap global multiple sequence alignment."""
262
+ if len(records) < 2:
263
+ raise BioAlignError("At least 2 sequences are required for alignment.")
264
+
265
+ ungapped = [
266
+ SequenceRecord(
267
+ id=r.id,
268
+ seq=r.seq.replace("-", "").replace(".", "").upper(),
269
+ description=r.description,
270
+ )
271
+ for r in records
272
+ ]
273
+ if any(len(r.seq) == 0 for r in ungapped):
274
+ raise BioAlignError("Cannot align empty sequences.")
275
+
276
+ seq_type = sequence_type or detect_sequence_type(ungapped)
277
+ n = len(ungapped)
278
+
279
+ if n == 2:
280
+ return _align_profiles([ungapped[0]], [ungapped[1]], seq_type, gap_open, gap_extend)
281
+
282
+ kmer = 3 if seq_type == "protein" else 5
283
+ kmers = []
284
+ for r in ungapped:
285
+ s = r.seq
286
+ if len(s) <= kmer:
287
+ kmers.append({s})
288
+ else:
289
+ kmers.append({s[i : i + kmer] for i in range(len(s) - kmer + 1)})
290
+
291
+ clusters: Dict[int, List[SequenceRecord]] = {i: [ungapped[i]] for i in range(n)}
292
+ dists: Dict[Tuple[int, int], float] = {}
293
+ for i in range(n):
294
+ for j in range(i + 1, n):
295
+ inter = len(kmers[i] & kmers[j])
296
+ union = len(kmers[i] | kmers[j]) or 1
297
+ d = 1.0 - (inter / union)
298
+ dists[(i, j)] = d
299
+ dists[(j, i)] = d
300
+
301
+ next_id = n
302
+ while len(clusters) > 1:
303
+ keys = sorted(clusters.keys())
304
+ best_pair = (keys[0], keys[1])
305
+ best_d = float("inf")
306
+ for idx_a in range(len(keys)):
307
+ for idx_b in range(idx_a + 1, len(keys)):
308
+ ka, kb = keys[idx_a], keys[idx_b]
309
+ d = dists[(ka, kb)]
310
+ if d < best_d:
311
+ best_d = d
312
+ best_pair = (ka, kb)
313
+ ka, kb = best_pair
314
+ merged_prof = _align_profiles(clusters[ka], clusters[kb], seq_type, gap_open, gap_extend)
315
+ wa = len(clusters[ka])
316
+ wb = len(clusters[kb])
317
+ del clusters[ka]
318
+ del clusters[kb]
319
+ for other in list(clusters.keys()):
320
+ d_new = (dists[(ka, other)] * wa + dists[(kb, other)] * wb) / (wa + wb)
321
+ dists[(next_id, other)] = d_new
322
+ dists[(other, next_id)] = d_new
323
+ clusters[next_id] = merged_prof
324
+ next_id += 1
325
+
326
+ final_prof = next(iter(clusters.values()))
327
+ by_id = {r.id: r for r in final_prof}
328
+ if len(by_id) == len(records):
329
+ return [by_id[r.id] for r in records]
330
+ return final_prof
331
+
332
+
333
+ def poisson_distance_matrix(identity_matrix_pct: Sequence[Sequence[float]]) -> List[List[float]]:
334
+ """Compute BioAlign Poisson-corrected divergence matrix from pairwise identity (%) matrix."""
335
+ n = len(identity_matrix_pct)
336
+ dist = [[0.0] * n for _ in range(n)]
337
+ for i in range(n):
338
+ for j in range(i + 1, n):
339
+ ident = float(identity_matrix_pct[i][j])
340
+ p = max(0.0, min(1.0, 1.0 - ident / 100.0))
341
+ if p < 0.85:
342
+ d = -math.log(1.0 - p)
343
+ else:
344
+ d = 1.9 + (p - 0.85) * 4.0
345
+ d_round = round(d, 4)
346
+ dist[i][j] = d_round
347
+ dist[j][i] = d_round
348
+ return dist
349
+
350
+
351
+ def compute_alignment_stats(records: Sequence[SequenceRecord]) -> Dict[str, object]:
352
+ """Compute conservation (%), Shannon entropy (bits), consensus, pairwise identity (%), and Poisson distances."""
353
+ if not records:
354
+ raise BioAlignError("Alignment contains no sequences.")
355
+ lengths = {len(r.seq) for r in records}
356
+ if len(lengths) != 1:
357
+ raise BioAlignError(
358
+ f"Aligned sequences must share an equal column length; found lengths {sorted(lengths)}."
359
+ )
360
+ num_seqs = len(records)
361
+ aln_len = len(records[0].seq)
362
+ seq_type = detect_sequence_type(records)
363
+
364
+ conservation_pct: List[float] = []
365
+ shannon_bits: List[float] = []
366
+ gap_pct: List[float] = []
367
+ consensus_chars: List[str] = []
368
+
369
+ total_gaps = 0
370
+ for col_idx in range(aln_len):
371
+ counts: Dict[str, int] = {}
372
+ gaps = 0
373
+ for rec in records:
374
+ ch = rec.seq[col_idx].upper()
375
+ if ch in ("-", "."):
376
+ gaps += 1
377
+ else:
378
+ counts[ch] = counts.get(ch, 0) + 1
379
+ total_gaps += gaps
380
+ nongap = num_seqs - gaps
381
+ gap_pct.append(round((gaps / num_seqs) * 100.0, 4))
382
+
383
+ if nongap == 0:
384
+ conservation_pct.append(0.0)
385
+ shannon_bits.append(0.0)
386
+ consensus_chars.append("-")
387
+ continue
388
+
389
+ top_symbol, top_count = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0]
390
+ cons = (top_count / num_seqs) * 100.0
391
+ conservation_pct.append(round(cons, 4))
392
+ consensus_chars.append(top_symbol if top_count / num_seqs >= 0.5 else top_symbol.lower())
393
+
394
+ ent = 0.0
395
+ for c in counts.values():
396
+ p = c / nongap
397
+ if p > 0:
398
+ ent -= p * math.log2(p)
399
+ shannon_bits.append(round(ent, 4))
400
+
401
+ identity_matrix = [[100.0] * num_seqs for _ in range(num_seqs)]
402
+ off_diag: List[float] = []
403
+ for i in range(num_seqs):
404
+ si = records[i].seq.upper()
405
+ for j in range(i + 1, num_seqs):
406
+ sj = records[j].seq.upper()
407
+ matches = 0
408
+ compared = 0
409
+ for k in range(aln_len):
410
+ ci, cj = si[k], sj[k]
411
+ if ci in ("-", ".") and cj in ("-", "."):
412
+ continue
413
+ compared += 1
414
+ if ci == cj and ci not in ("-", "."):
415
+ matches += 1
416
+ pct = round((matches / compared) * 100.0, 4) if compared > 0 else 0.0
417
+ identity_matrix[i][j] = pct
418
+ identity_matrix[j][i] = pct
419
+ off_diag.append(pct)
420
+
421
+ distance_matrix = poisson_distance_matrix(identity_matrix)
422
+ fully_conserved = sum(1 for c, g in zip(conservation_pct, gap_pct) if c >= 99.9999 and g == 0.0)
423
+
424
+ return {
425
+ "sequence_type": seq_type,
426
+ "num_sequences": num_seqs,
427
+ "alignment_length": aln_len,
428
+ "gap_percentage": round((total_gaps / (num_seqs * aln_len)) * 100.0, 4),
429
+ "mean_conservation_pct": round(float(np.mean(conservation_pct)), 4),
430
+ "mean_shannon_entropy_bits": round(float(np.mean(shannon_bits)), 4),
431
+ "fully_conserved_columns": fully_conserved,
432
+ "mean_pairwise_identity_pct": round(float(np.mean(off_diag)), 4) if off_diag else 100.0,
433
+ "min_pairwise_identity_pct": round(float(min(off_diag)), 4) if off_diag else 100.0,
434
+ "max_pairwise_identity_pct": round(float(max(off_diag)), 4) if off_diag else 100.0,
435
+ "consensus": "".join(consensus_chars),
436
+ "conservation_pct": conservation_pct,
437
+ "shannon_entropy_bits": shannon_bits,
438
+ "column_gap_pct": gap_pct,
439
+ "sequence_ids": [r.id for r in records],
440
+ "identity_matrix": identity_matrix,
441
+ "poisson_distance_matrix": distance_matrix,
442
+ }