viro-networks 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.
- viro_networks-0.1.0/LICENSE +21 -0
- viro_networks-0.1.0/PKG-INFO +120 -0
- viro_networks-0.1.0/README.md +101 -0
- viro_networks-0.1.0/pyproject.toml +34 -0
- viro_networks-0.1.0/setup.cfg +4 -0
- viro_networks-0.1.0/viro_networks/__init__.py +35 -0
- viro_networks-0.1.0/viro_networks/cli.py +165 -0
- viro_networks-0.1.0/viro_networks/clr_consensus.py +226 -0
- viro_networks-0.1.0/viro_networks/hub_perturbation.py +156 -0
- viro_networks-0.1.0/viro_networks/sloan_neutral.py +165 -0
- viro_networks-0.1.0/viro_networks.egg-info/PKG-INFO +120 -0
- viro_networks-0.1.0/viro_networks.egg-info/SOURCES.txt +14 -0
- viro_networks-0.1.0/viro_networks.egg-info/dependency_links.txt +1 -0
- viro_networks-0.1.0/viro_networks.egg-info/entry_points.txt +2 -0
- viro_networks-0.1.0/viro_networks.egg-info/requires.txt +3 -0
- viro_networks-0.1.0/viro_networks.egg-info/top_level.txt +1 -0
|
@@ -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,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: viro-networks
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Compositional virome co-occurrence consensus networks and Sloan neutral community model solver
|
|
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,ecological-networks,sparcc,neutral-model,compositional-data
|
|
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
|
+
# viro-networks
|
|
21
|
+
|
|
22
|
+
[](https://pypi.org/project/viro-networks/)
|
|
23
|
+
[](https://github.com/molecularplantpathology/Virome-Suite/actions/workflows/ci.yml)
|
|
24
|
+
[](LICENSE)
|
|
25
|
+
|
|
26
|
+
**Compositional CLR Consensus Co-Occurrence Networks, Sloan Neutral Community Modeling, and Pure-Python Topological Hub Perturbation.**
|
|
27
|
+
|
|
28
|
+
`viro-networks` is a standalone package within the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Ecological & Statistical Methodology
|
|
33
|
+
|
|
34
|
+
1. **Sample-Size Safety Gate & CLR Normalization (`viro_networks.clr_consensus`):**
|
|
35
|
+
- Enforces a minimum cohort size guard ($N_{\text{samples}} < 5 \implies$ `CohortInsufficientError` / CLI exit code `4` `ABSTAIN_INSUFFICIENT_SAMPLES`) to prevent underpowered false-positive networks.
|
|
36
|
+
- Applies Centered Log-Ratio (CLR) transformation across a pseudocount sensitivity grid $\delta \in \{0.1, 0.5, 1.0\}$ and reports edge Jaccard concordance across pseudocount extremes.
|
|
37
|
+
2. **Three-Estimator Bootstrap Consensus Network (`viro_networks.clr_consensus`):**
|
|
38
|
+
Retains an undirected signed edge $(i, j)$ if and only if **$\ge 2$ of 3 compositional estimators** agree in sign above threshold AND sample-level bootstrap stability across $B = 100$ resamples meets `stability_threshold` ($\ge 0.80$):
|
|
39
|
+
- **Positive-Floored SparCC:** Log-ratio variation basis variance floored at $\omega_i^2 \ge \max(0.10\,\mathrm{Var}(\mathrm{CLR}_{\cdot i}), 10^{-6})$ ($|r^{\text{SparCC}}| \ge 0.35$).
|
|
40
|
+
- **Shrinkage Graphical Partial Correlation:** Regularized CLR correlation precision inversion $\mathbf{\Theta} = ((1 - \alpha)\mathbf{R}_{\text{CLR}} + \alpha \mathbf{I})^{-1}$ with $\alpha = 0.15$ ($|\omega_{ij}| \ge 0.25$).
|
|
41
|
+
- **CLR Rank Association:** Spearman rank correlation on CLR coordinates ($|\rho^{\text{rank}}_{ij}| \ge 0.35$).
|
|
42
|
+
3. **Domain-Clipped Sloan Neutral Community Model (`viro_networks.sloan_neutral`):**
|
|
43
|
+
Fits Sloan's (2006) neutral immigration-drift parameter $N_e m \in [10^{-3}, 10^4]$ predicting taxon occupancy $\hat{f}_i = 1 - \mathrm{I}_d(2 N_e m p_i, 2 N_e m (1 - p_i))$ from mean relative abundance $p_i$, reporting zero-variance-guarded $R^2$, 95% Wilson score intervals, and Benjamini-Hochberg FDR-adjusted binomial departure $q$-values (`neutral_drift_consistent`, `candidate_above_neutral_partition`, `candidate_below_neutral_partition`).
|
|
44
|
+
4. **Topological Hub Perturbation (`viro_networks.hub_perturbation`):**
|
|
45
|
+
Computes degree centrality, exact Brandes shortest-path betweenness centrality, largest connected component (LCC) retention, and eigenvalue natural connectivity drop $\Delta \bar{\lambda}\%$ upon *in silico* single-node removal using pure NumPy/Python (zero `networkx` dependency).
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install viro-networks
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Command-Line Usage (`viro-networks`)
|
|
58
|
+
|
|
59
|
+
### Input Cohort Count Matrix (`virome_cohort_counts.tsv`)
|
|
60
|
+
|
|
61
|
+
Rows represent samples ($N \ge 5$) and columns represent viral taxa/OTUs (raw mapped read counts or RPKM/CPM):
|
|
62
|
+
|
|
63
|
+
```tsv
|
|
64
|
+
sample_id Badnavirus_A Badnavirus_B Poacevirus_SCSMV Polerovirus_SCYLV Begomovirus_C Mastrevirus_D
|
|
65
|
+
SAMPLE_01 169 560 0 0 552 68
|
|
66
|
+
SAMPLE_02 1327 1053 3486 2921 665 112
|
|
67
|
+
SAMPLE_03 833 0 0 0 269 320
|
|
68
|
+
...
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Run Network & Neutral Model Inference
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
viro-networks infer \
|
|
75
|
+
--counts virome_cohort_counts.tsv \
|
|
76
|
+
--metadata cohort_metadata.tsv \
|
|
77
|
+
--bootstraps 100 \
|
|
78
|
+
--stability 0.80 \
|
|
79
|
+
--output network_results/
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### CLI Options (`viro-networks infer`)
|
|
83
|
+
|
|
84
|
+
| Argument | Required | Default | Description |
|
|
85
|
+
| :--- | :---: | :---: | :--- |
|
|
86
|
+
| `--counts` | Yes | — | Tab-separated sample $\times$ taxon abundance matrix TSV (first column = `sample_id`) |
|
|
87
|
+
| `--metadata` | No | `None` | Optional sample metadata TSV |
|
|
88
|
+
| `--bootstraps` | No | `100` | Number of sample-level bootstrap resamples for consensus stability |
|
|
89
|
+
| `--stability` | No | `0.80` | Minimum bootstrap selection frequency in $[0, 1]$ required to retain an edge |
|
|
90
|
+
| `-o`, `--output` | Yes | — | Output directory for network edges, Sloan neutral fit, and hub rankings |
|
|
91
|
+
|
|
92
|
+
**Exit Codes:** `0` = success, `2` = missing/malformed count table, `4` = safe abstention when cohort has $N < 5$ samples (`ABSTAIN_INSUFFICIENT_SAMPLES`).
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Python API Usage
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import pandas as pd
|
|
100
|
+
from viro_networks.clr_consensus import infer_consensus_network
|
|
101
|
+
from viro_networks.sloan_neutral import fit_sloan_neutral_model
|
|
102
|
+
from viro_networks.hub_perturbation import evaluate_hub_perturbation
|
|
103
|
+
|
|
104
|
+
df = pd.read_csv("virome_cohort_counts.tsv", sep="\t", index_col=0)
|
|
105
|
+
counts = df.to_numpy(dtype=float)
|
|
106
|
+
taxa = list(df.columns)
|
|
107
|
+
|
|
108
|
+
edges, net_diag = infer_consensus_network(counts, taxa, n_boot=100, stability_threshold=0.80)
|
|
109
|
+
sloan_rows, sloan_diag = fit_sloan_neutral_model(counts, taxa)
|
|
110
|
+
hubs = evaluate_hub_perturbation(taxa, [(e.taxon_a, e.taxon_b) for e in edges])
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## Output Files & Column Schema
|
|
116
|
+
|
|
117
|
+
- **`consensus_edges.tsv`:** `taxon_a`, `taxon_b`, `sign` (`+1` or `-1`), `sparcc_r`, `partial_omega`, `spearman_rho`, `estimators_supporting`, `bootstrap_stability`, `pseudocount_concordance`.
|
|
118
|
+
- **`sloan_neutral_fit.tsv`:** `taxon`, `mean_rel_abundance`, `observed_occurrence`, `predicted_occurrence`, `wilson_95_low`, `wilson_95_high`, `p_value`, `q_value`, `partition_class`.
|
|
119
|
+
- **`topological_hub_candidates.tsv`:** `taxon`, `degree`, `degree_centrality`, `betweenness_centrality`, `natural_connectivity_drop_pct`, `lcc_fraction_after_removal`.
|
|
120
|
+
- **`network_summary.json`:** Cohort sample/taxon counts, pseudocount Jaccard concordance, $N_e m$ estimate, and $R^2$ goodness-of-fit.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# viro-networks
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/viro-networks/)
|
|
4
|
+
[](https://github.com/molecularplantpathology/Virome-Suite/actions/workflows/ci.yml)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
**Compositional CLR Consensus Co-Occurrence Networks, Sloan Neutral Community Modeling, and Pure-Python Topological Hub Perturbation.**
|
|
8
|
+
|
|
9
|
+
`viro-networks` is a standalone package within the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Ecological & Statistical Methodology
|
|
14
|
+
|
|
15
|
+
1. **Sample-Size Safety Gate & CLR Normalization (`viro_networks.clr_consensus`):**
|
|
16
|
+
- Enforces a minimum cohort size guard ($N_{\text{samples}} < 5 \implies$ `CohortInsufficientError` / CLI exit code `4` `ABSTAIN_INSUFFICIENT_SAMPLES`) to prevent underpowered false-positive networks.
|
|
17
|
+
- Applies Centered Log-Ratio (CLR) transformation across a pseudocount sensitivity grid $\delta \in \{0.1, 0.5, 1.0\}$ and reports edge Jaccard concordance across pseudocount extremes.
|
|
18
|
+
2. **Three-Estimator Bootstrap Consensus Network (`viro_networks.clr_consensus`):**
|
|
19
|
+
Retains an undirected signed edge $(i, j)$ if and only if **$\ge 2$ of 3 compositional estimators** agree in sign above threshold AND sample-level bootstrap stability across $B = 100$ resamples meets `stability_threshold` ($\ge 0.80$):
|
|
20
|
+
- **Positive-Floored SparCC:** Log-ratio variation basis variance floored at $\omega_i^2 \ge \max(0.10\,\mathrm{Var}(\mathrm{CLR}_{\cdot i}), 10^{-6})$ ($|r^{\text{SparCC}}| \ge 0.35$).
|
|
21
|
+
- **Shrinkage Graphical Partial Correlation:** Regularized CLR correlation precision inversion $\mathbf{\Theta} = ((1 - \alpha)\mathbf{R}_{\text{CLR}} + \alpha \mathbf{I})^{-1}$ with $\alpha = 0.15$ ($|\omega_{ij}| \ge 0.25$).
|
|
22
|
+
- **CLR Rank Association:** Spearman rank correlation on CLR coordinates ($|\rho^{\text{rank}}_{ij}| \ge 0.35$).
|
|
23
|
+
3. **Domain-Clipped Sloan Neutral Community Model (`viro_networks.sloan_neutral`):**
|
|
24
|
+
Fits Sloan's (2006) neutral immigration-drift parameter $N_e m \in [10^{-3}, 10^4]$ predicting taxon occupancy $\hat{f}_i = 1 - \mathrm{I}_d(2 N_e m p_i, 2 N_e m (1 - p_i))$ from mean relative abundance $p_i$, reporting zero-variance-guarded $R^2$, 95% Wilson score intervals, and Benjamini-Hochberg FDR-adjusted binomial departure $q$-values (`neutral_drift_consistent`, `candidate_above_neutral_partition`, `candidate_below_neutral_partition`).
|
|
25
|
+
4. **Topological Hub Perturbation (`viro_networks.hub_perturbation`):**
|
|
26
|
+
Computes degree centrality, exact Brandes shortest-path betweenness centrality, largest connected component (LCC) retention, and eigenvalue natural connectivity drop $\Delta \bar{\lambda}\%$ upon *in silico* single-node removal using pure NumPy/Python (zero `networkx` dependency).
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install viro-networks
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Command-Line Usage (`viro-networks`)
|
|
39
|
+
|
|
40
|
+
### Input Cohort Count Matrix (`virome_cohort_counts.tsv`)
|
|
41
|
+
|
|
42
|
+
Rows represent samples ($N \ge 5$) and columns represent viral taxa/OTUs (raw mapped read counts or RPKM/CPM):
|
|
43
|
+
|
|
44
|
+
```tsv
|
|
45
|
+
sample_id Badnavirus_A Badnavirus_B Poacevirus_SCSMV Polerovirus_SCYLV Begomovirus_C Mastrevirus_D
|
|
46
|
+
SAMPLE_01 169 560 0 0 552 68
|
|
47
|
+
SAMPLE_02 1327 1053 3486 2921 665 112
|
|
48
|
+
SAMPLE_03 833 0 0 0 269 320
|
|
49
|
+
...
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Run Network & Neutral Model Inference
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
viro-networks infer \
|
|
56
|
+
--counts virome_cohort_counts.tsv \
|
|
57
|
+
--metadata cohort_metadata.tsv \
|
|
58
|
+
--bootstraps 100 \
|
|
59
|
+
--stability 0.80 \
|
|
60
|
+
--output network_results/
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### CLI Options (`viro-networks infer`)
|
|
64
|
+
|
|
65
|
+
| Argument | Required | Default | Description |
|
|
66
|
+
| :--- | :---: | :---: | :--- |
|
|
67
|
+
| `--counts` | Yes | — | Tab-separated sample $\times$ taxon abundance matrix TSV (first column = `sample_id`) |
|
|
68
|
+
| `--metadata` | No | `None` | Optional sample metadata TSV |
|
|
69
|
+
| `--bootstraps` | No | `100` | Number of sample-level bootstrap resamples for consensus stability |
|
|
70
|
+
| `--stability` | No | `0.80` | Minimum bootstrap selection frequency in $[0, 1]$ required to retain an edge |
|
|
71
|
+
| `-o`, `--output` | Yes | — | Output directory for network edges, Sloan neutral fit, and hub rankings |
|
|
72
|
+
|
|
73
|
+
**Exit Codes:** `0` = success, `2` = missing/malformed count table, `4` = safe abstention when cohort has $N < 5$ samples (`ABSTAIN_INSUFFICIENT_SAMPLES`).
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Python API Usage
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import pandas as pd
|
|
81
|
+
from viro_networks.clr_consensus import infer_consensus_network
|
|
82
|
+
from viro_networks.sloan_neutral import fit_sloan_neutral_model
|
|
83
|
+
from viro_networks.hub_perturbation import evaluate_hub_perturbation
|
|
84
|
+
|
|
85
|
+
df = pd.read_csv("virome_cohort_counts.tsv", sep="\t", index_col=0)
|
|
86
|
+
counts = df.to_numpy(dtype=float)
|
|
87
|
+
taxa = list(df.columns)
|
|
88
|
+
|
|
89
|
+
edges, net_diag = infer_consensus_network(counts, taxa, n_boot=100, stability_threshold=0.80)
|
|
90
|
+
sloan_rows, sloan_diag = fit_sloan_neutral_model(counts, taxa)
|
|
91
|
+
hubs = evaluate_hub_perturbation(taxa, [(e.taxon_a, e.taxon_b) for e in edges])
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Output Files & Column Schema
|
|
97
|
+
|
|
98
|
+
- **`consensus_edges.tsv`:** `taxon_a`, `taxon_b`, `sign` (`+1` or `-1`), `sparcc_r`, `partial_omega`, `spearman_rho`, `estimators_supporting`, `bootstrap_stability`, `pseudocount_concordance`.
|
|
99
|
+
- **`sloan_neutral_fit.tsv`:** `taxon`, `mean_rel_abundance`, `observed_occurrence`, `predicted_occurrence`, `wilson_95_low`, `wilson_95_high`, `p_value`, `q_value`, `partition_class`.
|
|
100
|
+
- **`topological_hub_candidates.tsv`:** `taxon`, `degree`, `degree_centrality`, `betweenness_centrality`, `natural_connectivity_drop_pct`, `lcc_fraction_after_removal`.
|
|
101
|
+
- **`network_summary.json`:** Cohort sample/taxon counts, pseudocount Jaccard concordance, $N_e m$ estimate, and $R^2$ goodness-of-fit.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "viro-networks"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Compositional virome co-occurrence consensus networks and Sloan neutral community model solver"
|
|
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", "ecological-networks", "sparcc", "neutral-model", "compositional-data"]
|
|
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
|
+
viro-networks = "viro_networks.cli:main"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools]
|
|
34
|
+
packages = ["viro_networks"]
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Package 5: viro_networks — Compositional Virome Co-Occurrence Networks & Sloan Neutral Model."""
|
|
2
|
+
|
|
3
|
+
from viro_networks.clr_consensus import (
|
|
4
|
+
CohortInsufficientError,
|
|
5
|
+
ConsensusEdge,
|
|
6
|
+
clr_transform,
|
|
7
|
+
compute_shrinkage_partial_corr,
|
|
8
|
+
compute_sparcc_matrix,
|
|
9
|
+
compute_spearman_clr,
|
|
10
|
+
infer_consensus_network,
|
|
11
|
+
)
|
|
12
|
+
from viro_networks.hub_perturbation import HubVulnerabilityRecord, evaluate_hub_perturbation
|
|
13
|
+
from viro_networks.sloan_neutral import (
|
|
14
|
+
SloanTaxonFit,
|
|
15
|
+
fit_sloan_neutral_model,
|
|
16
|
+
sloan_predicted_occurrence,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"__version__",
|
|
23
|
+
"CohortInsufficientError",
|
|
24
|
+
"ConsensusEdge",
|
|
25
|
+
"HubVulnerabilityRecord",
|
|
26
|
+
"SloanTaxonFit",
|
|
27
|
+
"clr_transform",
|
|
28
|
+
"compute_shrinkage_partial_corr",
|
|
29
|
+
"compute_sparcc_matrix",
|
|
30
|
+
"compute_spearman_clr",
|
|
31
|
+
"evaluate_hub_perturbation",
|
|
32
|
+
"fit_sloan_neutral_model",
|
|
33
|
+
"infer_consensus_network",
|
|
34
|
+
"sloan_predicted_occurrence",
|
|
35
|
+
]
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""CLI Entrypoint and Pipeline Runner for Package 5: `viro-networks`."""
|
|
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 List, Optional
|
|
11
|
+
|
|
12
|
+
import pandas as pd
|
|
13
|
+
|
|
14
|
+
from viro_networks import __version__
|
|
15
|
+
from viro_networks.clr_consensus import CohortInsufficientError, infer_consensus_network
|
|
16
|
+
from viro_networks.hub_perturbation import evaluate_hub_perturbation
|
|
17
|
+
from viro_networks.sloan_neutral import fit_sloan_neutral_model
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
21
|
+
parser = argparse.ArgumentParser(
|
|
22
|
+
prog="viro-networks",
|
|
23
|
+
description="viro_networks: CLR compositional normalization, multi-estimator consensus networks, and Sloan neutral model.",
|
|
24
|
+
)
|
|
25
|
+
parser.add_argument("--version", action="version", version=f"viro-networks {__version__}")
|
|
26
|
+
sub = parser.add_subparsers(dest="subcommand", required=True)
|
|
27
|
+
|
|
28
|
+
inf_p = sub.add_parser("infer", help="Infer consensus co-occurrence network and fit Sloan neutral drift model.")
|
|
29
|
+
inf_p.add_argument("--counts", type=pathlib.Path, required=True, help="Raw viral count matrix TSV.")
|
|
30
|
+
inf_p.add_argument("--metadata", type=pathlib.Path, required=False, help="Optional sample metadata TSV.")
|
|
31
|
+
inf_p.add_argument("--bootstraps", type=int, default=100, help="Bootstrap resamples for consensus stability.")
|
|
32
|
+
inf_p.add_argument("--stability", type=float, default=0.80, help="Minimum bootstrap stability threshold.")
|
|
33
|
+
inf_p.add_argument("-o", "--output", type=pathlib.Path, required=True, help="Output directory.")
|
|
34
|
+
return parser
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
38
|
+
parser = build_parser()
|
|
39
|
+
try:
|
|
40
|
+
args = parser.parse_args(argv)
|
|
41
|
+
except SystemExit as exc:
|
|
42
|
+
return int(exc.code) if exc.code is not None else 2
|
|
43
|
+
|
|
44
|
+
if args.subcommand == "infer":
|
|
45
|
+
if not args.counts.exists():
|
|
46
|
+
print(f"Error: Counts matrix not found: {args.counts}", file=sys.stderr)
|
|
47
|
+
return 2
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
df = pd.read_csv(args.counts, sep="\t", index_col=0)
|
|
51
|
+
taxa_names = [str(c) for c in df.columns]
|
|
52
|
+
mat = df.to_numpy(dtype=float)
|
|
53
|
+
except Exception as exc:
|
|
54
|
+
print(f"Counts table parse error: {exc}", file=sys.stderr)
|
|
55
|
+
return 2
|
|
56
|
+
|
|
57
|
+
args.output.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
summary_path = args.output / "network_summary.json"
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
edges, net_diag = infer_consensus_network(
|
|
62
|
+
counts=mat,
|
|
63
|
+
taxa_names=taxa_names,
|
|
64
|
+
n_boot=args.bootstraps,
|
|
65
|
+
stability_threshold=args.stability,
|
|
66
|
+
)
|
|
67
|
+
sloan_rows, sloan_diag = fit_sloan_neutral_model(counts=mat, taxa_names=taxa_names)
|
|
68
|
+
hubs = evaluate_hub_perturbation(
|
|
69
|
+
taxa_names=taxa_names,
|
|
70
|
+
edge_pairs=[(e.taxon_a, e.taxon_b) for e in edges],
|
|
71
|
+
)
|
|
72
|
+
except CohortInsufficientError as exc:
|
|
73
|
+
summary_path.write_text(
|
|
74
|
+
json.dumps({"status": "ABSTAIN_INSUFFICIENT_SAMPLES", "message": str(exc)}, indent=2),
|
|
75
|
+
encoding="utf-8",
|
|
76
|
+
)
|
|
77
|
+
return 4
|
|
78
|
+
|
|
79
|
+
edges_tsv = args.output / "consensus_edges.tsv"
|
|
80
|
+
with edges_tsv.open("w", encoding="utf-8", newline="") as ef:
|
|
81
|
+
fields = [
|
|
82
|
+
"taxon_a", "taxon_b", "sign", "sparcc_r", "partial_omega",
|
|
83
|
+
"spearman_rho", "estimators_supporting", "bootstrap_stability",
|
|
84
|
+
"pseudocount_concordance",
|
|
85
|
+
]
|
|
86
|
+
w = csv.DictWriter(ef, fieldnames=fields, delimiter="\t")
|
|
87
|
+
w.writeheader()
|
|
88
|
+
for e in edges:
|
|
89
|
+
w.writerow(
|
|
90
|
+
{
|
|
91
|
+
"taxon_a": e.taxon_a,
|
|
92
|
+
"taxon_b": e.taxon_b,
|
|
93
|
+
"sign": e.sign,
|
|
94
|
+
"sparcc_r": f"{e.sparcc_r:.4f}",
|
|
95
|
+
"partial_omega": f"{e.partial_omega:.4f}",
|
|
96
|
+
"spearman_rho": f"{e.spearman_rho:.4f}",
|
|
97
|
+
"estimators_supporting": e.estimators_supporting,
|
|
98
|
+
"bootstrap_stability": f"{e.bootstrap_stability:.4f}",
|
|
99
|
+
"pseudocount_concordance": f"{e.pseudocount_concordance:.4f}",
|
|
100
|
+
}
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
sloan_tsv = args.output / "sloan_neutral_fit.tsv"
|
|
104
|
+
with sloan_tsv.open("w", encoding="utf-8", newline="") as sf:
|
|
105
|
+
s_fields = [
|
|
106
|
+
"taxon", "mean_rel_abundance", "observed_occurrence",
|
|
107
|
+
"predicted_occurrence", "wilson_95_low", "wilson_95_high",
|
|
108
|
+
"p_value", "q_value", "partition_class",
|
|
109
|
+
]
|
|
110
|
+
sw = csv.DictWriter(sf, fieldnames=s_fields, delimiter="\t")
|
|
111
|
+
sw.writeheader()
|
|
112
|
+
for s in sloan_rows:
|
|
113
|
+
sw.writerow(
|
|
114
|
+
{
|
|
115
|
+
"taxon": s.taxon,
|
|
116
|
+
"mean_rel_abundance": f"{s.mean_rel_abundance:.6f}",
|
|
117
|
+
"observed_occurrence": f"{s.observed_occurrence:.4f}",
|
|
118
|
+
"predicted_occurrence": f"{s.predicted_occurrence:.4f}",
|
|
119
|
+
"wilson_95_low": f"{s.wilson_95_low:.4f}",
|
|
120
|
+
"wilson_95_high": f"{s.wilson_95_high:.4f}",
|
|
121
|
+
"p_value": f"{s.p_value:.6e}",
|
|
122
|
+
"q_value": f"{s.q_value:.6e}",
|
|
123
|
+
"partition_class": s.partition_class,
|
|
124
|
+
}
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
hubs_tsv = args.output / "topological_hub_candidates.tsv"
|
|
128
|
+
with hubs_tsv.open("w", encoding="utf-8", newline="") as hf:
|
|
129
|
+
h_fields = [
|
|
130
|
+
"taxon", "degree", "degree_centrality",
|
|
131
|
+
"betweenness_centrality", "natural_connectivity_drop_pct",
|
|
132
|
+
"lcc_fraction_after_removal",
|
|
133
|
+
]
|
|
134
|
+
hw = csv.DictWriter(hf, fieldnames=h_fields, delimiter="\t")
|
|
135
|
+
hw.writeheader()
|
|
136
|
+
for h in hubs:
|
|
137
|
+
hw.writerow(
|
|
138
|
+
{
|
|
139
|
+
"taxon": h.taxon,
|
|
140
|
+
"degree": h.degree,
|
|
141
|
+
"degree_centrality": f"{h.degree_centrality:.4f}",
|
|
142
|
+
"betweenness_centrality": f"{h.betweenness_centrality:.4f}",
|
|
143
|
+
"natural_connectivity_drop_pct": f"{h.natural_connectivity_drop_pct:.2f}",
|
|
144
|
+
"lcc_fraction_after_removal": f"{h.lcc_fraction_after_removal:.4f}",
|
|
145
|
+
}
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
summary_path.write_text(
|
|
149
|
+
json.dumps(
|
|
150
|
+
{
|
|
151
|
+
"status": "SUCCESS",
|
|
152
|
+
"network_diagnostics": net_diag,
|
|
153
|
+
"sloan_neutral_model": sloan_diag,
|
|
154
|
+
},
|
|
155
|
+
indent=2,
|
|
156
|
+
),
|
|
157
|
+
encoding="utf-8",
|
|
158
|
+
)
|
|
159
|
+
return 0
|
|
160
|
+
|
|
161
|
+
return 0
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Compositional CLR Normalization & Three-Estimator Bootstrap Consensus Network (`viro_networks.clr_consensus`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import math
|
|
7
|
+
from typing import Dict, List, Sequence, Tuple
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from scipy.stats import spearmanr
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CohortInsufficientError(ValueError):
|
|
14
|
+
"""Raised when sample count N < 5 requires safe abstention (Exit Code 4)."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclasses.dataclass
|
|
18
|
+
class ConsensusEdge:
|
|
19
|
+
"""Validated non-random candidate co-occurrence edge."""
|
|
20
|
+
|
|
21
|
+
taxon_a: str
|
|
22
|
+
taxon_b: str
|
|
23
|
+
sign: int # +1 or -1
|
|
24
|
+
sparcc_r: float
|
|
25
|
+
partial_omega: float
|
|
26
|
+
spearman_rho: float
|
|
27
|
+
estimators_supporting: int
|
|
28
|
+
bootstrap_stability: float
|
|
29
|
+
pseudocount_concordance: float
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def clr_transform(counts: np.ndarray, pseudocount: float = 0.5) -> np.ndarray:
|
|
33
|
+
"""Apply pseudocount zero-replacement and Centered Log-Ratio (CLR) per sample row."""
|
|
34
|
+
c_adj = np.asarray(counts, dtype=float) + float(pseudocount)
|
|
35
|
+
log_c = np.log(np.maximum(c_adj, 1e-12))
|
|
36
|
+
return log_c - np.mean(log_c, axis=1, keepdims=True)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def compute_sparcc_matrix(counts: np.ndarray, pseudocount: float = 0.5) -> np.ndarray:
|
|
40
|
+
"""Positive-floored SparCC compositional correlation estimator (`P0-VN-2`)."""
|
|
41
|
+
c_adj = np.asarray(counts, dtype=float) + float(pseudocount)
|
|
42
|
+
log_c = np.log(np.maximum(c_adj, 1e-12))
|
|
43
|
+
clr_mat = log_c - np.mean(log_c, axis=1, keepdims=True)
|
|
44
|
+
|
|
45
|
+
n_samples, p_taxa = log_c.shape
|
|
46
|
+
if p_taxa < 3 or n_samples < 2:
|
|
47
|
+
corr = np.corrcoef(clr_mat, rowvar=False)
|
|
48
|
+
return np.nan_to_num(corr, nan=0.0)
|
|
49
|
+
|
|
50
|
+
# Aitchison log-ratio variation matrix t_ij = Var(ln(x_i / x_j))
|
|
51
|
+
diff = log_c[:, :, None] - log_c[:, None, :]
|
|
52
|
+
t_mat = np.var(diff, axis=0, ddof=1)
|
|
53
|
+
t_row_sums = np.sum(t_mat, axis=1)
|
|
54
|
+
total_t = float(np.sum(t_row_sums))
|
|
55
|
+
|
|
56
|
+
clr_vars = np.var(clr_mat, axis=0, ddof=1)
|
|
57
|
+
raw_omega2 = (t_row_sums - (total_t / (2.0 * float(p_taxa - 1)))) / float(p_taxa - 2)
|
|
58
|
+
# Positive floor prevents negative basis variance -> NaN (`P0-VN-2`)
|
|
59
|
+
omega2 = np.maximum(np.maximum(0.10 * clr_vars, 1e-6), raw_omega2)
|
|
60
|
+
omega = np.sqrt(omega2)
|
|
61
|
+
|
|
62
|
+
denom = 2.0 * np.outer(omega, omega)
|
|
63
|
+
r_sparcc = (omega2[:, None] + omega2[None, :] - t_mat) / np.maximum(denom, 1e-12)
|
|
64
|
+
r_sparcc = np.clip(r_sparcc, -1.0, 1.0)
|
|
65
|
+
np.fill_diagonal(r_sparcc, 1.0)
|
|
66
|
+
return r_sparcc
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def compute_shrinkage_partial_corr(clr_mat: np.ndarray, alpha: float = 0.15) -> np.ndarray:
|
|
70
|
+
"""Correlation-scaled shrinkage precision matrix partial correlation (`P1-VN-3`)."""
|
|
71
|
+
p_taxa = clr_mat.shape[1]
|
|
72
|
+
if p_taxa < 2:
|
|
73
|
+
return np.ones((p_taxa, p_taxa), dtype=float)
|
|
74
|
+
|
|
75
|
+
stds = np.std(clr_mat, axis=0, ddof=1)
|
|
76
|
+
safe_stds = np.where(stds > 1e-12, stds, 1.0)
|
|
77
|
+
z_mat = (clr_mat - np.mean(clr_mat, axis=0, keepdims=True)) / safe_stds
|
|
78
|
+
r_corr = (z_mat.T @ z_mat) / float(max(1, clr_mat.shape[0] - 1))
|
|
79
|
+
np.fill_diagonal(r_corr, 1.0)
|
|
80
|
+
|
|
81
|
+
shrunk = (1.0 - alpha) * r_corr + alpha * np.eye(p_taxa)
|
|
82
|
+
theta = np.linalg.pinv(shrunk)
|
|
83
|
+
diag_sqrt = np.sqrt(np.maximum(np.diag(theta), 1e-12))
|
|
84
|
+
omega = -theta / np.outer(diag_sqrt, diag_sqrt)
|
|
85
|
+
omega = np.clip(omega, -1.0, 1.0)
|
|
86
|
+
np.fill_diagonal(omega, 1.0)
|
|
87
|
+
return omega
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def compute_spearman_clr(clr_mat: np.ndarray) -> np.ndarray:
|
|
91
|
+
"""Rank-based Spearman correlation matrix on CLR coordinates."""
|
|
92
|
+
p_taxa = clr_mat.shape[1]
|
|
93
|
+
if p_taxa < 2:
|
|
94
|
+
return np.ones((p_taxa, p_taxa), dtype=float)
|
|
95
|
+
res = spearmanr(clr_mat, axis=0).statistic
|
|
96
|
+
if np.ndim(res) == 0:
|
|
97
|
+
mat = np.array([[1.0, float(res)], [float(res), 1.0]])
|
|
98
|
+
else:
|
|
99
|
+
mat = np.asarray(res, dtype=float)
|
|
100
|
+
mat = np.nan_to_num(mat, nan=0.0)
|
|
101
|
+
np.fill_diagonal(mat, 1.0)
|
|
102
|
+
return mat
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _ensemble_vote_matrix(
|
|
106
|
+
counts: np.ndarray,
|
|
107
|
+
pseudocount: float = 0.5,
|
|
108
|
+
thresh_sparcc: float = 0.35,
|
|
109
|
+
thresh_partial: float = 0.25,
|
|
110
|
+
thresh_rank: float = 0.35,
|
|
111
|
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
112
|
+
"""Return (signed_support_matrix, vote_count_matrix, r_sparcc, omega_part, rho_rank)."""
|
|
113
|
+
clr_mat = clr_transform(counts, pseudocount=pseudocount)
|
|
114
|
+
r_sp = compute_sparcc_matrix(counts, pseudocount=pseudocount)
|
|
115
|
+
om_p = compute_shrinkage_partial_corr(clr_mat)
|
|
116
|
+
rh_r = compute_spearman_clr(clr_mat)
|
|
117
|
+
|
|
118
|
+
s1 = np.where(np.abs(r_sp) >= thresh_sparcc, np.sign(r_sp), 0.0)
|
|
119
|
+
s2 = np.where(np.abs(om_p) >= thresh_partial, np.sign(om_p), 0.0)
|
|
120
|
+
s3 = np.where(np.abs(rh_r) >= thresh_rank, np.sign(rh_r), 0.0)
|
|
121
|
+
|
|
122
|
+
pos_votes = (s1 > 0).astype(int) + (s2 > 0).astype(int) + (s3 > 0).astype(int)
|
|
123
|
+
neg_votes = (s1 < 0).astype(int) + (s2 < 0).astype(int) + (s3 < 0).astype(int)
|
|
124
|
+
|
|
125
|
+
signed_consensus = np.zeros_like(r_sp, dtype=int)
|
|
126
|
+
vote_counts = np.zeros_like(r_sp, dtype=int)
|
|
127
|
+
|
|
128
|
+
pos_mask = pos_votes >= 2
|
|
129
|
+
neg_mask = neg_votes >= 2
|
|
130
|
+
signed_consensus[pos_mask] = 1
|
|
131
|
+
signed_consensus[neg_mask] = -1
|
|
132
|
+
vote_counts[pos_mask] = pos_votes[pos_mask]
|
|
133
|
+
vote_counts[neg_mask] = neg_votes[neg_mask]
|
|
134
|
+
np.fill_diagonal(signed_consensus, 0)
|
|
135
|
+
np.fill_diagonal(vote_counts, 0)
|
|
136
|
+
return signed_consensus, vote_counts, r_sp, om_p, rh_r
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def infer_consensus_network(
|
|
140
|
+
counts: np.ndarray,
|
|
141
|
+
taxa_names: Sequence[str],
|
|
142
|
+
n_boot: int = 100,
|
|
143
|
+
stability_threshold: float = 0.80,
|
|
144
|
+
pseudocount_grid: Tuple[float, ...] = (0.1, 0.5, 1.0),
|
|
145
|
+
seed: int = 42,
|
|
146
|
+
) -> Tuple[List[ConsensusEdge], Dict[str, float]]:
|
|
147
|
+
"""Infer bootstrap-stabilized 3-estimator consensus co-occurrence network."""
|
|
148
|
+
mat = np.asarray(counts, dtype=float)
|
|
149
|
+
n_samples, p_taxa = mat.shape
|
|
150
|
+
if n_samples < 5:
|
|
151
|
+
raise CohortInsufficientError(
|
|
152
|
+
f"Cohort has N={n_samples} samples (< 5 minimum required); abstaining safely."
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# Filter taxa present in >= max(2, ceil(0.10 * N)) samples
|
|
156
|
+
min_prev = max(2, int(math.ceil(0.10 * n_samples)))
|
|
157
|
+
keep_mask = np.sum(mat > 0, axis=0) >= min_prev
|
|
158
|
+
kept_indices = [i for i, k in enumerate(keep_mask) if k]
|
|
159
|
+
if len(kept_indices) < 2:
|
|
160
|
+
return [], {"retained_taxa": len(kept_indices), "pseudocount_grid_jaccard": 1.0}
|
|
161
|
+
|
|
162
|
+
sub_mat = mat[:, kept_indices]
|
|
163
|
+
sub_names = [taxa_names[i] for i in kept_indices]
|
|
164
|
+
p_kept = len(sub_names)
|
|
165
|
+
|
|
166
|
+
# Primary fit at default pseudocount = 0.5
|
|
167
|
+
base_sign, base_votes, r_sp, om_p, rh_r = _ensemble_vote_matrix(sub_mat, pseudocount=0.5)
|
|
168
|
+
|
|
169
|
+
# Pseudocount sensitivity evaluation (`T5.2`)
|
|
170
|
+
grid_signs = {}
|
|
171
|
+
for pc in pseudocount_grid:
|
|
172
|
+
gs, _, _, _, _ = _ensemble_vote_matrix(sub_mat, pseudocount=pc)
|
|
173
|
+
grid_signs[pc] = gs
|
|
174
|
+
|
|
175
|
+
# Sample-level bootstrap resampling (`B = 100`)
|
|
176
|
+
rng = np.random.default_rng(seed)
|
|
177
|
+
pos_boot_counts = np.zeros((p_kept, p_kept), dtype=int)
|
|
178
|
+
neg_boot_counts = np.zeros((p_kept, p_kept), dtype=int)
|
|
179
|
+
for _ in range(n_boot):
|
|
180
|
+
b_idx = rng.integers(0, n_samples, size=n_samples)
|
|
181
|
+
b_sign, _, _, _, _ = _ensemble_vote_matrix(sub_mat[b_idx, :], pseudocount=0.5)
|
|
182
|
+
pos_boot_counts += (b_sign == 1).astype(int)
|
|
183
|
+
neg_boot_counts += (b_sign == -1).astype(int)
|
|
184
|
+
|
|
185
|
+
edges: List[ConsensusEdge] = []
|
|
186
|
+
for i in range(p_kept):
|
|
187
|
+
for j in range(i + 1, p_kept):
|
|
188
|
+
sgn = int(base_sign[i, j])
|
|
189
|
+
if sgn == 0:
|
|
190
|
+
continue
|
|
191
|
+
stab = (
|
|
192
|
+
float(pos_boot_counts[i, j]) / float(n_boot)
|
|
193
|
+
if sgn == 1
|
|
194
|
+
else float(neg_boot_counts[i, j]) / float(n_boot)
|
|
195
|
+
)
|
|
196
|
+
if stab < stability_threshold:
|
|
197
|
+
continue
|
|
198
|
+
agree_pc = sum(1 for pc in pseudocount_grid if int(grid_signs[pc][i, j]) == sgn)
|
|
199
|
+
pc_conc = float(agree_pc) / float(len(pseudocount_grid))
|
|
200
|
+
edges.append(
|
|
201
|
+
ConsensusEdge(
|
|
202
|
+
taxon_a=sub_names[i],
|
|
203
|
+
taxon_b=sub_names[j],
|
|
204
|
+
sign=sgn,
|
|
205
|
+
sparcc_r=float(r_sp[i, j]),
|
|
206
|
+
partial_omega=float(om_p[i, j]),
|
|
207
|
+
spearman_rho=float(rh_r[i, j]),
|
|
208
|
+
estimators_supporting=int(base_votes[i, j]),
|
|
209
|
+
bootstrap_stability=stab,
|
|
210
|
+
pseudocount_concordance=pc_conc,
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
# Compute overall Jaccard concordance between pseudocount extremes
|
|
215
|
+
e_lo = set(zip(*np.where(np.triu(grid_signs[pseudocount_grid[0]], k=1) != 0)))
|
|
216
|
+
e_hi = set(zip(*np.where(np.triu(grid_signs[pseudocount_grid[-1]], k=1) != 0)))
|
|
217
|
+
union_len = len(e_lo | e_hi)
|
|
218
|
+
jacc = float(len(e_lo & e_hi)) / float(union_len) if union_len > 0 else 1.0
|
|
219
|
+
|
|
220
|
+
diagnostics = {
|
|
221
|
+
"n_samples": n_samples,
|
|
222
|
+
"retained_taxa": p_kept,
|
|
223
|
+
"consensus_edge_count": len(edges),
|
|
224
|
+
"pseudocount_extremes_jaccard": round(jacc, 4),
|
|
225
|
+
}
|
|
226
|
+
return edges, diagnostics
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Zero-`networkx` Pure-Python Centrality & Hub Perturbation Engine (`viro_networks.hub_perturbation`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import collections
|
|
6
|
+
import dataclasses
|
|
7
|
+
import math
|
|
8
|
+
from typing import Dict, List, Sequence, Set, Tuple
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclasses.dataclass
|
|
14
|
+
class HubVulnerabilityRecord:
|
|
15
|
+
"""Topological centrality and node-knockout structural impact (non-causal)."""
|
|
16
|
+
|
|
17
|
+
taxon: str
|
|
18
|
+
degree: int
|
|
19
|
+
degree_centrality: float
|
|
20
|
+
betweenness_centrality: float
|
|
21
|
+
natural_connectivity_drop_pct: float
|
|
22
|
+
lcc_fraction_after_removal: float
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _natural_connectivity(adj: np.ndarray) -> float:
|
|
26
|
+
"""Compute Estrada/Wu natural connectivity ln((1/N) * sum(exp(lambda_i)))."""
|
|
27
|
+
n = adj.shape[0]
|
|
28
|
+
if n == 0:
|
|
29
|
+
return 0.0
|
|
30
|
+
eigvals = np.linalg.eigvalsh(adj)
|
|
31
|
+
max_ev = float(np.max(eigvals))
|
|
32
|
+
# Log-sum-exp for overflow safety
|
|
33
|
+
lse = max_ev + math.log(float(np.mean(np.exp(eigvals - max_ev))))
|
|
34
|
+
return lse
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _largest_connected_component_size(adj: np.ndarray) -> int:
|
|
38
|
+
n = adj.shape[0]
|
|
39
|
+
if n == 0:
|
|
40
|
+
return 0
|
|
41
|
+
visited: Set[int] = set()
|
|
42
|
+
best = 0
|
|
43
|
+
for start in range(n):
|
|
44
|
+
if start in visited:
|
|
45
|
+
continue
|
|
46
|
+
q = collections.deque([start])
|
|
47
|
+
visited.add(start)
|
|
48
|
+
comp = 0
|
|
49
|
+
while q:
|
|
50
|
+
u = q.popleft()
|
|
51
|
+
comp += 1
|
|
52
|
+
for v in range(n):
|
|
53
|
+
if adj[u, v] > 0 and v not in visited:
|
|
54
|
+
visited.add(v)
|
|
55
|
+
q.append(v)
|
|
56
|
+
if comp > best:
|
|
57
|
+
best = comp
|
|
58
|
+
return best
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _brandes_betweenness(adj: np.ndarray) -> List[float]:
|
|
62
|
+
"""Unweighted Brandes (2001) shortest-path betweenness centrality in pure Python (`P1-VN-3`)."""
|
|
63
|
+
n = adj.shape[0]
|
|
64
|
+
cb = [0.0] * n
|
|
65
|
+
if n <= 2:
|
|
66
|
+
return cb
|
|
67
|
+
|
|
68
|
+
neighbors = [[v for v in range(n) if adj[u, v] > 0] for u in range(n)]
|
|
69
|
+
|
|
70
|
+
for s in range(n):
|
|
71
|
+
stack: List[int] = []
|
|
72
|
+
preds: List[List[int]] = [[] for _ in range(n)]
|
|
73
|
+
sigma = [0.0] * n
|
|
74
|
+
sigma[s] = 1.0
|
|
75
|
+
dist = [-1] * n
|
|
76
|
+
dist[s] = 0
|
|
77
|
+
q = collections.deque([s])
|
|
78
|
+
|
|
79
|
+
while q:
|
|
80
|
+
v = q.popleft()
|
|
81
|
+
stack.append(v)
|
|
82
|
+
for w in neighbors[v]:
|
|
83
|
+
if dist[w] < 0:
|
|
84
|
+
q.append(w)
|
|
85
|
+
dist[w] = dist[v] + 1
|
|
86
|
+
if dist[w] == dist[v] + 1:
|
|
87
|
+
sigma[w] += sigma[v]
|
|
88
|
+
preds[w].append(v)
|
|
89
|
+
|
|
90
|
+
delta = [0.0] * n
|
|
91
|
+
while stack:
|
|
92
|
+
w = stack.pop()
|
|
93
|
+
for v in preds[w]:
|
|
94
|
+
if sigma[w] > 0:
|
|
95
|
+
delta[v] += (sigma[v] / sigma[w]) * (1.0 + delta[w])
|
|
96
|
+
if w != s:
|
|
97
|
+
cb[w] += delta[w]
|
|
98
|
+
|
|
99
|
+
# Normalize for undirected graph: divide by (n - 1)(n - 2)
|
|
100
|
+
scale = 1.0 / float((n - 1) * (n - 2))
|
|
101
|
+
return [val * scale for val in cb]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def evaluate_hub_perturbation(
|
|
105
|
+
taxa_names: Sequence[str],
|
|
106
|
+
edge_pairs: Sequence[Tuple[str, str]],
|
|
107
|
+
) -> List[HubVulnerabilityRecord]:
|
|
108
|
+
"""Rank candidate topological hubs via centrality and in silico node deletion (`P1-VN-3`)."""
|
|
109
|
+
names = list(taxa_names)
|
|
110
|
+
n = len(names)
|
|
111
|
+
if n == 0:
|
|
112
|
+
return []
|
|
113
|
+
|
|
114
|
+
idx_map: Dict[str, int] = {t: i for i, t in enumerate(names)}
|
|
115
|
+
adj = np.zeros((n, n), dtype=float)
|
|
116
|
+
for a, b in edge_pairs:
|
|
117
|
+
if a in idx_map and b in idx_map and a != b:
|
|
118
|
+
i, j = idx_map[a], idx_map[b]
|
|
119
|
+
adj[i, j] = 1.0
|
|
120
|
+
adj[j, i] = 1.0
|
|
121
|
+
|
|
122
|
+
base_nc = _natural_connectivity(adj)
|
|
123
|
+
btw = _brandes_betweenness(adj)
|
|
124
|
+
records: List[HubVulnerabilityRecord] = []
|
|
125
|
+
|
|
126
|
+
for i, taxon in enumerate(names):
|
|
127
|
+
deg = int(np.sum(adj[i, :] > 0))
|
|
128
|
+
deg_c = float(deg) / float(max(1, n - 1))
|
|
129
|
+
|
|
130
|
+
if n > 1:
|
|
131
|
+
keep = [k for k in range(n) if k != i]
|
|
132
|
+
sub_adj = adj[np.ix_(keep, keep)]
|
|
133
|
+
rem_nc = _natural_connectivity(sub_adj)
|
|
134
|
+
drop_pct = (
|
|
135
|
+
max(0.0, (base_nc - rem_nc) / base_nc * 100.0)
|
|
136
|
+
if base_nc > 1e-9
|
|
137
|
+
else 0.0
|
|
138
|
+
)
|
|
139
|
+
lcc_frac = float(_largest_connected_component_size(sub_adj)) / float(n - 1)
|
|
140
|
+
else:
|
|
141
|
+
drop_pct = 0.0
|
|
142
|
+
lcc_frac = 0.0
|
|
143
|
+
|
|
144
|
+
records.append(
|
|
145
|
+
HubVulnerabilityRecord(
|
|
146
|
+
taxon=taxon,
|
|
147
|
+
degree=deg,
|
|
148
|
+
degree_centrality=deg_c,
|
|
149
|
+
betweenness_centrality=btw[i],
|
|
150
|
+
natural_connectivity_drop_pct=drop_pct,
|
|
151
|
+
lcc_fraction_after_removal=lcc_frac,
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
records.sort(key=lambda r: (-r.degree, -r.natural_connectivity_drop_pct, r.taxon))
|
|
156
|
+
return records
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Domain-Clipped Sloan Neutral Community Model Solver (`viro_networks.sloan_neutral`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import math
|
|
7
|
+
from typing import Dict, List, Sequence, Tuple
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from scipy.optimize import minimize_scalar
|
|
11
|
+
from scipy.special import betainc
|
|
12
|
+
from scipy.stats import binomtest
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclasses.dataclass
|
|
16
|
+
class SloanTaxonFit:
|
|
17
|
+
"""Neutral community occurrence-abundance fit for an individual viral taxon."""
|
|
18
|
+
|
|
19
|
+
taxon: str
|
|
20
|
+
mean_rel_abundance: float
|
|
21
|
+
observed_occurrence: float
|
|
22
|
+
predicted_occurrence: float
|
|
23
|
+
wilson_95_low: float
|
|
24
|
+
wilson_95_high: float
|
|
25
|
+
p_value: float
|
|
26
|
+
q_value: float
|
|
27
|
+
partition_class: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _wilson_interval(p_pred: float, n_samples: int, z: float = 1.959963984540054) -> Tuple[float, float]:
|
|
31
|
+
p = min(max(float(p_pred), 1e-9), 1.0 - 1e-9)
|
|
32
|
+
n = float(max(1, n_samples))
|
|
33
|
+
z2 = z * z
|
|
34
|
+
denom = 1.0 + z2 / n
|
|
35
|
+
center = (p + z2 / (2.0 * n)) / denom
|
|
36
|
+
half = (z * math.sqrt((p * (1.0 - p) / n) + (z2 / (4.0 * n * n)))) / denom
|
|
37
|
+
return max(0.0, center - half), min(1.0, center + half)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def sloan_predicted_occurrence(
|
|
41
|
+
p_vec: np.ndarray,
|
|
42
|
+
ne_m: float,
|
|
43
|
+
detection_limit: float,
|
|
44
|
+
) -> np.ndarray:
|
|
45
|
+
"""Domain-clipped Sloan (2006) incomplete Beta prediction (`P0-VN-1`)."""
|
|
46
|
+
p_c = np.clip(np.asarray(p_vec, dtype=float), 1e-9, 1.0 - 1e-9)
|
|
47
|
+
d_c = min(max(float(detection_limit), 1e-9), 1.0 - 1e-9)
|
|
48
|
+
nm = min(max(float(ne_m), 1e-3), 1e4)
|
|
49
|
+
a = np.maximum(2.0 * nm * p_c, 1e-9)
|
|
50
|
+
b = np.maximum(2.0 * nm * (1.0 - p_c), 1e-9)
|
|
51
|
+
return 1.0 - betainc(a, b, d_c)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def fit_sloan_neutral_model(
|
|
55
|
+
counts: np.ndarray,
|
|
56
|
+
taxa_names: Sequence[str],
|
|
57
|
+
alpha_fdr: float = 0.05,
|
|
58
|
+
) -> Tuple[List[SloanTaxonFit], Dict[str, float]]:
|
|
59
|
+
"""Fit Sloan Neutral Community Model on untransformed relative abundances (`P0-VN-1`)."""
|
|
60
|
+
mat = np.asarray(counts, dtype=float)
|
|
61
|
+
n_samples, _p_taxa = mat.shape
|
|
62
|
+
if n_samples < 5:
|
|
63
|
+
raise ValueError("Sloan neutral model requires at least 5 samples.")
|
|
64
|
+
|
|
65
|
+
row_totals = np.sum(mat, axis=1)
|
|
66
|
+
valid_rows = row_totals > 0
|
|
67
|
+
if int(np.sum(valid_rows)) < 5:
|
|
68
|
+
raise ValueError("Fewer than 5 non-empty samples for Sloan neutral model.")
|
|
69
|
+
|
|
70
|
+
mat_valid = mat[valid_rows, :]
|
|
71
|
+
totals_valid = row_totals[valid_rows]
|
|
72
|
+
n_eff = mat_valid.shape[0]
|
|
73
|
+
|
|
74
|
+
# Retain taxa observed at least once across the cohort
|
|
75
|
+
present_mask = np.sum(mat_valid > 0, axis=0) > 0
|
|
76
|
+
kept_idx = [i for i, flag in enumerate(present_mask) if flag]
|
|
77
|
+
if not kept_idx:
|
|
78
|
+
return [], {"Ne_m": 0.0, "r_squared": 0.0, "detection_limit": 0.0}
|
|
79
|
+
|
|
80
|
+
sub_counts = mat_valid[:, kept_idx]
|
|
81
|
+
sub_names = [taxa_names[i] for i in kept_idx]
|
|
82
|
+
|
|
83
|
+
rel_abund = sub_counts / totals_valid[:, None]
|
|
84
|
+
mean_p = np.clip(np.mean(rel_abund, axis=0), 1e-9, 1.0 - 1e-9)
|
|
85
|
+
obs_f = np.mean(sub_counts > 0, axis=0)
|
|
86
|
+
d_lim = min(max(1.0 / float(np.median(totals_valid)), 1e-9), 0.5)
|
|
87
|
+
|
|
88
|
+
def sse_log_obj(log10_nm: float) -> float:
|
|
89
|
+
pred = sloan_predicted_occurrence(mean_p, 10.0 ** float(log10_nm), d_lim)
|
|
90
|
+
return float(np.sum((obs_f - pred) ** 2))
|
|
91
|
+
|
|
92
|
+
# Coarse log-grid scan across 10^-3 .. 10^4 prevents flat plateau trapping when betainc saturates
|
|
93
|
+
grid_logs = np.linspace(-3.0, 4.0, 71)
|
|
94
|
+
grid_vals = [sse_log_obj(float(lg)) for lg in grid_logs]
|
|
95
|
+
best_idx = int(np.argmin(grid_vals))
|
|
96
|
+
lo_log = float(grid_logs[max(0, best_idx - 2)])
|
|
97
|
+
hi_log = float(grid_logs[min(len(grid_logs) - 1, best_idx + 2)])
|
|
98
|
+
opt = minimize_scalar(sse_log_obj, bounds=(lo_log, hi_log), method="bounded")
|
|
99
|
+
ne_m_hat = float(10.0 ** float(opt.x))
|
|
100
|
+
pred_f = sloan_predicted_occurrence(mean_p, ne_m_hat, d_lim)
|
|
101
|
+
|
|
102
|
+
# Zero-variance R^2 guard (`P0-VN-1`)
|
|
103
|
+
ss_res = float(np.sum((obs_f - pred_f) ** 2))
|
|
104
|
+
f_bar = float(np.mean(obs_f))
|
|
105
|
+
ss_tot = float(np.sum((obs_f - f_bar) ** 2))
|
|
106
|
+
p_len = float(len(obs_f))
|
|
107
|
+
if ss_tot >= 1e-12:
|
|
108
|
+
r2 = max(-1.0, min(1.0, 1.0 - (ss_res / ss_tot)))
|
|
109
|
+
else:
|
|
110
|
+
denom_guard = p_len * max(f_bar * (1.0 - f_bar), 0.05)
|
|
111
|
+
r2 = max(0.0, min(1.0, 1.0 - (ss_res / denom_guard)))
|
|
112
|
+
|
|
113
|
+
# Binomial departure p-values + Benjamini-Hochberg adjustment
|
|
114
|
+
raw_pvals: List[float] = []
|
|
115
|
+
obs_k_list = np.sum(sub_counts > 0, axis=0).astype(int)
|
|
116
|
+
for k_obs, pf in zip(obs_k_list, pred_f):
|
|
117
|
+
pf_c = min(max(float(pf), 1e-9), 1.0 - 1e-9)
|
|
118
|
+
pv = float(binomtest(int(k_obs), n=n_eff, p=pf_c).pvalue)
|
|
119
|
+
raw_pvals.append(pv)
|
|
120
|
+
|
|
121
|
+
m_taxa = len(raw_pvals)
|
|
122
|
+
order = sorted(range(m_taxa), key=lambda i: raw_pvals[i])
|
|
123
|
+
q_vals = [1.0] * m_taxa
|
|
124
|
+
running = 1.0
|
|
125
|
+
for rank_back in range(m_taxa - 1, -1, -1):
|
|
126
|
+
orig_i = order[rank_back]
|
|
127
|
+
cand_q = (raw_pvals[orig_i] * float(m_taxa)) / float(rank_back + 1)
|
|
128
|
+
running = min(running, cand_q)
|
|
129
|
+
q_vals[orig_i] = running
|
|
130
|
+
|
|
131
|
+
results: List[SloanTaxonFit] = []
|
|
132
|
+
for idx, name in enumerate(sub_names):
|
|
133
|
+
w_lo, w_hi = _wilson_interval(float(pred_f[idx]), n_eff)
|
|
134
|
+
of = float(obs_f[idx])
|
|
135
|
+
pf = float(pred_f[idx])
|
|
136
|
+
qv = q_vals[idx]
|
|
137
|
+
if qv <= alpha_fdr and of > w_hi:
|
|
138
|
+
p_class = "candidate_above_neutral_partition"
|
|
139
|
+
elif qv <= alpha_fdr and of < w_lo:
|
|
140
|
+
p_class = "candidate_below_neutral_partition"
|
|
141
|
+
else:
|
|
142
|
+
p_class = "neutral_drift_consistent"
|
|
143
|
+
|
|
144
|
+
results.append(
|
|
145
|
+
SloanTaxonFit(
|
|
146
|
+
taxon=name,
|
|
147
|
+
mean_rel_abundance=float(mean_p[idx]),
|
|
148
|
+
observed_occurrence=of,
|
|
149
|
+
predicted_occurrence=pf,
|
|
150
|
+
wilson_95_low=w_lo,
|
|
151
|
+
wilson_95_high=w_hi,
|
|
152
|
+
p_value=raw_pvals[idx],
|
|
153
|
+
q_value=qv,
|
|
154
|
+
partition_class=p_class,
|
|
155
|
+
)
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
summary = {
|
|
159
|
+
"Ne_m": ne_m_hat,
|
|
160
|
+
"r_squared": r2,
|
|
161
|
+
"detection_limit": d_lim,
|
|
162
|
+
"n_samples_used": n_eff,
|
|
163
|
+
"n_taxa_evaluated": m_taxa,
|
|
164
|
+
}
|
|
165
|
+
return results, summary
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: viro-networks
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Compositional virome co-occurrence consensus networks and Sloan neutral community model solver
|
|
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,ecological-networks,sparcc,neutral-model,compositional-data
|
|
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
|
+
# viro-networks
|
|
21
|
+
|
|
22
|
+
[](https://pypi.org/project/viro-networks/)
|
|
23
|
+
[](https://github.com/molecularplantpathology/Virome-Suite/actions/workflows/ci.yml)
|
|
24
|
+
[](LICENSE)
|
|
25
|
+
|
|
26
|
+
**Compositional CLR Consensus Co-Occurrence Networks, Sloan Neutral Community Modeling, and Pure-Python Topological Hub Perturbation.**
|
|
27
|
+
|
|
28
|
+
`viro-networks` is a standalone package within the [Virome-Suite](https://github.com/molecularplantpathology/Virome-Suite) ecosystem developed at the **Molecular Plant Pathology Lab, ICAR-Indian Sugarcane Research Institute**.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Ecological & Statistical Methodology
|
|
33
|
+
|
|
34
|
+
1. **Sample-Size Safety Gate & CLR Normalization (`viro_networks.clr_consensus`):**
|
|
35
|
+
- Enforces a minimum cohort size guard ($N_{\text{samples}} < 5 \implies$ `CohortInsufficientError` / CLI exit code `4` `ABSTAIN_INSUFFICIENT_SAMPLES`) to prevent underpowered false-positive networks.
|
|
36
|
+
- Applies Centered Log-Ratio (CLR) transformation across a pseudocount sensitivity grid $\delta \in \{0.1, 0.5, 1.0\}$ and reports edge Jaccard concordance across pseudocount extremes.
|
|
37
|
+
2. **Three-Estimator Bootstrap Consensus Network (`viro_networks.clr_consensus`):**
|
|
38
|
+
Retains an undirected signed edge $(i, j)$ if and only if **$\ge 2$ of 3 compositional estimators** agree in sign above threshold AND sample-level bootstrap stability across $B = 100$ resamples meets `stability_threshold` ($\ge 0.80$):
|
|
39
|
+
- **Positive-Floored SparCC:** Log-ratio variation basis variance floored at $\omega_i^2 \ge \max(0.10\,\mathrm{Var}(\mathrm{CLR}_{\cdot i}), 10^{-6})$ ($|r^{\text{SparCC}}| \ge 0.35$).
|
|
40
|
+
- **Shrinkage Graphical Partial Correlation:** Regularized CLR correlation precision inversion $\mathbf{\Theta} = ((1 - \alpha)\mathbf{R}_{\text{CLR}} + \alpha \mathbf{I})^{-1}$ with $\alpha = 0.15$ ($|\omega_{ij}| \ge 0.25$).
|
|
41
|
+
- **CLR Rank Association:** Spearman rank correlation on CLR coordinates ($|\rho^{\text{rank}}_{ij}| \ge 0.35$).
|
|
42
|
+
3. **Domain-Clipped Sloan Neutral Community Model (`viro_networks.sloan_neutral`):**
|
|
43
|
+
Fits Sloan's (2006) neutral immigration-drift parameter $N_e m \in [10^{-3}, 10^4]$ predicting taxon occupancy $\hat{f}_i = 1 - \mathrm{I}_d(2 N_e m p_i, 2 N_e m (1 - p_i))$ from mean relative abundance $p_i$, reporting zero-variance-guarded $R^2$, 95% Wilson score intervals, and Benjamini-Hochberg FDR-adjusted binomial departure $q$-values (`neutral_drift_consistent`, `candidate_above_neutral_partition`, `candidate_below_neutral_partition`).
|
|
44
|
+
4. **Topological Hub Perturbation (`viro_networks.hub_perturbation`):**
|
|
45
|
+
Computes degree centrality, exact Brandes shortest-path betweenness centrality, largest connected component (LCC) retention, and eigenvalue natural connectivity drop $\Delta \bar{\lambda}\%$ upon *in silico* single-node removal using pure NumPy/Python (zero `networkx` dependency).
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install viro-networks
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Command-Line Usage (`viro-networks`)
|
|
58
|
+
|
|
59
|
+
### Input Cohort Count Matrix (`virome_cohort_counts.tsv`)
|
|
60
|
+
|
|
61
|
+
Rows represent samples ($N \ge 5$) and columns represent viral taxa/OTUs (raw mapped read counts or RPKM/CPM):
|
|
62
|
+
|
|
63
|
+
```tsv
|
|
64
|
+
sample_id Badnavirus_A Badnavirus_B Poacevirus_SCSMV Polerovirus_SCYLV Begomovirus_C Mastrevirus_D
|
|
65
|
+
SAMPLE_01 169 560 0 0 552 68
|
|
66
|
+
SAMPLE_02 1327 1053 3486 2921 665 112
|
|
67
|
+
SAMPLE_03 833 0 0 0 269 320
|
|
68
|
+
...
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Run Network & Neutral Model Inference
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
viro-networks infer \
|
|
75
|
+
--counts virome_cohort_counts.tsv \
|
|
76
|
+
--metadata cohort_metadata.tsv \
|
|
77
|
+
--bootstraps 100 \
|
|
78
|
+
--stability 0.80 \
|
|
79
|
+
--output network_results/
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### CLI Options (`viro-networks infer`)
|
|
83
|
+
|
|
84
|
+
| Argument | Required | Default | Description |
|
|
85
|
+
| :--- | :---: | :---: | :--- |
|
|
86
|
+
| `--counts` | Yes | — | Tab-separated sample $\times$ taxon abundance matrix TSV (first column = `sample_id`) |
|
|
87
|
+
| `--metadata` | No | `None` | Optional sample metadata TSV |
|
|
88
|
+
| `--bootstraps` | No | `100` | Number of sample-level bootstrap resamples for consensus stability |
|
|
89
|
+
| `--stability` | No | `0.80` | Minimum bootstrap selection frequency in $[0, 1]$ required to retain an edge |
|
|
90
|
+
| `-o`, `--output` | Yes | — | Output directory for network edges, Sloan neutral fit, and hub rankings |
|
|
91
|
+
|
|
92
|
+
**Exit Codes:** `0` = success, `2` = missing/malformed count table, `4` = safe abstention when cohort has $N < 5$ samples (`ABSTAIN_INSUFFICIENT_SAMPLES`).
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Python API Usage
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
import pandas as pd
|
|
100
|
+
from viro_networks.clr_consensus import infer_consensus_network
|
|
101
|
+
from viro_networks.sloan_neutral import fit_sloan_neutral_model
|
|
102
|
+
from viro_networks.hub_perturbation import evaluate_hub_perturbation
|
|
103
|
+
|
|
104
|
+
df = pd.read_csv("virome_cohort_counts.tsv", sep="\t", index_col=0)
|
|
105
|
+
counts = df.to_numpy(dtype=float)
|
|
106
|
+
taxa = list(df.columns)
|
|
107
|
+
|
|
108
|
+
edges, net_diag = infer_consensus_network(counts, taxa, n_boot=100, stability_threshold=0.80)
|
|
109
|
+
sloan_rows, sloan_diag = fit_sloan_neutral_model(counts, taxa)
|
|
110
|
+
hubs = evaluate_hub_perturbation(taxa, [(e.taxon_a, e.taxon_b) for e in edges])
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## Output Files & Column Schema
|
|
116
|
+
|
|
117
|
+
- **`consensus_edges.tsv`:** `taxon_a`, `taxon_b`, `sign` (`+1` or `-1`), `sparcc_r`, `partial_omega`, `spearman_rho`, `estimators_supporting`, `bootstrap_stability`, `pseudocount_concordance`.
|
|
118
|
+
- **`sloan_neutral_fit.tsv`:** `taxon`, `mean_rel_abundance`, `observed_occurrence`, `predicted_occurrence`, `wilson_95_low`, `wilson_95_high`, `p_value`, `q_value`, `partition_class`.
|
|
119
|
+
- **`topological_hub_candidates.tsv`:** `taxon`, `degree`, `degree_centrality`, `betweenness_centrality`, `natural_connectivity_drop_pct`, `lcc_fraction_after_removal`.
|
|
120
|
+
- **`network_summary.json`:** Cohort sample/taxon counts, pseudocount Jaccard concordance, $N_e m$ estimate, and $R^2$ goodness-of-fit.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
viro_networks/__init__.py
|
|
5
|
+
viro_networks/cli.py
|
|
6
|
+
viro_networks/clr_consensus.py
|
|
7
|
+
viro_networks/hub_perturbation.py
|
|
8
|
+
viro_networks/sloan_neutral.py
|
|
9
|
+
viro_networks.egg-info/PKG-INFO
|
|
10
|
+
viro_networks.egg-info/SOURCES.txt
|
|
11
|
+
viro_networks.egg-info/dependency_links.txt
|
|
12
|
+
viro_networks.egg-info/entry_points.txt
|
|
13
|
+
viro_networks.egg-info/requires.txt
|
|
14
|
+
viro_networks.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
viro_networks
|