quasispecies-profiler 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 Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute
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,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: quasispecies-profiler
3
+ Version: 0.1.0
4
+ Summary: Replicate-aware Beta-Binomial intra-host viral variant caller and diversity profiler
5
+ Author-email: "Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute" <shwetabac@gmail.com>
6
+ Maintainer-email: "Dr. Shweta Singh" <shwetabac@gmail.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/molecularplantpathology/Virome-Suite
9
+ Project-URL: Repository, https://github.com/molecularplantpathology/Virome-Suite.git
10
+ Project-URL: Issues, https://github.com/molecularplantpathology/Virome-Suite/issues
11
+ Keywords: virome,quasispecies,variant-calling,beta-binomial,bioinformatics
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.24.0
16
+ Requires-Dist: scipy>=1.10.0
17
+ Requires-Dist: pandas>=2.0.0
18
+ Dynamic: license-file
19
+
20
+ # quasispecies-profiler
21
+
22
+ **Replicate-Aware Hierarchical Empirical Bayes Beta-Binomial Intra-Host Variant Caller & Diversity Profiler**
23
+
24
+ Part of the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
25
+
26
+ ## Key Features
27
+ - **PCR Amplification Jackpot Filtering:** Separates genuine intra-host viral variants (0.5%–5% VAF) from single-replicate RT-PCR overdispersion artifacts across technical and biological replicates.
28
+ - **Ultra-Deep Numerical Stability:** Log-space `betaln`/`gammaln` Beta-Binomial optimization stable beyond $100,000\times$ sequencing coverage.
29
+ - **Empirical Null Calibration & Profile CIs:** Vectorized null parametric bootstrap calibration with Benjamini-Hochberg FDR control, 95% Profile Likelihood Confidence Intervals, and depth-dependent Limits of Detection.
30
+ - **Population Genetics Metrics:** Genome-wide Shannon entropy ($H$), nucleotide diversity ($\pi$), and Nei-Gojobori $d_N/d_S$ selection ratios.
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install quasispecies-profiler
36
+ ```
37
+
38
+ ## Quick Start
39
+
40
+ ```bash
41
+ quasispecies-profiler call --manifest replicates_counts.tsv -o out_variants/
42
+ ```
@@ -0,0 +1,23 @@
1
+ # quasispecies-profiler
2
+
3
+ **Replicate-Aware Hierarchical Empirical Bayes Beta-Binomial Intra-Host Variant Caller & Diversity Profiler**
4
+
5
+ Part of the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
6
+
7
+ ## Key Features
8
+ - **PCR Amplification Jackpot Filtering:** Separates genuine intra-host viral variants (0.5%–5% VAF) from single-replicate RT-PCR overdispersion artifacts across technical and biological replicates.
9
+ - **Ultra-Deep Numerical Stability:** Log-space `betaln`/`gammaln` Beta-Binomial optimization stable beyond $100,000\times$ sequencing coverage.
10
+ - **Empirical Null Calibration & Profile CIs:** Vectorized null parametric bootstrap calibration with Benjamini-Hochberg FDR control, 95% Profile Likelihood Confidence Intervals, and depth-dependent Limits of Detection.
11
+ - **Population Genetics Metrics:** Genome-wide Shannon entropy ($H$), nucleotide diversity ($\pi$), and Nei-Gojobori $d_N/d_S$ selection ratios.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pip install quasispecies-profiler
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```bash
22
+ quasispecies-profiler call --manifest replicates_counts.tsv -o out_variants/
23
+ ```
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "quasispecies-profiler"
7
+ version = "0.1.0"
8
+ description = "Replicate-aware Beta-Binomial intra-host viral variant caller and diversity profiler"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {text = "MIT"}
12
+ authors = [
13
+ { name = "Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute", email = "shwetabac@gmail.com" },
14
+ ]
15
+ maintainers = [
16
+ { name = "Dr. Shweta Singh", email = "shwetabac@gmail.com" },
17
+ ]
18
+ keywords = ["virome", "quasispecies", "variant-calling", "beta-binomial", "bioinformatics"]
19
+ dependencies = [
20
+ "numpy>=1.24.0",
21
+ "scipy>=1.10.0",
22
+ "pandas>=2.0.0",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/molecularplantpathology/Virome-Suite"
27
+ Repository = "https://github.com/molecularplantpathology/Virome-Suite.git"
28
+ Issues = "https://github.com/molecularplantpathology/Virome-Suite/issues"
29
+
30
+ [project.scripts]
31
+ quasispecies-profiler = "quasispecies_profiler.cli:main"
32
+
33
+ [tool.setuptools]
34
+ packages = ["quasispecies_profiler"]
@@ -0,0 +1,30 @@
1
+ """Package 3: quasispecies_profiler — Replicate Beta-Binomial Intra-Host Variant Caller."""
2
+
3
+ from quasispecies_profiler.beta_binomial_caller import (
4
+ VariantCallRecord,
5
+ call_variants_across_replicates,
6
+ compute_profile_ci_95,
7
+ estimate_background_error_and_prior,
8
+ log_beta_binomial_pmf,
9
+ penalized_log_likelihood,
10
+ )
11
+ from quasispecies_profiler.diversity_metrics import (
12
+ compute_nei_gojobori_dnds,
13
+ compute_nucleotide_diversity_pi,
14
+ compute_shannon_entropy,
15
+ )
16
+
17
+ __version__ = "0.1.0"
18
+
19
+ __all__ = [
20
+ "__version__",
21
+ "VariantCallRecord",
22
+ "call_variants_across_replicates",
23
+ "compute_nei_gojobori_dnds",
24
+ "compute_nucleotide_diversity_pi",
25
+ "compute_profile_ci_95",
26
+ "compute_shannon_entropy",
27
+ "estimate_background_error_and_prior",
28
+ "log_beta_binomial_pmf",
29
+ "penalized_log_likelihood",
30
+ ]
@@ -0,0 +1,395 @@
1
+ """Hierarchical Empirical Bayes Beta-Binomial Variant Caller (`quasispecies_profiler.beta_binomial_caller`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import math
7
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
8
+
9
+ import numpy as np
10
+ from scipy.optimize import brentq, minimize, minimize_scalar
11
+ from scipy.special import betaln, gammaln
12
+ from scipy.stats import chi2
13
+
14
+
15
+ @dataclasses.dataclass
16
+ class VariantCallRecord:
17
+ """Evaluated intra-host candidate site output."""
18
+
19
+ pos: int
20
+ ref: str
21
+ alt: str
22
+ mean_depth: float
23
+ vaf_hat: float
24
+ rho_hat: float
25
+ ci_95_low: float
26
+ ci_95_high: float
27
+ lrt_stat: float
28
+ p_value: float
29
+ q_value: float
30
+ status: str
31
+ is_called: bool
32
+ replicate_vafs: List[float]
33
+
34
+
35
+ def log_beta_binomial_pmf(
36
+ k: np.ndarray,
37
+ n: np.ndarray,
38
+ mu: float,
39
+ rho: float,
40
+ ) -> np.ndarray:
41
+ """Numerically stable log-PMF of Beta-Binomial(n, mu, rho) in pure log-space (`EC-3.1`)."""
42
+ mu_c = min(max(float(mu), 1e-7), 1.0 - 1e-7)
43
+ rho_c = min(max(float(rho), 1e-7), 0.5)
44
+ phi = (1.0 / rho_c) - 1.0
45
+ alpha = mu_c * phi
46
+ beta_p = (1.0 - mu_c) * phi
47
+ log_comb = gammaln(n + 1.0) - gammaln(k + 1.0) - gammaln(n - k + 1.0)
48
+ return log_comb + betaln(k + alpha, n - k + beta_p) - betaln(alpha, beta_p)
49
+
50
+
51
+ def penalized_log_likelihood(
52
+ mu: float,
53
+ rho: float,
54
+ k: np.ndarray,
55
+ n: np.ndarray,
56
+ mu_rho_prior: float,
57
+ sigma_rho_prior: float,
58
+ ) -> float:
59
+ """Penalized Empirical Bayes Beta-Binomial log-likelihood."""
60
+ ll = float(np.sum(log_beta_binomial_pmf(k, n, mu, rho)))
61
+ penalty = ((math.log(max(rho, 1e-7)) - mu_rho_prior) ** 2) / (2.0 * (sigma_rho_prior ** 2))
62
+ return ll - penalty
63
+
64
+
65
+ def estimate_background_error_and_prior(
66
+ sites: Sequence[Dict[str, Any]],
67
+ max_bg_vaf: float = 0.002,
68
+ ) -> Tuple[Dict[str, float], float, float, float]:
69
+ """Select monomorphic background sites via MAX replicate VAF < 0.002 (`P0-QP-1`).
70
+
71
+ Returns (context_eps_map, global_eps_bg, mu_rho_prior, sigma_rho_prior).
72
+ """
73
+ bg_sites: List[Tuple[str, np.ndarray, np.ndarray]] = []
74
+ for s in sites:
75
+ k_arr = np.asarray(s["k"], dtype=float)
76
+ n_arr = np.asarray(s["n"], dtype=float)
77
+ if np.any(n_arr <= 0):
78
+ continue
79
+ vafs = k_arr / n_arr
80
+ if float(np.max(vafs)) < max_bg_vaf:
81
+ sub_ctx = f"{s.get('ref', 'N')}>{s.get('alt', 'N')}"
82
+ bg_sites.append((sub_ctx, k_arr, n_arr))
83
+
84
+ if not bg_sites:
85
+ return {}, 5e-4, math.log(1e-4), 3.5
86
+
87
+ total_k = sum(float(np.sum(k)) for _, k, _ in bg_sites)
88
+ total_n = sum(float(np.sum(n)) for _, _, n in bg_sites)
89
+ global_eps = max(5e-4, total_k / max(1.0, total_n))
90
+
91
+ ctx_counts: Dict[str, List[Tuple[np.ndarray, np.ndarray]]] = {}
92
+ log_rhos: List[float] = []
93
+ for ctx, k_arr, n_arr in bg_sites:
94
+ ctx_counts.setdefault(ctx, []).append((k_arr, n_arr))
95
+ # Method-of-moments overdispersion estimate bounded to [1e-6, 0.5]
96
+ p_bar = float(np.sum(k_arr)) / max(1.0, float(np.sum(n_arr)))
97
+ n_bar = float(np.mean(n_arr))
98
+ if p_bar > 0 and n_bar > 1.0 and len(k_arr) >= 2:
99
+ s2 = float(np.var(k_arr, ddof=1))
100
+ bin_var = n_bar * p_bar * (1.0 - p_bar)
101
+ rho_mm = (s2 - bin_var) / max(1e-9, bin_var * (n_bar - 1.0))
102
+ rho_est = min(max(rho_mm, 1e-6), 0.5)
103
+ else:
104
+ rho_est = 1e-5
105
+ log_rhos.append(math.log(rho_est))
106
+
107
+ ctx_eps_map: Dict[str, float] = {}
108
+ for ctx, items in ctx_counts.items():
109
+ if len(items) >= 5:
110
+ ck = sum(float(np.sum(x[0])) for x in items)
111
+ cn = sum(float(np.sum(x[1])) for x in items)
112
+ ctx_eps_map[ctx] = max(5e-4, ck / max(1.0, cn))
113
+ else:
114
+ ctx_eps_map[ctx] = global_eps
115
+
116
+ mu_rho = float(np.mean(log_rhos)) if log_rhos else math.log(1e-4)
117
+ raw_std = float(np.std(log_rhos, ddof=1)) if len(log_rhos) >= 2 else 0.0
118
+ # Weakly informative diffuse log-dispersion prior scale (`P0-QP-2`)
119
+ sigma_rho = max(3.5, raw_std)
120
+ return ctx_eps_map, global_eps, mu_rho, sigma_rho
121
+
122
+
123
+ def _fit_penalized_mle(
124
+ k: np.ndarray,
125
+ n: np.ndarray,
126
+ mu_rho_prior: float,
127
+ sigma_rho_prior: float,
128
+ ) -> Tuple[float, float, float]:
129
+ """Bounded L-BFGS-B + multi-start initialization for (mu_hat, rho_hat, max_ll)."""
130
+ p_init = min(max(float(np.sum(k)) / max(1.0, float(np.sum(n))), 1e-5), 1.0 - 1e-5)
131
+
132
+ def neg_obj(params: np.ndarray) -> float:
133
+ mu_val = float(params[0])
134
+ rho_val = math.exp(float(params[1]))
135
+ return -penalized_log_likelihood(mu_val, rho_val, k, n, mu_rho_prior, sigma_rho_prior)
136
+
137
+ best_mu = p_init
138
+ best_rho = math.exp(mu_rho_prior)
139
+ best_ll = penalized_log_likelihood(best_mu, best_rho, k, n, mu_rho_prior, sigma_rho_prior)
140
+
141
+ for rho_start in (1e-5, 1e-3, 0.02):
142
+ res = minimize(
143
+ neg_obj,
144
+ x0=np.array([p_init, math.log(rho_start)]),
145
+ method="L-BFGS-B",
146
+ bounds=[(1e-5, 1.0 - 1e-5), (math.log(1e-6), math.log(0.5))],
147
+ )
148
+ cand_mu = float(res.x[0])
149
+ cand_rho = math.exp(float(res.x[1]))
150
+ cand_ll = -float(res.fun)
151
+ if cand_ll > best_ll:
152
+ best_ll = cand_ll
153
+ best_mu = cand_mu
154
+ best_rho = cand_rho
155
+
156
+ return best_mu, best_rho, best_ll
157
+
158
+
159
+ def _profile_ll_at_mu(
160
+ mu_fixed: float,
161
+ k: np.ndarray,
162
+ n: np.ndarray,
163
+ mu_rho_prior: float,
164
+ sigma_rho_prior: float,
165
+ ) -> Tuple[float, float]:
166
+ """Maximize penalized log-likelihood over rho for a fixed mu."""
167
+ res = minimize_scalar(
168
+ lambda log_r: -penalized_log_likelihood(
169
+ mu_fixed, math.exp(float(log_r)), k, n, mu_rho_prior, sigma_rho_prior
170
+ ),
171
+ bounds=(math.log(1e-6), math.log(0.5)),
172
+ method="bounded",
173
+ )
174
+ rho_opt = math.exp(float(res.x))
175
+ return -float(res.fun), rho_opt
176
+
177
+
178
+ def compute_profile_ci_95(
179
+ mu_hat: float,
180
+ max_ll: float,
181
+ k: np.ndarray,
182
+ n: np.ndarray,
183
+ mu_rho_prior: float,
184
+ sigma_rho_prior: float,
185
+ ) -> Tuple[float, float]:
186
+ """Compute sign-bracketed 95% Profile Likelihood Confidence Interval (`P1-QP-4`)."""
187
+ cutoff = 3.841458820694124 # chi2_{1, 0.95}
188
+ mu_min = 1e-5
189
+ mu_max = 1.0 - 1e-5
190
+
191
+ def diff_fn(m: float) -> float:
192
+ pll, _ = _profile_ll_at_mu(m, k, n, mu_rho_prior, sigma_rho_prior)
193
+ return 2.0 * (max_ll - pll) - cutoff
194
+
195
+ # Lower bound in [mu_min, mu_hat]
196
+ if mu_hat <= mu_min or diff_fn(mu_min) <= 0.0:
197
+ ci_low = 0.0
198
+ else:
199
+ ci_low = float(brentq(diff_fn, mu_min, mu_hat, xtol=1e-6))
200
+
201
+ # Upper bound in [mu_hat, mu_max]
202
+ if mu_hat >= mu_max or diff_fn(mu_max) <= 0.0:
203
+ ci_high = 1.0
204
+ else:
205
+ ci_high = float(brentq(diff_fn, mu_hat, mu_max, xtol=1e-6))
206
+
207
+ return ci_low, ci_high
208
+
209
+
210
+ def _vectorized_null_bootstrap_pvalue(
211
+ obs_lrt: float,
212
+ n: np.ndarray,
213
+ eps_bg: float,
214
+ rho_null: float,
215
+ n_boot: int = 2000,
216
+ seed: int = 42,
217
+ ) -> float:
218
+ """Vectorized null parametric bootstrap p-value with asymptotic tail resolution (`P0-QP-3`)."""
219
+ if obs_lrt <= 0.0:
220
+ return 1.0
221
+
222
+ rng = np.random.default_rng(seed)
223
+ m_reps = len(n)
224
+ rho_c = min(max(rho_null, 1e-6), 0.5)
225
+ phi = (1.0 / rho_c) - 1.0
226
+ a_null = max(eps_bg * phi, 1e-6)
227
+ b_null = max((1.0 - eps_bg) * phi, 1e-6)
228
+
229
+ # Simulate (n_boot, m_reps) Beta-Binomial null counts in one vectorized NumPy draw
230
+ p_draws = rng.beta(a_null, b_null, size=(n_boot, m_reps))
231
+ k_boot = rng.binomial(n.astype(int)[None, :], p_draws).astype(float)
232
+
233
+ n_row = n[None, :]
234
+ mu_boot = np.clip(np.sum(k_boot, axis=1) / np.sum(n_row, axis=1), eps_bg, 1.0 - 1e-5)
235
+
236
+ # Evaluate vectorized Beta-Binomial LRT under null dispersion
237
+ a_alt = mu_boot[:, None] * phi
238
+ b_alt = (1.0 - mu_boot[:, None]) * phi
239
+ ll_alt = np.sum(betaln(k_boot + a_alt, n_row - k_boot + b_alt) - betaln(a_alt, b_alt), axis=1)
240
+ ll_0 = np.sum(betaln(k_boot + a_null, n_row - k_boot + b_null) - betaln(a_null, b_null), axis=1)
241
+ lrt_boot = np.maximum(0.0, 2.0 * (ll_alt - ll_0))
242
+
243
+ b_exceed = int(np.sum(lrt_boot >= obs_lrt))
244
+ if b_exceed == 0 and obs_lrt > 15.0:
245
+ # Extreme tail resolution calibrated by 0.5 * chi2_1 survival function capped by 1/(n_boot+1)
246
+ asymp_p = 0.5 * float(chi2.sf(obs_lrt, df=1))
247
+ return min(1.0 / float(n_boot + 1), max(asymp_p, 1e-16))
248
+
249
+ return float(b_exceed + 1) / float(n_boot + 1)
250
+
251
+
252
+ def call_variants_across_replicates(
253
+ sites: Sequence[Dict[str, Any]],
254
+ replicate_type: str = "technical",
255
+ alpha_fdr: float = 0.01,
256
+ n_boot: int = 2000,
257
+ seed: int = 42,
258
+ ) -> List[VariantCallRecord]:
259
+ """Execute full Empirical Bayes Beta-Binomial variant calling across M replicates."""
260
+ ctx_eps_map, global_eps, mu_rho_prior, sigma_rho_prior = estimate_background_error_and_prior(sites)
261
+
262
+ prelim_records: List[VariantCallRecord] = []
263
+ evaluable_indices: List[int] = []
264
+
265
+ for idx, site in enumerate(sites):
266
+ pos = int(site["pos"])
267
+ ref = str(site.get("ref", "N")).upper()
268
+ alt = str(site.get("alt", "N")).upper()
269
+ k = np.asarray(site["k"], dtype=float)
270
+ n = np.asarray(site["n"], dtype=float)
271
+ m_reps = len(k)
272
+ mean_depth = float(np.mean(n)) if m_reps > 0 else 0.0
273
+ rep_vafs = [float(kv / max(1.0, nv)) for kv, nv in zip(k, n)]
274
+ pooled_vaf = float(np.sum(k)) / max(1.0, float(np.sum(n)))
275
+
276
+ # Short-circuit zero alternate counts (`EC-3.4`)
277
+ if float(np.sum(k)) <= 0.0:
278
+ prelim_records.append(
279
+ VariantCallRecord(
280
+ pos=pos, ref=ref, alt=alt, mean_depth=mean_depth,
281
+ vaf_hat=0.0, rho_hat=1e-6, ci_95_low=0.0, ci_95_high=0.0,
282
+ lrt_stat=0.0, p_value=1.0, q_value=1.0,
283
+ status="MONOMORPHIC_ZERO", is_called=False, replicate_vafs=rep_vafs,
284
+ )
285
+ )
286
+ continue
287
+
288
+ # Step 1: Depth-dependent Limit of Detection Pre-Gate (`EC-3.3`)
289
+ if mean_depth < 100.0:
290
+ prelim_records.append(
291
+ VariantCallRecord(
292
+ pos=pos, ref=ref, alt=alt, mean_depth=mean_depth,
293
+ vaf_hat=pooled_vaf, rho_hat=1e-6, ci_95_low=0.0, ci_95_high=0.0,
294
+ lrt_stat=0.0, p_value=1.0, q_value=1.0,
295
+ status="UNASSESSED_LOW_DEPTH", is_called=False, replicate_vafs=rep_vafs,
296
+ )
297
+ )
298
+ continue
299
+
300
+ if mean_depth < 1000.0 and pooled_vaf < 0.030:
301
+ prelim_records.append(
302
+ VariantCallRecord(
303
+ pos=pos, ref=ref, alt=alt, mean_depth=mean_depth,
304
+ vaf_hat=pooled_vaf, rho_hat=1e-6, ci_95_low=0.0, ci_95_high=0.0,
305
+ lrt_stat=0.0, p_value=1.0, q_value=1.0,
306
+ status="BELOW_LOD_AT_DEPTH", is_called=False, replicate_vafs=rep_vafs,
307
+ )
308
+ )
309
+ continue
310
+
311
+ ctx_key = f"{ref}>{alt}"
312
+ eps_bg = ctx_eps_map.get(ctx_key, global_eps)
313
+
314
+ # Fit penalized Beta-Binomial MLE
315
+ mu_hat, rho_hat, max_ll = _fit_penalized_mle(k, n, mu_rho_prior, sigma_rho_prior)
316
+
317
+ # Pure monomorphic / sub-threshold background check (`P0-QP-1`)
318
+ active_thresh = max(3.0 * eps_bg, 0.0015)
319
+ m_active = sum(1 for v in rep_vafs if v > active_thresh)
320
+ cv_vaf = (float(np.std(rep_vafs, ddof=1)) / max(1e-9, float(np.mean(rep_vafs)))) if m_reps >= 2 else 0.0
321
+
322
+ if float(np.max(rep_vafs)) < 0.002 or (m_active == 0 and (mu_hat <= eps_bg or pooled_vaf < 0.005)):
323
+ prelim_records.append(
324
+ VariantCallRecord(
325
+ pos=pos, ref=ref, alt=alt, mean_depth=mean_depth,
326
+ vaf_hat=mu_hat, rho_hat=rho_hat, ci_95_low=0.0, ci_95_high=min(1.0, mu_hat * 2.0),
327
+ lrt_stat=0.0, p_value=1.0, q_value=1.0,
328
+ status="BACKGROUND_NOISE", is_called=False, replicate_vafs=rep_vafs,
329
+ )
330
+ )
331
+ continue
332
+
333
+ # Technical Replicate Jackpot Veto (`P0-QP-2`)
334
+ if replicate_type == "technical" and m_reps >= 3 and (
335
+ m_active <= 1 or (rho_hat > 0.005 and cv_vaf > 1.0)
336
+ ):
337
+ prelim_records.append(
338
+ VariantCallRecord(
339
+ pos=pos, ref=ref, alt=alt, mean_depth=mean_depth,
340
+ vaf_hat=mu_hat, rho_hat=rho_hat, ci_95_low=0.0, ci_95_high=min(1.0, max(rep_vafs)),
341
+ lrt_stat=0.0, p_value=1.0, q_value=1.0,
342
+ status="REJECTED_PCR_JACKPOT", is_called=False, replicate_vafs=rep_vafs,
343
+ )
344
+ )
345
+ continue
346
+
347
+ if mu_hat <= eps_bg or pooled_vaf < 0.005:
348
+ prelim_records.append(
349
+ VariantCallRecord(
350
+ pos=pos, ref=ref, alt=alt, mean_depth=mean_depth,
351
+ vaf_hat=mu_hat, rho_hat=rho_hat, ci_95_low=0.0, ci_95_high=min(1.0, mu_hat * 2.0),
352
+ lrt_stat=0.0, p_value=1.0, q_value=1.0,
353
+ status="BACKGROUND_NOISE", is_called=False, replicate_vafs=rep_vafs,
354
+ )
355
+ )
356
+ continue
357
+
358
+ null_ll, rho_0 = _profile_ll_at_mu(eps_bg, k, n, mu_rho_prior, sigma_rho_prior)
359
+ lrt_stat = max(0.0, 2.0 * (max_ll - null_ll))
360
+ p_val = _vectorized_null_bootstrap_pvalue(
361
+ obs_lrt=lrt_stat, n=n, eps_bg=eps_bg, rho_null=max(rho_0, math.exp(mu_rho_prior)),
362
+ n_boot=n_boot, seed=seed + idx,
363
+ )
364
+ ci_low, ci_high = compute_profile_ci_95(mu_hat, max_ll, k, n, mu_rho_prior, sigma_rho_prior)
365
+
366
+ evaluable_indices.append(idx)
367
+ prelim_records.append(
368
+ VariantCallRecord(
369
+ pos=pos, ref=ref, alt=alt, mean_depth=mean_depth,
370
+ vaf_hat=mu_hat, rho_hat=rho_hat, ci_95_low=ci_low, ci_95_high=ci_high,
371
+ lrt_stat=lrt_stat, p_value=p_val, q_value=1.0,
372
+ status="CANDIDATE_EVALUATED", is_called=False, replicate_vafs=rep_vafs,
373
+ )
374
+ )
375
+
376
+ # Benjamini-Hochberg FDR multiplicity adjustment over evaluable candidate family (`P0-QP-3`)
377
+ m_eval = len(evaluable_indices)
378
+ if m_eval > 0:
379
+ sorted_eval = sorted(evaluable_indices, key=lambda i: prelim_records[i].p_value)
380
+ q_raw = [0.0] * m_eval
381
+ for rank_idx, rec_idx in enumerate(sorted_eval, start=1):
382
+ q_raw[rank_idx - 1] = (prelim_records[rec_idx].p_value * float(m_eval)) / float(rank_idx)
383
+ # Enforce monotonicity from largest rank down
384
+ running_min = 1.0
385
+ for r_back in range(m_eval - 1, -1, -1):
386
+ running_min = min(running_min, q_raw[r_back])
387
+ rec_i = sorted_eval[r_back]
388
+ prelim_records[rec_i].q_value = running_min
389
+ if running_min <= alpha_fdr:
390
+ prelim_records[rec_i].is_called = True
391
+ prelim_records[rec_i].status = "PASS_ISNV"
392
+ else:
393
+ prelim_records[rec_i].status = "FILTERED_FDR"
394
+
395
+ return prelim_records
@@ -0,0 +1,147 @@
1
+ """CLI Entrypoint and Pipeline Runner for Package 3: `quasispecies-profiler`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ import pathlib
9
+ import sys
10
+ from typing import Any, Dict, List, Optional
11
+
12
+ from quasispecies_profiler import __version__
13
+ from quasispecies_profiler.beta_binomial_caller import call_variants_across_replicates
14
+ from quasispecies_profiler.diversity_metrics import (
15
+ compute_nucleotide_diversity_pi,
16
+ compute_shannon_entropy,
17
+ )
18
+
19
+
20
+ def _parse_replicate_tsv(manifest_path: pathlib.Path) -> List[Dict[str, Any]]:
21
+ with manifest_path.open("r", encoding="utf-8") as f:
22
+ rows = list(csv.DictReader(f, delimiter="\t"))
23
+ if not rows:
24
+ raise ValueError(f"Replicate table is empty: {manifest_path}")
25
+
26
+ cols = list(rows[0].keys())
27
+ k_cols = sorted([c for c in cols if c.endswith("_k")])
28
+ n_cols = sorted([c for c in cols if c.endswith("_n")])
29
+ if not k_cols or len(k_cols) != len(n_cols):
30
+ raise ValueError("Manifest TSV must contain matched rep*_k and rep*_n columns.")
31
+
32
+ sites: List[Dict[str, Any]] = []
33
+ for r in rows:
34
+ sites.append(
35
+ {
36
+ "pos": int(r["pos"]),
37
+ "ref": r.get("ref", "N"),
38
+ "alt": r.get("alt", "N"),
39
+ "k": [float(r[c]) for c in k_cols],
40
+ "n": [float(r[c]) for c in n_cols],
41
+ }
42
+ )
43
+ return sites
44
+
45
+
46
+ def build_parser() -> argparse.ArgumentParser:
47
+ parser = argparse.ArgumentParser(
48
+ prog="quasispecies-profiler",
49
+ description="quasispecies_profiler: Hierarchical Empirical Bayes Beta-Binomial intra-host variant caller.",
50
+ )
51
+ parser.add_argument("--version", action="version", version=f"quasispecies-profiler {__version__}")
52
+ sub = parser.add_subparsers(dest="subcommand", required=True)
53
+
54
+ call_p = sub.add_parser("call", help="Call replicate-aware intra-host variants (iSNVs) with PCR noise filtering.")
55
+ call_p.add_argument("--manifest", type=pathlib.Path, required=True, help="Replicate count table TSV.")
56
+ call_p.add_argument("--ref", type=pathlib.Path, required=False, help="Optional viral reference genome FASTA.")
57
+ call_p.add_argument(
58
+ "--replicate-type",
59
+ choices=["technical", "biological"],
60
+ default="technical",
61
+ help="Replication model.",
62
+ )
63
+ call_p.add_argument("--alpha", type=float, default=0.01, help="Target Benjamini-Hochberg FDR threshold.")
64
+ call_p.add_argument("-o", "--output", type=pathlib.Path, required=True, help="Output directory.")
65
+ return parser
66
+
67
+
68
+ def main(argv: Optional[List[str]] = None) -> int:
69
+ parser = build_parser()
70
+ try:
71
+ args = parser.parse_args(argv)
72
+ except SystemExit as exc:
73
+ return int(exc.code) if exc.code is not None else 2
74
+
75
+ if args.subcommand == "call":
76
+ if not args.manifest.exists():
77
+ print(f"Error: Manifest file not found: {args.manifest}", file=sys.stderr)
78
+ return 2
79
+
80
+ try:
81
+ sites = _parse_replicate_tsv(args.manifest)
82
+ except Exception as exc:
83
+ print(f"Manifest parse error: {exc}", file=sys.stderr)
84
+ return 2
85
+
86
+ genome_len: Optional[int] = None
87
+ if args.ref is not None and args.ref.exists():
88
+ raw_lines = [
89
+ ln.strip() for ln in args.ref.read_text(encoding="utf-8").splitlines()
90
+ if ln.strip() and not ln.startswith(">")
91
+ ]
92
+ genome_len = sum(len(ln) for ln in raw_lines)
93
+
94
+ calls = call_variants_across_replicates(
95
+ sites=sites,
96
+ replicate_type=args.replicate_type,
97
+ alpha_fdr=args.alpha,
98
+ )
99
+
100
+ args.output.mkdir(parents=True, exist_ok=True)
101
+ out_tsv = args.output / "variants_called.tsv"
102
+ summary_json = args.output / "quasispecies_summary.json"
103
+
104
+ fieldnames = [
105
+ "pos", "ref", "alt", "mean_depth", "vaf_hat", "rho_hat",
106
+ "ci_95_low", "ci_95_high", "lrt_stat", "p_value", "q_value",
107
+ "status", "is_called",
108
+ ]
109
+ with out_tsv.open("w", encoding="utf-8", newline="") as tf:
110
+ writer = csv.DictWriter(tf, fieldnames=fieldnames, delimiter="\t")
111
+ writer.writeheader()
112
+ for c in calls:
113
+ writer.writerow(
114
+ {
115
+ "pos": c.pos,
116
+ "ref": c.ref,
117
+ "alt": c.alt,
118
+ "mean_depth": f"{c.mean_depth:.1f}",
119
+ "vaf_hat": f"{c.vaf_hat:.6f}",
120
+ "rho_hat": f"{c.rho_hat:.6f}",
121
+ "ci_95_low": f"{c.ci_95_low:.6f}",
122
+ "ci_95_high": f"{c.ci_95_high:.6f}",
123
+ "lrt_stat": f"{c.lrt_stat:.4f}",
124
+ "p_value": f"{c.p_value:.6e}",
125
+ "q_value": f"{c.q_value:.6e}",
126
+ "status": c.status,
127
+ "is_called": c.is_called,
128
+ }
129
+ )
130
+
131
+ passed_vafs = [c.vaf_hat if c.is_called else 0.0 for c in calls]
132
+ depths = [c.mean_depth for c in calls]
133
+ summary = {
134
+ "total_evaluated_loci": len(calls),
135
+ "called_isnv_count": sum(1 for c in calls if c.is_called),
136
+ "rejected_pcr_jackpots": sum(1 for c in calls if c.status == "REJECTED_PCR_JACKPOT"),
137
+ "shannon_entropy_H": compute_shannon_entropy(passed_vafs, genome_length=genome_len),
138
+ "nucleotide_diversity_pi": compute_nucleotide_diversity_pi(passed_vafs, depths, genome_length=genome_len),
139
+ }
140
+ summary_json.write_text(json.dumps(summary, indent=2), encoding="utf-8")
141
+ return 0
142
+
143
+ return 0
144
+
145
+
146
+ if __name__ == "__main__":
147
+ raise SystemExit(main())
@@ -0,0 +1,149 @@
1
+ """Intra-Host Viral Population Genetics Metrics (`quasispecies_profiler.diversity_metrics`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Dict, Optional, Sequence, Tuple
7
+
8
+ _STANDARD_CODON_TABLE: Dict[str, str] = {
9
+ "TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L",
10
+ "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L",
11
+ "ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M",
12
+ "GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
13
+ "TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S",
14
+ "CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P",
15
+ "ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T",
16
+ "GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A",
17
+ "TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*",
18
+ "CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q",
19
+ "AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K",
20
+ "GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E",
21
+ "TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W",
22
+ "CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R",
23
+ "AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R",
24
+ "GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G",
25
+ }
26
+
27
+
28
+ def compute_shannon_entropy(vafs: Sequence[float], genome_length: Optional[int] = None) -> float:
29
+ """Compute mean normalized per-site Shannon entropy H in bits across genome length L."""
30
+ l_denom = int(genome_length) if (genome_length is not None and genome_length > 0) else max(1, len(vafs))
31
+ total_h = 0.0
32
+ ln2 = math.log(2.0)
33
+ for mu in vafs:
34
+ p = min(max(float(mu), 0.0), 1.0)
35
+ if 0.0 < p < 1.0:
36
+ total_h += -(p * math.log(p) + (1.0 - p) * math.log(1.0 - p)) / ln2
37
+ return total_h / float(l_denom)
38
+
39
+
40
+ def compute_nucleotide_diversity_pi(
41
+ vafs: Sequence[float],
42
+ depths: Sequence[float],
43
+ genome_length: Optional[int] = None,
44
+ ) -> float:
45
+ """Compute unbiased intra-host nucleotide diversity pi with n_i < 2 zero-division guard (`P1-QP-4`)."""
46
+ l_denom = int(genome_length) if (genome_length is not None and genome_length > 0) else max(1, len(vafs))
47
+ total_pi = 0.0
48
+ for mu, n_val in zip(vafs, depths):
49
+ n_f = float(n_val)
50
+ if n_f < 2.0:
51
+ continue
52
+ p = min(max(float(mu), 0.0), 1.0)
53
+ total_pi += (n_f / (n_f - 1.0)) * 2.0 * p * (1.0 - p)
54
+ return total_pi / float(l_denom)
55
+
56
+
57
+ def _codon_syn_nonsyn_sites(codon: str) -> Tuple[float, float]:
58
+ """Count Nei-Gojobori (1986) synonymous (s) and non-synonymous (n) sites for a sense codon (`P1-QP-4`)."""
59
+ c = codon.upper()
60
+ aa = _STANDARD_CODON_TABLE.get(c, "*")
61
+ if aa == "*" or len(c) != 3:
62
+ return 0.0, 0.0
63
+
64
+ s_sites = 0.0
65
+ n_sites = 0.0
66
+ for pos in range(3):
67
+ syn_neighbors = 0
68
+ valid_neighbors = 0
69
+ for base in "ACGT":
70
+ if base == c[pos]:
71
+ continue
72
+ mut = c[:pos] + base + c[pos + 1 :]
73
+ mut_aa = _STANDARD_CODON_TABLE.get(mut, "*")
74
+ if mut_aa == "*":
75
+ continue # Exclude nonsense stop-codon pathways (`P1-QP-4`)
76
+ valid_neighbors += 1
77
+ if mut_aa == aa:
78
+ syn_neighbors += 1
79
+ if valid_neighbors > 0:
80
+ frac_s = syn_neighbors / float(valid_neighbors)
81
+ s_sites += frac_s
82
+ n_sites += (1.0 - frac_s)
83
+ return s_sites, n_sites
84
+
85
+
86
+ def _jukes_cantor_distance(p: float) -> float:
87
+ """Guarded Jukes-Cantor saturation correction (`P1-QP-4`)."""
88
+ if p <= 0.0:
89
+ return 0.0
90
+ if p >= 0.749999:
91
+ return -0.75 * math.log(1.0 - (4.0 / 3.0) * 0.749999)
92
+ return -0.75 * math.log(1.0 - (4.0 / 3.0) * p)
93
+
94
+
95
+ def compute_nei_gojobori_dnds(
96
+ cds_seq: str,
97
+ coding_variants: Sequence[Tuple[int, str, float]],
98
+ ) -> Dict[str, Optional[float]]:
99
+ """Compute frequency-weighted Nei-Gojobori dN, dS, and dN/dS across a coding sequence (`P1-QP-4`).
100
+
101
+ `coding_variants`: sequence of `(zero_based_cds_nt_offset, alt_base, vaf)`.
102
+ """
103
+ seq = cds_seq.upper()
104
+ n_codons = len(seq) // 3
105
+ total_s_sites = 0.0
106
+ total_n_sites = 0.0
107
+
108
+ for c_idx in range(n_codons):
109
+ codon = seq[3 * c_idx : 3 * c_idx + 3]
110
+ s_c, n_c = _codon_syn_nonsyn_sites(codon)
111
+ total_s_sites += s_c
112
+ total_n_sites += n_c
113
+
114
+ s_diffs = 0.0
115
+ n_diffs = 0.0
116
+ for nt_offset, alt_base, vaf in coding_variants:
117
+ c_idx = int(nt_offset) // 3
118
+ pos_in_codon = int(nt_offset) % 3
119
+ if c_idx < 0 or c_idx >= n_codons:
120
+ continue
121
+ ref_codon = seq[3 * c_idx : 3 * c_idx + 3]
122
+ ref_aa = _STANDARD_CODON_TABLE.get(ref_codon, "*")
123
+ if ref_aa == "*":
124
+ continue
125
+ mut_codon = ref_codon[:pos_in_codon] + alt_base.upper() + ref_codon[pos_in_codon + 1 :]
126
+ mut_aa = _STANDARD_CODON_TABLE.get(mut_codon, "*")
127
+ if mut_aa == "*":
128
+ continue
129
+ w = min(max(float(vaf), 0.0), 1.0)
130
+ if mut_aa == ref_aa:
131
+ s_diffs += w
132
+ else:
133
+ n_diffs += w
134
+
135
+ p_s = s_diffs / total_s_sites if total_s_sites > 0 else 0.0
136
+ p_n = n_diffs / total_n_sites if total_n_sites > 0 else 0.0
137
+ d_s = _jukes_cantor_distance(p_s)
138
+ d_n = _jukes_cantor_distance(p_n)
139
+ dnds: Optional[float] = (d_n / d_s) if d_s > 0.0 else None
140
+
141
+ return {
142
+ "S_sites": total_s_sites,
143
+ "N_sites": total_n_sites,
144
+ "p_S": p_s,
145
+ "p_N": p_n,
146
+ "d_S": d_s,
147
+ "d_N": d_n,
148
+ "dN_dS": dnds,
149
+ }
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.4
2
+ Name: quasispecies-profiler
3
+ Version: 0.1.0
4
+ Summary: Replicate-aware Beta-Binomial intra-host viral variant caller and diversity profiler
5
+ Author-email: "Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute" <shwetabac@gmail.com>
6
+ Maintainer-email: "Dr. Shweta Singh" <shwetabac@gmail.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/molecularplantpathology/Virome-Suite
9
+ Project-URL: Repository, https://github.com/molecularplantpathology/Virome-Suite.git
10
+ Project-URL: Issues, https://github.com/molecularplantpathology/Virome-Suite/issues
11
+ Keywords: virome,quasispecies,variant-calling,beta-binomial,bioinformatics
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.24.0
16
+ Requires-Dist: scipy>=1.10.0
17
+ Requires-Dist: pandas>=2.0.0
18
+ Dynamic: license-file
19
+
20
+ # quasispecies-profiler
21
+
22
+ **Replicate-Aware Hierarchical Empirical Bayes Beta-Binomial Intra-Host Variant Caller & Diversity Profiler**
23
+
24
+ Part of the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
25
+
26
+ ## Key Features
27
+ - **PCR Amplification Jackpot Filtering:** Separates genuine intra-host viral variants (0.5%–5% VAF) from single-replicate RT-PCR overdispersion artifacts across technical and biological replicates.
28
+ - **Ultra-Deep Numerical Stability:** Log-space `betaln`/`gammaln` Beta-Binomial optimization stable beyond $100,000\times$ sequencing coverage.
29
+ - **Empirical Null Calibration & Profile CIs:** Vectorized null parametric bootstrap calibration with Benjamini-Hochberg FDR control, 95% Profile Likelihood Confidence Intervals, and depth-dependent Limits of Detection.
30
+ - **Population Genetics Metrics:** Genome-wide Shannon entropy ($H$), nucleotide diversity ($\pi$), and Nei-Gojobori $d_N/d_S$ selection ratios.
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install quasispecies-profiler
36
+ ```
37
+
38
+ ## Quick Start
39
+
40
+ ```bash
41
+ quasispecies-profiler call --manifest replicates_counts.tsv -o out_variants/
42
+ ```
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ quasispecies_profiler/__init__.py
5
+ quasispecies_profiler/beta_binomial_caller.py
6
+ quasispecies_profiler/cli.py
7
+ quasispecies_profiler/diversity_metrics.py
8
+ quasispecies_profiler.egg-info/PKG-INFO
9
+ quasispecies_profiler.egg-info/SOURCES.txt
10
+ quasispecies_profiler.egg-info/dependency_links.txt
11
+ quasispecies_profiler.egg-info/entry_points.txt
12
+ quasispecies_profiler.egg-info/requires.txt
13
+ quasispecies_profiler.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ quasispecies-profiler = quasispecies_profiler.cli:main
@@ -0,0 +1,3 @@
1
+ numpy>=1.24.0
2
+ scipy>=1.10.0
3
+ pandas>=2.0.0
@@ -0,0 +1 @@
1
+ quasispecies_profiler
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+