diff --git a/.github/workflows/build-ete4-windows-wheels.yml b/.github/workflows/build-ete4-windows-wheels.yml
new file mode 100644
index 0000000..f77ad39
--- /dev/null
+++ b/.github/workflows/build-ete4-windows-wheels.yml
@@ -0,0 +1,80 @@
+name: build-ete4-windows-wheels
+
+# Build Windows (win_amd64) wheels for ete4, which upstream does NOT ship for
+# Windows (PyPI has an sdist only; conda-forge has no win-64 build). ete4 is a
+# hard FunVIP dependency, so without a Windows wheel FunVIP cannot be pip/conda
+# installed on Windows at all. This applies the small etetoolkit/ete PR #783
+# path-separator fix (tools/ete4-windows/ete4-windows.patch) and builds wheels
+# with cibuildwheel.
+#
+# Trigger manually: Actions tab -> "build-ete4-windows-wheels" -> "Run workflow".
+# The built wheels are uploaded as a downloadable artifact.
+#
+# ete4 is GPL-3.0-or-later; if you redistribute these wheels, also publish the
+# corresponding (patched) source and keep ete4's LICENSE. See
+# tools/ete4-windows/README.md.
+
+on:
+ workflow_dispatch:
+ inputs:
+ ete4_version:
+ description: "ete4 version to build Windows wheels for"
+ required: true
+ default: "4.4.0"
+
+jobs:
+ build-windows-wheels:
+ name: ete4 ${{ github.event.inputs.ete4_version }} win_amd64
+ runs-on: windows-latest
+ steps:
+ - name: Checkout FunVIP (for the patch)
+ uses: actions/checkout@v4
+
+ - name: Set up host Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.12"
+
+ - name: Download and unpack the ete4 source
+ shell: bash
+ run: |
+ set -euxo pipefail
+ VER="${{ github.event.inputs.ete4_version }}"
+ python -m pip install --upgrade pip
+ python -m pip download "ete4==${VER}" --no-deps --no-binary :all: -d sdist
+ tar -xzf "sdist/ete4-${VER}.tar.gz"
+ echo "ETE4_SRC=ete4-${VER}" >> "$GITHUB_ENV"
+
+ - name: Apply the Windows build patch (etetoolkit/ete PR #783)
+ shell: bash
+ run: |
+ set -euxo pipefail
+ cd "$ETE4_SRC"
+ git init -q # give `git apply` a worktree to operate in
+ git apply --verbose "../tools/ete4-windows/ete4-windows.patch"
+ echo "--- patched lines ---"
+ grep -n "replace(sep" setup.py
+ grep -n "expanduser" ete4/config.py
+
+ - name: Build wheels with cibuildwheel
+ shell: bash
+ env:
+ # FunVIP-supported CPythons; narrow this to speed up a first "does it
+ # compile?" check (e.g. just cp312-win_amd64).
+ CIBW_BUILD: "cp310-win_amd64 cp311-win_amd64 cp312-win_amd64 cp313-win_amd64"
+ CIBW_BUILD_VERBOSITY: "1"
+ # Import test loads the compiled Cython .pyd -- proves the wheel actually
+ # works on Windows, not merely that it compiled. Single-quoted Python
+ # strings keep this robust under Windows cmd.
+ CIBW_TEST_COMMAND: python -c "import ete4; from ete4 import Tree; print('ete4', ete4.__version__)"
+ run: |
+ set -euxo pipefail
+ python -m pip install cibuildwheel
+ python -m cibuildwheel --output-dir wheelhouse "$ETE4_SRC"
+
+ - name: Upload wheels
+ uses: actions/upload-artifact@v4
+ with:
+ name: ete4-${{ github.event.inputs.ete4_version }}-windows-wheels
+ path: wheelhouse/*.whl
+ if-no-files-found: error
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..6de8f0f
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,96 @@
+name: CI
+
+on:
+ push:
+ branches: [main, development]
+ pull_request:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ # Fast, broad matrix. The unit tests import only lightweight deps (pandas,
+ # numpy, matplotlib, biopython, pyyaml, psutil, unidecode) -- NOT ete4 -- so
+ # they run across Python versions and OSes without ete4's Cython build hurdle.
+ unit:
+ name: unit / py${{ matrix.python }} / ${{ matrix.os }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest]
+ python: ["3.10", "3.11", "3.12", "3.13"]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python }}
+ - name: Install unit-test dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install pytest "pandas>=2.2.2,<4.0.0" "numpy<2" matplotlib biopython pyyaml psutil unidecode tabulate
+ - name: Run unit tests
+ run: pytest -q
+ env:
+ PYTHONPATH: .
+
+ # One combo that exercises the real Linux install path: a fresh conda env, then a
+ # pip install of the package. ete4 is pulled and built from PyPI by pip (not conda:
+ # conda-forge's ete4 lags PyPI and does not have the pinned version), matching the
+ # documented install (conda for the external tools, pip for FunVIP + ete4). Then a
+ # full import + unit-test smoke test.
+ install-smoke:
+ name: full install (conda env + pip) / ubuntu / py3.12
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ shell: bash -el {0}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: conda-incubator/setup-miniconda@v3
+ with:
+ python-version: "3.12"
+ channels: conda-forge,bioconda
+ channel-priority: flexible
+ auto-activate-base: false
+ activate-environment: funvip-ci
+ - name: Install FunVIP with test extras (pip pulls + builds ete4 from PyPI)
+ run: pip install -e ".[test]"
+ - name: Smoke test (package imports) + unit tests
+ run: |
+ # The install step above is the real check: it proves ete4 builds from
+ # its PyPI sdist and the whole dependency set resolves in a fresh env.
+ # We intentionally do NOT import ete4 here -- ete4 eagerly imports PyQt6
+ # (GUI), which needs Qt system libraries (libGL, libEGL, libX11, ...) that
+ # a headless runner may lack. That is a runtime/deployment concern, not an
+ # install one, and real users have those libs. funvip's package init is
+ # import-safe (no ete4/Qt), so this check stays reliable.
+ python -c "import funvip; print('funvip imports OK')"
+ pytest -q
+
+ # Same as install-smoke, on Apple Silicon macOS. The macOS-specific value is
+ # confirming ete4 compiles from its PyPI sdist on osx-arm64 (conda-forge lags the
+ # pinned version, so ete4 comes via pip here too). Qt-free smoke, as on Linux
+ # (macOS provides Qt at runtime via conda's pyqt in the documented recipe).
+ install-smoke-macos:
+ name: full install (conda env + pip) / macos-arm64 / py3.12
+ runs-on: macos-latest
+ defaults:
+ run:
+ shell: bash -el {0}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: conda-incubator/setup-miniconda@v3
+ with:
+ python-version: "3.12"
+ channels: conda-forge,bioconda
+ channel-priority: flexible
+ auto-activate-base: false
+ activate-environment: funvip-ci
+ - name: Install FunVIP with test extras (pip pulls + builds ete4 from PyPI)
+ run: pip install -e ".[test]"
+ - name: Smoke test (package imports) + unit tests
+ run: |
+ python -c "import funvip; print('funvip imports OK')"
+ pytest -q
diff --git a/.gitignore b/.gitignore
index d51df1d..fd29ed3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,13 +12,11 @@
/*.fasta
/*.nwk
/funid/external/MAFFT_Windows/
-!/funid/external/mmseqs_Windows/bin/*
-!/funid/external/mmseqs_Windows/bin/*.exe
-!/funid/external/mmseqs_Windows/bin/*.dll
-!/funip/external/mmseqs_Windows/bin/*
-!/funip/external/mmseqs_Windows/bin/*.exe
-!/funip/external/mmseqs_Windows/bin/*.dll
-!/funvip/external/mmseqs_Windows/bin/*
+/funvip/external/MAFFT_Windows/
+# mmseqs' bundled busybox self-installs a symlink per POSIX tool name (ls, cat,
+# grep, ...) into this dir at runtime; only the real committed binaries should
+# be tracked.
+/funvip/external/mmseqs_Windows/bin/*
!/funvip/external/mmseqs_Windows/bin/*.exe
!/funvip/external/mmseqs_Windows/bin/*.dll
/funid/__pycache__/*.pyc
@@ -44,6 +42,10 @@
/DB/blast/*/*.nsq
/DB/mmseqs/*/*
!/DB/mmseqs/*/*.gitignore
+
+# Runtime BLAST/mmseqs db cache, built next to the installed package (see
+# funvip/src/initialize.py: self.in_db)
+/funvip/db/
/FunID-win32-x64/*
/FunIP-win32-x64/*
/FunVIP-win32-x64/*
@@ -67,3 +69,15 @@ DB.fasta
/funvip/FunVIP.egg-info/*
CLAUDE.md
.claude/
+
+# Python + pytest caches
+__pycache__/
+*.pyc
+.pytest_cache/
+.coverage
+htmlcov/
+
+# Virtual environments
+.venv/
+.venv*/
+venv/
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..84afb55
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,71 @@
+# Changelog
+
+All notable changes to FunVIP are documented here. This project adheres to
+[Semantic Versioning](https://semver.org/).
+
+## [1.0.0] - 2026-07-09
+
+First stable release. The pipeline was ported from ete3 to ete4, made
+substantially faster, hardened across the board, and given native Windows support.
+
+Upgrading from 0.5.x: 0.5.x is built on ete3 and 1.0 on ete4 (different packages),
+so rebuild the conda environment instead of `pip install --upgrade`. See
+`tutorial/installation.md` (Migrating from 0.5.x to 1.0).
+
+### Major
+- **ete4 engine.** Migrated the whole tree layer from ete3 to ete4. Supported
+ Python is now 3.9-3.13.
+- **Native Windows support.** ete4 has no Windows wheel on PyPI; FunVIP now bundles
+ prebuilt ete4 wheels (`funvip/_vendor/ete4_wheels`) and installs the matching one
+ on first run, falling back to building ete4 from source (patched for Windows) when
+ no wheel matches. The Windows install is now the same `pip install FunVIP` as
+ Linux/macOS.
+
+### Performance
+- Tree interpretation roughly 13x faster (memoized tree search, per-tree set-cache
+ in `decide_type`, numpy `calculate_zero`, within-cluster `diff_min` instead of an
+ O(n^2) distance matrix).
+- `seperate_clade` no longer re-deep-copies the resolved comb at every level
+ (dropped an O(depth^2) copy).
+- Vectorized group clustering; `generate_dataset` pre-indexes sequences by group
+ (was O(groups x genes x N)).
+- Pool workers share the sequence universe via fork copy-on-write instead of
+ per-task pickling.
+- `concatenate` frees per-gene search tables after building the concatenated table
+ and dictionary-encodes its string columns.
+
+### Fixed
+- **5.8S / conserved-gene interpretation crash.** The conserved-gene tree step used
+ to fail silently (RecursionError / pickle failure); it now interprets correctly.
+- **Result-affecting preset bug.** An explicitly given cluster cutoff was discarded,
+ so runs used the wrong cutoff; presets and CLI cutoffs are now applied correctly.
+- **TCS (t-coffee) no longer eats all system memory.** The bundled t-coffee
+ crash-loops on modern kernels (PID-indexed static array vs. large
+ `kernel.pid_max`); FunVIP no longer executes t-coffee just to detect it, caps and
+ times out the TCS run, and skips TCS cleanly on failure. See `tools/tcoffee/` for
+ a recipe to build a working t-coffee.
+- Numerous correctness and robustness fixes: external-tool exit codes are checked,
+ option/preset validation bugs, several always-wrong guards, a list-mutation bug,
+ `--all` handling, `homogenize`, and the GenMine executable resolution.
+
+### Added
+- Typed exception hierarchy with a top-level handler, plus a logging overhaul across
+ the core modules.
+- Method-aware external-tool preflight (checks only the tools the chosen methods
+ need) and a more robust `Version` probe.
+- Unit-test suite and CI (pip matrix on Python 3.10-3.13 + a conda install smoke
+ test), and a marked terrei end-to-end integration test.
+- `environment.yml` and a `Dockerfile` for reproducible installs.
+- Self-contained HTML report and per-group statistics.
+- Parameter reference (`docs/parameters.md`), refreshed README and installation
+ docs, and build recipes under `tools/` (working t-coffee for TCS; ete4 Windows
+ wheels).
+
+### Changed (behavior)
+- Cluster e-value default is now `1e-4` (a single clean preset key).
+- Group-assignment ties are broken by top-bitscore majority.
+- Missing per-gene bitscores in the concatenated table are filled by projecting onto
+ the fitted regression line.
+- Removed confirmed-dead / broken code paths.
+
+[1.0.0]: https://github.com/Changwanseo/FunVIP/releases/tag/v1.0.0
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..b232df4
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,19 @@
+# FunVIP in a self-contained conda environment (bundles the external tools).
+# Useful on Windows/WSL or anywhere a native install is awkward.
+#
+# docker build -t funvip .
+# docker run --rm -v "$PWD:/data" funvip --test terrei --email you@example.com --outdir /data/out
+#
+FROM condaforge/miniforge3:latest
+
+# Build the environment from environment.yml (external tools via conda + FunVIP
+# via pip). Clean caches to keep the image small.
+COPY environment.yml /tmp/environment.yml
+RUN mamba env create -f /tmp/environment.yml && mamba clean -a -y
+
+# Headless Qt for ete4 tree rendering
+ENV QT_QPA_PLATFORM=offscreen
+
+# Run FunVIP inside the env by default; arguments passed to `docker run` go to FunVIP.
+ENTRYPOINT ["conda", "run", "--no-capture-output", "-n", "funvip", "FunVIP"]
+CMD ["--help"]
diff --git a/README.md b/README.md
index f73be15..8220362 100644
--- a/README.md
+++ b/README.md
@@ -25,8 +25,6 @@ Bug reports are always welcomed
-#### IMPORTANT NOTICE: The python dependency for Linux platform has changed from 3.12 to 3.11 for TCS inclusion. Please remake conda environment for FunVIP 0.3.25 update
-
## Tutorial
* [Part 1 - Getting started!](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/tutorial.md)
* [Part 2 - Preparing database and query](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/tutorial2.md)
@@ -34,6 +32,7 @@ Bug reports are always welcomed
## Documentation
* See [Documentation](https://github.com/Changwanseo/FunVIP/blob/main/Documentation.md) for advanced usage !
+* See the [command-line parameter reference](docs/parameters.md) for every option, or run `FunVIP --help`
## Requirements
- Conda or Mamba environment
@@ -43,10 +42,23 @@ Bug reports are always welcomed
\* Recently, Mamba is a lot faster than conda. See [here](https://github.com/conda-forge/miniforge?tab=readme-ov-file) to how to install mamba environment
## Installation
-* [Windows](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md##Windows)
-* [Mac - apple silicon](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md##Apple )
-* [Linux](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md##Linux)
-* [from source](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md##Installation)
+* [Windows](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md#windows)
+* [Mac - apple silicon](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md#apple-silicon-mac)
+* [Linux](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md#linux)
+* [from source](https://github.com/Changwanseo/FunVIP/blob/main/tutorial/installation.md#installation-from-source-for-developers)
+
+### Quick install (conda / mamba)
+The external aligners and tree tools install via conda; FunVIP and its Python dependencies (including ete4) install via pip (which works on Linux/macOS).
+```bash
+conda env create -f environment.yml # or: mamba env create -f environment.yml
+conda activate funvip
+FunVIP --test terrei --email you@example.com
+```
+Or run everything in a container (no local install; handy on Windows/WSL):
+```bash
+docker build -t funvip .
+docker run --rm -v "$PWD:/data" funvip --test terrei --email you@example.com --outdir /data/out
+```
## Usage
```FunVIP --db {Your database file} --query {Your query file} --email {Your email} --gene {Your genes} --preset {fast or accurate}```
@@ -54,6 +66,10 @@ Bug reports are always welcomed
### Example
```FunVIP --db Penicillium.xlsx --query Query.xlsx --email {Your email} --thread 8 --gene ITS BenA RPB2 CaM --preset fast```
+### Quick check
+Verify your installation on a bundled dataset (needs an e-mail for the GenBank accessions):
+```FunVIP --test terrei --email {Your email}```
+
\* See documentation for detailed usage
@@ -88,11 +104,12 @@ tabular (```.xlsx```, ```.csv```, ```.parquet```, ```.ftr```) form
* TREE_METHOD : fasttree is fastest, but least accurate (However, still a lot accurate than NJ tree). It is treated that iqtree is faster but slightly less accurate than raxml, but iqtree requires at least 1000 bootstrap. So in case of speed, raxml could be a little bit faster when low bootstrap selected-->
## Results
-* ```Section Assignment.xlsx``` : Your clustering result is here. You can find which of your sequences are clustered to which section
-* ```Identification_result.xlsx``` : Your final identification result. Shows how your sequences were assigned to species level through tree-based identification
-* ```report.xlsx``` : overall statistics about the tree. If your find taxon ends with numbers, these taxon are found to be paraphyletic, so should be checked
-* ```/Tree/{section}_{gene}.svg``` : Final collapsed tree in svg format. Can be edited in vector graphics programs, or in powerpoint (by ungroup)
-* ```/Tree/{section}_{gene}_original.svg ``` : Uncollapsed tree for inspection
+Outputs are written to `{outdir}/{runname}/`:
+* ```{runname}.result.csv``` : Final identification result: how each query was assigned to the group and species level through tree-based identification
+* ```{runname}.dataset.csv``` : Clustering result: which group (e.g. genus/section) each sequence was assigned to
+* ```{runname}.report.txt``` : Run report with the options used and a per-step summary. Taxa ending with a number are paraphyletic and should be checked
+* ```07_Tree/{runname}_{group}_{gene}.svg``` : Final collapsed tree (SVG), editable in vector-graphics programs or PowerPoint (ungroup)
+* ```07_Tree/{runname}_{group}_{gene}_original.svg``` : Uncollapsed tree for inspection
* Example output tree of FunVIP

@@ -106,6 +123,9 @@ Will be tested by our lab memebers to fix bugs and advance features~~
Will be tested by peer taxonomists
3. Stable release (ver 1.0)
+## Running the tests
+```pytest``` runs the fast unit tests (no external tools needed). ```pytest -m integration``` runs the end-to-end terrei test (needs the external tools on PATH and ```FUNVIP_TEST_EMAIL``` set). See [tests/README.md](tests/README.md).
+
## License
[GPL 3.0](https://github.com/Changwanseo/FunVIP/blob/main/LICENSE)
diff --git a/RELEASING.md b/RELEASING.md
new file mode 100644
index 0000000..f3d5e39
--- /dev/null
+++ b/RELEASING.md
@@ -0,0 +1,54 @@
+# Releasing FunVIP
+
+Maintainer checklist for cutting a release (e.g. 1.0.0). Run from a clean checkout
+of `development` (or the release branch).
+
+## 1. Bundle the ete4 Windows wheels
+ete4 has no Windows wheel on PyPI, so FunVIP ships them under
+`funvip/_vendor/ete4_wheels/` and installs the right one on first Windows run.
+
+- [ ] Run the **build-ete4-windows-wheels** GitHub Action (Actions tab -> Run
+ workflow). It builds `cp310`-`cp313` `win_amd64` wheels and import-tests them.
+- [ ] Download the artifact and place all four `.whl` files in
+ `funvip/_vendor/ete4_wheels/`, then commit them.
+- [ ] Confirm the wheel version satisfies the ete4 pin in `pyproject.toml`
+ (`>=4.4.0,<4.5.0`).
+
+(The `cp312` wheel is already vendored and validated on a real Windows machine;
+the Action produces the remaining versions on a clean runner.)
+
+## 2. Version and changelog
+- [ ] Bump `version` in `pyproject.toml`. It is the single source of truth
+ (`FunVIP --version` reads it via `importlib.metadata`).
+- [ ] Add/finish the release entry in `CHANGELOG.md` and set its date.
+
+## 3. Verify (do not skip)
+- [ ] `pytest` passes (unit suite).
+- [ ] Linux end-to-end: `FUNVIP_TEST_EMAIL= pytest -m integration` (or
+ `FunVIP --test terrei --email ` in a temp dir) produces a result CSV.
+- [ ] Windows end-to-end: in a fresh Python 3.12 conda env, `pip install .` then
+ `FunVIP --test terrei --email ` -- confirm it prints
+ "installing bundled ete4" (uses the wheel, no compile) and completes.
+- [ ] macOS: run the recipe once, or mark Intel Mac "experimental" in the docs.
+- [ ] At least one real, dataset-scale run (the intended workload) completes.
+
+## 4. Build and publish
+- [ ] Clean build: `python -m build` (produces sdist + a `py3-none-any` wheel;
+ confirm `funvip/_vendor/ete4_wheels/*.whl`, `funvip/external/*`, `funvip/data`,
+ and `funvip/preset` are inside the built artifacts).
+- [ ] `twine check dist/*`.
+- [ ] Upload: `twine upload dist/*` (test first on TestPyPI if unsure). Note: the
+ PyPI `FunVIP` was last published at 0.5.x (ete3); 1.0.0 is the ete4 line.
+- [ ] Do NOT put a direct git/URL ete4 dependency in `pyproject.toml`; PyPI rejects
+ those. The Windows wheels ship inside the package, not as a URL dependency.
+
+## 5. Tag and announce
+- [ ] Tag: `git tag v1.0.0 && git push origin v1.0.0`.
+- [ ] Create the GitHub release from the tag; paste the CHANGELOG entry.
+- [ ] Merge `development` into `main` if that is the release branch.
+
+## Known issues to mention in the release notes
+- TCS is optional and Linux-only; the prebuilt bioconda t-coffee is broken (see
+ `tools/tcoffee/`). FunVIP skips TCS automatically when t-coffee is absent.
+- On Windows, MAFFT's bundled bash prints a harmless "could not find /tmp" warning;
+ it does not affect results.
diff --git a/docs/RELEASE_NOTES_v1.0.0.md b/docs/RELEASE_NOTES_v1.0.0.md
new file mode 100644
index 0000000..e34fc23
--- /dev/null
+++ b/docs/RELEASE_NOTES_v1.0.0.md
@@ -0,0 +1,98 @@
+# FunVIP 1.0.0
+
+First stable release. FunVIP moved from ete3 to ete4, became substantially faster,
+was hardened across the board, and now installs natively on Windows with the same
+one-line `pip install` as Linux and macOS.
+
+## Highlights
+
+- **New ete4 tree engine.** The whole tree layer was ported from ete3 to ete4.
+ Supported Python is now 3.9-3.13.
+- **Native Windows support.** ete4 has no Windows wheel on PyPI, so FunVIP bundles
+ prebuilt ete4 wheels and installs the right one on first run (building from a
+ patched source only if no wheel matches). Windows now uses the same install steps
+ as the other platforms.
+- **About 13x faster tree interpretation**, plus faster clustering, dataset
+ building, and concatenation.
+- **Conserved-gene (5.8S) crash fixed** and a **result-affecting cluster-cutoff bug
+ fixed** (an explicit cutoff used to be discarded).
+- **TCS no longer exhausts system memory.** The optional t-coffee step is now safely
+ contained and skipped when unavailable.
+- **Test suite + CI, reproducible installs** (`environment.yml`, `Dockerfile`), and
+ a **self-contained HTML report**.
+
+## Install
+
+Linux (external tools via conda, FunVIP + ete4 via pip):
+```
+conda create -n FunVIP python=3.12
+conda activate FunVIP
+conda config --add channels conda-forge
+conda install -c bioconda raxml iqtree "modeltest-ng==0.1.7" mmseqs2 "blast>=2.12" mafft trimal gblocks fasttree
+pip install FunVIP
+FunVIP --test terrei --email
+```
+
+Windows is the same recipe (`conda create` / `activate` / `pip install FunVIP` /
+`--test`); FunVIP installs the bundled ete4 automatically on first run. See
+`tutorial/installation.md` for macOS and the one-file `environment.yml` recipe.
+
+## Upgrading from 0.5.x
+
+0.5.x is built on **ete3** and 1.0 on **ete4** (different packages, not two versions
+of one). Do **not** `pip install --upgrade` across this jump; rebuild the conda
+environment from scratch instead. Your input data, databases, and result folders are
+untouched. Full steps are in `tutorial/installation.md`.
+
+## Changes
+
+### Performance
+- Tree interpretation about 13x faster (memoized tree search, per-tree set-cache in
+ `decide_type`, numpy `calculate_zero`, within-cluster `diff_min` instead of an
+ O(n^2) distance matrix); removed an O(depth^2) copy in `seperate_clade`.
+- Vectorized group clustering; `generate_dataset` pre-indexes sequences by group.
+- Pool workers share the sequence universe via fork copy-on-write instead of
+ per-task pickling.
+- `concatenate` frees per-gene tables and dictionary-encodes string columns.
+
+### Fixed
+- Conserved-gene (5.8S) interpretation crash (silent RecursionError / pickle
+ failure) now interprets correctly.
+- Cluster cutoff given explicitly (preset or CLI) is now applied instead of being
+ discarded.
+- TCS (t-coffee) no longer hangs and consumes all memory: FunVIP never executes
+ t-coffee just to detect it, caps and times out the TCS run, and skips it cleanly
+ on failure. See `tools/tcoffee/` for a recipe to build a working t-coffee.
+- Many correctness and robustness fixes: external-tool exit codes are checked,
+ option/preset validation bugs, several always-wrong guards, a list-mutation bug,
+ `--all` handling, `homogenize`, and GenMine executable resolution.
+
+### Added
+- Typed exception hierarchy with a top-level handler and a logging overhaul.
+- Method-aware external-tool preflight and a more robust version probe.
+- Unit-test suite and CI (pip matrix on Python 3.10-3.13 plus a conda install smoke
+ test) and a marked terrei end-to-end integration test.
+- `environment.yml` and a `Dockerfile`.
+- Self-contained HTML report and per-group statistics.
+- Parameter reference (`docs/parameters.md`), refreshed README and installation
+ docs, and build recipes under `tools/` (working t-coffee for TCS; ete4 Windows
+ wheels).
+
+### Changed (behavior)
+- Cluster e-value default is now `1e-4`.
+- Group-assignment ties are broken by top-bitscore majority.
+- Missing per-gene bitscores in the concatenated table are filled by projecting onto
+ the fitted regression line.
+- Removed confirmed-dead / broken code paths.
+
+## Known issues
+
+- TCS is optional and Linux-only. The prebuilt bioconda t-coffee is broken on modern
+ kernels (see `tools/tcoffee/`); FunVIP skips TCS automatically when t-coffee is
+ absent.
+- On Windows, MAFFT's bundled shell prints a harmless "could not find /tmp" warning;
+ it does not affect results.
+
+## Citation
+
+If you use FunVIP, please cite the FunVIP publication (see the repository README).
diff --git a/docs/gen_param_reference.py b/docs/gen_param_reference.py
new file mode 100644
index 0000000..053cf90
--- /dev/null
+++ b/docs/gen_param_reference.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+"""Generate docs/parameters.md from the live argparse parser in command.py.
+
+Run from the repo root: python docs/gen_param_reference.py > docs/parameters.md
+This keeps the parameter reference in sync with funvip/src/command.py.
+"""
+import sys
+
+sys.argv = ["FunVIP"] # so the parser's parse_args() call sees no arguments
+
+from funvip.src.command import CommandParser
+
+
+def _type_name(action):
+ if action.const is True or action.nargs == 0:
+ return "flag"
+ if action.type is not None:
+ return getattr(action.type, "__name__", str(action.type))
+ if action.nargs in ("*", "+"):
+ return "list"
+ return "str"
+
+
+def main():
+ cp = CommandParser()
+ cp.get_args() # builds cp.parser (harmlessly parses no arguments)
+ parser = cp.parser
+
+ out = [
+ "# FunVIP command-line parameters",
+ "",
+ "_Auto-generated from `funvip/src/command.py` by `docs/gen_param_reference.py`;",
+ "do not edit by hand. Regenerate after changing the CLI._",
+ ]
+ for group in parser._action_groups:
+ actions = [a for a in group._group_actions if a.option_strings]
+ if not actions:
+ continue
+ title = (group.title or "options").strip()
+ out += ["", f"## {title}", "", "| Option | Type | Description |", "|---|---|---|"]
+ for a in actions:
+ opts = ", ".join(f"`{o}`" for o in a.option_strings)
+ help_ = (a.help or "").replace("|", r"\|").replace("\n", " ")
+ out.append(f"| {opts} | {_type_name(a)} | {help_} |")
+ print("\n".join(out))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docs/parameters.md b/docs/parameters.md
new file mode 100644
index 0000000..fdca8e9
--- /dev/null
+++ b/docs/parameters.md
@@ -0,0 +1,114 @@
+# FunVIP command-line parameters
+
+_Auto-generated from `funvip/src/command.py` by `docs/gen_param_reference.py`;
+do not edit by hand. Regenerate after changing the CLI._
+
+## options
+
+| Option | Type | Description |
+|---|---|---|
+| `-h`, `--help` | flag | show this help message and exit |
+| `--email`, `-e` | str | E-mail notation to download data from GenBank |
+| `--api`, `-a` | str | NCBI API strings to download data from GenBank |
+| `--version` | flag | show program's version number and exit |
+
+## required
+
+| Option | Type | Description |
+|---|---|---|
+| `--query`, `-q` | str | Query fasta or table files, delimitated by space |
+| `--db`, `-d` | str | Database table files, delimitated by space |
+| `--gene`, `-g` | str | Gene names to be analyzed |
+
+## test
+
+| Option | Type | Description |
+|---|---|---|
+| `--test` | str | Run on a bundled test dataset, one of [penicillium, terrei, sanghuangporus]. Requires --email for the bundled GenBank accessions. |
+
+## run
+
+| Option | Type | Description |
+|---|---|---|
+| `--thread`, `-t` | int | Threads to be used for pipeline, default : system maximum |
+| `--memory`, `-m` | str | Max memory limit in 'nG' form, ex: '16G', should be more than 4G, default : system maximum |
+| `--outdir` | str | Out file location, default : current directory |
+| `--runname` | str | Name prefix to current run : default : current timestamp |
+| `--mode` | str | Analysis mode, one of [identification, validation]. default : identification |
+| `--continue` | flag | Continue from previous run, default: False |
+| `--step` | str | With --continue, resume from this pipeline step, one of [setup, search, cluster, align, trim, concatenate, modeltest, tree, visualize, report]. Ignored without a valid --continue. |
+| `--level` | str | Taxonomic level at which each phylogenetic tree is built, one of [genus, subseries, series, subsection, section, subtribe, tribe, subfamily, family, suborder, order, subclass, class, subphylum, phylum, subdivision, division, subkingdom, kingdom]. default : genus |
+| `--all` | flag | Run FunVIP for all database sequences, regardless of corresponding sequences exists in query, default : False |
+| `--confident` | str | Skip blast analysis among database sequences, use it when your database sequences contains large number of misidentified sequences, default : False |
+| `--maxoutgroup` | int | Maximum number of outgroup sequences to include in each phylogenetic tree, default : 3 |
+
+## method
+
+| Option | Type | Description |
+|---|---|---|
+| `--search` | str | Search method for selecting genes, groups and outgroups, one of [blast, mmseqs]. default : blast |
+| `--alignment` | str | Multiple sequence alignment methods, [mafft], default : mafft |
+| `--notcs` | flag | Skip T-COFFEE TCS(Transitive Consistency Score) for alignment validation. default: False |
+| `--trim` | str | Trimming methods, [trimal, gblocks, none], default : trimal |
+| `--modeltest` | str | Model test methods, [iqtree, modeltestng, none], default : none |
+| `--tree` | str | Tree methods to build phylogenetic tree, [fasttree, iqtree, raxml], default : fasttree |
+
+## visualize
+
+| Option | Type | Description |
+|---|---|---|
+| `--bscutoff` | int | Bootstrap cutoff for visualize, default : 70 |
+| `--highlight` | str | Color to highlight query sequences in tree visualization. Either in html svg recognizable string or hex code, default: #AA0000 |
+| `--heightmultiplier` | float | Height multiplier in drawing collapsing nodes. Change it if you want to show collapse node more or less expanded. Default: 6 |
+| `--maxwordlength` | int | Maximum letters to be shown in single line of tree annotation. Default: 48 |
+| `--backgroundcolor` | str | Alternating background band colors in the tree, space-delimited hex codes in quotes. default: "#ffe0e0" "#ffefef". To remove the background use --backgroundcolor "#FFFFFF" "#FFFFFF". |
+| `--outgroupcolor` | str | Background colors to indicate outgroup, default: #999999 |
+| `--ftype` | str | Font to use for phylogenetic tree, default: Arial |
+| `--fsize` | float | Font size for phylogenetic tree labels, default: 14 |
+| `--fsize_bootstrap` | float | Font size to use for bootstrap support in phylogenetic tree, default: 9 |
+
+## advanced
+
+| Option | Type | Description |
+|---|---|---|
+| `--verbose`, `-v` | int | Verbosity level, 0: quiet, 1: info, 2: warning, 3: debug, default : 2 |
+| `--collapsedistcutoff` | float | Maximum tree distance to be considered as same species, default : 0.01 |
+| `--collapsebscutoff` | float | Minimum bootstrap support to collapse a clade as one species; the default 101 (above the 100 maximum) disables bootstrap-based collapsing. default : 101 |
+| `--bootstrap` | int | Bootstrap replicates for tree analysis (ignored when tree method is fasttree). default : 100 (the accurate preset uses 1000) |
+| `--nosolveflat` | flag | Do not detect 0 length branch and automatically solve them, default : False |
+| `--regex` | str | Regex groups to parse strain numbers from your input. Maybe useful if your sequence descriptions are dirty. See documentation |
+| `--cluster-cutoff` | float | Minimum percent identity to be considered as same group in clustering analysis. Should be between 0 and 1, default : 0.97 |
+| `--cluster-evalue` | float | E-value cutoff for the blast/mmseqs clustering search; an explicit value overrides the preset. default : 0.0001 |
+| `--cluster-wordsize` | int | Word size for blast/mmseqs search, default : 7 |
+| `--cluster-max_target_seqs` | int | Max_target_seqs for blast/mmseqs search, increase this when expected search match is not found. default : 100 |
+| `--mafft-algorithm` | str | MAFFT algorithm for alignment (see MAFFT docs). default : auto |
+| `--mafft-op` | float | MAFFT op (gap opening penalty) value, default : 1.3 |
+| `--mafft-ep` | float | MAFFT ep value, default : 0.1 |
+| `--trimal-algorithm` | str | trimAl algorithm for trimming (see trimAl docs). default : gt |
+| `--trimal-gt` | float | trimAl -gt (gap threshold), between 0 and 1. default : 0.2 |
+| `--allow-innertrimming` | flag | Turn off FunVIP adjustment to not to trim inner alignment columns, default: False |
+| `--criterion` | str | Model-selection criterion for modeltest, one of [AIC, AICc, BIC]. default : BIC |
+| `--noavx` | flag | Do not use AVX for RAxML, default: False |
+| `--outgroupoffset` | int | outgroupoffset value. Highering this value may select more distant outgroup, default : 20 |
+| `--nosuspicious` | flag | Do not include suspicious samples for sequence-set. Mostly for metabarcoding analysis. May deduce inaccurate result with problematic database. |
+| `--terminate` | flag | Terminate FunVIP run when critical error detected |
+
+## cache
+
+| Option | Type | Description |
+|---|---|---|
+| `--nocachedb` | flag | Disable caching current search database. Use it if your database is too big for system directory, default : True |
+| `--usecache` | flag | Use cached search database, turn off if your cached database makes error, default : True |
+
+## save
+
+| Option | Type | Description |
+|---|---|---|
+| `--tableformat` | str | Default format for table files, [csv, xlsx], default : csv |
+| `--nosearchresult` | flag | Do not save blast/mmseqs search matrix, use when dataset gets too big and generates IO bottleneck, default: False |
+
+## setting
+
+| Option | Type | Description |
+|---|---|---|
+| `--preset` | str | [fast, accurate], or json formatted option config file. Check documentation for each preset, default : fast |
diff --git a/environment.yml b/environment.yml
new file mode 100644
index 0000000..6c4718c
--- /dev/null
+++ b/environment.yml
@@ -0,0 +1,38 @@
+# Reproducible conda/mamba environment for FunVIP.
+#
+# conda env create -f environment.yml # or: mamba env create -f environment.yml
+# conda activate funvip
+# FunVIP --test terrei --email you@example.com
+#
+# The external aligners/tree tools come from conda (bioconda/conda-forge); FunVIP
+# and its Python dependencies (incl. ete4) come from PyPI, which installs cleanly
+# on Linux/macOS. To use the development version instead of the PyPI release,
+# remove the `- FunVIP` pip line below and run `pip install -e .` from the repo.
+name: funvip
+channels:
+ - conda-forge
+ - bioconda
+dependencies:
+ - python=3.12
+ # External tools (tested versions in comments; unpinned to track conda updates)
+ - blast # 2.17.0
+ - mmseqs2 # 18.8cc5c
+ - mafft # 7.526
+ - trimal # 1.5.x
+ - fasttree # 2.2.0
+ - iqtree # 3.1.2
+ - raxml # 8.2.x
+ - modeltest-ng # 0.1.7
+ # - t-coffee # OMITTED BY DEFAULT. TCS (optional alignment validation) needs
+ # t-coffee, but the bioconda build crash-loops and consumes all RAM
+ # on modern kernels: it indexes a static array by raw PID yet is
+ # compiled with MAX_N_PID=260000, so when kernel.pid_max is large
+ # (e.g. 4194304, the current default) its own PID overflows the
+ # array -> SIGSEGV -> infinite fault loop. The MAX_N_PID_4_TCOFFEE
+ # override is NOT compiled into that binary, so it cannot be raised
+ # at runtime. For working TCS use a t-coffee built with
+ # MAX_N_PID >= pid_max (or a host with pid_max < 260000). FunVIP
+ # caps + times out t-coffee and skips TCS cleanly when it fails.
+ - pip
+ - pip:
+ - FunVIP
diff --git a/funvip/_vendor/__init__.py b/funvip/_vendor/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/funvip/_vendor/ete4_wheels/LICENSE b/funvip/_vendor/ete4_wheels/LICENSE
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/funvip/_vendor/ete4_wheels/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/funvip/_vendor/ete4_wheels/README.md b/funvip/_vendor/ete4_wheels/README.md
new file mode 100644
index 0000000..0ebbd7e
--- /dev/null
+++ b/funvip/_vendor/ete4_wheels/README.md
@@ -0,0 +1,27 @@
+# Bundled ete4 Windows wheels
+
+FunVIP installs the matching wheel from this directory on the **first Windows run**
+(see `_ensure_ete4` in `funvip/main.py`), because ete4 has no Windows wheel on PyPI
+and cannot compile there. On Linux/macOS this directory is unused (ete4 installs
+normally from PyPI).
+
+## What goes here
+
+`ete4--cp3XX-cp3XX-win_amd64.whl` for each supported CPython (3.10–3.13),
+e.g. `ete4-4.4.0-cp312-cp312-win_amd64.whl`.
+
+## How to produce them
+
+Run the **build-ete4-windows-wheels** GitHub Actions workflow (see
+`tools/ete4-windows/`), download the `ete4--windows-wheels` artifact, and
+drop the `.whl` files here, then commit them. They are declared as package data in
+`pyproject.toml`, so they ship inside the FunVIP wheel/sdist.
+
+The wheel version must satisfy FunVIP's ete4 pin (`>=4.4.0,<4.5.0`).
+
+## License
+
+These wheels are ete4, distributed under **GPL-3.0-or-later** (see `LICENSE` in this
+directory). FunVIP bundles them unmodified except for the small Windows build fix in
+`tools/ete4-windows/ete4-windows.patch`; the corresponding source is ete4's public
+release plus that patch. FunVIP (also GPL-3.0) may redistribute them under the GPL.
diff --git a/funvip/_vendor/ete4_wheels/ete4-4.4.0-cp312-cp312-win_amd64.whl b/funvip/_vendor/ete4_wheels/ete4-4.4.0-cp312-cp312-win_amd64.whl
new file mode 100644
index 0000000..e04c154
Binary files /dev/null and b/funvip/_vendor/ete4_wheels/ete4-4.4.0-cp312-cp312-win_amd64.whl differ
diff --git a/funvip/main.py b/funvip/main.py
index 8d40ca5..efd8c92 100644
--- a/funvip/main.py
+++ b/funvip/main.py
@@ -18,7 +18,132 @@ def _ensure_deterministic_hash():
_ensure_deterministic_hash()
-def main():
+# ete4 version fetched when building from source on Windows. Matches the pin in
+# pyproject.toml and the bundled wheels; the source patch in _build_ete4_from_source
+# targets this version.
+_ETE4_SRC_VERSION = "4.4.0"
+
+
+def _pip(*args):
+ import subprocess
+
+ subprocess.check_call(
+ [sys.executable, "-m", "pip", "--disable-pip-version-check", *args]
+ )
+
+
+def _patch_line(path, old, new):
+ with open(path, encoding="utf-8") as fh:
+ text = fh.read()
+ if new in text:
+ return
+ if old not in text:
+ raise RuntimeError(f"expected text not found while patching {os.path.basename(path)}")
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write(text.replace(old, new))
+
+
+def _build_ete4_from_source():
+ """Download the ete4 sdist, apply the Windows build fix (etetoolkit/ete PR #783),
+ and pip-install it. Needs a C/C++ compiler and internet; runs at most once."""
+ import glob
+ import json
+ import tarfile
+ import tempfile
+ import urllib.request
+
+ with tempfile.TemporaryDirectory() as tmp:
+ # Fetch the raw sdist tarball directly (not via `pip download`): pip would
+ # invoke the sdist's build backend to resolve metadata, which runs ete4's
+ # unpatched setup.py and hits the exact Windows path bug (PR #783) we are
+ # about to patch -- before we ever get a chance to apply the patch.
+ with urllib.request.urlopen(
+ f"https://pypi.org/pypi/ete4/{_ETE4_SRC_VERSION}/json"
+ ) as resp:
+ release = json.load(resp)
+ sdist_url = next(
+ f["url"] for f in release["urls"] if f["packagetype"] == "sdist"
+ )
+ sdist = os.path.join(tmp, "ete4.tar.gz")
+ urllib.request.urlretrieve(sdist_url, sdist)
+ with tarfile.open(sdist) as tar:
+ try:
+ tar.extractall(tmp, filter="data")
+ except TypeError: # filter= added in Python 3.12
+ tar.extractall(tmp)
+ src = next(d for d in glob.glob(os.path.join(tmp, "ete4-*")) if os.path.isdir(d))
+ _patch_line(
+ os.path.join(src, "setup.py"),
+ "from os.path import isfile", "from os.path import isfile, sep",
+ )
+ _patch_line(
+ os.path.join(src, "setup.py"),
+ "path.replace('/', '.')", "path.replace(sep, '.')",
+ )
+ _patch_line(
+ os.path.join(src, "ete4", "config.py"),
+ "os.environ['HOME']", "os.path.expanduser('~')",
+ )
+ _pip("install", "--no-deps", src)
+
+
+def _ensure_ete4():
+ """Make ete4 importable. ete4 has no Windows wheel on PyPI, so on Windows it is
+ not a pip dependency; instead FunVIP installs a prebuilt wheel bundled under
+ funvip/_vendor/ete4_wheels, or, if none is bundled for this Python, builds ete4
+ from source (patched for Windows). No-op on Linux/macOS and once ete4 imports."""
+ try:
+ import ete4 # noqa: F401
+
+ return
+ except ImportError:
+ pass
+
+ if sys.platform != "win32":
+ # Off Windows ete4 is an ordinary dependency; a failed import is a genuine
+ # installation problem, so let it surface rather than masking it.
+ raise
+
+ import glob
+ import importlib
+
+ tag = f"cp{sys.version_info.major}{sys.version_info.minor}"
+ wheel_dir = os.path.join(os.path.dirname(__file__), "_vendor", "ete4_wheels")
+ wheels = sorted(
+ glob.glob(os.path.join(wheel_dir, f"ete4-*-{tag}-{tag}-win_amd64.whl"))
+ )
+ try:
+ if wheels:
+ wheel = wheels[-1]
+ print(
+ f"[FunVIP] First Windows run: installing bundled ete4 "
+ f"({os.path.basename(wheel)}). This happens only once.",
+ flush=True,
+ )
+ _pip("install", "--no-deps", wheel)
+ else:
+ print(
+ f"[FunVIP] First Windows run: no bundled ete4 wheel for Python {tag}; "
+ "building ete4 from source now (one-time; needs a C/C++ compiler and "
+ "internet, may take a few minutes).",
+ flush=True,
+ )
+ _build_ete4_from_source()
+ except Exception as e:
+ raise SystemExit(
+ f"[FunVIP] Could not set up ete4 automatically: {e}\n"
+ "If the build failed for lack of a compiler, install one with:\n"
+ " conda install -c conda-forge cxx-compiler\n"
+ "then rerun. Otherwise place a prebuilt ete4 wheel in "
+ "funvip/_vendor/ete4_wheels (see tools/ete4-windows/)."
+ )
+
+ importlib.invalidate_caches()
+ import ete4 # noqa: F401 -- verify it imports now
+
+
+def _run_funvip():
+ _ensure_ete4() # install the bundled ete4 wheel on first Windows run (no-op elsewhere)
from funvip.src import align
from funvip.src import tree_interpretation_pipe
from funvip.src import cluster
@@ -39,7 +164,7 @@ def main():
from funvip.src.command import CommandParser
from funvip.src.tool import index_step
from funvip.src.opt_generator import opt_generator
- from funvip.src.version import Version
+ from funvip.src.version import Version, preflight
from time import time
from time import sleep
import pandas as pd
@@ -52,7 +177,7 @@ def main():
import shutil
import sys
import logging
- import PyQt5
+ import PyQt6
# To prevent pyqt error
os.environ["QT_QPA_PLATFORM"] = "offscreen"
@@ -90,6 +215,10 @@ def main():
logger.setup_logging(list_info, list_warning, list_error, path, opt, tool)
+ # Fail fast (before any heavy work) with a clear message if a required
+ # external tool for the selected methods is not available on PATH.
+ preflight(opt)
+
# V contains all intermediate variables for FunVIP Run
V = dataset.FunVIP_var()
# R includes all reporting objects such as warnings, errors, statistics
@@ -97,13 +226,23 @@ def main():
# Reload previous session from shelve if --continue selected
if opt.continue_from_previous is True:
+ from funvip.src.exceptions import ConfigError
+
var = save.load_session(opt, savefile=path.save)
- if "V" in var:
- V = var["V"]
- if "R" in var:
- R = var["R"]
- if "path" in var:
- path = var["path"]
+ # A previous checkpoint that failed to save a required key (an unpicklable
+ # object logged only as a warning, an interrupted write, or a missing
+ # save.shelve) leaves these absent; resuming would silently run on an empty
+ # V and emit a 0-row result.csv reported as success. Fail clearly instead.
+ for _required in ("V", "R", "path"):
+ if _required not in var:
+ raise ConfigError(
+ f"--continue was requested but the saved session at {path.save} is "
+ f"missing required key '{_required}'. A previous checkpoint save was "
+ "incomplete or the session file is absent; re-run from an earlier --step."
+ )
+ V = var["V"]
+ R = var["R"]
+ path = var["path"]
if "model_dict" in var:
model_dict = var["model_dict"]
if "GenMine_flag" in var:
@@ -429,7 +568,7 @@ def main():
try:
logging.info(f"Time report generation: {round(time_end-time_visualize,3)}s")
except:
- logging.warning(f"Failed logging reoprt generation time")
+ logging.warning(f"Failed logging report generation time")
# At the end of the run, print critical messages once again to be noticed
with open(path.criticallog, "r") as frclog:
@@ -451,3 +590,27 @@ def main():
for line in critical_logs:
print(line)
+
+
+def main():
+ """Entry point: run FunVIP under a top-level handler so an expected
+ FunVIPError is reported cleanly and any unexpected crash is logged with a
+ full traceback, instead of dumping a bare stack trace at the user."""
+ import logging
+ import sys
+ import traceback
+ from funvip.src.exceptions import FunVIPError
+
+ try:
+ _run_funvip()
+ except FunVIPError as e:
+ logging.critical(f"FunVIP stopped: {e}")
+ sys.exit(1)
+ except KeyboardInterrupt:
+ logging.warning("FunVIP interrupted by user (KeyboardInterrupt)")
+ sys.exit(130)
+ except Exception as e:
+ logging.critical(
+ f"FunVIP crashed with an unexpected error: {e}\n{traceback.format_exc()}"
+ )
+ sys.exit(1)
diff --git a/funvip/preset/accurate.yaml b/funvip/preset/accurate.yaml
index 56266a8..de027ea 100644
--- a/funvip/preset/accurate.yaml
+++ b/funvip/preset/accurate.yaml
@@ -1,7 +1,7 @@
MODE: identification
CONTINUE: false
QUERYONLY: true
-CONFIDENT: fale
+CONFIDENT: false
MAXOUTGROUP: 3
SEARCH: blast
ALIGNMENT: mafft
@@ -9,7 +9,7 @@ TRIM: trimal
MODELTEST: modelfinder
TREE: raxml
CLUSTER-CUTOFF: 0.97
-CLUSTER-EVALUE: 10
+CLUSTER-EVALUE: 1.0e-04
MAFFT-ALGORITHM: localpair
TRIMAL-ALGORITHM: gt
COLLAPSEDISTCUTOFF: 0.01
@@ -18,7 +18,6 @@ SOLVEFLAT: true
VERBOSE: 2
MATRIXFORMAT: csv
WORDSIZE: 7
-EVALUE: 1.0e-04
TRIMAL-gt: 0.2
MAFFT-op: 1.3
MAFFT-ep: 0.1
diff --git a/funvip/preset/fast.yaml b/funvip/preset/fast.yaml
index 6f6bfdb..8612405 100644
--- a/funvip/preset/fast.yaml
+++ b/funvip/preset/fast.yaml
@@ -8,14 +8,13 @@ ALIGNMENT: mafft
TRIM: trimal
TREE: fasttree
CLUSTER-CUTOFF: 0.97
-CLUSTER-EVALUE: 10
+CLUSTER-EVALUE: 1.0e-04
MAFFT-ALGORITHM: auto
COLLAPSEDISTCUTOFF: 0.01
SOLVEFLAT: true
VERBOSE: 2
MATRIXFORMAT: csv
WORDSIZE: 7
-EVALUE: 1.0e-04
TRIMAL-gt: 0.2
MAFFT-op: 1.3
MAFFT-ep: 0.1
diff --git a/funvip/src/__pycache__/CATV_pipe.cpython-310.pyc b/funvip/src/__pycache__/CATV_pipe.cpython-310.pyc
deleted file mode 100644
index 08330d5..0000000
Binary files a/funvip/src/__pycache__/CATV_pipe.cpython-310.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/CAT_V.cpython-310.pyc b/funvip/src/__pycache__/CAT_V.cpython-310.pyc
deleted file mode 100644
index 22484be..0000000
Binary files a/funvip/src/__pycache__/CAT_V.cpython-310.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/CAT_V.cpython-39.pyc b/funvip/src/__pycache__/CAT_V.cpython-39.pyc
deleted file mode 100644
index a0d28f1..0000000
Binary files a/funvip/src/__pycache__/CAT_V.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/CAT_V_pipe.cpython-39.pyc b/funvip/src/__pycache__/CAT_V_pipe.cpython-39.pyc
deleted file mode 100644
index 07afed9..0000000
Binary files a/funvip/src/__pycache__/CAT_V_pipe.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/__init__.cpython-310.pyc b/funvip/src/__pycache__/__init__.cpython-310.pyc
deleted file mode 100644
index 4d2af06..0000000
Binary files a/funvip/src/__pycache__/__init__.cpython-310.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/__init__.cpython-39.pyc b/funvip/src/__pycache__/__init__.cpython-39.pyc
deleted file mode 100644
index 433b1a9..0000000
Binary files a/funvip/src/__pycache__/__init__.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/align.cpython-310.pyc b/funvip/src/__pycache__/align.cpython-310.pyc
deleted file mode 100644
index e86567d..0000000
Binary files a/funvip/src/__pycache__/align.cpython-310.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/cluster.cpython-39.pyc b/funvip/src/__pycache__/cluster.cpython-39.pyc
deleted file mode 100644
index 494db76..0000000
Binary files a/funvip/src/__pycache__/cluster.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/dataset.cpython-39.pyc b/funvip/src/__pycache__/dataset.cpython-39.pyc
deleted file mode 100644
index f2f309e..0000000
Binary files a/funvip/src/__pycache__/dataset.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/ext.cpython-310.pyc b/funvip/src/__pycache__/ext.cpython-310.pyc
deleted file mode 100644
index 4da9360..0000000
Binary files a/funvip/src/__pycache__/ext.cpython-310.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/ext.cpython-39.pyc b/funvip/src/__pycache__/ext.cpython-39.pyc
deleted file mode 100644
index 2b79204..0000000
Binary files a/funvip/src/__pycache__/ext.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/hasher.cpython-39.pyc b/funvip/src/__pycache__/hasher.cpython-39.pyc
deleted file mode 100644
index 7489147..0000000
Binary files a/funvip/src/__pycache__/hasher.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/initialize.cpython-39.pyc b/funvip/src/__pycache__/initialize.cpython-39.pyc
deleted file mode 100644
index 83f076d..0000000
Binary files a/funvip/src/__pycache__/initialize.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/io.cpython-310.pyc b/funvip/src/__pycache__/io.cpython-310.pyc
deleted file mode 100644
index 6ac42fd..0000000
Binary files a/funvip/src/__pycache__/io.cpython-310.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/io.cpython-39.pyc b/funvip/src/__pycache__/io.cpython-39.pyc
deleted file mode 100644
index a279770..0000000
Binary files a/funvip/src/__pycache__/io.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/logger.cpython-39.pyc b/funvip/src/__pycache__/logger.cpython-39.pyc
deleted file mode 100644
index bf0832d..0000000
Binary files a/funvip/src/__pycache__/logger.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/modeltest.cpython-39.pyc b/funvip/src/__pycache__/modeltest.cpython-39.pyc
deleted file mode 100644
index b9465e8..0000000
Binary files a/funvip/src/__pycache__/modeltest.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/multigene.cpython-39.pyc b/funvip/src/__pycache__/multigene.cpython-39.pyc
deleted file mode 100644
index f429bc1..0000000
Binary files a/funvip/src/__pycache__/multigene.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/ncbi.cpython-39.pyc b/funvip/src/__pycache__/ncbi.cpython-39.pyc
deleted file mode 100644
index 5aeb8f4..0000000
Binary files a/funvip/src/__pycache__/ncbi.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/opt_generator.cpython-39.pyc b/funvip/src/__pycache__/opt_generator.cpython-39.pyc
deleted file mode 100644
index 504df3c..0000000
Binary files a/funvip/src/__pycache__/opt_generator.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/reporter.cpython-39.pyc b/funvip/src/__pycache__/reporter.cpython-39.pyc
deleted file mode 100644
index 37bae44..0000000
Binary files a/funvip/src/__pycache__/reporter.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/search.cpython-39.pyc b/funvip/src/__pycache__/search.cpython-39.pyc
deleted file mode 100644
index cc2165c..0000000
Binary files a/funvip/src/__pycache__/search.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/tool.cpython-39.pyc b/funvip/src/__pycache__/tool.cpython-39.pyc
deleted file mode 100644
index 0f26997..0000000
Binary files a/funvip/src/__pycache__/tool.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/validation.cpython-39.pyc b/funvip/src/__pycache__/validation.cpython-39.pyc
deleted file mode 100644
index 67101d5..0000000
Binary files a/funvip/src/__pycache__/validation.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/__pycache__/visualize.cpython-39.pyc b/funvip/src/__pycache__/visualize.cpython-39.pyc
deleted file mode 100644
index 287c7f3..0000000
Binary files a/funvip/src/__pycache__/visualize.cpython-39.pyc and /dev/null differ
diff --git a/funvip/src/cluster.py b/funvip/src/cluster.py
index 78da7b9..1d8dcd1 100644
--- a/funvip/src/cluster.py
+++ b/funvip/src/cluster.py
@@ -14,6 +14,7 @@
import logging
import gc
from funvip.src.ext import mmseqs
+from funvip.src.exceptions import ClusterError
import sys
@@ -45,7 +46,9 @@ def append_query_group(V):
for FI in V.list_FI:
group_dict[FI.hash] = FI.adjusted_group
- V.cSR["query_group"] = V.cSR["qseqid"].apply(lambda x: group_dict.get(x))
+ # vectorized map (every qseqid is an FI hash present in group_dict, so this is
+ # equivalent to the former per-row .apply(lambda x: group_dict.get(x)))
+ V.cSR["query_group"] = V.cSR["qseqid"].map(group_dict)
logging.debug(V.cSR["query_group"])
@@ -80,18 +83,20 @@ def assign_gene(result_dict, V, cutoff=0.99):
# get each of the dataframe for each FI
current_df = gene_result_grouped.get_group(f"{FI.hash}_{n}")
# sort by bitscore
- # sorting has peformed after split for better performance
+ # sorting is performed after split for better performance
current_df.sort_values(by=["bitscore"], inplace=True, ascending=False)
# reset index to easily get maximum
current_df.reset_index(inplace=True, drop=True)
- # get result stasifies over cutoff
+ # get result satisfies over cutoff
cutoff_df = current_df[
current_df["bitscore"] > current_df["bitscore"][0] * cutoff
]
gene_count = len(set(cutoff_df["gene"]))
gene_list = list(set(cutoff_df["gene"]))
- except:
+ except (KeyError, IndexError):
+ # no search hits for this query seq/gene (get_group raises KeyError)
+ # or an empty result frame -> treat as "no gene assignable"
gene_count = 0
gene_list = []
@@ -109,19 +114,45 @@ def assign_gene(result_dict, V, cutoff=0.99):
FI.update_seq(gene_list[0], seq)
else:
- logging.error("DEVELOPMENTAL ERROR IN GENE ASSIGN")
- raise Exception
+ raise ClusterError(
+ f"unexpected gene_count={gene_count} while assigning a gene to {FI.id}"
+ )
return V
-# This function assigns group to each FI
-def cluster(FI, V_list_group, V_cSR, path, opt):
- # Reduce memory by focusing on relevant rows
- df_search = V_cSR[V_cSR["qseqid"] == FI.hash]
+# Assign a query to a group when its best-hit cutoff set spans >=2 groups.
+# Rule: count subject_groups among the hits TIED at the highest bitscore; the
+# plurality wins. If that count ties, fold in the next (lower) bitscore level and
+# recount, and so on. This respects the best-scoring hits and avoids the whole-
+# cutoff-window bias where an over-represented distant group can outvote the real
+# best match. cutoff_df must already be sorted by bitscore descending.
+def _majority_top_group(cutoff_df):
+ counts = {}
+ leaders = []
+ for _, level in cutoff_df.groupby("bitscore", sort=False):
+ for grp in level["subject_group"]:
+ counts[grp] = counts.get(grp, 0) + 1
+ max_count = max(counts.values())
+ leaders = [grp for grp, c in counts.items() if c == max_count]
+ if len(leaders) == 1:
+ return leaders[0]
+ # All bitscore levels folded in and still tied: take the highest-bitscore hit
+ # among the tied leaders (deterministic given the descending sort).
+ leader_set = set(leaders)
+ for grp in cutoff_df["subject_group"]:
+ if grp in leader_set:
+ return grp
+
+# This function assigns group to each FI
+def cluster(FI, df_search, opt):
+ # df_search: this FI's pre-sliced rows of the concatenated search table
+ # (columns qseqid, bitscore, subject_group). Previously each call re-scanned the
+ # whole cSR (V_cSR[V_cSR["qseqid"] == FI.hash]) -> O(N_FI * N_rows), and the whole
+ # table was pickled to every mp worker; pipe_cluster now slices once via groupby.
if df_search.empty:
# If confident is False and FI datatype is "db"
- if opt.confident is False and FI.datatype is "db":
+ if opt.confident is False and FI.datatype == "db":
logging.warning(f"No adjusted_group assigned to {FI}")
FI.adjusted_group = FI.group
return FI
@@ -139,10 +170,6 @@ def cluster(FI, V_list_group, V_cSR, path, opt):
cutoff = df_search["bitscore"].iloc[0] * opt.cluster.cutoff
cutoff_df = df_search[df_search["bitscore"] > cutoff]
- # Clear unused data
- del df_search
- gc.collect()
-
# Extract group information
unique_groups = set(cutoff_df["subject_group"])
group_count = len(unique_groups)
@@ -159,12 +186,13 @@ def cluster(FI, V_list_group, V_cSR, path, opt):
f"Query seq in {FI.id} has multiple matches to groups within {opt.cluster.cutoff} cutoff: {list(unique_groups)}"
)
- # Among the multiple matches, get the best group
- FI.adjusted_group = cutoff_df["subject_group"].iloc[0]
+ # Assign by group plurality among the best (tied-top-bitscore) hits
+ FI.adjusted_group = _majority_top_group(cutoff_df)
else:
- logging.error("DEVELOPMENTAL ERROR IN GROUP ASSIGN")
- raise Exception
+ raise ClusterError(
+ f"unexpected group_count={group_count} while assigning a group to {FI.id}"
+ )
logging.info(f"{FI.id} has clustered to {FI.adjusted_group}")
@@ -173,16 +201,18 @@ def cluster(FI, V_list_group, V_cSR, path, opt):
if not (FI.adjusted_group in unique_groups):
logging.warning(f"Clustering result collides for {FI.id}")
- if unique_groups:
- return FI
- else:
- return FI
+ return FI
### Append outgroup to given group-gene dataset by search matrix
-def append_outgroup(V_list_FI, df_search, gene, group, path, opt):
+# V.list_FI shared with outgroup-append pool workers via fork copy-on-write, set
+# before the Pool is created, instead of being pickled into every task tuple.
+_OUTGROUP_SHARED = {}
+
+
+def append_outgroup(df_search, gene, group, path, opt):
logging.info(f"Appending outgroup on group: {group}, Gene: {gene}")
- list_FI = V_list_FI
+ list_FI = _OUTGROUP_SHARED["list_FI"]
# In multiprocessing, delete V to reduce memory consumption
# del V
@@ -208,12 +238,14 @@ def append_outgroup(V_list_FI, df_search, gene, group, path, opt):
bitscore_cutoff = max(
1, min(cutoff_set_df["bitscore"]) - opt.cluster.outgroupoffset
)
- except:
- bitscore_cutoff = 999999 # use infinite if failed
+ except ValueError:
+ # cutoff_set_df empty (no ingroup hits for this group) -> min() raises;
+ # fall back to an effectively infinite cutoff so all hits stay candidates
+ bitscore_cutoff = 999999
# print(f"Ingroup cutoff {bitscore_cutoff} selected for group {group} gene {gene}")
- ## get result stasifies over cutoff
+ ## get result satisfies over cutoff
# outgroup should be outside of ingroup
cutoff_df = df_search[df_search["bitscore"] < bitscore_cutoff]
@@ -228,9 +260,15 @@ def append_outgroup(V_list_FI, df_search, gene, group, path, opt):
# For each of the input, should use different cutoff
ambiguous_db = set()
if opt.suspicious is True:
+ # Pre-group once instead of rescanning the whole (per-group) search table
+ # with a boolean mask for every qseqid (was O(n_queries * len(df_search))).
+ df_search_by_qseqid = df_search.groupby("qseqid")
for qseqid, _df in cutoff_set_df.groupby(["qseqid"]):
# Select dataframe corresponding to current qseqid
- df_qseqid = df_search[df_search["qseqid"] == qseqid[0]]
+ try:
+ df_qseqid = df_search_by_qseqid.get_group(qseqid[0])
+ except KeyError:
+ continue
# Get the list of subjects, which is closer than furtest ingroup
ambiguous_df = df_qseqid[
@@ -310,7 +348,7 @@ def append_outgroup(V_list_FI, df_search, gene, group, path, opt):
)
# Move outgroup within ambiguous db to outgroup
- for FI in ambiguous_db:
+ for FI in list(ambiguous_db):
if FI.group == subject_group:
ambiguous_db.remove(FI)
outgroup_dict[subject_group].append(FI)
@@ -340,7 +378,7 @@ def append_outgroup(V_list_FI, df_search, gene, group, path, opt):
)
# Move outgroup within ambiguous db to outgroup
- for FI in ambiguous_db:
+ for FI in list(ambiguous_db):
if FI.group == max_group:
ambiguous_db.remove(FI)
outgroup_dict[max_group].append(FI)
@@ -360,10 +398,9 @@ def group_cluster_opt_generator(V, opt, path):
# cluster(FO, df_search, V, path, opt)
if len(V.list_qr_gene) == 0:
- logging.error(
- "In group_cluster_option_generator, no available query genes were selected"
+ raise ClusterError(
+ "no query genes are available for clustering (V.list_qr_gene is empty)"
)
- raise Exception
# For concatenated analysis
else:
@@ -391,7 +428,7 @@ def group_cluster_opt_generator(V, opt, path):
def outgroup_append_opt_generator(V, path, opt):
opt_append_outgroup = []
- #### Pararellize this part
+ #### Parallelize this part
# Assign different outgroup for each dataset
# if concatenated analysis is true
@@ -405,10 +442,10 @@ def outgroup_append_opt_generator(V, path, opt):
# Generating outgroup opt for multiprocessing
for gene in V.dict_dataset[group]:
opt_append_outgroup.append(
- (V.list_FI, df_group_, gene, group, path, opt)
+ (df_group_, gene, group, path, opt)
)
- except:
+ except KeyError:
logging.warning(
f"{group} / concatenated dataset exists, but cannot append outgroup due to no corresponding search result"
)
@@ -422,28 +459,20 @@ def pipe_cluster(V, opt, path):
if opt.method.search in ("blast", "mmseqs"):
logging.info("group clustering")
- rslt_cluster = []
-
- # cluster opt generation for multiprocessing
- # (FI, V, path, opt)
- opt_cluster = group_cluster_opt_generator(V, opt, path)
-
- # print(f"opt_cluster : {sys.getsizeof(opt_cluster)}")
-
- batch_size = opt.thread * 100
- opt_cluster_batches = batched_generator(opt_cluster, batch_size)
-
- # run multiprocessing start
- if opt.verbose < 3:
- for batch in opt_cluster_batches:
- batch_list = list(batch)
+ # Assign each query's group from ONE in-process groupby over the concatenated
+ # search table. The former path scanned the whole cSR once per FI inside an
+ # mp.Pool that was handed the entire table per task -> O(N_FI * N_rows) plus
+ # repeated full-table pickling, which dominated the cluster step at scale.
+ hash_to_FI = {FI.hash: FI for FI in V.list_FI}
+ cSR_subset = V.cSR[["qseqid", "bitscore", "subject_group"]]
- with mp.Pool(opt.thread) as p:
- rslt_cluster.extend(p.starmap(cluster, batch_list))
+ rslt_cluster = []
+ for qseqid, df_search in cSR_subset.groupby("qseqid", sort=False):
+ FI = hash_to_FI.get(qseqid)
+ if FI is None:
+ continue
+ rslt_cluster.append(cluster(FI, df_search, opt))
- else:
- # non-multithreading mode for debugging
- rslt_cluster = [cluster(*o) for o in opt_cluster]
# gather cluster result
for cluster_result in rslt_cluster:
FI = cluster_result
@@ -509,6 +538,10 @@ def pipe_cluster(V, opt, path):
def pipe_append_outgroup(V, path, opt):
opt_append_outgroup = outgroup_append_opt_generator(V, path, opt)
+ # Share V.list_FI with pool workers via fork copy-on-write (set before the Pool)
+ # instead of pickling the whole list into every task.
+ _OUTGROUP_SHARED["list_FI"] = V.list_FI
+
# run multiprocessing start
if opt.verbose < 3:
p = mp.Pool(opt.thread)
@@ -533,11 +566,12 @@ def pipe_append_outgroup(V, path, opt):
# Add outgroup and ambiguous groups to dataset
# Ambiguous groups are strains locating between outgroup and ingroups, so cannot be decided
- print(f"{group} {gene}")
- print(f"outgroup {len(outgroup)}")
- print(f"ambiguous_group {len(ambiguous_group)}")
- print(f"db: {len(V.dict_dataset[group][gene].list_db_FI)}")
- print(f"query: {len(V.dict_dataset[group][gene].list_qr_FI)}")
+ logging.debug(
+ f"Outgroup selection for {group} {gene}: outgroup={len(outgroup)}, "
+ f"ambiguous={len(ambiguous_group)}, "
+ f"db={len(V.dict_dataset[group][gene].list_db_FI)}, "
+ f"query={len(V.dict_dataset[group][gene].list_qr_FI)}"
+ )
if len(outgroup) == 0 and len(ambiguous_group) == 0:
logging.critical(
@@ -576,11 +610,15 @@ def pipe_append_outgroup(V, path, opt):
)
critical_flag = 1
V.dict_dataset.pop(group, None)
- except:
+ except KeyError:
+ # group already removed above / not present; nothing to do
pass
# Terminate if terminate option is given, and critical error occurs
if critical_flag == 1 and opt.terminate is True:
- raise Exception
+ raise ClusterError(
+ "stopping: one or more group/gene datasets could not be built "
+ "(see the CRITICAL messages above); --terminate is set"
+ )
return V, path, opt
diff --git a/funvip/src/command.py b/funvip/src/command.py
index 4694843..60dfa60 100644
--- a/funvip/src/command.py
+++ b/funvip/src/command.py
@@ -54,7 +54,7 @@ def get_args(self) -> argparse.Namespace:
)
group_test.add_argument(
"--test",
- help="Use test dataset, [Penicillium, Terrei, Sanghuangporus]",
+ help="Run on a bundled test dataset, one of [penicillium, terrei, sanghuangporus]. Requires --email for the bundled GenBank accessions.",
type=str,
)
@@ -84,7 +84,7 @@ def get_args(self) -> argparse.Namespace:
)
group_run.add_argument(
"--mode",
- help="Mode setup in species identification, see documents for detailed explanations, [validation, identification] default : validation",
+ help="Analysis mode, one of [identification, validation]. default : identification",
type=str,
)
group_run.add_argument(
@@ -95,12 +95,12 @@ def get_args(self) -> argparse.Namespace:
)
group_run.add_argument(
"--step",
- help="[WIP] Steps to continue from previous run, will be ignored if invalid --continue option [setup, search, cluster, align, trim, concatenate, modeltest, tree, visualize, report]",
+ help="With --continue, resume from this pipeline step, one of [setup, search, cluster, align, trim, concatenate, modeltest, tree, visualize, report]. Ignored without a valid --continue.",
type=str,
)
group_run.add_argument(
"--level",
- help="Taxonomic level for each phylogenetic tree. Should be one of [subseries, series, subsection, section, subtribe, tribe, subfamily, family, suborder, order, subclass, class, subphylum, phylum, subdivision, division, subkingdom, kingdom]",
+ help="Taxonomic level at which each phylogenetic tree is built, one of [genus, subseries, series, subsection, section, subtribe, tribe, subfamily, family, suborder, order, subclass, class, subphylum, phylum, subdivision, division, subkingdom, kingdom]. default : genus",
type=str,
)
group_run.add_argument(
@@ -119,7 +119,7 @@ def get_args(self) -> argparse.Namespace:
)
group_method.add_argument(
"--search",
- help="Search methods to be used in selecting genes, groups and outgroups, [blast, mmseqs], default : mmseqs",
+ help="Search method for selecting genes, groups and outgroups, one of [blast, mmseqs]. default : blast",
type=str,
)
group_method.add_argument(
@@ -176,7 +176,7 @@ def get_args(self) -> argparse.Namespace:
group_visualize.add_argument(
"--backgroundcolor",
- help='List of background colors to be shown in tree, default: #f4f4f4, #c6c6c6. Input should be used with quotes, delimit with spaces and recommended to be used as hex codes. To remove background, use --backgroundcolor "#FFFFFF" "#FFFFFF" ',
+ help='Alternating background band colors in the tree, space-delimited hex codes in quotes. default: "#ffe0e0" "#ffefef". To remove the background use --backgroundcolor "#FFFFFF" "#FFFFFF".',
nargs="*",
type=str,
)
@@ -193,7 +193,7 @@ def get_args(self) -> argparse.Namespace:
)
group_visualize.add_argument(
"--fsize",
- help="Font size to use for phylogenetic tree, default: 10",
+ help="Font size for phylogenetic tree labels, default: 14",
type=float,
)
group_visualize.add_argument(
@@ -214,7 +214,8 @@ def get_args(self) -> argparse.Namespace:
)
group_run.add_argument(
"--maxoutgroup",
- help="Maximum outgroup numbers to include in phylogenetic analysis, default : 1",
+ help="Maximum number of outgroup sequences to include in each phylogenetic tree, default : 3",
+ type=int,
)
group_advanced.add_argument(
"--collapsedistcutoff",
@@ -223,12 +224,12 @@ def get_args(self) -> argparse.Namespace:
)
group_advanced.add_argument(
"--collapsebscutoff",
- help="Minimum bootstrap to be considered as same species, default : 100",
+ help="Minimum bootstrap support to collapse a clade as one species; the default 101 (above the 100 maximum) disables bootstrap-based collapsing. default : 101",
type=float,
)
group_advanced.add_argument(
"--bootstrap",
- help="Boostrap number for tree analysis, will be ignored if fasttree is selected for tree method, default : 1000",
+ help="Bootstrap replicates for tree analysis (ignored when tree method is fasttree). default : 100 (the accurate preset uses 1000)",
type=int,
)
group_advanced.add_argument(
@@ -252,7 +253,7 @@ def get_args(self) -> argparse.Namespace:
group_advanced.add_argument(
"--cluster-evalue",
dest="cluster_evalue",
- help="E-value cutoffs for blast/mmseqs search, default : 0.0000001",
+ help="E-value cutoff for the blast/mmseqs clustering search; an explicit value overrides the preset. default : 0.0001",
type=float,
)
group_advanced.add_argument(
@@ -271,7 +272,8 @@ def get_args(self) -> argparse.Namespace:
group_advanced.add_argument(
"--mafft-algorithm",
dest="mafft_algorithm",
- help="MAFFT algorithm for alignment, see mafft documents, will be ignored if mafft not selected for alignment option, default : auto",
+ help="MAFFT algorithm for alignment (see MAFFT docs). default : auto",
+ type=str,
)
group_advanced.add_argument(
"--mafft-op",
@@ -288,10 +290,11 @@ def get_args(self) -> argparse.Namespace:
group_advanced.add_argument(
"--trimal-algorithm",
dest="trimal_algorithm",
- help="Trimal algorithm for trimming, see trimal documents, will be ignored if trimal not selected for trimming option, default : gt",
+ help="trimAl algorithm for trimming (see trimAl docs). default : gt",
+ type=str,
)
group_advanced.add_argument(
- "--trimal-gt", dest="trimal_gt", help="gt value for trimal", type=float
+ "--trimal-gt", dest="trimal_gt", help="trimAl -gt (gap threshold), between 0 and 1. default : 0.2", type=float
)
group_advanced.add_argument(
"--allow-innertrimming",
@@ -301,7 +304,7 @@ def get_args(self) -> argparse.Namespace:
)
group_advanced.add_argument(
"--criterion",
- help="Modeltest criterion to use, either AIC, AICc or BIC",
+ help="Model-selection criterion for modeltest, one of [AIC, AICc, BIC]. default : BIC",
type=str,
)
diff --git a/funvip/src/concatenate.py b/funvip/src/concatenate.py
index 91d53ce..0213d26 100644
--- a/funvip/src/concatenate.py
+++ b/funvip/src/concatenate.py
@@ -7,6 +7,7 @@
import pandas as pd
from copy import deepcopy
from funvip.src import search, hasher
+from funvip.src.exceptions import DatasetError
from scipy.optimize import minimize
import numpy as np
import shutil
@@ -121,11 +122,10 @@ def combine_alignment(V, opt, path):
}
else:
- logging.error(f"V.dict_dataset {group}: {V.dict_dataset[group]}")
- logging.error(
- f"[DEVELOPMENTAL ERROR] Failed constructing concatenated alignment for {group}"
+ raise DatasetError(
+ f"cannot build concatenated alignment for group {group}: "
+ f"no gene datasets besides 'concatenated' (got {list(V.dict_dataset[group])})"
)
- raise Exception
else:
logging.warning(
@@ -269,23 +269,33 @@ def objective(x):
)
def vectorized_prediction(df, gene_list, coeff, grad):
- for k, gene in enumerate(gene_list):
- linear_constant = (coeff[k] - df[f"{gene}_bitscore"]) / grad[k]
- mean_linear_constant = linear_constant.mean()
-
- # Fill missing bitscores
- """
- df[f"{gene}_bitscore"].fillna(
- coeff[k] - mean_linear_constant * grad[k], inplace=True
- )
- """
- df.fillna(
- {f"{gene}_bitscore": coeff[k] - mean_linear_constant * grad[k]},
- inplace=True,
- )
+ # Fill a row's missing gene bitscore by projecting the row's KNOWN gene
+ # bitscores onto the fitted regression line (X_i = coeff_i - t*grad_i) and
+ # reading off the missing coordinate. The former version used each gene's
+ # column mean, which reduces algebraically to a single constant per gene
+ # and ignores the row's other genes entirely. t is the least-squares line
+ # parameter over the row's present dimensions:
+ # t = -sum_j grad_j (X_j - coeff_j) / sum_j grad_j^2 (j = present genes)
+ cols = [f"{gene}_bitscore" for gene in gene_list]
+ coeff_a = np.asarray(coeff, dtype=float)
+ grad_a = np.asarray(grad, dtype=float)
+ X = df[cols].to_numpy(dtype=float)
+ present = ~np.isnan(X)
+ a = X - coeff_a # NaN where missing
+ grad_row = np.broadcast_to(grad_a, X.shape)
+ num = np.sum(np.where(present, grad_row * a, 0.0), axis=1)
+ den = np.sum(np.where(present, grad_row**2, 0.0), axis=1)
+ with np.errstate(divide="ignore", invalid="ignore"):
+ t = np.where(den > 0, -num / den, 0.0)
+ pred = coeff_a[None, :] - t[:, None] * grad_a[None, :]
+ # Bitscores are non-negative; guard a line that extrapolates below zero.
+ pred = np.clip(pred, 0.0, None)
+ X_filled = np.where(present, X, pred)
+ for i, col in enumerate(cols):
+ df[col] = X_filled[:, i]
return df
- # Change to numpy for faster cazlculation
+ # Change to numpy for faster calculation
np_bitscore = df_multigene_regression[
[f"{gene}_bitscore" for gene in gene_list]
].to_numpy()
@@ -324,6 +334,14 @@ def vectorized_prediction(df, gene_list, coeff, grad):
].mean(axis=1)
V.cSR = df_multigene_regression.reset_index()
+ # Dictionary-encode the repeated hash / group string columns of the
+ # concatenated search table (which persists for the rest of the run) to cut
+ # its memory footprint (category is ~8-29x smaller than object/str on these
+ # columns); the stored values are unchanged.
+ for _col in V.cSR.columns:
+ if not pd.api.types.is_numeric_dtype(V.cSR[_col]):
+ V.cSR[_col] = V.cSR[_col].astype("category")
+
# Save it
# decode df is not working well here
if opt.nosearchresult is False:
@@ -333,4 +351,9 @@ def vectorized_prediction(df, gene_list, coeff, grad):
fmt=opt.tableformat,
)
+ # The per-gene search tables are only needed to build V.cSR above; drop them so
+ # they do not stay resident (and get re-pickled into every later session
+ # checkpoint) for the rest of the run.
+ V.dict_gene_SR = {}
+
return V
diff --git a/funvip/src/dataset.py b/funvip/src/dataset.py
index d483749..fc55aca 100644
--- a/funvip/src/dataset.py
+++ b/funvip/src/dataset.py
@@ -2,6 +2,7 @@
from funvip.src import hasher
from funvip.src import ext
from funvip.src.opt_generator import opt_generator
+from funvip.src.exceptions import ConfigError, DatasetError
from Bio import SeqIO
import os
import sys
@@ -154,7 +155,7 @@ def exist_dataset(self, group, gene):
try:
self.dict_dataset[group][gene]
return True
- except:
+ except KeyError:
return False
# Check if dict_group has been properly generated
@@ -199,67 +200,50 @@ def check_dict_group(self, opt):
)
else:
- logging.error(f"DEVELOPMENTAL ERROR, UNEXPECTED LEVEL {opt.level} selected")
- raise Exception
+ raise ConfigError(f"unexpected taxonomic level {opt.level!r} (check --level)")
# generate dataset by group and gene
def generate_dataset(self, opt):
# Format : dict_funinfo = {group: {gene : [FI]}}
dict_funinfo = {}
+ # Pre-index FIs by adjusted_group in a single pass (preserving list_FI
+ # order) so the per-group/per-gene loops below filter a small bucket
+ # instead of rescanning the whole FI universe each time -- the former was
+ # O(N_groups * N_genes * N_FI) and dominated wall-clock at metabarcoding
+ # scale. Order is preserved, so datasets are built identically.
+ group_query = {}
+ group_db = {}
+ for FI in self.list_FI:
+ if FI.datatype == "query":
+ group_query.setdefault(FI.adjusted_group, []).append(FI)
+ elif FI.datatype == "db":
+ group_db.setdefault(FI.adjusted_group, []).append(FI)
+
for group in self.list_group:
logging.info(f"Generating dataset for {group}")
- # print(f"opt.queryonly: {opt.queryonly}")
-
dict_funinfo[group] = {}
+ group_query_FI = group_query.get(group, [])
+ group_db_FI = group_db.get(group, [])
+
# For queryonly case
if opt.queryonly is True:
- # whether to run this group
- group_flag = False
- for gene in self.list_db_gene:
- logging.debug(
- f"Searching dataset {group} {gene} includes query sequences"
- )
- list_qr = [
- FI
- for FI in self.list_FI
- if (
- gene in FI.seq
- and FI.datatype == "query"
- and FI.adjusted_group == group
- )
- ]
-
- # do not manage db when --queryonly True (--all False) and query does not exists
- if len(list_qr) > 0:
- group_flag = True
+ # whether to run this group: any query in this group carries any
+ # of the target genes
+ group_flag = any(
+ gene in FI.seq
+ for gene in self.list_db_gene
+ for FI in group_query_FI
+ )
# if decided to run this group
if group_flag is True:
logging.info(f"Decided to construct dataset on {group}")
for gene in self.list_db_gene:
- list_qr = [
- FI
- for FI in self.list_FI
- if (
- gene in FI.seq
- and FI.datatype == "query"
- and FI.adjusted_group == group
- )
- ]
-
- list_db = [
- FI
- for FI in self.list_FI
- if (
- gene in FI.seq
- and FI.datatype == "db"
- and FI.adjusted_group == group
- )
- ]
-
+ list_qr = [FI for FI in group_query_FI if gene in FI.seq]
+ list_db = [FI for FI in group_db_FI if gene in FI.seq]
self.add_dataset(group, gene, list_qr, list_db, [])
else:
@@ -268,43 +252,26 @@ def generate_dataset(self, opt):
)
# for concatenated
- list_qr = [
- FI
- for FI in self.list_FI
- if (FI.datatype == "query" and FI.adjusted_group == group)
- ]
+ list_qr = list(group_query_FI)
# do not manage db when query only mode and query does not exists
if len(list_qr) > 0:
- list_db = [
- FI
- for FI in self.list_FI
- if (FI.datatype == "db" and FI.adjusted_group == group)
- ]
+ list_db = list(group_db_FI)
self.add_dataset(group, "concatenated", list_qr, list_db, [])
# For opt.queryonly is False -> run all dataset in database if possible
else:
for gene in self.list_db_gene:
- list_qr = []
- for FI in self.list_FI:
- if (
- FI.datatype == "query"
- and FI.adjusted_group == group
- and gene in FI.seq
- ):
- if FI.seq[gene] != "":
- list_db.append(FI)
-
- list_db = []
- for FI in self.list_FI:
- if (
- FI.datatype == "db"
- and FI.adjusted_group == group
- and gene in FI.seq
- ):
- if FI.seq[gene] != "":
- list_db.append(FI)
+ list_qr = [
+ FI
+ for FI in group_query_FI
+ if gene in FI.seq and FI.seq[gene] != ""
+ ]
+ list_db = [
+ FI
+ for FI in group_db_FI
+ if gene in FI.seq and FI.seq[gene] != ""
+ ]
# If none of the database is possible for this group and gene pair, it should be excluded
if len(list_db) > 0:
@@ -315,16 +282,8 @@ def generate_dataset(self, opt):
)
# for concatenated
- list_qr = [
- FI
- for FI in self.list_FI
- if (FI.datatype == "query" and FI.adjusted_group == group)
- ]
- list_db = [
- FI
- for FI in self.list_FI
- if (FI.datatype == "db" and FI.adjusted_group == group)
- ]
+ list_qr = list(group_query_FI)
+ list_db = list(group_db_FI)
self.add_dataset(group, "concatenated", list_qr, list_db, [])
self.check_dict_group(opt)
@@ -344,10 +303,11 @@ def homogenize_dataset(self):
self.dict_hash_FI[h].final_species = FI.final_species
# If they collides, it is error
else:
- logging.error(
- f"DEVELOPMNETAL ERROR Both list_FI and dict_hash_FI have conflicting final species, {FI.final_species} and {self.dict_hash_FI[h].final_species} for hash {h}"
+ raise DatasetError(
+ f"conflicting final_species for hash {h}: "
+ f"{FI.final_species!r} (list_FI) vs "
+ f"{self.dict_hash_FI[h].final_species!r} (dict_hash_FI)"
)
- raise Exception
# adjusted group
if FI.adjusted_group != self.dict_hash_FI[h].adjusted_group:
@@ -356,10 +316,11 @@ def homogenize_dataset(self):
elif self.dict_hash_FI[h].adjusted_group == "":
self.dict_hash_FI[h].adjusted_group = FI.adjusted_group
else:
- logging.error(
- f"DEVELOPMENTAL ERROR Both list_FI and dict_hash_FI have conflicting final group, {FI.adjusted_group} and {self.dict_hash_FI[h].adjusted_group}, {FI}"
+ raise DatasetError(
+ f"conflicting adjusted_group for {FI.id}: "
+ f"{FI.adjusted_group!r} (list_FI) vs "
+ f"{self.dict_hash_FI[h].adjusted_group!r} (dict_hash_FI)"
)
- raise Exception
elif (
FI.adjusted_group == ""
@@ -384,13 +345,14 @@ def homogenize_dataset(self):
pass
elif not (FI.bygene_species):
FI.bygene_species = self.dict_hash_FI[h].bygene_species
- elif self.dict_hash_FI[h].bygene_species:
+ elif not (self.dict_hash_FI[h].bygene_species):
self.dict_hash_FI[h].bygene_species = FI.bygene_species
else:
- logging.error(
- f"DEVELOPMENTAL ERROR Both list_FI and dict_hash_FI have conflicting gene identification results, {FI.bygene_species} and {self.dict_hash_FI[h].bygene}"
+ raise DatasetError(
+ f"conflicting bygene_species for hash {h}: "
+ f"{FI.bygene_species!r} vs "
+ f"{self.dict_hash_FI[h].bygene_species!r}"
)
- raise Exception
# Remove invalid dataset to be analyzed
def remove_invalid_dataset(self):
@@ -448,13 +410,12 @@ def save_dataset(self, path, opt):
)
# Remove no seqs
- for fasta in fasta_list:
- save.save_fasta(
- fasta_list,
- gene,
- f"{path.out_adjusted}/{opt.runname}_Adjusted_{group}_{gene}.fasta",
- by="hash",
- )
+ save.save_fasta(
+ fasta_list,
+ gene,
+ f"{path.out_adjusted}/{opt.runname}_Adjusted_{group}_{gene}.fasta",
+ by="hash",
+ )
# Validate if any multiple sequence alignment has no overlapping region
def validate_alignments(self, path, opt):
@@ -475,11 +436,11 @@ def validate_alignments(self, path, opt):
f"{path.out_alignment}/{opt.runname}_trimmed_{group}_{gene}.fasta"
)
):
- logger.warning(
+ logging.warning(
f"Alignment file {path.out_alignment}/{opt.runname}_trimmed_{group}_{gene}.fasta does not exists"
)
- fail_list.append(group_gene)
+ fail_list.append((group, gene))
else:
# If alignment exists, check if alignment does have overlapping regions
@@ -493,17 +454,16 @@ def validate_alignments(self, path, opt):
# Remove sequences that has not been existed during alignment stage
seq_id_list = [seq.id for seq in seq_list]
- for FI in self.dict_dataset[group][gene].list_db_FI:
- if not (FI.hash in seq_id_list):
- self.dict_dataset[group][gene].list_db_FI.remove(FI)
-
- for FI in self.dict_dataset[group][gene].list_qr_FI:
- if not (FI.hash in seq_id_list):
- self.dict_dataset[group][gene].list_qr_FI.remove(FI)
-
- for FI in self.dict_dataset[group][gene].list_og_FI:
- if not (FI.hash in seq_id_list):
- self.dict_dataset[group][gene].list_og_FI.remove(FI)
+ dataset = self.dict_dataset[group][gene]
+ dataset.list_db_FI = [
+ FI for FI in dataset.list_db_FI if FI.hash in seq_id_list
+ ]
+ dataset.list_qr_FI = [
+ FI for FI in dataset.list_qr_FI if FI.hash in seq_id_list
+ ]
+ dataset.list_og_FI = [
+ FI for FI in dataset.list_og_FI if FI.hash in seq_id_list
+ ]
# Remove empty sequences
remove_hash = []
@@ -619,7 +579,10 @@ def validate_alignments(self, path, opt):
# Terminate if terminate option is given, and critical error occurs
if critical_flag == 1 and opt.terminate is True:
- raise Exception
+ raise DatasetError(
+ "stopping: one or more datasets failed alignment validation "
+ "(see the CRITICAL messages above); --terminate is set"
+ )
# Remove bad datasets
for fail in fail_list:
@@ -647,27 +610,19 @@ def validate_alignments(self, path, opt):
if group in self.dict_dataset:
if gene in self.dict_dataset[group]:
for _hash in remove_dict[group][gene]:
- if _hash in self.dict_dataset[group][gene].list_qr_FI:
- self.dict_dataset[group][gene].list_qr_FI.remove(
- self.dict_hash_FI[_hash]
- )
- logging.warning(
- f"{self.dict_hash_ID[_hash]} removed from dataset {group} {gene}. Please check the alignment and see the region is correct"
- )
- if _hash in self.dict_dataset[group][gene].list_db_FI:
- self.dict_dataset[group][gene].list_db_FI.remove(
- self.dict_hash_FI[_hash]
- )
- logging.warning(
- f"{self.dict_hash_ID[_hash]} removed from dataset {group} {gene}. Please check the alignment and see the region is correct"
- )
- if _hash in self.dict_dataset[group][gene].list_og_FI:
- self.dict_dataset[group][gene].list_og_FI.remove(
- self.dict_hash_FI[_hash]
- )
- logging.warning(
- f"{self.dict_hash_ID[_hash]} removed from dataset {group} {gene}. Please check the alignment and see the region is correct"
+ for _attr in ("list_qr_FI", "list_db_FI", "list_og_FI"):
+ _lst = getattr(
+ self.dict_dataset[group][gene], _attr
)
+ if any(x.hash == _hash for x in _lst):
+ setattr(
+ self.dict_dataset[group][gene],
+ _attr,
+ [x for x in _lst if x.hash != _hash],
+ )
+ logging.warning(
+ f"{self.dict_hash_id[_hash]} removed from dataset {group} {gene}. Please check the alignment and see the region is correct"
+ )
# Finally, check again if the datasets meet criteria
final_fail_list = []
@@ -745,49 +700,60 @@ def validate_alignments(self, path, opt):
if opt.method.tcs is True:
bad_cnt = 0
- if opt.verbose < 3:
- tcs_opt = opt_generator(
- V=self, opt=opt, path=path, step="tcs", thread=1
+ # TCS is optional alignment QC; a broken/leaking t-coffee must not abort
+ # the whole run. Log and skip on failure (the memory cap in ext.TCS keeps
+ # a leaking t-coffee from consuming the machine).
+ try:
+ if opt.verbose < 3:
+ tcs_opt = opt_generator(
+ V=self, opt=opt, path=path, step="tcs", thread=1
+ )
+ with mp.Pool(opt.thread) as p:
+ p.starmap(ext.TCS, tcs_opt)
+
+ else:
+ tcs_opt = opt_generator(V=self, opt=opt, path=path, step="tcs")
+ for option in tcs_opt:
+ ext.TCS(*option)
+ except Exception as e:
+ logging.warning(
+ f"TCS alignment validation failed and was skipped: {e}"
)
- p = mp.Pool(opt.thread)
- p.starmap(ext.TCS, tcs_opt)
- p.close()
- p.join()
- else:
- tcs_opt = opt_generator(V=self, opt=opt, path=path, step="tcs")
- for option in tcs_opt:
- ext.TCS(*option)
-
- # non-multithreading mode for debugging
- for group in self.dict_dataset:
- for gene in self.dict_dataset[group]:
- # Running TCS for concatenated alignment is duplicate
- if gene != "concatenated":
- tcs_out = f"{path.out_alignment}/alignment/{opt.runname}_{group}_{gene}.tcs"
- # Parse tcs result
- with open(tcs_out, "r") as f_tcs:
- tcs_result_raw = f_tcs.read()
- tcs_result = tcs_result_raw.split("*")[2].split("cons")[
- 0
- ]
- for line in tcs_result.split("\n")[1:-1]:
- _hash = line.split(":")[0].strip()
- tcs_score = int(line.split(":")[1].strip())
- if (
- tcs_score < 50
- ): # cutoff 50 comes from TCS documentation
- FI_id = self.dict_hash_FI[_hash].id
- logging.warning(
- f"{FI_id} has poor alignment score in {group} {gene}"
- )
- bad_cnt += 1
+ # Parse whatever TCS score files were produced. A dataset whose TCS run
+ # failed leaves no score file, so skip missing/unparseable ones instead
+ # of crashing the whole run.
+ for group in self.dict_dataset:
+ for gene in self.dict_dataset[group]:
+ # Running TCS for concatenated alignment is duplicate
+ if gene == "concatenated":
+ continue
+ tcs_out = f"{path.out_alignment}/alignment/{opt.runname}_{group}_{gene}.tcs"
+ if not os.path.exists(tcs_out):
+ continue
+ try:
+ with open(tcs_out, "r") as f_tcs:
+ tcs_result_raw = f_tcs.read()
+ tcs_result = tcs_result_raw.split("*")[2].split("cons")[0]
+ for line in tcs_result.split("\n")[1:-1]:
+ _hash = line.split(":")[0].strip()
+ tcs_score = int(line.split(":")[1].strip())
+ if tcs_score < 50: # cutoff 50 from TCS documentation
+ FI_id = self.dict_hash_FI[_hash].id
+ logging.warning(
+ f"{FI_id} has poor alignment score in {group} {gene}"
+ )
+ bad_cnt += 1
+ except Exception as e:
+ logging.warning(
+ f"Could not parse TCS score file {tcs_out}: {e}"
+ )
if bad_cnt == 0:
logging.info(f"All sequences in alignment passed TCS validation")
else:
logging.warning(
- f"{bad_cnt} sequences in alignment failed TCS validation. Please check sequneces"
+ f"{bad_cnt} sequences in alignment failed TCS validation. Please check sequences"
)
# check inconsistency exists along identification result of each genes
diff --git a/funvip/src/exceptions.py b/funvip/src/exceptions.py
new file mode 100644
index 0000000..d67fc19
--- /dev/null
+++ b/funvip/src/exceptions.py
@@ -0,0 +1,46 @@
+"""FunVIP exception hierarchy.
+
+Every error FunVIP raises on purpose derives from :class:`FunVIPError`, so the
+top-level handler in ``main`` (and any caller) can tell an *expected, explained*
+FunVIP failure apart from an unexpected bug and report it cleanly.
+
+Guidance:
+- Raise the most specific subclass that fits, with a message that names the
+ offending thing (group, gene, FI id, file path, option) -- never a bare
+ ``raise Exception``.
+- Reserve a plain ``FunVIPError`` for cases that do not fit a subclass.
+- Do not use these for internal control flow; they mean "stop and tell the user".
+"""
+
+
+class FunVIPError(Exception):
+ """Base class for all FunVIP errors."""
+
+
+class ConfigError(FunVIPError):
+ """Invalid or inconsistent command-line options / configuration."""
+
+
+class InputError(FunVIPError):
+ """Malformed or missing query/database input (sequences, tables, metadata)."""
+
+
+class SearchError(FunVIPError):
+ """Failure in the BLAST/mmseqs search stage or its result matrices."""
+
+
+class ClusterError(FunVIPError):
+ """Failure assigning sequences to groups or selecting an outgroup."""
+
+
+class DatasetError(FunVIPError):
+ """Failure building a group/gene dataset or its (concatenated) alignment."""
+
+
+class TreeError(FunVIPError):
+ """Failure building, rooting, or interpreting a phylogenetic tree."""
+
+
+class ExternalToolError(FunVIPError):
+ """An external tool (mafft, trimal, fasttree, iqtree, raxml, mmseqs, gblocks,
+ modeltest, ...) was missing, failed, or returned an unusable result."""
diff --git a/funvip/src/ext.py b/funvip/src/ext.py
index 9c37c7c..b42b7a0 100644
--- a/funvip/src/ext.py
+++ b/funvip/src/ext.py
@@ -9,6 +9,7 @@
from pathlib import Path
from funvip.src.save import save_tree
from funvip.src.tool import mkdir
+from funvip.src.exceptions import ExternalToolError, SearchError
# Search methods
@@ -31,6 +32,8 @@ def blast(query, db, out, path, opt):
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise SearchError(f"blastn failed (exit code {Run}) for query {query} vs db {db}")
# mmseqs
@@ -52,6 +55,8 @@ def mmseqs(query, db, out, tmp, path, opt):
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise SearchError(f"mmseqs easy-search failed (exit code {Run}) for query {query} vs db {db}")
# DB building methods
@@ -81,7 +86,9 @@ def makeblastdb(fasta, db, path):
CMD = f"{path_makeblastdb} -in {fasta_tmp} -blastdb_version 4 -title {db_tmp} -dbtype nucl"
logging.info(CMD)
# I cannot find any "quiet" options for makeblastdb
- Run = subprocess.call(CMD, stdout=open(os.devnull, "wb"), shell=True)
+ Run = subprocess.call(CMD, stdout=subprocess.DEVNULL, shell=True)
+ if Run != 0:
+ raise ExternalToolError(f"makeblastdb failed (exit code {Run}) for {fasta}")
# Change db names
shutil.move(fasta_tmp + ".nsq", db + ".nsq")
shutil.move(fasta_tmp + ".nin", db + ".nin")
@@ -95,11 +102,10 @@ def makeblastdb(fasta, db, path):
CMD = f"makeblastdb -in '{fasta}' -blastdb_version 4 -title '{db}' -dbtype nucl"
logging.info(CMD)
# I cannot find any "quiet" options for makeblastdb
- return_code = subprocess.call(CMD, stdout=open(os.devnull, "wb"), shell=True)
+ return_code = subprocess.call(CMD, stdout=subprocess.DEVNULL, shell=True)
if return_code != 0:
- logging.error(f"Make blast_db failed!!")
- install_flag = 1
+ raise ExternalToolError(f"makeblastdb failed (exit code {return_code}) for {fasta}")
# Change db names
shutil.move(fasta + ".nsq", db + ".nsq")
@@ -122,6 +128,8 @@ def makemmseqsdb(fasta, db, path):
CMD = f"mmseqs createdb '{fasta}' '{db}' --createdb-mode 0 --dbtype 2"
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise ExternalToolError(f"mmseqs createdb failed (exit code {Run}) for {fasta}")
# Alignments
@@ -155,11 +163,9 @@ def MAFFT(
CMD = f"mafft --thread {thread} --{algorithm} --maxiterate {maxiterate} --{adjust} --op {op} --ep {ep} --quiet '{fasta}' > '{out}'"
logging.info(CMD)
- try:
- Run = subprocess.call(CMD, shell=True)
- except:
- logging.error(f"Failed on {CMD}")
- raise Exception
+ Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise ExternalToolError(f"MAFFT failed (exit code {Run}) for {fasta}")
# Trimming
@@ -176,37 +182,40 @@ def Gblocks(fasta, out, path):
try:
shutil.move(f"{fasta}.gb", out)
- except: # when only one sequence and Gblocks failed
+ except FileNotFoundError: # when only one sequence and Gblocks failed
shutil.move(fasta, out)
- # Parse and return column statistics
- with open(f"{fasta}.gb.txt", "r") as f:
- lines = f.readlines()
- for line in lines:
- if line.startswith("Flanks:"):
- flank_log = line
- flank_log = (
- flank_log.replace("Flanks:", "")
- .replace(" ", " ")
- .replace("[", "")
- .replace("]", "")
- .strip()
- )
- flank_log = flank_log.split(" ")
- print(flank_log)
- try:
- flank_log = [int(x) for x in flank_log]
- start_pos = flank_log[0]
- end_pos = flank_log[-1] - 1
- except:
- start_pos = -1
- end_pos = -1
-
- print(f"start_pos: {start_pos}, end_pos: {end_pos}")
+ # Parse and return column statistics. (Gblocks returns a nonzero exit code even
+ # on success, so its exit code is intentionally not checked.) Default to the
+ # (-1, -1) failure sentinel so a missing/format-drifted .gb.txt cannot NameError.
+ start_pos = -1
+ end_pos = -1
+ if os.path.exists(f"{fasta}.gb.txt"):
+ with open(f"{fasta}.gb.txt", "r") as f:
+ for line in f:
+ if line.startswith("Flanks:"):
+ flank_log = (
+ line.replace("Flanks:", "")
+ .replace(" ", " ")
+ .replace("[", "")
+ .replace("]", "")
+ .strip()
+ .split(" ")
+ )
+ logging.debug(f"Gblocks flanks for {fasta}: {flank_log}")
+ try:
+ flank_log = [int(x) for x in flank_log]
+ start_pos = flank_log[0]
+ end_pos = flank_log[-1] - 1
+ except (ValueError, IndexError):
+ start_pos = -1
+ end_pos = -1
+
+ logging.debug(f"Gblocks start_pos: {start_pos}, end_pos: {end_pos}")
try:
shutil.move(f"{fasta}.gb.txt", path.extlog)
- except:
+ except FileNotFoundError:
pass
return (start_pos, end_pos)
@@ -229,10 +238,12 @@ def Trimal(fasta, out, path, algorithm="gt", threshold=0.2):
CMD = f"{path.sys_path}/external/trimal.v1.4/trimAl/bin/trimal.exe -in {fasta} -out {out_dir} -{algorithm} -terminalonly -colnumbering > {out_colnumbering}"
else:
- CMD = f"trimal -in {fasta} -out {out} -{algorithm} -terminalonly -colnumbering > {out}.colnumbering"
+ CMD = f"trimal -in '{fasta}' -out '{out}' -{algorithm} -terminalonly -colnumbering > '{out}.colnumbering'"
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ if Run != 0 or not os.path.exists(out):
+ raise ExternalToolError(f"trimal failed (exit code {Run}) for {fasta}")
# to remove unexpected hash included - maybe not needed after stabilization
fasta_list = list(SeqIO.parse(out, "fasta"))
@@ -252,13 +263,13 @@ def Trimal(fasta, out, path, algorithm="gt", threshold=0.2):
cols = [int(x) for x in cols]
start_pos = cols[0]
end_pos = cols[-1]
- except:
+ except (ValueError, IndexError):
start_pos = -2
end_pos = -2
try:
shutil.move(f"{out}.colnumbering", path.extlog)
- except:
+ except FileNotFoundError:
pass
# Trimal uses 0 based position, return with +1
@@ -280,6 +291,8 @@ def Modeltest_ng(fasta, out, path, models, thread):
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise ExternalToolError(f"modeltest-ng failed (exit code {Run}) for {fasta}")
# IQTREE ModelFinder
@@ -291,10 +304,9 @@ def ModelFinder(fasta, opt, path, thread):
elif opt.method.tree == "fasttree":
model_term = "-m MF --mset JC,JC+G4,GTR,GTR+G4"
else:
- logging.error(
- f"Modelterm cannot be selected to tree method {opt.method.tree} while running modelfinder"
+ raise ExternalToolError(
+ f"cannot select a model term for tree method {opt.method.tree!r} in ModelFinder"
)
- raise Exception
if platform == "win32":
if " " in fasta:
@@ -305,6 +317,10 @@ def ModelFinder(fasta, opt, path, thread):
CMD = f"iqtree --seqtype DNA -s '{fasta}' {model_term} -merit {opt.criterion} -nt AUTO -ntmax {thread} -mem {opt.memory} --quiet"
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise ExternalToolError(
+ f"IQTREE ModelFinder failed (exit code {Run}) for {fasta}"
+ )
# Tree building
@@ -322,68 +338,66 @@ def RAxML(
if model == "skip":
model = ""
- # Because RAxML does not allows out location, change directory for running
+ # Because RAxML does not allow an out location, change directory for running.
+ # Wrap in try/finally so the original cwd is always restored, even if RAxML
+ # (or CMD selection) fails -- otherwise later relative-path operations break.
path_ori = os.getcwd()
os.chdir(path.tmp)
+ try:
+ if platform == "win32":
+ if " " in fasta:
+ fasta = f'"{fasta}"'
+ if " " in out:
+ out = f'"{out}"'
- if platform == "win32":
- if " " in fasta:
- fasta = f'"{fasta}"'
- if " " in out:
- out = f'"{out}"'
-
- CMD = f"{path.sys_path}/external/RAxML_Windows/raxmlHPC-PTHREADS-AVX2.exe -s {fasta} -n {out} -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model} --silent"
- elif platform == "darwin":
- # For Rossetta
-
- if (
- subprocess.run(
- "raxmlHPC-PTHREADS -v",
- shell=True,
- stdout=open(os.devnull, "wb"),
- stderr=subprocess.STDOUT,
- ).returncode
- == 0
- ):
- CMD = f"raxmlHPC-PTHREADS -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model}"
- # For arm native
- elif (
- subprocess.run(
- "raxmlHPC -v",
- shell=True,
- stdout=open(os.devnull, "wb"),
- stderr=subprocess.STDOUT,
- ).returncode
- == 0
- ):
- CMD = f"raxmlHPC -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model}"
- else:
- logging.error("Cannot find correct RAxML for apple silicon system!")
- raise Exception
+ CMD = f"{path.sys_path}/external/RAxML_Windows/raxmlHPC-PTHREADS-AVX2.exe -s {fasta} -n {out} -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model} --silent"
+ elif platform == "darwin":
+ # For Rosetta
+ if (
+ subprocess.run(
+ "raxmlHPC-PTHREADS -v",
+ shell=True,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.STDOUT,
+ ).returncode
+ == 0
+ ):
+ CMD = f"raxmlHPC-PTHREADS -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model}"
+ # For arm native
+ elif (
+ subprocess.run(
+ "raxmlHPC -v",
+ shell=True,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.STDOUT,
+ ).returncode
+ == 0
+ ):
+ CMD = f"raxmlHPC -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model}"
+ else:
+ raise ExternalToolError(
+ "cannot find a working RAxML for this Apple Silicon system"
+ )
- else:
- if version == "old":
- CMD = f"raxmlHPC-PTHREADS-AVX -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model} --silent"
- elif version == "new":
- CMD = f"raxmlHPC-PTHREADS-AVX2 -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model} --silent"
else:
- logging.error(
- f"DEVELOPMENTAL ERROR - unexpected RAxML version, {version} in ext.py"
- )
- raise Exception
+ if version == "old":
+ CMD = f"raxmlHPC-PTHREADS-AVX -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model} --silent"
+ elif version == "new":
+ CMD = f"raxmlHPC-PTHREADS-AVX2 -s '{fasta}' -n '{out}' -p 1 -T {thread} -f a -# {bootstrap} -x 1 {model} --silent"
+ else:
+ raise ExternalToolError(f"unexpected RAxML version {version!r}")
- if not (partition is None):
- CMD += f" -q {partition}"
+ if not (partition is None):
+ CMD += f" -q {partition}"
- logging.info(CMD)
- Run = subprocess.call(CMD, shell=True)
-
- if Run != 0:
- logging.error(f"RAxML Failed!")
- raise Exception
+ logging.info(CMD)
+ Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise ExternalToolError(f"RAxML failed (exit code {Run}) for {fasta}")
+ finally:
+ # Always restore the original working directory
+ os.chdir(path_ori)
- # Return result to original directory
- os.chdir(path_ori)
file = out.split("/")[-1]
out = f"RAxML_bipartitions.{out}"
save_tree(
@@ -418,6 +432,9 @@ def FastTree(fasta, out, hash_dict, path, model=""):
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ tree_file = f"{path.tmp}/{out}"
+ if Run != 0 or not os.path.exists(tree_file) or os.path.getsize(tree_file) == 0:
+ raise ExternalToolError(f"FastTree failed (exit code {Run}) for {fasta}")
file = out.split("/")[-1]
save_tree(
out=f"{path.tmp}/{out}",
@@ -470,18 +487,21 @@ def IQTREE(
logging.info(CMD)
Run = subprocess.call(CMD, shell=True)
+ if Run != 0:
+ raise ExternalToolError(
+ f"IQTREE failed (exit code {Run}) for {fasta}; refusing to use any "
+ "stale .contree left by a previous run"
+ )
try:
if partition is None:
shutil.move(f"{fasta}.contree", f"{path.tmp}/{out}")
- print(f"DEBUG Moved {fasta}.contree to {path.tmp}/{out}")
else:
shutil.move(f"{partition}.contree", f"{path.tmp}/{out}")
- print(f"DEBUG Moved {partition}.contree to {path.tmp}/{out}")
-
- except:
- logging.error(
- "IQTREE FAILED. Maybe due to memory problem if partitioned analysis included."
- )
+ except FileNotFoundError as e:
+ raise ExternalToolError(
+ f"IQTREE failed (exit code {Run}, no .contree produced) for {fasta}; "
+ "possibly a memory problem for partitioned analysis"
+ ) from e
file = out.split("/")[-1]
save_tree(
@@ -495,8 +515,7 @@ def IQTREE(
# TCS calculation from T-COFFEE
def TCS(fasta, thread, out):
if platform == "win32":
- logging.error("TCS(From T-COFFEE) is only available in Linux")
- raise Exception
+ raise ExternalToolError("TCS (from T-COFFEE) is only available on Linux")
else:
# T_COFFEE env variable MAX_N_PID_4_TCOFFEE should be changed for 64bit machine
# should be already done in installation check process
@@ -504,12 +523,52 @@ def TCS(fasta, thread, out):
CMD = f"t_coffee -infile {fasta} -cpu {thread} -method fast_pair -type DNA -evaluate -output score_ascii -outfile {out} -quiet"
logging.info(CMD)
- # Even though "quiet" option exists, TCS show some blank lines
- # Run = subprocess.call(CMD, stdout=open(os.devnull, "wb"), shell=True)
- Run = subprocess.run(
- CMD, stdout=open(os.devnull, "wb"), stderr=subprocess.STDOUT, shell=True
- ).returncode
+ # Even though "quiet" option exists, TCS shows some blank lines.
+ # Root cause of the "t-coffee eats all RAM" problem: the bioconda t-coffee
+ # indexes a static array by the raw OS PID but is compiled with MAX_N_PID=260000.
+ # On kernels with a large kernel.pid_max (e.g. 4194304) the process PID overflows
+ # that array -> SIGSEGV -> t-coffee's own signal handler re-runs the faulting
+ # instruction in an infinite loop, growing the heap until all memory is gone.
+ # It is a crash-loop, not a real leak, and it fires on ANY invocation (even
+ # `t_coffee -version`). The documented MAX_N_PID_4_TCOFFEE override is not
+ # compiled into this binary, so it cannot be raised at runtime. We cannot fix a
+ # third-party binary here, so bound it: cap the child's address space and wall
+ # time and kill its whole process group on timeout, so a crash-looping t-coffee
+ # is reported as failed instead of taking down the machine.
+ import os
+ import signal
+ import resource
+
+ _AS_CAP = 8 * 1024**3 # 8 GB address-space cap for the t-coffee subprocess
+
+ def _limit_tcs_child():
+ os.setsid()
+ try:
+ resource.setrlimit(resource.RLIMIT_AS, (_AS_CAP, _AS_CAP))
+ except (ValueError, OSError):
+ pass
+
+ proc = subprocess.Popen(
+ CMD,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.STDOUT,
+ shell=True,
+ preexec_fn=_limit_tcs_child,
+ )
+ try:
+ # Bound a hung/slow t-coffee. A leaking one is stopped sooner by the
+ # address-space cap above; this backstops a t-coffee that hangs at low
+ # memory. Legit TCS on normal alignments finishes well within this.
+ Run = proc.wait(timeout=300)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ proc.wait()
+ raise ExternalToolError(
+ "TCS (T-COFFEE) timed out (possible t-coffee memory leak/hang)"
+ )
if Run != 0:
- logging.error(f"TCS Failed!")
- raise Exception
+ raise ExternalToolError(f"TCS (T-COFFEE) failed (exit code {Run})")
diff --git a/funvip/src/hasher.py b/funvip/src/hasher.py
index ce70a54..50d58c7 100644
--- a/funvip/src/hasher.py
+++ b/funvip/src/hasher.py
@@ -65,25 +65,21 @@ def decode(
content = fp.read()
if newick and svg:
- hash_dict = {
- re.escape(k): svg_legal(newick_legal(v)) for k, v in hash_dict.items()
- }
+ lookup = {k: svg_legal(newick_legal(v)) for k, v in hash_dict.items()}
elif newick:
- hash_dict = {re.escape(k): newick_legal(v) for k, v in hash_dict.items()}
+ lookup = {k: newick_legal(v) for k, v in hash_dict.items()}
elif svg:
- hash_dict = {re.escape(k): svg_legal(v) for k, v in hash_dict.items()}
+ lookup = {k: svg_legal(v) for k, v in hash_dict.items()}
else:
- hash_dict = {re.escape(k): v for k, v in hash_dict.items()}
+ lookup = dict(hash_dict)
- """
- hash_dict = {
- re.escape(k): (newick_legal(v) if newick else v) for k, v in hash_dict.items()
- }
- """
- pattern = re.compile("|".join(hash_dict.keys()))
-
- # Perform the substitution
- decoded_content = pattern.sub(lambda m: hash_dict[re.escape(m.group(0))], content)
+ # Every hash has the fixed, self-delimiting form HSHE, so match that
+ # single token and look each occurrence up, instead of compiling an
+ # N-alternative regex ("|".join of every hash) and re-escaping each match --
+ # the former is O(text * N_hashes) and a hotspot at metabarcoding scale.
+ # A HSHE token not present in the dict is left unchanged.
+ pattern = re.compile(r"HS\d+HE")
+ decoded_content = pattern.sub(lambda m: lookup.get(m.group(0), m.group(0)), content)
with open(out, "w") as fw:
fw.write(decoded_content)
@@ -110,9 +106,9 @@ def decode(hash_dict: dict, file: str, out: str, newick: bool = True) -> None:
# Decode given dataframe with given hash_dict
def decode_df(hash_dict: dict, df: pd.DataFrame) -> pd.DataFrame:
- hash_dict = dict((re.escape(k), v) for k, v in hash_dict.items())
-
- df_return = copy.deepcopy(df)
+ # hashes are HSHE (no regex metacharacters), so no escaping is needed;
+ # each cell is either exactly a hash to replace or is left as-is.
+ df_return = df.copy()
for column in df.columns:
df_return[column] = df_return[column].map(lambda x: hash_dict.get(x, x))
diff --git a/funvip/src/logics.py b/funvip/src/logics.py
index 8155909..2ccf8c8 100644
--- a/funvip/src/logics.py
+++ b/funvip/src/logics.py
@@ -1,5 +1,6 @@
import logging
import re
+import numpy as np
from matplotlib import colors as mcolors # for color debugging
# Move all simple logics function deciding True all False here
@@ -15,8 +16,8 @@ def isnan(value) -> bool:
def isvalidcolor(color: str) -> bool:
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
- # Check if color is named colors
- if color in colors.keys():
+ # Check if color is named colors (CSS4 keys are lowercase; normalize input)
+ if color.lower() in colors:
return True
# Check if color is available hex color
elif re.fullmatch(r"^#(?:[0-9a-fA-F]{3}){1,2}$", color):
@@ -25,38 +26,6 @@ def isvalidcolor(color: str) -> bool:
return False
-def isnewicklegal(string: str) -> bool:
- """
- if string is newick legal -> return True
- if string is newick illegal -> return False
- """
- NEWICK_ILLEGAL = (
- "(",
- '"',
- "[",
- ":",
- ";",
- "/",
- "[",
- "]",
- "{",
- "}",
- "(",
- ")",
- ",",
- "]",
- "+",
- '"',
- ")",
- " ",
- )
-
- if any(x in string for x in NEWICK_ILLEGAL):
- return True
- else:
- return False
-
-
def isuniquecolumn(
list_column: list, column: tuple, table_name: str, check_none: bool = True
) -> bool:
diff --git a/funvip/src/modeltest.py b/funvip/src/modeltest.py
index 3019518..ce8ac7b 100644
--- a/funvip/src/modeltest.py
+++ b/funvip/src/modeltest.py
@@ -340,10 +340,7 @@ def parse_model(modeltest_file, opt, path):
)
break
- # Currently using BIC model
- model_cmd = model_dict["BIC"]
-
- except:
+ except Exception:
logging.warning(f"Cannot parse modeltest file for {modeltest_file}")
else:
diff --git a/funvip/src/ncbi.py b/funvip/src/ncbi.py
deleted file mode 100644
index f129fd6..0000000
--- a/funvip/src/ncbi.py
+++ /dev/null
@@ -1,160 +0,0 @@
-from Bio import Entrez
-from Bio import SeqIO
-from Bio.Blast.Applications import NcbiblastnCommandline
-from Bio.Blast import NCBIXML
-from Bio.Seq import Seq
-import time
-from time import sleep
-import pickle
-import json
-import re
-import logging
-from datetime import datetime
-from itertools import repeat
-import xmltodict
-import os, sys, subprocess
-import random
-import pickle
-import pandas as pd
-import shutil
-
-# from .logger import Mes
-
-
-def Downloadbyacclist(Email, list_ID, out):
- if len(list_ID) == 0:
- return []
-
- path_tmp = "tmp_download"
-
- # print(list_ID)
-
- def xml2dict(record):
- dict_type = xmltodict.parse(record)
- json_type = json.dumps(dict_type, indent=4)
- dict2_type = json.loads(json_type)
- return dict2_type
-
- Entrez.email = Email
-
- logging.info(f"Number of IDs: {len(list_ID)}")
-
- # Parse
- cnt = 0
- cut = 50 # parse by 50 sequences
- cnt_all = len(list_ID)
-
- start_time = time.time()
-
- record_list = []
-
- for i in range(int((len(list_ID) - 1) / cut) + 1):
- # last chunk
- if i * cut + cut > len(list_ID):
- # Mes(i)
- ID_string = ",".join(list_ID[i * cut :])
- sleep(0.3)
- cnt += len(list_ID[i * cut :])
- logging.info(
- f"{cnt}/{cnt_all} {100*cnt/cnt_all}% {time.time()-start_time}s"
- )
-
- try:
- print(ID_string)
- handle = Entrez.efetch(
- db="nucleotide", id=ID_string, rettype="gb", retmode="xml"
- )
- except: # Retry
- logging.info("Requesting again...")
- try:
- sleep(10)
- handle = Entrez.efetch(
- db="nucleotide", id=ID_string, rettype="gb", retmode="xml"
- )
- except:
- sleep(100)
- handle = Entrez.efetch(
- db="nucleotide", id=ID_string, rettype="gb", retmode="xml"
- )
-
- pre_record = handle.read()
- json_record = xml2dict(pre_record)
- tmp_record_list = []
-
- # If only one result available
- if type(json_record["GBSet"]["GBSeq"]) is dict:
- json_record["GBSet"]["GBSeq"] = [json_record["GBSet"]["GBSeq"]]
-
- if len(list_ID[i * cut :]) != 1:
- for record in json_record["GBSet"]["GBSeq"]:
- print(record)
- record_list.append(record)
- tmp_record_list.append(record)
- else:
- record = json_record["GBSet"]["GBSeq"]
- record_list.append(record)
- tmp_record_list.append(record)
-
- try:
- with open(f"./{path_tmp}/{i}", "wb") as f:
- pickle.dump(tmp_record_list, f)
- except:
- logging.error("Saving Error")
- raise Exception
-
- # non last chunk
- else:
- # Mes(i)
- ID_string = ",".join(list_ID[i * cut : i * cut + cut])
- sleep(0.3)
- cnt += cut
- logging.info(
- f"{cnt}/{cnt_all} {100*cnt/cnt_all}% {time.time()-start_time}s"
- )
-
- try:
- handle = Entrez.efetch(
- db="nucleotide", id=ID_string, rettype="gb", retmode="xml"
- )
- except: # Retry
- logging.info("Requesting again...")
- try:
- sleep(10)
- handle = Entrez.efetch(
- db="nucleotide", id=ID_string, rettype="gb", retmode="xml"
- )
- except:
- sleep(100)
- handle = Entrez.efetch(
- db="nucleotide", id=ID_string, rettype="gb", retmode="xml"
- )
-
- pre_record = handle.read()
- json_record = xml2dict(pre_record)
- tmp_record_list = []
-
- if len(list_ID[i * cut :]) != 1:
- for record in json_record["GBSet"]["GBSeq"]:
- record_list.append(record)
- tmp_record_list.append(record)
- else:
- record = json_record["GBSet"]["GBSeq"]
- record_list.append(record)
- tmp_record_list.append(record)
-
- try:
- with open(f"./{path_tmp}/{i}", "wb") as f:
- pickle.dump(tmp_record_list, f)
- except:
- logging.error("Saving Error")
- raise Exception
-
- with open(out, "w") as fp:
- json_term = json.dump(record_list, fp, indent=4)
-
- # If success, remove tmp files
- tmp_file_list = [file for file in os.listdir(f"./{path_tmp}/")]
- for file in tmp_file_list:
- os.remove(f"./{path_tmp}/{file}")
-
- return record_list
diff --git a/funvip/src/reporter.py b/funvip/src/reporter.py
index 6aece83..e48f9ec 100644
--- a/funvip/src/reporter.py
+++ b/funvip/src/reporter.py
@@ -84,8 +84,7 @@ def __init__(self):
"IDENTIFIED": [],
"NEW SPECIES CANDIDATE": [],
"MISIDENTIFIED": [],
- "AMBIGUOUS": [],
- "ERROR": [],
+ "UNDETERMINED": [],
"TOTAL": [],
}
@@ -211,6 +210,7 @@ def update_result(self, V, opt):
# Check if data analysis had performed for specific FI, group, gene combination
if (
gene in FI.bygene_species
+ and gene in FI.seq
and len(FI.seq[gene]) > 0
and gene in V.dict_dataset[FI.adjusted_group]
):
@@ -292,60 +292,45 @@ def update_result(self, V, opt):
self.query_result["DATATYPE"] == "query"
]
- ### Update statistics by result
-
- # Groupby group
- df_result_group = self.query_result.groupby(["GROUP_ASSIGNED"])
-
- # Count groups
- for group in sorted(list(set(self.query_result["GROUP_ASSIGNED"]))):
- df_group = df_result_group.get_group((group,))
-
- # Collect statistics
- """
- cnt_correctly_identified = list(df_group["STATUS"]).count(
- "correctly identified"
- )
- cnt_undetermined = list(df_group["STATUS"]).count("undetermined")
- cnt_new_species_candidate = list(df_group["STATUS"]).count(
- "new species candidate"
- )
- cnt_misidentified = list(df_group["STATUS"]).count("misidentified")
- cnt_error = list(df_group["STATUS"]).count("ERROR")
- cnt_total = sum(
- (
- cnt_correctly_identified,
- cnt_undetermined,
- cnt_new_species_candidate,
- cnt_misidentified,
- cnt_error,
- )
- )
- """
-
- # Write into dictionary
- """
+ self.update_statistics()
+
+ # Per-group counts of query identification outcomes, from the STATUS column.
+ def update_statistics(self):
+ cols = [
+ "IDENTIFIED",
+ "NEW SPECIES CANDIDATE",
+ "MISIDENTIFIED",
+ "UNDETERMINED",
+ ]
+ self.statistics = {"GROUP": [], **{c: [] for c in cols}, "TOTAL": []}
+ if self.query_result is None or len(self.query_result) == 0:
+ return
+ # STATUS (set in update_result) -> human-facing statistics category
+ category = {
+ "match": "IDENTIFIED", # given name confirmed by the tree
+ "assigned": "IDENTIFIED", # unnamed query assigned a species
+ "new species": "NEW SPECIES CANDIDATE",
+ "conflict": "MISIDENTIFIED", # assigned differs from the given name
+ "failed": "UNDETERMINED", # could not be resolved
+ }
+ df = self.query_result
+ df = df[df["DATATYPE"] == "query"]
+ for group in sorted(set(df["GROUP_ASSIGNED"])):
+ sub = df[df["GROUP_ASSIGNED"] == group]
+ counts = {c: 0 for c in cols}
+ for status in sub["STATUS"]:
+ cat = category.get(str(status).strip())
+ if cat is not None:
+ counts[cat] += 1
self.statistics["GROUP"].append(group)
- self.statistics["IDENTIFIED"].append(cnt_correctly_identified)
- self.statistics["AMBIGUOUS"].append(cnt_undetermined)
- self.statistics["NEW SPECIES CANDIDATE"].append(cnt_new_species_candidate)
- self.statistics["MISIDENTIFIED"].append(cnt_misidentified)
- self.statistics["ERROR"].append(cnt_error)
- self.statistics["TOTAL"].append(cnt_total)
- """
-
- # Add final summations
- """
- self.statistics["GROUP"].append("TOTAL")
- self.statistics["IDENTIFIED"].append(sum(self.statistics["IDENTIFIED"]))
- self.statistics["AMBIGUOUS"].append(sum(self.statistics["AMBIGUOUS"]))
- self.statistics["NEW SPECIES CANDIDATE"].append(
- sum(self.statistics["NEW SPECIES CANDIDATE"])
- )
- self.statistics["MISIDENTIFIED"].append(sum(self.statistics["MISIDENTIFIED"]))
- self.statistics["ERROR"].append(sum(self.statistics["ERROR"]))
- self.statistics["TOTAL"].append(sum(self.statistics["TOTAL"]))
- """
+ for c in cols:
+ self.statistics[c].append(counts[c])
+ self.statistics["TOTAL"].append(len(sub))
+ # Grand-total row
+ if self.statistics["GROUP"]:
+ self.statistics["GROUP"].append("TOTAL")
+ for c in cols + ["TOTAL"]:
+ self.statistics[c].append(sum(self.statistics[c]))
### Main report runner
# Update report by pipeline step
@@ -377,6 +362,7 @@ def update_report(self, V, path, opt, step, version, GenMine_flag):
self.update_result(V, opt)
self.report_table(V, path, opt, step)
self.report_text(V, path, opt, step, version, GenMine_flag)
+ self.report_html(V, path, opt, version)
else:
logging.error(
f"DEVELOPMENTAL ERROR : BAD STEP INPUT {step} WHILE UPDATE REPORT"
@@ -450,8 +436,8 @@ def report_text(self, V, path, opt, step, version, GenMine_flag):
## Write options used (in concise form)
if index_step(step) >= 0:
f.write(f"[OPTION]\n")
- f.write(f"DB: {opt.query}\n")
- f.write(f"QUERY: {opt.db}\n")
+ f.write(f"DB: {opt.db}\n")
+ f.write(f"QUERY: {opt.query}\n")
f.write(f"GENE: {opt.gene}\n")
f.write(f"EMAIL: {opt.email}\n")
f.write(f"API: {opt.api}\n")
@@ -521,30 +507,23 @@ def report_text(self, V, path, opt, step, version, GenMine_flag):
## Write identification statistics
# Should be written after tree_interpretation
- '''
if index_step(step) >= 9:
f.write(f"[STATISTICS]\n")
f.write(tabulate(self.statistics, headers=self.statistics.keys()))
f.write("\n\n")
f.write(
- "IDENTIFIED : Number of well-identified strains without any concerns. \n"
+ "IDENTIFIED : Query strains assigned a species (a given name confirmed by the tree, or an unnamed query newly assigned)\n"
)
- """
- f.write(
- "AMBIGUOUS : Multiple clades with same taxon name. Your database may contain misidentified sequences. \n"
- )
- """
f.write(
- "NEW SPECIES CANDIDATE : New species candidate strains found by topology, phylogenetic distance and bootstrap criteria\n"
+ "NEW SPECIES CANDIDATE : Query strains flagged as a new species candidate by topology, phylogenetic distance and bootstrap\n"
)
f.write(
- "MISIDENTIFIED : Strains that shows different identification result from original annotation\n"
+ "MISIDENTIFIED : Query strains whose assigned species differs from the given name\n"
)
f.write(
- "ERROR : Strains that cannot be analyzed. Please check if appropriate database sequence / outgroup sequences are given\n"
+ "UNDETERMINED : Query strains that could not be resolved to a species (check the database and outgroup sequences)\n"
)
f.write("\n\n")
- '''
## Write identification result
# Should be written after tree_interpretation
@@ -563,7 +542,7 @@ def report_text(self, V, path, opt, step, version, GenMine_flag):
f.write("\n\n")
f.write("ID : Name of the strain\n")
f.write(
- "HASH : Temporary name of the strain to prevent unexpected error during run. Use this when manually edit intermediate step data and run from middle, or debugging unexpectively terminated run\n"
+ "HASH : Temporary name of the strain to prevent unexpected error during run. Use this when manually edit intermediate step data and run from middle, or debugging unexpectedly terminated run\n"
)
f.write("DATATYPE : query or database\n")
f.write("GROUP_ORIGINAL : group name given by user\n")
@@ -855,7 +834,7 @@ def report_table(self, V, path, opt, step):
if index_step(step) >= 9:
list_table.append("identification")
- # list_table.append("statistics")
+ list_table.append("statistics")
# Write tables
for table in list_table:
@@ -884,5 +863,57 @@ def report_table(self, V, path, opt, step):
)
raise Exception
- def report_html(V, path, opt):
- pass
+ def report_html(self, V, path, opt, version):
+ import os
+ import glob
+ import html as _html
+
+ result_df = (
+ self.query_result
+ if (self.query_result is not None and opt.queryonly is True)
+ else pd.DataFrame(self.result)
+ )
+ stats_df = pd.DataFrame(self.statistics)
+
+ # Link the collapsed tree figures (relative to the report), skipping the
+ # uncollapsed *_original.svg companions.
+ trees = sorted(
+ t
+ for t in glob.glob(f"{path.out_tree}/{opt.runname}_*.svg")
+ if not t.endswith("_original.svg")
+ )
+ tree_items = "".join(
+ f'