routecost 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Taner Karagöl, Alper 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,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: routecost
3
+ Version: 0.1.0
4
+ Summary: Exact deposit-agreement diagnostics and multi-step substitution route epistasis from deep mutational scans
5
+ Author-email: Taner Karagöl <karagolt@mit.edu>, Alper Karagöl <akaragol@mit.edu>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://www.tanerkaragol.com/toolkits-resources
8
+ Project-URL: Repository, https://github.com/karagol-taner/two-step-substitution-routes
9
+ Project-URL: Preprint, https://doi.org/10.64898/2026.11.17.767252
10
+ Keywords: bioinformatics,deep-mutational-scanning,epistasis,protein-design,mavedb,mutational-pathways
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
+ # routecost
28
+
29
+ [![PyPI version](https://img.shields.io/pypi/v/routecost)](https://pypi.org/project/routecost/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
30
+
31
+ `routecost` quantifies multi-step amino acid substitution routes across paired deep mutational scans (MaveDB score-set URNs or local CSV/TSV files) and runs the pre-analysis Spearman rank agreement test that determines whether two scans can be compared on a shared biological scale.
32
+
33
+ 230 of the 380 ordered pairs of standard amino acids require more than a single nucleotide change. Single-parent mutational scans measure only the direct substitution from one background; wherever the same protein has been assayed on two parental sequences that differ at one or more positions, `routecost` extracts the double-difference routing residuals, dispersion-matched shared-parent control nulls, and exact single-difference rank correlations.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install routecost
39
+ ```
40
+
41
+ ## Command-Line Usage
42
+
43
+ Compare two MaveDB score-set URNs directly:
44
+
45
+ ```bash
46
+ routecost --a urn:mavedb:00000044-a-1 --b urn:mavedb:00000668-a-1 -o routes.csv
47
+ ```
48
+
49
+ Compare two local CSV or TSV deep mutational scan tables (`hgvs_pro` + `score`, or `pos`/`wt`/`alt`/`score` columns):
50
+
51
+ ```bash
52
+ routecost --csv-a scan_parent1.csv --seq-a MKTIIALSYIFCLVFA \
53
+ --csv-b scan_parent2.csv --seq-b MKTIIALSYVFCLVFA \
54
+ -o routes.csv
55
+ ```
56
+
57
+ Run the exact rank-agreement check (`rho_test` at differing positions, `rho_control` across shared-parent positions, and predictor attenuation ceiling):
58
+
59
+ ```bash
60
+ routecost --csv-a scan_parent1.csv --seq-a MKTIIALSYIFCLVFA \
61
+ --csv-b scan_parent2.csv --seq-b MKTIIALSYVFCLVFA \
62
+ --exact-test
63
+ ```
64
+
65
+ Query minimum nucleotide base changes and single-step codon intermediates between any two amino acids:
66
+
67
+ ```bash
68
+ routecost --codon-path W M
69
+ ```
70
+
71
+ ## Python API
72
+
73
+ ```python
74
+ from routecost import (
75
+ load_csv_scan,
76
+ analyse_routes,
77
+ exact_agreement_test,
78
+ codon_pathway,
79
+ )
80
+
81
+ info = codon_pathway("V", "T")
82
+ print(info["min_base_changes"], info["single_step_intermediates"])
83
+
84
+ scan_a = load_csv_scan("scan_a.csv", sequence="MKTIIALSYIFCLVFA", name="parent_A")
85
+ scan_b = load_csv_scan("scan_b.csv", sequence="MKTIIALSYVFCLVFA", name="parent_B")
86
+
87
+ rows, control_pool = analyse_routes(scan_a, scan_b, matched_null=True)
88
+ agreement = exact_agreement_test(scan_a, scan_b)
89
+ ```
90
+
91
+ ## Citation
92
+
93
+ Karagöl, T., Karagöl, A. Most substitutions need more than one base change and an exact test tells which deposited scans measure the route. *bioRxiv* (2026). https://doi.org/10.64898/2026.11.17.767252
94
+
95
+ ## License
96
+
97
+ Released under the MIT License.
@@ -0,0 +1,71 @@
1
+ # routecost
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/routecost)](https://pypi.org/project/routecost/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ `routecost` quantifies multi-step amino acid substitution routes across paired deep mutational scans (MaveDB score-set URNs or local CSV/TSV files) and runs the pre-analysis Spearman rank agreement test that determines whether two scans can be compared on a shared biological scale.
6
+
7
+ 230 of the 380 ordered pairs of standard amino acids require more than a single nucleotide change. Single-parent mutational scans measure only the direct substitution from one background; wherever the same protein has been assayed on two parental sequences that differ at one or more positions, `routecost` extracts the double-difference routing residuals, dispersion-matched shared-parent control nulls, and exact single-difference rank correlations.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install routecost
13
+ ```
14
+
15
+ ## Command-Line Usage
16
+
17
+ Compare two MaveDB score-set URNs directly:
18
+
19
+ ```bash
20
+ routecost --a urn:mavedb:00000044-a-1 --b urn:mavedb:00000668-a-1 -o routes.csv
21
+ ```
22
+
23
+ Compare two local CSV or TSV deep mutational scan tables (`hgvs_pro` + `score`, or `pos`/`wt`/`alt`/`score` columns):
24
+
25
+ ```bash
26
+ routecost --csv-a scan_parent1.csv --seq-a MKTIIALSYIFCLVFA \
27
+ --csv-b scan_parent2.csv --seq-b MKTIIALSYVFCLVFA \
28
+ -o routes.csv
29
+ ```
30
+
31
+ Run the exact rank-agreement check (`rho_test` at differing positions, `rho_control` across shared-parent positions, and predictor attenuation ceiling):
32
+
33
+ ```bash
34
+ routecost --csv-a scan_parent1.csv --seq-a MKTIIALSYIFCLVFA \
35
+ --csv-b scan_parent2.csv --seq-b MKTIIALSYVFCLVFA \
36
+ --exact-test
37
+ ```
38
+
39
+ Query minimum nucleotide base changes and single-step codon intermediates between any two amino acids:
40
+
41
+ ```bash
42
+ routecost --codon-path W M
43
+ ```
44
+
45
+ ## Python API
46
+
47
+ ```python
48
+ from routecost import (
49
+ load_csv_scan,
50
+ analyse_routes,
51
+ exact_agreement_test,
52
+ codon_pathway,
53
+ )
54
+
55
+ info = codon_pathway("V", "T")
56
+ print(info["min_base_changes"], info["single_step_intermediates"])
57
+
58
+ scan_a = load_csv_scan("scan_a.csv", sequence="MKTIIALSYIFCLVFA", name="parent_A")
59
+ scan_b = load_csv_scan("scan_b.csv", sequence="MKTIIALSYVFCLVFA", name="parent_B")
60
+
61
+ rows, control_pool = analyse_routes(scan_a, scan_b, matched_null=True)
62
+ agreement = exact_agreement_test(scan_a, scan_b)
63
+ ```
64
+
65
+ ## Citation
66
+
67
+ Karagöl, T., Karagöl, A. Most substitutions need more than one base change and an exact test tells which deposited scans measure the route. *bioRxiv* (2026). https://doi.org/10.64898/2026.11.17.767252
68
+
69
+ ## License
70
+
71
+ Released under the MIT License.
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "routecost"
7
+ version = "0.1.0"
8
+ description = "Exact deposit-agreement diagnostics and multi-step substitution route epistasis from deep mutational scans"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.8"
13
+ authors = [
14
+ { name = "Taner Karagöl", email = "karagolt@mit.edu" },
15
+ { name = "Alper Karagöl", email = "akaragol@mit.edu" },
16
+ ]
17
+ keywords = [
18
+ "bioinformatics",
19
+ "deep-mutational-scanning",
20
+ "epistasis",
21
+ "protein-design",
22
+ "mavedb",
23
+ "mutational-pathways",
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
+ ]
40
+
41
+ [project.urls]
42
+ Homepage = "https://www.tanerkaragol.com/toolkits-resources"
43
+ Repository = "https://github.com/karagol-taner/two-step-substitution-routes"
44
+ Preprint = "https://doi.org/10.64898/2026.11.17.767252"
45
+
46
+ [project.scripts]
47
+ routecost = "routecost.cli:main"
48
+
49
+ [tool.setuptools.packages.find]
50
+ include = ["routecost*"]
@@ -0,0 +1,32 @@
1
+ from .core import (
2
+ AA20,
3
+ CODON_TABLE,
4
+ RouteCostError,
5
+ analyse_routes,
6
+ benjamini_hochberg,
7
+ codon_pathway,
8
+ control_null,
9
+ exact_agreement_test,
10
+ load_csv_scan,
11
+ load_mavedb_scan,
12
+ spearman_rank,
13
+ translate_cds,
14
+ )
15
+
16
+ __version__ = "0.1.0"
17
+
18
+ __all__ = [
19
+ "__version__",
20
+ "AA20",
21
+ "CODON_TABLE",
22
+ "RouteCostError",
23
+ "analyse_routes",
24
+ "benjamini_hochberg",
25
+ "codon_pathway",
26
+ "control_null",
27
+ "exact_agreement_test",
28
+ "load_csv_scan",
29
+ "load_mavedb_scan",
30
+ "spearman_rank",
31
+ "translate_cds",
32
+ ]
@@ -0,0 +1,122 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import json
6
+ import sys
7
+ from typing import Optional, Sequence
8
+
9
+ import numpy as np
10
+
11
+ from . import __version__
12
+ from .core import (
13
+ MIN_ROUTES,
14
+ ROUTE_FIELDS,
15
+ RouteCostError,
16
+ analyse_routes,
17
+ codon_pathway,
18
+ exact_agreement_test,
19
+ load_csv_scan,
20
+ load_mavedb_scan,
21
+ )
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ ap = argparse.ArgumentParser(
26
+ prog="routecost",
27
+ description=(
28
+ "routecost: Multi-step substitution route epistasis and exact\n"
29
+ "deposit-agreement diagnostics across paired deep mutational scans."
30
+ ),
31
+ formatter_class=argparse.RawDescriptionHelpFormatter,
32
+ )
33
+ ap.add_argument("--a", help="MaveDB score-set URN of first parental background")
34
+ ap.add_argument("--b", help="MaveDB score-set URN of second parental background")
35
+ ap.add_argument("--csv-a", help="Local CSV/TSV score file for first parental background")
36
+ ap.add_argument("--seq-a", help="Protein sequence (or FASTA path) for --csv-a")
37
+ ap.add_argument("--csv-b", help="Local CSV/TSV score file for second parental background")
38
+ ap.add_argument("--seq-b", help="Protein sequence (or FASTA path) for --csv-b")
39
+ ap.add_argument("--score-col", default=None, help="Score column name override for local CSV/TSV")
40
+ ap.add_argument("-o", "--out", help="Output CSV path for per-position route residuals")
41
+ ap.add_argument("--cache", default=".routecost-cache", help="Cache directory for MaveDB downloads")
42
+ ap.add_argument("--quantile", type=float, default=90.0, help="Fallback wild-type percentile [default: 90]")
43
+ ap.add_argument("--draws", type=int, default=10000, help="Null permutation draws [default: 10000]")
44
+ ap.add_argument("--seed", type=int, default=20261111, help="Random seed [default: 20261111]")
45
+ ap.add_argument(
46
+ "--unmatched-null",
47
+ action="store_true",
48
+ help="Use pooled shared-parent null instead of dispersion-matched control null",
49
+ )
50
+ ap.add_argument(
51
+ "--exact-test",
52
+ action="store_true",
53
+ help="Run the exact Spearman rank agreement test and print JSON summary",
54
+ )
55
+ ap.add_argument(
56
+ "--codon-path",
57
+ nargs=2,
58
+ metavar=("SOURCE_AA", "TARGET_AA"),
59
+ help="Report minimum base changes and single-step codon intermediates between two amino acids",
60
+ )
61
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
62
+ return ap
63
+
64
+
65
+ def main(argv: Optional[Sequence[str]] = None) -> None:
66
+ ap = build_parser()
67
+ args = ap.parse_args(argv)
68
+
69
+ try:
70
+ if args.codon_path:
71
+ res = codon_pathway(args.codon_path[0], args.codon_path[1])
72
+ print(json.dumps(res, indent=2))
73
+ return
74
+
75
+ if args.a and args.b:
76
+ scan_a = load_mavedb_scan(args.a, cache_dir=args.cache, quantile=args.quantile)
77
+ scan_b = load_mavedb_scan(args.b, cache_dir=args.cache, quantile=args.quantile)
78
+ elif args.csv_a and args.seq_a and args.csv_b and args.seq_b:
79
+ scan_a = load_csv_scan(args.csv_a, args.seq_a, score_col=args.score_col, quantile=args.quantile)
80
+ scan_b = load_csv_scan(args.csv_b, args.seq_b, score_col=args.score_col, quantile=args.quantile)
81
+ else:
82
+ ap.error("Provide (--a URN_A --b URN_B), (--csv-a ... --seq-a ... --csv-b ... --seq-b ...), or --codon-path X Y")
83
+ return
84
+
85
+ if args.exact_test:
86
+ summary = exact_agreement_test(scan_a, scan_b)
87
+ print(json.dumps(summary, indent=2))
88
+ return
89
+
90
+ rows, pool = analyse_routes(
91
+ scan_a,
92
+ scan_b,
93
+ draws=args.draws,
94
+ seed=args.seed,
95
+ matched_null=not args.unmatched_null,
96
+ )
97
+
98
+ print(f"A {scan_a['urn']} ({scan_a['n']} substitutions, wt={scan_a['wt']:.4f}, mad={scan_a['mad']:.4f})")
99
+ print(f"B {scan_b['urn']} ({scan_b['n']} substitutions, wt={scan_b['wt']:.4f}, mad={scan_b['mad']:.4f})")
100
+ print(f"Shared-parent control pairs: {pool.size} (median |delta| = {float(np.median(np.abs(pool))):.4f})")
101
+ live = [r for r in rows if r["n_routes"] >= MIN_ROUTES]
102
+ print(f"Differing positions: {len(rows)} ({len(live)} testable)")
103
+ for r in sorted(live, key=lambda item: item["p_bh"]):
104
+ print(
105
+ f" pos {r['pos']:>4d} {r['res_from']}->{r['res_via']} "
106
+ f"routes={r['n_routes']:>2d} med_res={r['median_residual']:+.4f} "
107
+ f"CI=[{r['ci_low']:+.4f}, {r['ci_high']:+.4f}] q_BH={r['p_bh']:.5f}"
108
+ )
109
+
110
+ if args.out:
111
+ with open(args.out, "w", newline="", encoding="utf-8") as fh:
112
+ writer = csv.DictWriter(fh, fieldnames=ROUTE_FIELDS)
113
+ writer.writeheader()
114
+ writer.writerows(rows)
115
+ print(f"Wrote {args.out}")
116
+ except (RouteCostError, OSError) as exc:
117
+ print(f"[routecost] Error: {exc}", file=sys.stderr)
118
+ sys.exit(1)
119
+
120
+
121
+ if __name__ == "__main__":
122
+ main()
@@ -0,0 +1,536 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import itertools
5
+ import json
6
+ import os
7
+ import re
8
+ import urllib.request
9
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
10
+
11
+ import numpy as np
12
+
13
+ MAVEDB_API = "https://api.mavedb.org/api/v1/score-sets/"
14
+ AA20 = tuple(sorted("ACDEFGHIKLMNPQRSTVWY"))
15
+ AA20_SET = set(AA20)
16
+ THREE_TO_ONE = {
17
+ "Ala": "A", "Arg": "R", "Asn": "N", "Asp": "D", "Cys": "C",
18
+ "Gln": "Q", "Glu": "E", "Gly": "G", "His": "H", "Ile": "I",
19
+ "Leu": "L", "Lys": "K", "Met": "M", "Phe": "F", "Pro": "P",
20
+ "Ser": "S", "Thr": "T", "Trp": "W", "Tyr": "Y", "Val": "V",
21
+ "Ter": "*",
22
+ }
23
+ _BASES = "TCAG"
24
+ _AAS = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
25
+ CODON_TABLE: Dict[str, str] = {
26
+ a + b + c: _AAS[i]
27
+ for i, (a, b, c) in enumerate(itertools.product(_BASES, _BASES, _BASES))
28
+ }
29
+ AA_CODONS: Dict[str, List[str]] = {
30
+ aa: [cod for cod, res in CODON_TABLE.items() if res == aa]
31
+ for aa in AA20
32
+ }
33
+
34
+ HGVS_PRO_RE = re.compile(r"^p\.([A-Z][a-z]{2})(\d+)([A-Z][a-z]{2}|=)$")
35
+ SHORT_MUT_RE = re.compile(r"^([ACDEFGHIKLMNPQRSTVWY])(\d+)([ACDEFGHIKLMNPQRSTVWY\*=])$")
36
+
37
+ MIN_MAD = 0.01
38
+ MIN_POOL = 20
39
+ MIN_ROUTES = 6
40
+
41
+ ROUTE_FIELDS = [
42
+ "pos",
43
+ "res_from",
44
+ "res_via",
45
+ "min_base_changes_to_via",
46
+ "n_routes",
47
+ "targets",
48
+ "median_residual",
49
+ "ci_low",
50
+ "ci_high",
51
+ "median_abs_residual",
52
+ "null_median_abs",
53
+ "null_p95_abs",
54
+ "intermediate_cost",
55
+ "rho_position",
56
+ "p_perm",
57
+ "p_bh",
58
+ "note",
59
+ ]
60
+
61
+
62
+ class RouteCostError(ValueError):
63
+ pass
64
+
65
+
66
+ def _hamming(c1: str, c2: str) -> int:
67
+ return sum(x != y for x, y in zip(c1, c2))
68
+
69
+
70
+ def codon_pathway(source_aa: str, target_aa: str) -> Dict[str, Any]:
71
+ s = source_aa.strip().upper()
72
+ t = target_aa.strip().upper()
73
+ if s not in AA20_SET or t not in AA20_SET:
74
+ raise RouteCostError(f"Expected standard 1-letter amino acids, got {source_aa!r} and {target_aa!r}")
75
+ if s == t:
76
+ return {
77
+ "source": s,
78
+ "target": t,
79
+ "min_base_changes": 0,
80
+ "direct_single_nt": True,
81
+ "single_step_intermediates": [],
82
+ }
83
+
84
+ min_dist = min(_hamming(cs, ct) for cs in AA_CODONS[s] for ct in AA_CODONS[t])
85
+ intermediates = []
86
+ for mid in AA20:
87
+ if mid in (s, t):
88
+ continue
89
+ ok = any(
90
+ _hamming(cs, cm) == 1 and _hamming(cm, ct) == 1
91
+ for cs in AA_CODONS[s]
92
+ for cm in AA_CODONS[mid]
93
+ for ct in AA_CODONS[t]
94
+ )
95
+ if ok:
96
+ intermediates.append(mid)
97
+
98
+ return {
99
+ "source": s,
100
+ "target": t,
101
+ "min_base_changes": int(min_dist),
102
+ "direct_single_nt": min_dist == 1,
103
+ "single_step_intermediates": intermediates,
104
+ }
105
+
106
+
107
+ def translate_cds(nt: str) -> str:
108
+ clean = re.sub(r"\s+", "", nt).upper()
109
+ try:
110
+ return "".join(
111
+ CODON_TABLE[clean[i : i + 3]] for i in range(0, len(clean) - 2, 3)
112
+ ).rstrip("*")
113
+ except KeyError as exc:
114
+ raise RouteCostError(f"Untranslatable codon: {exc}") from exc
115
+
116
+
117
+ def _fetch_bytes(url: str, cache_path: Optional[str] = None, timeout: int = 120) -> bytes:
118
+ if cache_path and os.path.isfile(cache_path) and os.path.getsize(cache_path) > 50:
119
+ with open(cache_path, "rb") as fh:
120
+ return fh.read()
121
+ req = urllib.request.Request(url, headers={"Accept": "*/*", "User-Agent": "routecost/0.1.0"})
122
+ try:
123
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
124
+ if resp.status != 200:
125
+ raise RouteCostError(f"{url} returned HTTP {resp.status}")
126
+ raw = resp.read()
127
+ except RouteCostError:
128
+ raise
129
+ except Exception as exc:
130
+ raise RouteCostError(f"Failed fetching {url}: {type(exc).__name__}: {exc}") from exc
131
+ if cache_path:
132
+ os.makedirs(os.path.dirname(os.path.abspath(cache_path)), exist_ok=True)
133
+ with open(cache_path, "wb") as fh:
134
+ fh.write(raw)
135
+ return raw
136
+
137
+
138
+ def _rankdata(values: Sequence[float]) -> np.ndarray:
139
+ arr = np.asarray(values, dtype=float)
140
+ order = arr.argsort(kind="mergesort")
141
+ ranks = np.empty(len(arr), dtype=float)
142
+ i = 0
143
+ n = len(arr)
144
+ while i < n:
145
+ j = i
146
+ while j + 1 < n and arr[order[j + 1]] == arr[order[i]]:
147
+ j += 1
148
+ ranks[order[i : j + 1]] = (i + j) / 2.0 + 1.0
149
+ i = j + 1
150
+ return ranks
151
+
152
+
153
+ def spearman_rank(a: Sequence[float], b: Sequence[float], min_n: int = MIN_ROUTES) -> Optional[float]:
154
+ if len(a) != len(b) or len(a) < min_n:
155
+ return None
156
+ ra, rb = _rankdata(a), _rankdata(b)
157
+ da, db = ra - ra.mean(), rb - rb.mean()
158
+ denom = float((da * da).sum() * (db * db).sum())
159
+ if denom <= 0.0:
160
+ return None
161
+ return float((da * db).sum() / (denom ** 0.5))
162
+
163
+
164
+ def benjamini_hochberg(p_values: Sequence[float]) -> List[float]:
165
+ n = len(p_values)
166
+ if n == 0:
167
+ return []
168
+ order = sorted(range(n), key=lambda idx: p_values[idx])
169
+ out = [1.0] * n
170
+ prev = 1.0
171
+ for rank in range(n, 0, -1):
172
+ idx = order[rank - 1]
173
+ prev = min(prev, p_values[idx] * n / rank)
174
+ out[idx] = min(1.0, prev)
175
+ return out
176
+
177
+
178
+ def _parse_variant_row(row: Dict[str, str]) -> Optional[Tuple[str, int, str]]:
179
+ hgvs = (row.get("hgvs_pro") or row.get("mutant") or row.get("variant") or "").strip()
180
+ if hgvs:
181
+ for token in hgvs.split(";"):
182
+ token = token.strip()
183
+ m = HGVS_PRO_RE.match(token)
184
+ if m:
185
+ wt = THREE_TO_ONE.get(m.group(1))
186
+ pos = int(m.group(2))
187
+ alt = wt if m.group(3) == "=" else THREE_TO_ONE.get(m.group(3))
188
+ if wt in AA20_SET and alt is not None:
189
+ return wt, pos, alt
190
+ m2 = SHORT_MUT_RE.match(token)
191
+ if m2:
192
+ wt, pos, alt_raw = m2.group(1), int(m2.group(2)), m2.group(3)
193
+ alt = wt if alt_raw == "=" else alt_raw
194
+ return wt, pos, alt
195
+
196
+ pos_str = (row.get("pos") or row.get("position") or "").strip()
197
+ wt = (row.get("wt") or row.get("wildtype") or row.get("ref") or "").strip().upper()
198
+ alt = (row.get("alt") or row.get("mut") or row.get("aa") or "").strip().upper()
199
+ if pos_str.isdigit() and wt in AA20_SET and alt:
200
+ return wt, int(pos_str), (wt if alt == "=" else alt)
201
+ return None
202
+
203
+
204
+ def _build_scan_dict(
205
+ lines: Iterable[str],
206
+ prot: str,
207
+ identifier: str,
208
+ name: str,
209
+ quantile: float = 90.0,
210
+ score_col: Optional[str] = None,
211
+ delimiter: Optional[str] = None,
212
+ ) -> Dict[str, Any]:
213
+ line_list = [ln for ln in lines if ln.strip()]
214
+ if not line_list:
215
+ raise RouteCostError(f"{identifier}: empty score table")
216
+
217
+ if delimiter is None:
218
+ delimiter = "\t" if "\t" in line_list[0] and "," not in line_list[0] else ","
219
+
220
+ reader = csv.DictReader(line_list, delimiter=delimiter)
221
+ cols = reader.fieldnames or []
222
+ chosen_col = score_col
223
+ if chosen_col is None:
224
+ for cand in ("average", "score", "DMS_score", "value", "effect"):
225
+ if cand in cols:
226
+ chosen_col = cand
227
+ break
228
+ if not chosen_col or chosen_col not in cols:
229
+ raise RouteCostError(f"{identifier}: score column not found in {cols}")
230
+
231
+ eff: Dict[Tuple[int, str], float] = {}
232
+ self_vals: List[float] = []
233
+ ref_seen: Dict[int, str] = {}
234
+
235
+ for row in reader:
236
+ parsed = _parse_variant_row(row)
237
+ if parsed is None:
238
+ continue
239
+ wt, pos, alt = parsed
240
+ if alt not in AA20_SET:
241
+ continue
242
+ ref_seen.setdefault(pos, wt)
243
+ raw_val = (row.get(chosen_col) or "").strip()
244
+ if raw_val in ("", "NA", "NaN", "nan", "null", "None"):
245
+ continue
246
+ try:
247
+ val = float(raw_val)
248
+ except ValueError:
249
+ continue
250
+ if not np.isfinite(val):
251
+ continue
252
+ if wt == alt:
253
+ self_vals.append(val)
254
+ else:
255
+ eff[(pos, alt)] = val
256
+
257
+ if len(eff) < 20:
258
+ raise RouteCostError(f"{identifier} contains only {len(eff)} missense substitutions (minimum 20)")
259
+
260
+ prot_clean = re.sub(r"\s+", "", prot).upper().rstrip("*")
261
+ mismatches = [
262
+ pos for pos, wt in ref_seen.items() if 1 <= pos <= len(prot_clean) and prot_clean[pos - 1] != wt
263
+ ]
264
+ if mismatches:
265
+ raise RouteCostError(
266
+ f"{identifier}: variant reference residues disagree with target sequence at positions {mismatches[:5]}"
267
+ )
268
+
269
+ vals = np.fromiter(eff.values(), dtype=float)
270
+ mad = float(np.median(np.abs(vals - np.median(vals))))
271
+ if mad < MIN_MAD:
272
+ raise RouteCostError(f"{identifier}: median absolute deviation {mad:.5f} is below {MIN_MAD}")
273
+
274
+ wt_val = float(np.median(self_vals)) if self_vals else float(np.percentile(vals, quantile))
275
+ return {
276
+ "urn": identifier,
277
+ "name": name,
278
+ "prot": prot_clean,
279
+ "eff": eff,
280
+ "wt": wt_val,
281
+ "wt_deposited": bool(self_vals),
282
+ "mad": mad,
283
+ "column": chosen_col,
284
+ "n": len(eff),
285
+ }
286
+
287
+
288
+ def load_mavedb_scan(
289
+ urn: str,
290
+ cache_dir: Optional[str] = ".routecost-cache",
291
+ quantile: float = 90.0,
292
+ ) -> Dict[str, Any]:
293
+ meta_cache = os.path.join(cache_dir, urn.replace(":", "_") + ".json") if cache_dir else None
294
+ meta = json.loads(_fetch_bytes(MAVEDB_API + urn, meta_cache).decode("utf-8", "replace"))
295
+ if "detail" in meta:
296
+ raise RouteCostError(
297
+ f"{urn}: {meta['detail']}. Supply a score-set URN carrying a trailing index such as urn:mavedb:00000044-a-1."
298
+ )
299
+ tg = (meta.get("targetGenes") or [{}])[0]
300
+ ts = tg.get("targetSequence") or {}
301
+ seq_raw = (ts.get("sequence") or "").upper()
302
+ if not seq_raw:
303
+ raise RouteCostError(f"{urn} carries no targetSequence")
304
+ prot = translate_cds(seq_raw) if ts.get("sequenceType") == "dna" else seq_raw.rstrip("*")
305
+
306
+ csv_cache = os.path.join(cache_dir, urn.replace(":", "_") + ".csv") if cache_dir else None
307
+ score_lines = _fetch_bytes(MAVEDB_API + urn + "/scores", csv_cache).decode("utf-8", "replace").splitlines()
308
+ return _build_scan_dict(score_lines, prot, identifier=urn, name=tg.get("name") or urn, quantile=quantile)
309
+
310
+
311
+ def load_csv_scan(
312
+ csv_path: str,
313
+ sequence: str,
314
+ name: Optional[str] = None,
315
+ score_col: Optional[str] = None,
316
+ quantile: float = 90.0,
317
+ ) -> Dict[str, Any]:
318
+ if os.path.isfile(sequence):
319
+ with open(sequence, encoding="utf-8", errors="replace") as fh:
320
+ seq_lines = [ln.strip() for ln in fh if ln.strip() and not ln.startswith(">")]
321
+ sequence = "".join(seq_lines)
322
+ with open(csv_path, encoding="utf-8", errors="replace") as fh:
323
+ lines = fh.read().splitlines()
324
+ label = name or os.path.basename(csv_path)
325
+ return _build_scan_dict(
326
+ lines,
327
+ sequence,
328
+ identifier=label,
329
+ name=label,
330
+ quantile=quantile,
331
+ score_col=score_col,
332
+ )
333
+
334
+
335
+ def std_effect(scan: Dict[str, Any], pos: int, alt: str) -> Optional[float]:
336
+ val = scan["eff"].get((pos, alt))
337
+ if val is None:
338
+ return None
339
+ return float((val - scan["wt"]) / scan["mad"])
340
+
341
+
342
+ def control_null(scan_a: Dict[str, Any], scan_b: Dict[str, Any]) -> Tuple[np.ndarray, Dict[int, Tuple[float, np.ndarray]]]:
343
+ pooled: List[float] = []
344
+ by_pos: Dict[int, Tuple[float, np.ndarray]] = {}
345
+ length = min(len(scan_a["prot"]), len(scan_b["prot"]))
346
+ for pos in range(1, length + 1):
347
+ wt_a = scan_a["prot"][pos - 1]
348
+ if wt_a != scan_b["prot"][pos - 1]:
349
+ continue
350
+ diffs: List[float] = []
351
+ vals_a: List[float] = []
352
+ for alt in AA20:
353
+ if alt == wt_a:
354
+ continue
355
+ ua = std_effect(scan_a, pos, alt)
356
+ ub = std_effect(scan_b, pos, alt)
357
+ if ua is not None and ub is not None:
358
+ diffs.append(ub - ua)
359
+ vals_a.append(ua)
360
+ pooled.append(ub - ua)
361
+ if len(diffs) >= MIN_ROUTES:
362
+ disp = float(np.median(np.abs(np.asarray(vals_a) - np.median(vals_a))))
363
+ by_pos[pos] = (disp, np.asarray(diffs, dtype=float))
364
+ return np.asarray(pooled, dtype=float), by_pos
365
+
366
+
367
+ def analyse_routes(
368
+ scan_a: Dict[str, Any],
369
+ scan_b: Dict[str, Any],
370
+ draws: int = 10000,
371
+ seed: int = 20261111,
372
+ min_pool: int = MIN_POOL,
373
+ matched_null: bool = True,
374
+ ) -> Tuple[List[Dict[str, Any]], np.ndarray]:
375
+ if len(scan_a["prot"]) != len(scan_b["prot"]):
376
+ raise RouteCostError(
377
+ f"Target sequences have unequal lengths ({len(scan_a['prot'])} vs {len(scan_b['prot'])})"
378
+ )
379
+ pool, by_pos = control_null(scan_a, scan_b)
380
+ if pool.size < min_pool:
381
+ raise RouteCostError(
382
+ f"Only {pool.size} shared-parent control pairs found (minimum {min_pool} required)"
383
+ )
384
+
385
+ rng = np.random.default_rng(seed)
386
+ cached_nulls: Dict[int, np.ndarray] = {}
387
+ rows: List[Dict[str, Any]] = []
388
+
389
+ ctrl_items = sorted(by_pos.items(), key=lambda kv: kv[0])
390
+
391
+ for pos in range(1, len(scan_a["prot"]) + 1):
392
+ x = scan_a["prot"][pos - 1]
393
+ z = scan_b["prot"][pos - 1]
394
+ if x == z:
395
+ continue
396
+ pw = codon_pathway(x, z)
397
+ first = std_effect(scan_a, pos, z)
398
+ if first is None:
399
+ rows.append({
400
+ "pos": pos,
401
+ "res_from": x,
402
+ "res_via": z,
403
+ "min_base_changes_to_via": pw["min_base_changes"],
404
+ "n_routes": 0,
405
+ "note": f"first leg {x}->{z} not measured in {scan_a['urn']}",
406
+ })
407
+ continue
408
+
409
+ residuals: List[float] = []
410
+ targets: List[str] = []
411
+ one_vec: List[float] = []
412
+ two_vec: List[float] = []
413
+
414
+ for y in AA20:
415
+ if y in (x, z):
416
+ continue
417
+ one = std_effect(scan_a, pos, y)
418
+ second = std_effect(scan_b, pos, y)
419
+ if one is None or second is None:
420
+ continue
421
+ residuals.append((one - first) - second)
422
+ targets.append(y)
423
+ one_vec.append(one)
424
+ two_vec.append(second)
425
+
426
+ if len(residuals) < MIN_ROUTES:
427
+ rows.append({
428
+ "pos": pos,
429
+ "res_from": x,
430
+ "res_via": z,
431
+ "min_base_changes_to_via": pw["min_base_changes"],
432
+ "n_routes": len(residuals),
433
+ "note": f"fewer than {MIN_ROUTES} common target residues",
434
+ })
435
+ continue
436
+
437
+ res_arr = np.asarray(residuals, dtype=float)
438
+ stat = float(np.median(np.abs(res_arr)))
439
+ k = res_arr.size
440
+
441
+ if matched_null and len(ctrl_items) >= 8:
442
+ target_disp = float(np.median(np.abs(np.asarray(one_vec) - np.median(one_vec))))
443
+ ranked_ctrl = sorted(ctrl_items, key=lambda kv: abs(kv[1][0] - target_disp))
444
+ top_m = max(8, len(ranked_ctrl) // 3)
445
+ local_pool = np.concatenate([kv[1][1] for kv in ranked_ctrl[:top_m]])
446
+ idx = rng.integers(0, local_pool.size, (draws, k))
447
+ null_dist = np.sort(np.median(np.abs(local_pool[idx]), axis=1))
448
+ else:
449
+ if k not in cached_nulls:
450
+ idx = rng.integers(0, pool.size, (draws, k))
451
+ cached_nulls[k] = np.sort(np.median(np.abs(pool[idx]), axis=1))
452
+ null_dist = cached_nulls[k]
453
+
454
+ p_perm = (null_dist.size - int(np.searchsorted(null_dist, stat, "left")) + 1.0) / (null_dist.size + 1.0)
455
+ boot = np.median(res_arr[rng.integers(0, k, (2000, k))], axis=1)
456
+ rho_pos = spearman_rank(one_vec, two_vec)
457
+
458
+ rows.append({
459
+ "pos": pos,
460
+ "res_from": x,
461
+ "res_via": z,
462
+ "min_base_changes_to_via": pw["min_base_changes"],
463
+ "n_routes": k,
464
+ "targets": "".join(targets),
465
+ "median_residual": round(float(np.median(res_arr)), 5),
466
+ "ci_low": round(float(np.percentile(boot, 2.5)), 5),
467
+ "ci_high": round(float(np.percentile(boot, 97.5)), 5),
468
+ "median_abs_residual": round(stat, 5),
469
+ "null_median_abs": round(float(np.median(null_dist)), 5),
470
+ "null_p95_abs": round(float(np.percentile(null_dist, 95.0)), 5),
471
+ "intermediate_cost": round(float(first), 5),
472
+ "rho_position": "" if rho_pos is None else round(rho_pos, 5),
473
+ "p_perm": round(float(p_perm), 6),
474
+ "note": "",
475
+ })
476
+
477
+ live = [r for r in rows if r["n_routes"] >= MIN_ROUTES]
478
+ for r, q_val in zip(live, benjamini_hochberg([r["p_perm"] for r in live])):
479
+ r["p_bh"] = round(q_val, 6)
480
+
481
+ for r in rows:
482
+ r.setdefault("p_bh", "")
483
+ for key in ROUTE_FIELDS:
484
+ r.setdefault(key, "")
485
+
486
+ return rows, pool
487
+
488
+
489
+ def exact_agreement_test(scan_a: Dict[str, Any], scan_b: Dict[str, Any]) -> Dict[str, Any]:
490
+ if len(scan_a["prot"]) != len(scan_b["prot"]):
491
+ raise RouteCostError(
492
+ f"Target sequences have unequal lengths ({len(scan_a['prot'])} vs {len(scan_b['prot'])})"
493
+ )
494
+ diff_positions: List[Dict[str, Any]] = []
495
+ ctrl_rhos: List[float] = []
496
+
497
+ for pos in range(1, len(scan_a["prot"]) + 1):
498
+ xa = scan_a["prot"][pos - 1]
499
+ xb = scan_b["prot"][pos - 1]
500
+ if xa == xb:
501
+ ys = [
502
+ y for y in AA20
503
+ if y != xa and (pos, y) in scan_a["eff"] and (pos, y) in scan_b["eff"]
504
+ ]
505
+ rho = spearman_rank([scan_a["eff"][(pos, y)] for y in ys], [scan_b["eff"][(pos, y)] for y in ys])
506
+ if rho is not None:
507
+ ctrl_rhos.append(rho)
508
+ else:
509
+ ys = [
510
+ y for y in AA20
511
+ if y not in (xa, xb) and (pos, y) in scan_a["eff"] and (pos, y) in scan_b["eff"]
512
+ ]
513
+ rho = spearman_rank([scan_a["eff"][(pos, y)] for y in ys], [scan_b["eff"][(pos, y)] for y in ys])
514
+ diff_positions.append({
515
+ "pos": pos,
516
+ "parent_a": xa,
517
+ "parent_b": xb,
518
+ "n_targets": len(ys),
519
+ "rho_test": None if rho is None else round(rho, 5),
520
+ })
521
+
522
+ ctrl_med = float(np.median(ctrl_rhos)) if ctrl_rhos else float("nan")
523
+ test_vals = [d["rho_test"] for d in diff_positions if d["rho_test"] is not None]
524
+ test_med = float(np.median(test_vals)) if test_vals else float("nan")
525
+ ceiling = float(np.sqrt(max(0.0, ctrl_med))) if np.isfinite(ctrl_med) else float("nan")
526
+
527
+ return {
528
+ "n_differing_positions": len(diff_positions),
529
+ "exact_single_substitution_pair": len(diff_positions) == 1,
530
+ "identity_expectation_when_single_diff": 1.0,
531
+ "n_control_positions": len(ctrl_rhos),
532
+ "median_rho_control": None if np.isnan(ctrl_med) else round(ctrl_med, 5),
533
+ "median_rho_test": None if np.isnan(test_med) else round(test_med, 5),
534
+ "predictor_attenuation_ceiling": None if np.isnan(ceiling) else round(ceiling, 5),
535
+ "differing_positions": diff_positions,
536
+ }
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: routecost
3
+ Version: 0.1.0
4
+ Summary: Exact deposit-agreement diagnostics and multi-step substitution route epistasis from deep mutational scans
5
+ Author-email: Taner Karagöl <karagolt@mit.edu>, Alper Karagöl <akaragol@mit.edu>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://www.tanerkaragol.com/toolkits-resources
8
+ Project-URL: Repository, https://github.com/karagol-taner/two-step-substitution-routes
9
+ Project-URL: Preprint, https://doi.org/10.64898/2026.11.17.767252
10
+ Keywords: bioinformatics,deep-mutational-scanning,epistasis,protein-design,mavedb,mutational-pathways
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
+ # routecost
28
+
29
+ [![PyPI version](https://img.shields.io/pypi/v/routecost)](https://pypi.org/project/routecost/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
30
+
31
+ `routecost` quantifies multi-step amino acid substitution routes across paired deep mutational scans (MaveDB score-set URNs or local CSV/TSV files) and runs the pre-analysis Spearman rank agreement test that determines whether two scans can be compared on a shared biological scale.
32
+
33
+ 230 of the 380 ordered pairs of standard amino acids require more than a single nucleotide change. Single-parent mutational scans measure only the direct substitution from one background; wherever the same protein has been assayed on two parental sequences that differ at one or more positions, `routecost` extracts the double-difference routing residuals, dispersion-matched shared-parent control nulls, and exact single-difference rank correlations.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install routecost
39
+ ```
40
+
41
+ ## Command-Line Usage
42
+
43
+ Compare two MaveDB score-set URNs directly:
44
+
45
+ ```bash
46
+ routecost --a urn:mavedb:00000044-a-1 --b urn:mavedb:00000668-a-1 -o routes.csv
47
+ ```
48
+
49
+ Compare two local CSV or TSV deep mutational scan tables (`hgvs_pro` + `score`, or `pos`/`wt`/`alt`/`score` columns):
50
+
51
+ ```bash
52
+ routecost --csv-a scan_parent1.csv --seq-a MKTIIALSYIFCLVFA \
53
+ --csv-b scan_parent2.csv --seq-b MKTIIALSYVFCLVFA \
54
+ -o routes.csv
55
+ ```
56
+
57
+ Run the exact rank-agreement check (`rho_test` at differing positions, `rho_control` across shared-parent positions, and predictor attenuation ceiling):
58
+
59
+ ```bash
60
+ routecost --csv-a scan_parent1.csv --seq-a MKTIIALSYIFCLVFA \
61
+ --csv-b scan_parent2.csv --seq-b MKTIIALSYVFCLVFA \
62
+ --exact-test
63
+ ```
64
+
65
+ Query minimum nucleotide base changes and single-step codon intermediates between any two amino acids:
66
+
67
+ ```bash
68
+ routecost --codon-path W M
69
+ ```
70
+
71
+ ## Python API
72
+
73
+ ```python
74
+ from routecost import (
75
+ load_csv_scan,
76
+ analyse_routes,
77
+ exact_agreement_test,
78
+ codon_pathway,
79
+ )
80
+
81
+ info = codon_pathway("V", "T")
82
+ print(info["min_base_changes"], info["single_step_intermediates"])
83
+
84
+ scan_a = load_csv_scan("scan_a.csv", sequence="MKTIIALSYIFCLVFA", name="parent_A")
85
+ scan_b = load_csv_scan("scan_b.csv", sequence="MKTIIALSYVFCLVFA", name="parent_B")
86
+
87
+ rows, control_pool = analyse_routes(scan_a, scan_b, matched_null=True)
88
+ agreement = exact_agreement_test(scan_a, scan_b)
89
+ ```
90
+
91
+ ## Citation
92
+
93
+ Karagöl, T., Karagöl, A. Most substitutions need more than one base change and an exact test tells which deposited scans measure the route. *bioRxiv* (2026). https://doi.org/10.64898/2026.11.17.767252
94
+
95
+ ## License
96
+
97
+ Released under the MIT License.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ routecost/__init__.py
6
+ routecost/cli.py
7
+ routecost/core.py
8
+ routecost.egg-info/PKG-INFO
9
+ routecost.egg-info/SOURCES.txt
10
+ routecost.egg-info/dependency_links.txt
11
+ routecost.egg-info/entry_points.txt
12
+ routecost.egg-info/requires.txt
13
+ routecost.egg-info/top_level.txt
14
+ tests/test_routecost.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ routecost = routecost.cli:main
@@ -0,0 +1 @@
1
+ numpy>=1.20.0
@@ -0,0 +1 @@
1
+ routecost
@@ -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,79 @@
1
+ import csv
2
+ import os
3
+ import tempfile
4
+ import unittest
5
+
6
+ import numpy as np
7
+
8
+ from routecost import (
9
+ AA20,
10
+ analyse_routes,
11
+ codon_pathway,
12
+ exact_agreement_test,
13
+ load_csv_scan,
14
+ )
15
+ from routecost.cli import main as cli_main
16
+
17
+
18
+ class TestRouteCost(unittest.TestCase):
19
+ def test_230_multi_step_ordered_pairs(self):
20
+ multi = sum(
21
+ 1
22
+ for a in AA20
23
+ for b in AA20
24
+ if a != b and codon_pathway(a, b)["min_base_changes"] > 1
25
+ )
26
+ self.assertEqual(multi, 230)
27
+ vt = codon_pathway("V", "T")
28
+ self.assertEqual(vt["min_base_changes"], 2)
29
+ self.assertIn("A", vt["single_step_intermediates"])
30
+ self.assertIn("I", vt["single_step_intermediates"])
31
+
32
+ def test_single_diff_additive_identity_and_epistasis(self):
33
+ rng = np.random.default_rng(42)
34
+ seq_a = "MKTIIALSYIFCLVFADDD"
35
+ seq_b = "MKTIIALSYVFCLVFADDD"
36
+
37
+ aa_eff = {aa: float(rng.normal(0.0, 1.2)) for aa in AA20}
38
+ pos_eff = {p: float(rng.normal(0.0, 0.5)) for p in range(1, len(seq_a) + 1)}
39
+
40
+ with tempfile.TemporaryDirectory() as tmp:
41
+ pa = os.path.join(tmp, "a.csv")
42
+ pb = os.path.join(tmp, "b.csv")
43
+ out_csv = os.path.join(tmp, "out.csv")
44
+
45
+ for path, seq in ((pa, seq_a), (pb, seq_b)):
46
+ with open(path, "w", newline="", encoding="utf-8") as fh:
47
+ w = csv.writer(fh)
48
+ w.writerow(["variant", "score"])
49
+ for p in range(1, len(seq) + 1):
50
+ wt = seq[p - 1]
51
+ w.writerow([f"{wt}{p}=", "0.0"])
52
+ base = pos_eff[p] + aa_eff[wt]
53
+ for alt in AA20:
54
+ if alt == wt:
55
+ continue
56
+ val = (pos_eff[p] + aa_eff[alt]) - base
57
+ w.writerow([f"{wt}{p}{alt}", f"{val:.6f}"])
58
+
59
+ sa = load_csv_scan(pa, seq_a)
60
+ sb = load_csv_scan(pb, seq_b)
61
+
62
+ ag = exact_agreement_test(sa, sb)
63
+ self.assertTrue(ag["exact_single_substitution_pair"])
64
+ self.assertAlmostEqual(ag["median_rho_test"], 1.0, places=5)
65
+ self.assertAlmostEqual(ag["median_rho_control"], 1.0, places=5)
66
+
67
+ rows, pool = analyse_routes(sa, sb, draws=1000, seed=7)
68
+ self.assertEqual(len(rows), 1)
69
+ self.assertEqual(rows[0]["pos"], 10)
70
+ self.assertEqual(rows[0]["res_from"], "I")
71
+ self.assertEqual(rows[0]["res_via"], "V")
72
+ self.assertEqual(rows[0]["n_routes"], 18)
73
+
74
+ cli_main(["--csv-a", pa, "--seq-a", seq_a, "--csv-b", pb, "--seq-b", seq_b, "-o", out_csv])
75
+ self.assertTrue(os.path.isfile(out_csv))
76
+
77
+
78
+ if __name__ == "__main__":
79
+ unittest.main()