variantt 0.1.0__tar.gz

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.
variantt-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alper Karagöl, Taner Karagöl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: variantt
3
+ Version: 0.1.0
4
+ Summary: Polarised directional substitution asymmetry via ancestral-state reconstruction with Variant Tension (Tv) composition control
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/variantt
8
+ Project-URL: Repository, https://github.com/karagol-alper/Tvariant
9
+ Project-URL: Preprint, https://doi.org/10.64898/2026.03.10.710752
10
+ Keywords: bioinformatics,molecular-evolution,ancestral-sequence-reconstruction,substitution-asymmetry,variant-tension,phylogenetics
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
+ Requires-Dist: scipy>=1.8.0
26
+ Dynamic: license-file
27
+
28
+ # variantt
29
+
30
+ [![PyPI version](https://img.shields.io/pypi/v/variantt)](https://pypi.org/project/variantt/) [![Web Platform](https://img.shields.io/badge/Web%20Platform-VariantT-0f4c5c)](https://www.karagolresearch.com/variantt) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
31
+
32
+ `variantt` quantifies polarised directional amino acid substitution asymmetry (`A(X->Y) = (N(X->Y) - N(Y->X)) / (N(X->Y) + N(Y->X))`) on rooted protein phylogenies via unbiased random-tie Fitch ancestral-state reconstruction, exact two-sided binomial tests with Benjamini-Hochberg false discovery rate control, reversible-model parametric bootstrap, alphabet-order bias auditing, and the frequency-only Variant Tension (`Tv`) composition control.
33
+
34
+ Unrooted alignments and single-column frequency ratios carry no directional branch polarity. `variantt` requires an explicit outgroup (`--outgroup`), basal clade (`--root-taxa`), or `--midpoint` root before reporting directional counts, and computes `Tv` alongside `A(X->Y)` on the same alignment to separate compositional asymmetry from true evolutionary directionality.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install variantt
40
+ ```
41
+
42
+ ## Command-Line Usage
43
+
44
+ Run the built-in non-reversible and reversible simulation controls:
45
+
46
+ ```bash
47
+ variantt --selftest
48
+ ```
49
+
50
+ Analyse a FASTA alignment rooted on an outgroup regex with redundancy filtering and parametric bootstrap:
51
+
52
+ ```bash
53
+ variantt --msa alignment.fasta \
54
+ --outgroup "Danio|Xenopus|Latimeria" \
55
+ --weight-threshold 0.98 \
56
+ --min-events 10 \
57
+ --bootstrap 50 \
58
+ -o family_polarised
59
+ ```
60
+
61
+ Compute per-site frequency-only `Tv` composition profiles across alignment columns:
62
+
63
+ ```bash
64
+ variantt --msa alignment.fasta --tv-sites -o tv_profile.csv
65
+ ```
66
+
67
+ ## Python API
68
+
69
+ ```python
70
+ from variantt import (
71
+ analyse_alignment,
72
+ selftest,
73
+ tv_control,
74
+ tv_site_profile,
75
+ read_fasta,
76
+ encode_alignment,
77
+ )
78
+
79
+ controls = selftest(quiet=True)
80
+
81
+ result = analyse_alignment(
82
+ "alignment.fasta",
83
+ outgroup="Danio|Xenopus",
84
+ weight_threshold=0.98,
85
+ min_events=10,
86
+ bootstrap=50,
87
+ )
88
+ print(result["tested_pairs"][:5])
89
+ print("r(A, Tv) =", result["tv_correlation"])
90
+ ```
91
+
92
+ ## Citation
93
+
94
+ Karagöl, A., Karagöl, T. Variant Tension (Tv) as a Composition Control for Directional Substitution Asymmetry: Polarised Inference by Ancestral-State Reconstruction. *bioRxiv* (2026). https://doi.org/10.64898/2026.03.10.710752
95
+
96
+ ## License
97
+
98
+ Released under the MIT License.
@@ -0,0 +1,71 @@
1
+ # variantt
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/variantt)](https://pypi.org/project/variantt/) [![Web Platform](https://img.shields.io/badge/Web%20Platform-VariantT-0f4c5c)](https://www.karagolresearch.com/variantt) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ `variantt` quantifies polarised directional amino acid substitution asymmetry (`A(X->Y) = (N(X->Y) - N(Y->X)) / (N(X->Y) + N(Y->X))`) on rooted protein phylogenies via unbiased random-tie Fitch ancestral-state reconstruction, exact two-sided binomial tests with Benjamini-Hochberg false discovery rate control, reversible-model parametric bootstrap, alphabet-order bias auditing, and the frequency-only Variant Tension (`Tv`) composition control.
6
+
7
+ Unrooted alignments and single-column frequency ratios carry no directional branch polarity. `variantt` requires an explicit outgroup (`--outgroup`), basal clade (`--root-taxa`), or `--midpoint` root before reporting directional counts, and computes `Tv` alongside `A(X->Y)` on the same alignment to separate compositional asymmetry from true evolutionary directionality.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install variantt
13
+ ```
14
+
15
+ ## Command-Line Usage
16
+
17
+ Run the built-in non-reversible and reversible simulation controls:
18
+
19
+ ```bash
20
+ variantt --selftest
21
+ ```
22
+
23
+ Analyse a FASTA alignment rooted on an outgroup regex with redundancy filtering and parametric bootstrap:
24
+
25
+ ```bash
26
+ variantt --msa alignment.fasta \
27
+ --outgroup "Danio|Xenopus|Latimeria" \
28
+ --weight-threshold 0.98 \
29
+ --min-events 10 \
30
+ --bootstrap 50 \
31
+ -o family_polarised
32
+ ```
33
+
34
+ Compute per-site frequency-only `Tv` composition profiles across alignment columns:
35
+
36
+ ```bash
37
+ variantt --msa alignment.fasta --tv-sites -o tv_profile.csv
38
+ ```
39
+
40
+ ## Python API
41
+
42
+ ```python
43
+ from variantt import (
44
+ analyse_alignment,
45
+ selftest,
46
+ tv_control,
47
+ tv_site_profile,
48
+ read_fasta,
49
+ encode_alignment,
50
+ )
51
+
52
+ controls = selftest(quiet=True)
53
+
54
+ result = analyse_alignment(
55
+ "alignment.fasta",
56
+ outgroup="Danio|Xenopus",
57
+ weight_threshold=0.98,
58
+ min_events=10,
59
+ bootstrap=50,
60
+ )
61
+ print(result["tested_pairs"][:5])
62
+ print("r(A, Tv) =", result["tv_correlation"])
63
+ ```
64
+
65
+ ## Citation
66
+
67
+ Karagöl, A., Karagöl, T. Variant Tension (Tv) as a Composition Control for Directional Substitution Asymmetry: Polarised Inference by Ancestral-State Reconstruction. *bioRxiv* (2026). https://doi.org/10.64898/2026.03.10.710752
68
+
69
+ ## License
70
+
71
+ Released under the MIT License.
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "variantt"
7
+ version = "0.1.0"
8
+ description = "Polarised directional substitution asymmetry via ancestral-state reconstruction with Variant Tension (Tv) composition control"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.8"
13
+ authors = [
14
+ { name = "Alper Karagöl", email = "akaragol@mit.edu" },
15
+ { name = "Taner Karagöl", email = "karagolt@mit.edu" },
16
+ ]
17
+ keywords = [
18
+ "bioinformatics",
19
+ "molecular-evolution",
20
+ "ancestral-sequence-reconstruction",
21
+ "substitution-asymmetry",
22
+ "variant-tension",
23
+ "phylogenetics",
24
+ ]
25
+ classifiers = [
26
+ "Development Status :: 4 - Beta",
27
+ "Intended Audience :: Science/Research",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3.8",
31
+ "Programming Language :: Python :: 3.9",
32
+ "Programming Language :: Python :: 3.10",
33
+ "Programming Language :: Python :: 3.11",
34
+ "Programming Language :: Python :: 3.12",
35
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
36
+ ]
37
+ dependencies = [
38
+ "numpy>=1.20.0",
39
+ "scipy>=1.8.0",
40
+ ]
41
+
42
+ [project.urls]
43
+ Homepage = "https://www.karagolresearch.com/variantt"
44
+ Repository = "https://github.com/karagol-alper/Tvariant"
45
+ Preprint = "https://doi.org/10.64898/2026.03.10.710752"
46
+
47
+ [project.scripts]
48
+ variantt = "variantt.cli:main"
49
+
50
+ [tool.setuptools.packages.find]
51
+ include = ["variantt*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ from setuptools import setup
2
+
3
+ if __name__ == "__main__":
4
+ setup()
@@ -0,0 +1,44 @@
1
+ import os
2
+ import tempfile
3
+ import unittest
4
+
5
+ from variantt import VariantTError, analyse_alignment, selftest
6
+ from variantt.cli import main as cli_main
7
+
8
+
9
+ class TestVariantT(unittest.TestCase):
10
+ def test_selftest_recovers_forward_and_reversed_cycles(self):
11
+ res = selftest(n_tips=64, length=300, branch=0.06, seed=3, quiet=True)
12
+ self.assertEqual(len(res), 3)
13
+ self.assertGreater(res[0]["A"], 0.60)
14
+ self.assertLess(res[1]["A"], -0.60)
15
+ self.assertLess(abs(res[2]["A"]), 0.08)
16
+ for row in res:
17
+ self.assertLess(abs(row["tv"]), 0.05)
18
+
19
+ def test_unrooted_refused_and_cli_outputs_csvs(self):
20
+ with tempfile.TemporaryDirectory() as tmp:
21
+ fa = os.path.join(tmp, "demo.fasta")
22
+ with open(fa, "w", encoding="utf-8") as fh:
23
+ fh.write(
24
+ ">OUTGROUP_1\nACDEFGHIKLMNPQRSTVWYACDEFGHIKL\n"
25
+ ">OUTGROUP_2\nACDEFGHIKLMNPQRSTVWYACDEFGHIKM\n"
26
+ ">INGROUP_1\nVCDEFGHIKLMNPQRSTVWYVCDEFGHIKL\n"
27
+ ">INGROUP_2\nVCDEFGHIKLMNPQRSTVWYVCDEFGHIKV\n"
28
+ ">INGROUP_3\nTCDEFGHIKLMNPQRSTVWYTCDEFGHIKL\n"
29
+ )
30
+ with self.assertRaises(VariantTError):
31
+ analyse_alignment(fa)
32
+
33
+ prefix = os.path.join(tmp, "run")
34
+ cli_main(["--msa", fa, "--outgroup", "OUTGROUP", "--min-events", "1", "-o", prefix])
35
+ self.assertTrue(os.path.isfile(f"{prefix}_pairs.csv"))
36
+ self.assertTrue(os.path.isfile(f"{prefix}_counts.csv"))
37
+
38
+ tv_csv = os.path.join(tmp, "tv.csv")
39
+ cli_main(["--msa", fa, "--tv-sites", "-o", tv_csv])
40
+ self.assertTrue(os.path.isfile(tv_csv))
41
+
42
+
43
+ if __name__ == "__main__":
44
+ unittest.main()
@@ -0,0 +1,46 @@
1
+ from .core import (
2
+ AA,
3
+ VariantTError,
4
+ analyse_alignment,
5
+ asymmetry,
6
+ binomial_tests,
7
+ count_polarised,
8
+ encode_alignment,
9
+ fit_reversible_Q,
10
+ greedy_dedupe,
11
+ midpoint_root,
12
+ neighbour_join,
13
+ p_distance,
14
+ parametric_bootstrap,
15
+ poisson_correct,
16
+ read_fasta,
17
+ reroot_on_clade,
18
+ selftest,
19
+ tv_control,
20
+ tv_site_profile,
21
+ )
22
+
23
+ __version__ = "0.1.0"
24
+
25
+ __all__ = [
26
+ "__version__",
27
+ "AA",
28
+ "VariantTError",
29
+ "analyse_alignment",
30
+ "asymmetry",
31
+ "binomial_tests",
32
+ "count_polarised",
33
+ "encode_alignment",
34
+ "fit_reversible_Q",
35
+ "greedy_dedupe",
36
+ "midpoint_root",
37
+ "neighbour_join",
38
+ "p_distance",
39
+ "parametric_bootstrap",
40
+ "poisson_correct",
41
+ "read_fasta",
42
+ "reroot_on_clade",
43
+ "selftest",
44
+ "tv_control",
45
+ "tv_site_profile",
46
+ ]
@@ -0,0 +1,104 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import sys
6
+ from typing import Optional, Sequence
7
+
8
+ from . import __version__
9
+ from .core import (
10
+ AA,
11
+ VariantTError,
12
+ analyse_alignment,
13
+ read_fasta,
14
+ selftest,
15
+ tv_site_profile,
16
+ )
17
+
18
+
19
+ def build_parser() -> argparse.ArgumentParser:
20
+ ap = argparse.ArgumentParser(
21
+ prog="variantt",
22
+ description=(
23
+ "variantt: Polarised directional substitution asymmetry via rooted\n"
24
+ "ancestral-state reconstruction with Variant Tension (Tv) composition control."
25
+ ),
26
+ formatter_class=argparse.RawDescriptionHelpFormatter,
27
+ )
28
+ ap.add_argument("--msa", help="Input aligned FASTA file")
29
+ ap.add_argument("--outgroup", help="Regex matching outgroup sequence headers")
30
+ ap.add_argument("--root-taxa", help="Regex matching deepest-branching clade headers")
31
+ ap.add_argument("--midpoint", action="store_true", help="Midpoint rooting fallback")
32
+ ap.add_argument("--weight-threshold", type=float, default=1.0, help="Drop sequences >= identity threshold [default: 1.0]")
33
+ ap.add_argument("--min-events", type=int, default=10, help="Minimum X<->Y events to test [default: 10]")
34
+ ap.add_argument("--bootstrap", type=int, default=0, help="Reversible-model parametric bootstrap replicates")
35
+ ap.add_argument("--max-seqs", type=int, default=0, help="Optional random subsample cap (0 = all)")
36
+ ap.add_argument("--seed", type=int, default=1, help="Random seed [default: 1]")
37
+ ap.add_argument("-o", "--out", default="polarised", help="Output prefix (or CSV path with --tv-sites)")
38
+ ap.add_argument("--tv-sites", action="store_true", help="Write per-column Tv composition profile CSV")
39
+ ap.add_argument("--selftest", action="store_true", help="Run non-reversible and reversible simulation controls")
40
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
41
+ return ap
42
+
43
+
44
+ def main(argv: Optional[Sequence[str]] = None) -> None:
45
+ ap = build_parser()
46
+ args = ap.parse_args(argv)
47
+ try:
48
+ if args.selftest:
49
+ selftest()
50
+ return
51
+ if not args.msa:
52
+ ap.error("--msa is required unless --selftest is given")
53
+ return
54
+ if args.tv_sites:
55
+ seqs = read_fasta(args.msa)
56
+ prof = tv_site_profile(seqs)
57
+ out_csv = args.out if args.out.endswith(".csv") else f"{args.out}_tv_sites.csv"
58
+ with open(out_csv, "w", newline="", encoding="utf-8") as fh:
59
+ writer = csv.DictWriter(fh, fieldnames=list(prof[0].keys()))
60
+ writer.writeheader()
61
+ writer.writerows(prof)
62
+ print(f"Wrote {len(prof)} columns -> {out_csv}")
63
+ return
64
+
65
+ res = analyse_alignment(
66
+ args.msa,
67
+ outgroup=args.outgroup,
68
+ root_taxa=args.root_taxa,
69
+ midpoint=args.midpoint,
70
+ weight_threshold=args.weight_threshold,
71
+ min_events=args.min_events,
72
+ bootstrap=args.bootstrap,
73
+ max_seqs=args.max_seqs,
74
+ seed=args.seed,
75
+ )
76
+ print(f"Sequences: {res['n_sequences_used']} x {res['alignment_length']} columns ({res['rooted_by']})")
77
+ print(f"Substitutions mapped: {res['total_substitutions']}")
78
+ sig = [r for r in res["tested_pairs"] if r["q"] < 0.05]
79
+ print(f"Tested pairs (>={args.min_events} events): {len(res['tested_pairs'])}, significant at BH q<0.05: {len(sig)}")
80
+ if res["tv_correlation"] is not None:
81
+ print(f"Pearson r(polarised A, frequency-only Tv): {res['tv_correlation']:+.3f}")
82
+ if res["bootstrap"] is not None:
83
+ b = res["bootstrap"]
84
+ print(f"Bootstrap max |A| = {b['observed_max_abs_A']:.3f} (null p95 = {b['null_p95_max_abs_A']:.3f}, p = {b['empirical_p']:.4f})")
85
+
86
+ pairs_path = f"{args.out}_pairs.csv"
87
+ counts_path = f"{args.out}_counts.csv"
88
+ with open(pairs_path, "w", newline="", encoding="utf-8") as fh:
89
+ w = csv.DictWriter(fh, fieldnames=["from", "to", "n_fwd", "n_rev", "n_tot", "A", "p", "q"])
90
+ w.writeheader()
91
+ w.writerows(res["tested_pairs"])
92
+ with open(counts_path, "w", newline="", encoding="utf-8") as fh:
93
+ w2 = csv.writer(fh)
94
+ w2.writerow([""] + AA)
95
+ for idx, aa in enumerate(AA):
96
+ w2.writerow([aa] + [int(v) for v in res["counts"][idx]])
97
+ print(f"Wrote {pairs_path} and {counts_path}")
98
+ except (VariantTError, OSError) as exc:
99
+ print(f"[variantt] Error: {exc}", file=sys.stderr)
100
+ sys.exit(1)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
@@ -0,0 +1,744 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import random
5
+ import re
6
+ from collections import Counter, defaultdict
7
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
8
+
9
+ import numpy as np
10
+ from scipy.linalg import expm
11
+ from scipy.stats import binomtest, spearmanr
12
+
13
+ AA = list("ARNDCQEGHILKMFPSTWYV")
14
+ AA_SET = set(AA)
15
+ NA = len(AA)
16
+ IDX = {a: i for i, a in enumerate(AA)}
17
+ GAP = -1
18
+ FULL_MASK = np.uint32((1 << NA) - 1)
19
+
20
+
21
+ class VariantTError(ValueError):
22
+ pass
23
+
24
+
25
+ class Node:
26
+ __slots__ = ("name", "children", "parent", "length", "state", "setmask")
27
+
28
+ def __init__(self, name: Optional[str] = None) -> None:
29
+ self.name = name
30
+ self.children: List[Node] = []
31
+ self.parent: Optional[Node] = None
32
+ self.length = 0.0
33
+ self.state = GAP
34
+ self.setmask = 0
35
+
36
+ def is_leaf(self) -> bool:
37
+ return not self.children
38
+
39
+
40
+ def read_fasta(path: str) -> List[Tuple[str, str]]:
41
+ seqs: List[Tuple[str, str]] = []
42
+ name: Optional[str] = None
43
+ buf: List[str] = []
44
+ with open(path, encoding="utf-8", errors="replace") as fh:
45
+ for line in fh:
46
+ line = line.rstrip("\n\r")
47
+ if line.startswith(">"):
48
+ if name is not None:
49
+ seqs.append((name, "".join(buf)))
50
+ name, buf = line[1:].strip(), []
51
+ else:
52
+ buf.append(line.strip())
53
+ if name is not None:
54
+ seqs.append((name, "".join(buf)))
55
+ if not seqs:
56
+ raise VariantTError(f"No FASTA records found in {path}")
57
+ return seqs
58
+
59
+
60
+ def encode_alignment(seqs: Sequence[Tuple[str, str]]) -> np.ndarray:
61
+ if len(seqs) < 3:
62
+ raise VariantTError(f"Alignment requires at least 3 sequences, got {len(seqs)}")
63
+ length = min(len(s) for _, s in seqs)
64
+ if length == 0:
65
+ raise VariantTError("Alignment contains an empty sequence")
66
+ mat = np.full((len(seqs), length), GAP, dtype=np.int8)
67
+ for r_idx, (_, s) in enumerate(seqs):
68
+ for c_idx in range(length):
69
+ mat[r_idx, c_idx] = IDX.get(s[c_idx].upper(), GAP)
70
+ return mat
71
+
72
+
73
+ def p_distance(mat: np.ndarray) -> np.ndarray:
74
+ n, length = mat.shape
75
+ valid = mat != GAP
76
+ oh = np.zeros((n, length * NA), dtype=np.float32)
77
+ rows = np.repeat(np.arange(n), length)
78
+ cols = np.tile(np.arange(length), n) * NA + np.clip(mat.ravel(), 0, None)
79
+ keep = valid.ravel()
80
+ oh[rows[keep], cols[keep]] = 1.0
81
+
82
+ matches = oh @ oh.T
83
+ v = valid.astype(np.float32)
84
+ both = v @ v.T
85
+
86
+ dist = 1.0 - matches / np.maximum(both, 1.0)
87
+ dist[both == 0] = 1.0
88
+ dist = (dist + dist.T) / 2.0
89
+ np.fill_diagonal(dist, 0.0)
90
+ return dist.astype(np.float64)
91
+
92
+
93
+ def poisson_correct(dist: np.ndarray) -> np.ndarray:
94
+ with np.errstate(divide="ignore", invalid="ignore"):
95
+ corr = -np.log(np.clip(1.0 - dist, 1e-6, None))
96
+ np.fill_diagonal(corr, 0.0)
97
+ return corr
98
+
99
+
100
+ def neighbour_join(d0: np.ndarray, names: Sequence[str]) -> Node:
101
+ n = d0.shape[0]
102
+ total = 2 * n - 1
103
+ dist = np.zeros((total, total), dtype=np.float64)
104
+ dist[:n, :n] = d0
105
+ active = list(range(n))
106
+ nodes = {i: Node(names[i]) for i in range(n)}
107
+ next_id = n
108
+
109
+ while len(active) > 2:
110
+ k = len(active)
111
+ sub = dist[np.ix_(active, active)]
112
+ r = sub.sum(axis=1)
113
+ q_mat = (k - 2) * sub - r[:, None] - r[None, :]
114
+ np.fill_diagonal(q_mat, np.inf)
115
+ a, b = np.unravel_index(np.argmin(q_mat), q_mat.shape)
116
+ if a > b:
117
+ a, b = b, a
118
+ ia, ib = active[a], active[b]
119
+
120
+ d_ab = sub[a, b]
121
+ delta = (r[a] - r[b]) / (k - 2) if k > 2 else 0.0
122
+ la = max(0.0, 0.5 * d_ab + 0.5 * delta)
123
+ lb = max(0.0, d_ab - la)
124
+
125
+ parent = Node()
126
+ parent.children = [nodes[ia], nodes[ib]]
127
+ nodes[ia].parent = parent
128
+ nodes[ib].parent = parent
129
+ nodes[ia].length = la
130
+ nodes[ib].length = lb
131
+ nodes[next_id] = parent
132
+
133
+ others = np.array([m for m in active if m not in (ia, ib)], dtype=int)
134
+ if others.size:
135
+ dm = 0.5 * (dist[ia, others] + dist[ib, others] - d_ab)
136
+ np.maximum(dm, 0.0, out=dm)
137
+ dist[next_id, others] = dm
138
+ dist[others, next_id] = dm
139
+
140
+ active = others.tolist() + [next_id]
141
+ next_id += 1
142
+
143
+ i, j = active
144
+ root = Node()
145
+ root.children = [nodes[i], nodes[j]]
146
+ nodes[i].parent = root
147
+ nodes[j].parent = root
148
+ nodes[i].length = nodes[j].length = max(0.0, dist[i, j] / 2.0)
149
+ return root
150
+
151
+
152
+ def iter_nodes(root: Node):
153
+ stack, seen = [root], set()
154
+ while stack:
155
+ nd = stack.pop()
156
+ if id(nd) in seen:
157
+ raise VariantTError("Tree contains a cycle; rooting is malformed")
158
+ seen.add(id(nd))
159
+ yield nd
160
+ stack.extend(nd.children)
161
+
162
+
163
+ def leaves(root: Node) -> List[Node]:
164
+ return [nd for nd in iter_nodes(root) if nd.is_leaf()]
165
+
166
+
167
+ def reroot_on_clade(root: Node, member_names: Sequence[str]) -> Tuple[Node, float]:
168
+ target = set(member_names)
169
+ n_target = len(target)
170
+ order = list(iter_nodes(root))
171
+ hits: Dict[int, int] = {}
172
+ sizes: Dict[int, int] = {}
173
+ for nd in reversed(order):
174
+ if nd.is_leaf():
175
+ hits[id(nd)] = 1 if nd.name in target else 0
176
+ sizes[id(nd)] = 1
177
+ else:
178
+ hits[id(nd)] = sum(hits[id(c)] for c in nd.children)
179
+ sizes[id(nd)] = sum(sizes[id(c)] for c in nd.children)
180
+
181
+ best: Optional[Node] = None
182
+ best_score = -1.0
183
+ for nd in order:
184
+ if nd is root:
185
+ continue
186
+ inter = hits[id(nd)]
187
+ union = sizes[id(nd)] + n_target - inter
188
+ score = inter / union if union else 0.0
189
+ if score > best_score:
190
+ best, best_score = nd, score
191
+ if best is None or best_score <= 0:
192
+ return root, 0.0
193
+
194
+ chain: List[Node] = []
195
+ nd: Optional[Node] = best
196
+ while nd is not None and nd.parent is not None:
197
+ chain.append(nd)
198
+ nd = nd.parent
199
+ old_root = nd
200
+ assert old_root is not None
201
+ chain.append(old_root)
202
+ lengths = {id(x): x.length for x in chain}
203
+
204
+ new_root = Node()
205
+ half = best.length / 2.0
206
+ a1 = chain[1]
207
+
208
+ a1.children = [c for c in a1.children if c is not best]
209
+ new_root.children = [best, a1]
210
+ best.parent = new_root
211
+ best.length = half
212
+ a1.parent = new_root
213
+ a1.length = half
214
+
215
+ for i in range(1, len(chain) - 1):
216
+ cur, nxt = chain[i], chain[i + 1]
217
+ nxt.children = [c for c in nxt.children if c is not cur]
218
+ cur.children.append(nxt)
219
+ nxt.parent = cur
220
+ nxt.length = lengths[id(cur)]
221
+
222
+ if old_root.parent is not None and len(old_root.children) == 1:
223
+ only = old_root.children[0]
224
+ only.length += old_root.length
225
+ only.parent = old_root.parent
226
+ old_root.parent.children = [
227
+ only if c is old_root else c for c in old_root.parent.children
228
+ ]
229
+ return new_root, best_score
230
+
231
+
232
+ def midpoint_root(root: Node) -> Node:
233
+ ls = leaves(root)
234
+ if len(ls) < 2:
235
+ return root
236
+
237
+ def depths_from(start: Node) -> Dict[Node, float]:
238
+ dist, seen = {start: 0.0}, {start}
239
+ stack = [start]
240
+ while stack:
241
+ nd = stack.pop()
242
+ nbrs = list(nd.children) + ([nd.parent] if nd.parent else [])
243
+ for nb in nbrs:
244
+ if nb in seen:
245
+ continue
246
+ edge = nd.length if nb is nd.parent else nb.length
247
+ dist[nb] = dist[nd] + edge
248
+ seen.add(nb)
249
+ stack.append(nb)
250
+ return dist
251
+
252
+ d0 = depths_from(ls[0])
253
+ far1 = max((n for n in d0 if n.is_leaf()), key=lambda n: d0[n])
254
+ d1 = depths_from(far1)
255
+ far2 = max((n for n in d1 if n.is_leaf()), key=lambda n: d1[n])
256
+ total = d1[far2]
257
+ nd, acc = far2, 0.0
258
+ while nd.parent is not None and acc + nd.length < total / 2.0:
259
+ acc += nd.length
260
+ nd = nd.parent
261
+ newroot, _ = reroot_on_clade(root, [l.name for l in leaves(nd) if l.name is not None])
262
+ return newroot
263
+
264
+
265
+ def _lowest_set_index(mask: np.ndarray) -> np.ndarray:
266
+ m = mask.astype(np.int64)
267
+ lsb = m & (-m)
268
+ out = np.full(mask.shape, GAP, dtype=np.int8)
269
+ nz = lsb > 0
270
+ if nz.any():
271
+ out[nz] = np.rint(np.log2(lsb[nz].astype(np.float64))).astype(np.int8)
272
+ return out
273
+
274
+
275
+ def _random_set_index(mask: np.ndarray, rng: np.random.Generator) -> np.ndarray:
276
+ bits = ((mask[:, None] >> np.arange(NA, dtype=np.uint32)[None, :]) & np.uint32(1)).astype(bool)
277
+ pri = rng.random(bits.shape) * bits
278
+ out = np.where(bits.any(axis=1), pri.argmax(axis=1), GAP)
279
+ return out.astype(np.int8)
280
+
281
+
282
+ def fitch_all_columns(
283
+ root: Node,
284
+ mat: np.ndarray,
285
+ leaf_rows: Dict[str, int],
286
+ rng: Optional[np.random.Generator] = None,
287
+ ) -> Dict[int, np.ndarray]:
288
+ length = mat.shape[1]
289
+ order = list(iter_nodes(root))
290
+ masks: Dict[int, np.ndarray] = {}
291
+
292
+ for nd in reversed(order):
293
+ if nd.is_leaf():
294
+ assert nd.name is not None
295
+ st = mat[leaf_rows[nd.name]].astype(np.int64)
296
+ m = np.where(st < 0, 0, np.left_shift(1, np.clip(st, 0, None)))
297
+ masks[id(nd)] = m.astype(np.uint32)
298
+ else:
299
+ inter = np.full(length, FULL_MASK, dtype=np.uint32)
300
+ uni = np.zeros(length, dtype=np.uint32)
301
+ for c in nd.children:
302
+ cm = masks[id(c)]
303
+ inter &= np.where(cm == 0, FULL_MASK, cm)
304
+ uni |= cm
305
+ resolved = np.where(inter != 0, inter, uni)
306
+ masks[id(nd)] = np.where(uni == 0, 0, resolved).astype(np.uint32)
307
+
308
+ states: Dict[int, np.ndarray] = {}
309
+ for nd in order:
310
+ m = masks[id(nd)]
311
+ own = _lowest_set_index(m) if rng is None else _random_set_index(m, rng)
312
+ if nd.parent is None:
313
+ st = own
314
+ else:
315
+ pst = states[id(nd.parent)]
316
+ safe = np.clip(pst, 0, None).astype(np.uint32)
317
+ allowed = (pst >= 0) & (((m >> safe) & np.uint32(1)) == 1)
318
+ st = np.where(allowed, pst, own).astype(np.int8)
319
+ states[id(nd)] = np.where(m == 0, GAP, st).astype(np.int8)
320
+
321
+ return states
322
+
323
+
324
+ def _count_once(
325
+ root: Node,
326
+ mat: np.ndarray,
327
+ leaf_rows: Dict[str, int],
328
+ rng: np.random.Generator,
329
+ min_branch: float,
330
+ per_site: Optional[Dict[int, Counter]] = None,
331
+ ) -> np.ndarray:
332
+ states = fitch_all_columns(root, mat, leaf_rows, rng=rng)
333
+ counts = np.zeros((NA, NA), dtype=np.float64)
334
+ for nd in iter_nodes(root):
335
+ p = nd.parent
336
+ if p is None or nd.length < min_branch:
337
+ continue
338
+ ps, cs = states[id(p)], states[id(nd)]
339
+ changed = (ps >= 0) & (cs >= 0) & (ps != cs)
340
+ if not changed.any():
341
+ continue
342
+ a, b = ps[changed], cs[changed]
343
+ np.add.at(counts, (a, b), 1.0)
344
+ if per_site is not None:
345
+ for col, x, y in zip(np.flatnonzero(changed), a, b):
346
+ per_site[int(col)][(int(x), int(y))] += 1
347
+ return counts
348
+
349
+
350
+ def count_polarised(
351
+ root: Node,
352
+ mat: np.ndarray,
353
+ names: Sequence[str],
354
+ min_branch: float = 0.0,
355
+ replicates: int = 25,
356
+ seed: int = 0,
357
+ ) -> Tuple[np.ndarray, Dict[int, Counter]]:
358
+ leaf_rows = {names[i]: i for i in range(len(names))}
359
+ per_site: Dict[int, Counter] = defaultdict(Counter)
360
+ acc = np.zeros((NA, NA), dtype=np.float64)
361
+ for r in range(replicates):
362
+ rng = np.random.default_rng(seed + r)
363
+ acc += _count_once(
364
+ root,
365
+ mat,
366
+ leaf_rows,
367
+ rng,
368
+ min_branch,
369
+ per_site=per_site if r == 0 else None,
370
+ )
371
+ counts = np.rint(acc / replicates).astype(np.int64)
372
+ return counts, per_site
373
+
374
+
375
+ def asymmetry(counts: np.ndarray) -> np.ndarray:
376
+ tot = counts + counts.T
377
+ with np.errstate(invalid="ignore", divide="ignore"):
378
+ asym = (counts - counts.T) / tot
379
+ asym[tot == 0] = np.nan
380
+ return asym
381
+
382
+
383
+ def binomial_tests(counts: np.ndarray, min_events: int = 10) -> List[Dict[str, Any]]:
384
+ rows: List[Dict[str, Any]] = []
385
+ for x in range(NA):
386
+ for y in range(x + 1, NA):
387
+ nxy, nyx = int(counts[x, y]), int(counts[y, x])
388
+ tot = nxy + nyx
389
+ if tot < min_events:
390
+ continue
391
+ p_val = float(binomtest(nxy, tot, 0.5, alternative="two-sided").pvalue)
392
+ rows.append({
393
+ "from": AA[x],
394
+ "to": AA[y],
395
+ "n_fwd": nxy,
396
+ "n_rev": nyx,
397
+ "n_tot": tot,
398
+ "A": (nxy - nyx) / tot,
399
+ "p": p_val,
400
+ })
401
+ rows.sort(key=lambda r: r["p"])
402
+ m = len(rows)
403
+ for rank, r in enumerate(rows, start=1):
404
+ r["q"] = min(1.0, r["p"] * m / rank)
405
+ for i in range(m - 2, -1, -1):
406
+ rows[i]["q"] = min(rows[i]["q"], rows[i + 1]["q"])
407
+ return rows
408
+
409
+
410
+ def fit_reversible_Q(counts: np.ndarray, pseudo: float = 1.0) -> Tuple[np.ndarray, np.ndarray]:
411
+ sym = counts + counts.T + pseudo
412
+ np.fill_diagonal(sym, 0.0)
413
+ pi = counts.sum(axis=0) + counts.sum(axis=1) + pseudo
414
+ pi = pi / pi.sum()
415
+ q_mat = sym * pi[None, :]
416
+ np.fill_diagonal(q_mat, 0.0)
417
+ np.fill_diagonal(q_mat, -q_mat.sum(axis=1))
418
+ scale = -float(np.sum(pi * np.diag(q_mat)))
419
+ if scale > 0:
420
+ q_mat = q_mat / scale
421
+ return q_mat, pi
422
+
423
+
424
+ def simulate_on_tree(
425
+ root: Node,
426
+ q_mat: np.ndarray,
427
+ pi: np.ndarray,
428
+ length: int,
429
+ rng: np.random.Generator,
430
+ ) -> Dict[str, np.ndarray]:
431
+ nodes = list(iter_nodes(root))
432
+ cache: Dict[float, np.ndarray] = {}
433
+
434
+ def p_of(t: float) -> np.ndarray:
435
+ key = round(t, 6)
436
+ if key not in cache:
437
+ prob = expm(q_mat * max(key, 1e-9))
438
+ prob = np.clip(prob, 0, None)
439
+ prob = prob / prob.sum(axis=1, keepdims=True)
440
+ cache[key] = np.cumsum(prob, axis=1)
441
+ return cache[key]
442
+
443
+ out: Dict[str, np.ndarray] = {nd.name: np.empty(length, dtype=np.int8) for nd in nodes if nd.is_leaf() and nd.name is not None}
444
+ root_states = rng.choice(NA, size=length, p=pi)
445
+ states: Dict[Node, np.ndarray] = {root: root_states}
446
+ for nd in nodes:
447
+ if nd is root:
448
+ continue
449
+ assert nd.parent is not None
450
+ parent_states = states[nd.parent]
451
+ cum = p_of(nd.length)
452
+ u = rng.random(length)
453
+ child = np.empty(length, dtype=np.int64)
454
+ for s in range(NA):
455
+ sel = parent_states == s
456
+ if sel.any():
457
+ child[sel] = np.searchsorted(cum[s], u[sel])
458
+ states[nd] = child
459
+ if nd.is_leaf() and nd.name is not None:
460
+ out[nd.name] = child.astype(np.int8)
461
+ return out
462
+
463
+
464
+ def parametric_bootstrap(
465
+ root: Node,
466
+ counts: np.ndarray,
467
+ names: Sequence[str],
468
+ length: int,
469
+ n_rep: int,
470
+ rng: np.random.Generator,
471
+ min_events: int = 10,
472
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
473
+ q_mat, pi = fit_reversible_Q(counts)
474
+ max_a: List[float] = []
475
+ for _ in range(n_rep):
476
+ leafstates = simulate_on_tree(root, q_mat, pi, length, rng)
477
+ mat = np.stack([leafstates[nm] for nm in names])
478
+ c, _ = count_polarised(root, mat, names, replicates=5, seed=int(rng.integers(0, 1 << 30)))
479
+ asym = asymmetry(c)
480
+ tot = c + c.T
481
+ asym = np.where(tot >= min_events, np.abs(asym), np.nan)
482
+ if np.all(np.isnan(asym)):
483
+ continue
484
+ max_a.append(float(np.nanmax(asym)))
485
+ return np.array(max_a), q_mat, pi
486
+
487
+
488
+ def tv_control(mat: np.ndarray, sigma: float = 0.1) -> np.ndarray:
489
+ length = mat.shape[1]
490
+ acc = np.zeros((NA, NA))
491
+ used = 0
492
+ for c in range(length):
493
+ col = mat[:, c]
494
+ col = col[col != GAP]
495
+ if col.size == 0:
496
+ continue
497
+ f = np.bincount(col, minlength=NA).astype(float)
498
+ f /= f.sum()
499
+ d = f[:, None] - f[None, :]
500
+ kern = np.exp(-(d ** 2) / (2 * sigma ** 2))
501
+ s_vec = kern.sum(axis=1)
502
+ acc += np.log(s_vec[None, :] / s_vec[:, None])
503
+ used += 1
504
+ return acc / max(used, 1)
505
+
506
+
507
+ def tv_site_profile(seqs: Sequence[Tuple[str, str]], sigma: float = 0.10, window: int = 3, eps: float = 1e-10) -> List[Dict[str, Any]]:
508
+ mat = encode_alignment(seqs)
509
+ n_seq, length = mat.shape
510
+ rows: List[Dict[str, Any]] = []
511
+ for c in range(length):
512
+ col = mat[:, c]
513
+ valid = col[col != GAP]
514
+ n_valid = int(valid.size)
515
+ gap_frac = 1.0 - (n_valid / float(n_seq))
516
+ if n_valid == 0:
517
+ rows.append({
518
+ "position": c + 1,
519
+ "n_valid": 0,
520
+ "gap_fraction": round(gap_frac, 5),
521
+ "entropy_bits": 0.0,
522
+ "max_tv": 0.0,
523
+ "dominant_residue": "-",
524
+ })
525
+ continue
526
+ counts = np.bincount(valid, minlength=NA).astype(float)
527
+ freqs = counts / n_valid
528
+ nz = freqs[freqs > 0]
529
+ ent = float(-np.sum(nz * np.log2(nz)))
530
+ dom = AA[int(np.argmax(freqs))]
531
+
532
+ f_pad = np.where(freqs > 0, freqs, eps)
533
+ d = f_pad[:, None] - f_pad[None, :]
534
+ kern = np.exp(-(d ** 2) / (2 * sigma ** 2))
535
+ s_vec = kern.sum(axis=1)
536
+ tv_col = float(np.max(np.log(s_vec[None, :] / s_vec[:, None])))
537
+ rows.append({
538
+ "position": c + 1,
539
+ "n_valid": n_valid,
540
+ "gap_fraction": round(gap_frac, 5),
541
+ "entropy_bits": round(ent, 5),
542
+ "max_tv": round(tv_col, 4),
543
+ "dominant_residue": dom,
544
+ })
545
+ return rows
546
+
547
+
548
+ def greedy_dedupe(d_raw: np.ndarray, threshold: float) -> List[int]:
549
+ if threshold >= 1.0:
550
+ return list(range(d_raw.shape[0]))
551
+ ident = 1.0 - d_raw
552
+ kept: List[int] = []
553
+ for i in range(d_raw.shape[0]):
554
+ if not kept or ident[i, kept].max() < threshold:
555
+ kept.append(i)
556
+ return kept
557
+
558
+
559
+ def build_balanced_tree(depth: int, branch: float) -> Node:
560
+ counter = [0]
561
+
562
+ def rec(d: int) -> Node:
563
+ nd = Node()
564
+ if d == 0:
565
+ counter[0] += 1
566
+ nd.name = f"t{counter[0]}"
567
+ return nd
568
+ for _ in range(2):
569
+ ch = rec(d - 1)
570
+ ch.parent = nd
571
+ ch.length = branch
572
+ nd.children.append(ch)
573
+ return nd
574
+
575
+ return rec(depth)
576
+
577
+
578
+ def selftest(n_tips: int = 128, length: int = 600, branch: float = 0.06, seed: int = 3, quiet: bool = False) -> List[Dict[str, Any]]:
579
+ rng = np.random.default_rng(seed)
580
+ root = build_balanced_tree(int(math.log2(n_tips)), branch)
581
+ names = [l.name for l in leaves(root) if l.name is not None]
582
+ measured: List[Dict[str, Any]] = []
583
+
584
+ def say(*a: Any) -> None:
585
+ if not quiet:
586
+ print(*a)
587
+
588
+ def cycle_q(reverse: bool = False, rate: float = 1.0) -> np.ndarray:
589
+ q_mat = np.zeros((NA, NA))
590
+ for a in range(NA):
591
+ b = (a + 1) % NA
592
+ if reverse:
593
+ q_mat[b, a] = rate
594
+ else:
595
+ q_mat[a, b] = rate
596
+ np.fill_diagonal(q_mat, 0.0)
597
+ np.fill_diagonal(q_mat, -q_mat.sum(axis=1))
598
+ return q_mat
599
+
600
+ pi = np.ones(NA) / NA
601
+
602
+ for label, q_mat in [
603
+ ("non-reversible, forward cycle", cycle_q()),
604
+ ("non-reversible, reversed cycle", cycle_q(reverse=True)),
605
+ ("reversible control (symmetric)", None),
606
+ ]:
607
+ if q_mat is None:
608
+ sym = rng.random((NA, NA))
609
+ sym = sym + sym.T
610
+ np.fill_diagonal(sym, 0.0)
611
+ q_mat = sym * pi[None, :]
612
+ np.fill_diagonal(q_mat, 0.0)
613
+ np.fill_diagonal(q_mat, -q_mat.sum(axis=1))
614
+
615
+ leafstates = simulate_on_tree(root, q_mat, pi, length, rng)
616
+ mat = np.stack([leafstates[nm] for nm in names])
617
+ counts, _ = count_polarised(root, mat, names)
618
+ asym = asymmetry(counts)
619
+
620
+ cyc = np.array([asym[a, (a + 1) % NA] for a in range(NA)])
621
+ cyc = cyc[~np.isnan(cyc)]
622
+ off = ~np.eye(NA, dtype=bool)
623
+ all_a = asym[off]
624
+ all_a = all_a[~np.isnan(all_a)]
625
+
626
+ tvc = tv_control(mat)
627
+ tv_cyc = np.array([tvc[a, (a + 1) % NA] for a in range(NA)])
628
+
629
+ entry = {
630
+ "label": label,
631
+ "A": float(np.mean(cyc)),
632
+ "abs_A_all": float(np.mean(np.abs(all_a))),
633
+ "tv": float(np.mean(tv_cyc)),
634
+ "n_subs": int(counts.sum()),
635
+ }
636
+ measured.append(entry)
637
+ say(f"{label}: mean_cycle_A={entry['A']:+.3f}, Tv_control={entry['tv']:+.3f}, subs={entry['n_subs']}")
638
+
639
+ say("Polarised A tracks forward and reversed non-reversible cycles and remains near zero under reversible evolution, while Tv stays flat.")
640
+ return measured
641
+
642
+
643
+ def analyse_alignment(
644
+ msa_path: str,
645
+ outgroup: Optional[str] = None,
646
+ root_taxa: Optional[str] = None,
647
+ midpoint: bool = False,
648
+ weight_threshold: float = 1.0,
649
+ min_events: int = 10,
650
+ bootstrap: int = 0,
651
+ max_seqs: int = 0,
652
+ seed: int = 1,
653
+ ) -> Dict[str, Any]:
654
+ if not (outgroup or root_taxa or midpoint):
655
+ raise VariantTError(
656
+ "Unrooted trees carry no directional polarity; supply outgroup, root_taxa, or midpoint=True."
657
+ )
658
+ rng = np.random.default_rng(seed)
659
+ random.seed(seed)
660
+
661
+ seqs = read_fasta(msa_path)
662
+ names = [nm for nm, _ in seqs]
663
+ mat = encode_alignment(seqs)
664
+ d_raw = p_distance(mat)
665
+
666
+ if weight_threshold < 1.0:
667
+ keep = greedy_dedupe(d_raw, weight_threshold)
668
+ names = [names[i] for i in keep]
669
+ mat = mat[keep]
670
+ d_raw = d_raw[np.ix_(keep, keep)]
671
+
672
+ if max_seqs and len(names) > max_seqs:
673
+ keep = sorted(random.sample(range(len(names)), max_seqs))
674
+ names = [names[i] for i in keep]
675
+ mat = mat[keep]
676
+ d_raw = d_raw[np.ix_(keep, keep)]
677
+
678
+ d_corr = poisson_correct(d_raw)
679
+ root = neighbour_join(d_corr, names)
680
+
681
+ if outgroup:
682
+ og = [nm for nm in names if re.search(outgroup, nm)]
683
+ if not og:
684
+ raise VariantTError(f"Outgroup pattern {outgroup!r} matched zero sequences")
685
+ root, clade_score = reroot_on_clade(root, og)
686
+ rooted_by = f"outgroup ({len(og)} sequences, clade match {clade_score:.2f})"
687
+ elif root_taxa:
688
+ rt = [nm for nm in names if re.search(root_taxa, nm)]
689
+ if not rt:
690
+ raise VariantTError(f"Root-taxa pattern {root_taxa!r} matched zero sequences")
691
+ root, clade_score = reroot_on_clade(root, rt)
692
+ rooted_by = f"basal clade ({len(rt)} sequences, clade match {clade_score:.2f})"
693
+ else:
694
+ root = midpoint_root(root)
695
+ rooted_by = "midpoint"
696
+
697
+ counts, per_site = count_polarised(root, mat, names, seed=seed)
698
+ asym = asymmetry(counts)
699
+ rows = binomial_tests(counts, min_events=min_events)
700
+
701
+ tvc = tv_control(mat)
702
+ off = ~np.eye(NA, dtype=bool)
703
+ mask = off & (~np.isnan(asym))
704
+ tv_corr = float(np.corrcoef(asym[mask], tvc[mask])[0, 1]) if mask.sum() > 2 else None
705
+
706
+ bias_rho = None
707
+ bias_sign_p = None
708
+ if rows:
709
+ a_vals = [r["A"] for r in rows]
710
+ order_gap = [AA.index(r["to"]) - AA.index(r["from"]) for r in rows]
711
+ bias_rho = float(spearmanr(a_vals, order_gap).statistic)
712
+ pos_cnt = sum(1 for r in rows if r["A"] > 0)
713
+ bias_sign_p = float(binomtest(pos_cnt, len(rows), 0.5).pvalue)
714
+
715
+ boot_summary = None
716
+ if bootstrap > 0 and int(counts.sum()) > 0:
717
+ nullmax, _, _ = parametric_bootstrap(
718
+ root, counts, names, mat.shape[1], bootstrap, rng, min_events=min_events
719
+ )
720
+ if nullmax.size:
721
+ obs = float(np.nanmax(np.abs(np.where((counts + counts.T) >= min_events, asym, np.nan))))
722
+ emp_p = float((nullmax >= obs).sum() + 1) / (nullmax.size + 1)
723
+ boot_summary = {
724
+ "replicates": int(nullmax.size),
725
+ "observed_max_abs_A": round(obs, 5),
726
+ "null_mean_max_abs_A": round(float(nullmax.mean()), 5),
727
+ "null_p95_max_abs_A": round(float(np.percentile(nullmax, 95)), 5),
728
+ "empirical_p": round(emp_p, 5),
729
+ }
730
+
731
+ return {
732
+ "n_sequences_used": len(names),
733
+ "alignment_length": int(mat.shape[1]),
734
+ "rooted_by": rooted_by,
735
+ "total_substitutions": int(counts.sum()),
736
+ "counts": counts,
737
+ "asymmetry_matrix": asym,
738
+ "tested_pairs": rows,
739
+ "tv_matrix": tvc,
740
+ "tv_correlation": None if tv_corr is None or np.isnan(tv_corr) else round(tv_corr, 5),
741
+ "alphabet_bias_spearman": None if bias_rho is None or np.isnan(bias_rho) else round(bias_rho, 5),
742
+ "alphabet_bias_sign_p": None if bias_sign_p is None else round(bias_sign_p, 5),
743
+ "bootstrap": boot_summary,
744
+ }
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: variantt
3
+ Version: 0.1.0
4
+ Summary: Polarised directional substitution asymmetry via ancestral-state reconstruction with Variant Tension (Tv) composition control
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/variantt
8
+ Project-URL: Repository, https://github.com/karagol-alper/Tvariant
9
+ Project-URL: Preprint, https://doi.org/10.64898/2026.03.10.710752
10
+ Keywords: bioinformatics,molecular-evolution,ancestral-sequence-reconstruction,substitution-asymmetry,variant-tension,phylogenetics
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
+ Requires-Dist: scipy>=1.8.0
26
+ Dynamic: license-file
27
+
28
+ # variantt
29
+
30
+ [![PyPI version](https://img.shields.io/pypi/v/variantt)](https://pypi.org/project/variantt/) [![Web Platform](https://img.shields.io/badge/Web%20Platform-VariantT-0f4c5c)](https://www.karagolresearch.com/variantt) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
31
+
32
+ `variantt` quantifies polarised directional amino acid substitution asymmetry (`A(X->Y) = (N(X->Y) - N(Y->X)) / (N(X->Y) + N(Y->X))`) on rooted protein phylogenies via unbiased random-tie Fitch ancestral-state reconstruction, exact two-sided binomial tests with Benjamini-Hochberg false discovery rate control, reversible-model parametric bootstrap, alphabet-order bias auditing, and the frequency-only Variant Tension (`Tv`) composition control.
33
+
34
+ Unrooted alignments and single-column frequency ratios carry no directional branch polarity. `variantt` requires an explicit outgroup (`--outgroup`), basal clade (`--root-taxa`), or `--midpoint` root before reporting directional counts, and computes `Tv` alongside `A(X->Y)` on the same alignment to separate compositional asymmetry from true evolutionary directionality.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install variantt
40
+ ```
41
+
42
+ ## Command-Line Usage
43
+
44
+ Run the built-in non-reversible and reversible simulation controls:
45
+
46
+ ```bash
47
+ variantt --selftest
48
+ ```
49
+
50
+ Analyse a FASTA alignment rooted on an outgroup regex with redundancy filtering and parametric bootstrap:
51
+
52
+ ```bash
53
+ variantt --msa alignment.fasta \
54
+ --outgroup "Danio|Xenopus|Latimeria" \
55
+ --weight-threshold 0.98 \
56
+ --min-events 10 \
57
+ --bootstrap 50 \
58
+ -o family_polarised
59
+ ```
60
+
61
+ Compute per-site frequency-only `Tv` composition profiles across alignment columns:
62
+
63
+ ```bash
64
+ variantt --msa alignment.fasta --tv-sites -o tv_profile.csv
65
+ ```
66
+
67
+ ## Python API
68
+
69
+ ```python
70
+ from variantt import (
71
+ analyse_alignment,
72
+ selftest,
73
+ tv_control,
74
+ tv_site_profile,
75
+ read_fasta,
76
+ encode_alignment,
77
+ )
78
+
79
+ controls = selftest(quiet=True)
80
+
81
+ result = analyse_alignment(
82
+ "alignment.fasta",
83
+ outgroup="Danio|Xenopus",
84
+ weight_threshold=0.98,
85
+ min_events=10,
86
+ bootstrap=50,
87
+ )
88
+ print(result["tested_pairs"][:5])
89
+ print("r(A, Tv) =", result["tv_correlation"])
90
+ ```
91
+
92
+ ## Citation
93
+
94
+ Karagöl, A., Karagöl, T. Variant Tension (Tv) as a Composition Control for Directional Substitution Asymmetry: Polarised Inference by Ancestral-State Reconstruction. *bioRxiv* (2026). https://doi.org/10.64898/2026.03.10.710752
95
+
96
+ ## License
97
+
98
+ Released under the MIT License.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ tests/test_variantt.py
6
+ variantt/__init__.py
7
+ variantt/cli.py
8
+ variantt/core.py
9
+ variantt.egg-info/PKG-INFO
10
+ variantt.egg-info/SOURCES.txt
11
+ variantt.egg-info/dependency_links.txt
12
+ variantt.egg-info/entry_points.txt
13
+ variantt.egg-info/requires.txt
14
+ variantt.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ variantt = variantt.cli:main
@@ -0,0 +1,2 @@
1
+ numpy>=1.20.0
2
+ scipy>=1.8.0
@@ -0,0 +1 @@
1
+ variantt