Metadata-Version: 2.4
Name: Phylopower
Version: 0.1.0
Summary: PhyloPower: manuscript-aligned power and minimum-sample-size estimation for meta-omics beta-diversity studies.
Author: Yutong Li
License-Expression: MIT
Keywords: microbiome,metagenomics,metaproteomics,power-analysis,beta-diversity,PERMANOVA,phylogenetic,bootstrap,sample-size,PhyloFunc,Gemelli
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.22
Requires-Dist: pandas>=1.5
Requires-Dist: scipy>=1.9
Requires-Dist: scikit-bio>=0.6.3
Requires-Dist: joblib>=1.2
Requires-Dist: matplotlib>=3.7
Requires-Dist: tqdm>=4.64
Requires-Dist: psutil>=5.9
Requires-Dist: phylofunc<3,>=2.0
Requires-Dist: biopython>=1.80
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: black>=24.0; extra == "dev"
Dynamic: license-file

# PhyloPower

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.21991013.svg)](https://doi.org/10.5281/zenodo.21991013)
![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)

PhyloPower estimates the minimum balanced per-group sample size required for
community-level meta-omics studies at a target statistical power and realized
PERMANOVA effect size (ω²).

## For reviewers

The exact code version associated with the manuscript is permanently archived
at Zenodo: https://doi.org/10.5281/zenodo.21991013. To verify the manuscript's
claims, start from:

- `tutorials/tutorial.ipynb` — end-to-end
  walkthrough of both workflows on the bundled demo data;
- `figures/README.md` — figure-to-script map: every
  manuscript figure and supplementary figure has exactly one generating
  script, with precomputed result caches so figures can be regenerated
  without re-running the full simulations;
- `REPRODUCIBILITY.md` — environment setup, seeds, and
  Monte Carlo settings used for the manuscript;
- `validation_datasets/` — processed external
  validation cohorts with preparation summaries and checksums.

These companion files are distributed with the Zenodo archive and are not part
of the PyPI package; `pip install` provides the Python package and the bundled
demo datasets only.

## Overview

The manuscript-aligned implementation is `phylopower.cli`. It provides
two raw-pool workflows:

| Command | Synthetic generator | Distance |
|---|---|---|
| `gene` | PCAM | Gemelli phylogenetic RPCA |
| `protein` | MDC-TF-MC | PhyloFunc |

A step-by-step walkthrough of both workflows is provided in the tutorial
notebook `tutorials/tutorial.ipynb`. Manuscript
figure scripts and the figure-to-script map are documented in
`figures/README.md`.

`phylopower/cli.py` is a generated, self-contained runner. It embeds the
lower-level core and all other project-local runtime modules, so it does not
import an external `phylopower/core.py`.

## Usage

Run the workflows from this directory with `python -m phylopower`, or install
the package first (`python -m pip install .`) and use the `phylopower`
command. The bundled `phylopower/datagene/` and `phylopower/datapro/` demo
datasets are found automatically; set `PHYLOPOWER_DATA_DIR` or provide input
paths explicitly to use your own data.

For the protein workflow, install the runtime dependencies with:

```bash
python -m pip install \
  "numpy>=1.22" "pandas>=1.5" "scipy>=1.9" "scikit-bio>=0.6.3" \
  "joblib>=1.2" "matplotlib>=3.7" "tqdm>=4.64" "psutil>=5.9" \
  phylofunc "biopython>=1.80"
```

Both pandas 2.x and 3.x are supported; the workflows are verified against
pandas 3.0 Copy-on-Write semantics (`DataFrame.to_numpy()` read-only views).

The gene workflow must be launched from the compatible QIIME 2 environment
that contains Gemelli and `biom-format`; selecting that environment only with
`--qiime-env` is not a substitute for activating it because PCAM calls the
Gemelli Python API in-process.

```bash
python -m phylopower --help

python -m phylopower gene \
  --table /data/feature_table.csv \
  --tree /data/rooted_tree.nwk \
  --taxonomy /data/taxonomy.csv \
  --group /data/sample_metadata.csv \
  --target-power 0.80 \
  --out gene_result

python -m phylopower protein \
  --table /data/taxon_function_table.csv \
  --tree /data/rooted_tree.nwk \
  --group /data/sample_metadata.csv \
  --target-power 0.80 \
  --out protein_result
```

A full `protein` run with the default Monte Carlo settings targets
publication-grade estimates and can take tens of minutes and several GB of
memory. For a quick smoke test on the bundled demo data (reduced Monte Carlo
effort, not suitable for publication estimates):

```bash
python -m phylopower protein \
  --target-power 0.80 \
  --min-n 2 --max-n 4 --coarse-step 2 \
  --boot-number 10 --permutations 49 \
  --pool-size-per-group 10 \
  --mdctf-strength-candidates 6 --mdctf-preview-pool-size 60 \
  --power-preview-boot-number 5 --power-preview-permutations 19 \
  --out protein_quick
```

If `--target-omega2` is omitted, the observed ω² of the resolved pilot is used
and recorded in `summary.json`.

The effect grid is widened automatically when the target ω² exceeds the
simulated range (`--pcam-scale-extend-max` for `gene`, `--mdctf-strength-max`
for `protein`). If the target still falls outside the realized ω² range, the
fitted power at the target would rest on curve extrapolation only: a warning
is printed, the extrapolated fit is not allowed to qualify, no minimum n is
reported, and `summary.json` records `"target_omega2_bracketed": false`
(together with `low_omega_support_warning`). Widen the grid with the flags
above and rerun in that case.

### Monte Carlo settings

The default settings are `--boot-number 200` bootstrap iterations per
effect level and `--permutations 199` permutations per PERMANOVA; scikit-bio
applies the `+1` correction internally, so p-value denominators are 200.
Publication-grade estimates should use substantially larger counts — see
`REPRODUCIBILITY.md`. All stochastic steps, including
the PERMANOVA permutation streams and tree perturbation, are deterministically
derived from `--random-seed`, so a fixed seed reproduces a run bit-for-bit.

To inspect the exact embedded-module hashes:

```bash
python phylopower/cli.py --standalone-info
```

The maintainable build sources are `phylopower/_cli_source.py` and
`phylopower/_core_source.py`; both are included under `phylopower/`. They
are used only to regenerate the self-contained runners; the generated
`phylopower/cli.py` does not read them at runtime. The regeneration script
(`scripts/build_standalone.py`) is maintained in the GitHub repository.

### Optional controls

- **Parallelism:** `--scenario-n-jobs` sets the number of independent effect
  scenarios processed concurrently, and `--bootstrap-n-jobs` sets the joblib
  workers used inside the bootstrap/PERMANOVA loops (`0` = automatic).
- **Tree perturbation:** `--tree-jitter-sigma` and `--tree-nni-prob` set the
  perturbation magnitudes; `--tree-support-threshold` restricts NNI to nodes
  below a given support value; `--tree-set trees.nwk` estimates both
  magnitudes from a set of bootstrap or posterior trees, with explicit values
  taking precedence. All tree-perturbation options are off by default.
- **Pilot stability diagnostic:** `phylopower diagnose --modality
  {gene,protein} --table ... --tree ... --group ... [--taxonomy ...]
  --out diagnosis/` subsamples the pilot, reruns the workflow with a reduced
  effect grid, and reports the median and interquartile range of the resulting
  minimum n.

### Versions used for the manuscript

The reported analyses used Python 3.10.14, QIIME 2 2024.10.1 (environment
`qiime2-metagenome-2024.10`), Gemelli 0.0.12, PhyloFunc 2.0, scikit-bio 0.6.3,
biom-format 2.1.15, NumPy 1.26.4, pandas 2.2.2, SciPy 1.10.1, Biopython 1.83,
joblib 1.4.2, Matplotlib 3.8.4, tqdm 4.67.3, and psutil 6.1.0. The exact pins
are provided in `requirements-lock.txt`, which is shipped with the source
distribution and the archived release.

## Package installation

From this source directory:

```bash
python -m pip install .
phylopower --help
```

The installed `phylopower` command and `python -m phylopower` both invoke
`phylopower.cli`.

The tutorial notebook is installed with the package at
`phylopower/tutorials/tutorial.ipynb`; it is also provided as
`tutorials/tutorial.ipynb` in the archived release.


The protein workflow requires the dependencies declared in
`pyproject.toml`. The gene workflow additionally requires a QIIME 2
environment containing compatible versions of Gemelli, `biom-format`, and
scikit-bio. The manuscript development environment was named
`qiime2-metagenome-2024.10`. Activate that environment before installing and
running the gene workflow:

```bash
conda activate qiime2-metagenome-2024.10
python -m pip install .
phylopower gene --target-power 0.80 --out gene_result
```

## Python API

```python
from phylopower import (
    compute_gene_min_sample_size,
    compute_protein_min_sample_size,
    demo_path,
)

result = compute_protein_min_sample_size(
    table=demo_path("datapro", "taxon_function_table.csv"),
    tree=demo_path("datapro", "rooted_tree.nwk"),
    group=demo_path("datapro", "sample_metadata.csv"),
    target_power=0.80,
    target_omega2=0.05,
    out="protein_result",
)
```

The compatibility aliases `compute_taxon` and `compute_taxon_function` point
to these manuscript-aligned functions; they do not call the older workflows
in `core.py`.

## Input files

### Gene workflow

- feature table: CSV with a `Taxon` column and one column per sample;
- rooted phylogenetic tree: Newick;
- taxonomy: CSV containing `Feature ID` and `Taxon`;
- group map: CSV containing `sample_id` and `group_name`.

### Protein workflow

- Taxon–Function table: CSV with `Taxon`, `Function`, and one column per
  sample;
- rooted phylogenetic tree: Newick;
- group map: CSV containing `sample_id` and `group_name`.

The raw-pool implementation supports two or more groups (the per-group sample
size recommendation assumes a balanced design with the same n per group).

## Outputs

Each run writes:

- `summary.json`;
- `power_by_sample_size.csv`;
- `scenario_metrics_by_sample_size.csv` (per-scenario power with Monte Carlo
  standard error and 95% Wilson interval columns);
- `sample_size_decision.png`.

The Python API returns the same summary and two result tables in a dictionary.

## Reproducibility

See `REPRODUCIBILITY.md`.

The bundled datasets are convenient execution examples. Before a public
Zenodo release, the depositors should verify and document their original
accessions, citations, and redistribution terms.

## Citation and license

Citation metadata are provided in `CITATION.cff`. PhyloPower
is distributed under the MIT License; see `LICENSE`.
