Spaces:
Build error
Build error
Upload 4 files
Browse filesFiles changed (4)
- DockerfileAdded+117
- README.mdAdded+201
- app.pyAdded+1290
- requirements.txtAdded+9
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# WOLOJI Comprehensive Bacterial Genomics Suite: one Dockerfile for Hugging Face Spaces and local use.## WOLOJI_TOOLSET selects how much of the command-line stack is installed:# lite BLAST+, MAFFT, IQ-TREE 2 and Primer3 only (utilities tab; pipeline runs in dry-run mode)# standard lite + read QC, assembly, polishing, QUAST, Mash, skani, MLST, MinCED,# MOB-suite, IntegronFinder, Snippy and Gubbins (default)# full standard + geNomad, chewBBACA, PopPUNK, CheckM2 and GTDB-Tk# Local build example: docker build --build-arg WOLOJI_TOOLSET=full -t woloji .# On Hugging Face, change the default value on the ARG line below.## Reference databases are NOT downloaded here. Mount them (for example under /data)# and set GTDBTK_DATA_PATH, CHECKM2DB, GENOMAD_DB and MOB_SUITE_DB.
FROM python:3.11-slim-bookworm
ARG WOLOJI_TOOLSET=standardARG DEBIAN_FRONTEND=noninteractive
ENV PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=1 \ MAMBA_ROOT_PREFIX=/opt/micromamba \ WOLOJI_TOOLSET=${WOLOJI_TOOLSET}
# ---------------------------------------------------------------------------# 1. System packages and the utility tools used by the "sequence utilities" tab.# Debian's iqtree package provides the iqtree2 executable that app.py calls.# ---------------------------------------------------------------------------RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates curl bzip2 procps tini \ ncbi-blast+ mafft iqtree primer3 \ && rm -rf /var/lib/apt/lists/* \ && blastn -version && mafft --version && iqtree2 --version | head -n 1
# ---------------------------------------------------------------------------# 2. Bioinformatics pipeline tools from bioconda.# Each group lives in its own environment under /opt/envs, so their pins never# clash with each other or with the app's Python. Small wrapper scripts in# /opt/woloji/bin put the right environment first on PATH before starting a# tool (this matters for Perl and Python tools such as Snippy and mlst).# The wrapper folder is appended to PATH, so the app's Python 3.11 stays first.# ---------------------------------------------------------------------------RUN set -eu; \ mkdir -p /opt/woloji/bin /opt/envs "$MAMBA_ROOT_PREFIX"; \ if [ "$WOLOJI_TOOLSET" = "lite" ]; then echo "Toolset lite: skipping conda tools"; exit 0; fi; \ case "$WOLOJI_TOOLSET" in standard|full) ;; *) echo "Unknown WOLOJI_TOOLSET: $WOLOJI_TOOLSET" >&2; exit 1 ;; esac; \ curl -fsSL https://github.com/mamba-org/micromamba-releases/releases/latest/download/micromamba-linux-64 \ -o /usr/local/bin/micromamba; \ chmod 755 /usr/local/bin/micromamba; \ printf 'channels:\n - conda-forge\n - bioconda\nchannel_priority: strict\n' > /root/.mambarc; \ mkenv() { \ env="$1"; specs="$2"; exes="$3"; \ echo ">>> creating environment $env: $specs"; \ micromamba create -y -q -p "/opt/envs/$env" $specs; \ for exe in $exes; do \ test -x "/opt/envs/$env/bin/$exe" || { echo "Missing $exe in environment $env" >&2; exit 1; }; \ printf '#!/bin/sh\nexport CONDA_PREFIX="/opt/envs/%s"\nexport PATH="/opt/envs/%s/bin:$PATH"\nexec "/opt/envs/%s/bin/%s" "$@"\n' \ "$env" "$env" "$env" "$exe" > "/opt/woloji/bin/$exe"; \ chmod 755 "/opt/woloji/bin/$exe"; \ done; \ micromamba clean -a -y -q; \ }; \ mkenv readqc "fastp fastqc multiqc" "fastp fastqc multiqc"; \ mkenv assembly "spades unicycler>=0.5 bwa polypolish>=0.6" "spades.py unicycler bwa polypolish"; \ mkenv flye "flye" "flye"; \ mkenv quast "quast" "quast.py"; \ mkenv typing "mash skani mlst minced" "mash skani mlst minced"; \ mkenv mobsuite "mob_suite>=3.1" "mob_recon mob_typer"; \ mkenv integron "integron_finder>=2" "integron_finder"; \ mkenv snippy "snippy>=4.6" "snippy snippy-core"; \ mkenv gubbins "gubbins>=3.3" "run_gubbins.py"; \ if [ "$WOLOJI_TOOLSET" = "full" ]; then \ mkenv genomad "genomad" "genomad"; \ mkenv chewbbaca "chewbbaca>=3" "chewBBACA.py"; \ mkenv poppunk "poppunk" "poppunk"; \ mkenv checkm2 "checkm2" "checkm2"; \ mkenv gtdbtk "gtdbtk>=2.3" "gtdbtk"; \ fi; \ for d in /opt/envs/mobsuite/lib/python3*/site-packages/mob_suite/databases; do \ if [ -d "$d" ]; then chown -R 1000:1000 "$d"; fi; \ done; \ rm -rf /root/.cache /tmp/*
ENV PATH="${PATH}:/opt/woloji/bin"
# ---------------------------------------------------------------------------# 3. Non-root user required by Hugging Face Spaces (UID 1000) and the app itself.# ---------------------------------------------------------------------------RUN useradd -m -u 1000 -s /bin/bash userENV HOME=/home/userWORKDIR /home/user/app
COPY --chown=1000:1000 requirements.txt ./RUN python -m pip install --upgrade pip \ && python -m pip install --only-binary=:all: -r requirements.txt
COPY --chown=1000:1000 app.py README.md ./
USER 1000
# Streamlit settings. XSRF and CORS protection are disabled because Hugging Face serves# the app inside an iframe, where they block file uploads. Keep them enabled if you# expose the container directly on a network.ENV STREAMLIT_SERVER_PORT=7860 \ STREAMLIT_SERVER_ADDRESS=0.0.0.0 \ STREAMLIT_SERVER_HEADLESS=true \ STREAMLIT_SERVER_MAX_UPLOAD_SIZE=2048 \ STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION=false \ STREAMLIT_SERVER_ENABLE_CORS=false \ STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
EXPOSE 7860
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s \ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:7860/_stcore/health')"
ENTRYPOINT ["/usr/bin/tini", "--"]CMD ["streamlit", "run", "app.py"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201---title: WOLOJI Bacterial Genomics Suiteemoji: 🧬colorFrom: bluecolorTo: greensdk: dockerapp_port: 7860pinned: falselicense: mitfullWidth: trueshort_description: End-to-end bacterial whole-genome analysis---
# WOLOJI Comprehensive Bacterial Genomics Suite v2.1.0
WOLOJI is a Docker-based Streamlit platform for bacterial isolate whole-genome analysis. It starts from raw Illumina reads, Oxford Nanopore reads or finished assemblies, runs established command-line tools in a fixed order, and returns one ZIP package with results, logs and provenance records. It also provides standalone sequence utilities for primer design, local BLAST, phylogenetic trees and output concordance checks.
This Space is built from four files only:
| File | Purpose ||---|---|| `app.py` | The whole application: data model, pipeline, sequence utilities, output concordance tool and Streamlit interface || `Dockerfile` | Builds the container with Python, the web app and the command-line bioinformatics tools || `requirements.txt` | Pinned Python packages used by `app.py` || `README.md` | Hugging Face Space settings (front matter above) and this documentation |
## Analysis modules
| # | Module | Tools | Needs ||---|---|---|---|| 1 | Raw read QC | fastp, FastQC, MultiQC | Reads || 2 | Assembly and polishing | SPAdes (short), Flye (long), Unicycler (hybrid), Polypolish | Reads || 3 | Assembly QC | QUAST | Assembly || 4 | Completeness and contamination | CheckM2 | `CHECKM2DB` || 5 | Taxonomy and ANI | GTDB-Tk, Mash, skani | `GTDBTK_DATA_PATH` for GTDB-Tk; two or more genomes for Mash and skani || 6 | Mobileome | MOB-suite, geNomad, IntegronFinder, MinCED | `GENOMAD_DB` for geNomad || 7 | Classical MLST | mlst | Assembly || 8 | cgMLST / wgMLST | chewBBACA | Two or more genomes and a schema ZIP || 9 | Core SNP phylogenomics | Snippy, snippy-core, Gubbins, IQ-TREE 2 | Three or more isolates and a reference genome || 10 | Population genomics | PopPUNK | Three or more genomes (many more for stable clusters) |
Every run also writes input SHA256 checksums, a command manifest, a run manifest with software versions and database paths, an assembly summary table, N50 and GC figures (600 dpi) and a short methods note.
### Sequence utilities tab
* **Primer design** with Primer3 (primer3-py).* **GeneClean-BLAST**: local blastn of a query FASTA against a subject FASTA.* **PhyloForge**: MAFFT alignment and IQ-TREE 2 tree with ModelFinder and 1000 ultrafast bootstraps (at least four sequences).* **Output concordance**: compares a WOLOJI table with a table from a direct run of the same tool and reports key precision, recall, F1 and value disagreements.
### Out of scope in this build
Genome annotation (Bakta, Prokka), codon usage and composition, AMR detection, virulence screening, secondary metabolites, eggNOG-mapper and Panaroo are handled by separate dedicated tools.
## Deploying on Hugging Face
1. Create a new Space and choose **Docker** as the SDK.2. Upload the four files to the root of the Space.3. Choose the toolset by editing the `ARG WOLOJI_TOOLSET=` line in the `Dockerfile`:
| Toolset | What is installed | Typical use ||---|---|---|| `lite` | BLAST+, MAFFT, IQ-TREE 2, Primer3 | Sequence utilities and dry runs only; fastest build || `standard` (default) | lite plus read QC, assembly, polishing, QUAST, Mash, skani, mlst, MinCED, MOB-suite, IntegronFinder, Snippy, Gubbins | Routine isolate WGS and SNP phylogenies || `full` | standard plus geNomad, chewBBACA, PopPUNK, CheckM2, GTDB-Tk | Complete workflow with mounted databases |
4. Use CPU hardware with enough RAM for bacterial assembly. The free CPU Space is suitable for interface testing, utilities and small data sets. SPAdes on a typical 5 Mb genome at 100x coverage needs about 8 to 16 GB RAM, and GTDB-Tk needs far more.5. Attach persistent storage and place the reference databases under `/data`.6. Add the database locations as Space variables, for example:
```bashGTDBTK_DATA_PATH=/data/gtdbtkCHECKM2DB=/data/checkm2/uniref100.KO.1.dmndGENOMAD_DB=/data/genomad_dbMOB_SUITE_DB=/data/mob_suite```
7. Restart the Space, open **Tools & databases**, and confirm that the expected tools and databases are detected.8. Run one small, well characterised isolate before analysing study data.
The build does not download the large biological databases. Modules that depend on them stay visible and are recorded as skipped until the paths are configured. Initialise MOB-suite and download the GTDB-Tk release that matches the installed GTDB-Tk version before deployment, not during an analysis.
## Running locally
With Docker:
```bashdocker build -t woloji . # standard toolsetdocker build --build-arg WOLOJI_TOOLSET=full -t woloji . # full toolsetdocker run -p 7860:7860 -v /path/to/databases:/data \ -e GTDBTK_DATA_PATH=/data/gtdbtk -e CHECKM2DB=/data/checkm2/uniref100.KO.1.dmnd \ -e GENOMAD_DB=/data/genomad_db -e MOB_SUITE_DB=/data/mob_suite woloji```
Then open `http://localhost:7860`.
Without Docker (Python 3.11 or newer):
```bashpython -m venv .venvsource .venv/bin/activatepip install -r requirements.txtstreamlit run app.py```
Without the command-line tools installed, use **Dry run** in the sidebar. It records every intended command in the result package without running it, which is useful for checking inputs and settings.
## Input
Upload FASTQ, FASTQ.GZ, FASTA, FASTA.GZ or one ZIP that contains them.
Without a metadata table, WOLOJI pairs reads by file name: `Sample01_R1.fastq.gz` / `Sample01_R2.fastq.gz`, `Sample01_1.fq` / `Sample01_2.fq` and lane suffixes such as `_R1_001` are recognised. A FASTQ without a pair is treated as long reads, and a FASTA file is treated as a finished assembly. If two files claim the same role for one sample, the run stops and asks for a metadata table instead of guessing.
A metadata CSV or TSV gives full control. `Sample_ID` is required and every file it names must be uploaded:
```csvSample_ID,Read_1,Read_2,Long_Reads,Assembly,Genus,SpeciesISO01,ISO01_R1.fastq.gz,ISO01_R2.fastq.gz,,,Escherichia,coliISO02,,,ISO02_nanopore.fastq.gz,,Klebsiella,pneumoniaeISO03,,,,ISO03.fasta,Staphylococcus,aureus```
Other inputs: a reference genome (FASTA or GenBank) for core SNP analysis, and a chewBBACA schema as a ZIP for cgMLST or wgMLST. Use the same schema and training file for every isolate you compare.
## Method notes
* **Assembly strategy.** In Auto mode, isolates with both short and long reads are assembled with Unicycler, long reads alone with Flye (`--nano-hq`) and then Polypolish when short reads are present, and short reads alone with SPAdes `--isolate`. Set the expected genome size for Flye in the sidebar.* **GTDB-Tk.** `classify_wf` runs with `--skip_ani_screen`, which is required from GTDB-Tk 2.2 onwards when no Mash database is supplied. Do not mix GTDB-Tk software and reference data releases.* **Core SNP tree.** Snippy uses reads when available and assemblies otherwise. After Gubbins removes recombinant regions, the tree is inferred from polymorphic sites only, so WOLOJI adds ascertainment bias correction (`+ASC`) to the IQ-TREE model. Without it, branch lengths are overestimated.* **fastp** `--n_base_limit` is an absolute count of N bases per read, not a percentage.
## Result package
```text00_input/ uploaded files and schema01_read_qc/ fastp, FastQC and MultiQC reports02_assembly/ SPAdes, Flye or Unicycler output03_polishing/ Polypolish output04_assembly_qc/ QUAST and CheckM205_taxonomy/ GTDB-Tk, Mash and skani12_mobileome/ MOB-suite, geNomad, IntegronFinder, MinCED13_typing/ mlst and chewBBACA16_phylogenomics/ Snippy, snippy-core, Gubbins, IQ-TREE17_population/ PopPUNK20_publication_report/ tables, figures, methods_note.txt, run_summary.jsonlogs/ stdout and stderr of every commandinput_manifest.tsv SHA256 checksum of every input filecommand_manifest.json every executed or skipped command with exit code, times and reasonrun_manifest.json parameters, modules, database paths and software versions```
## Validation before publication
Passing a dry run or a successful deployment does not establish biological validity. Before a manuscript, compare WOLOJI output with direct command-line runs of the same tools on public or curated data sets, using the same software and database releases:
1. Read QC and assembly: retained reads, assembly size, contigs, N50, genome fraction and misassemblies.2. Taxonomy: species calls, ANI and aligned fraction against curated reference genomes.3. Mobile elements: curated positive and negative genomes, with database versions.4. MLST and cgMLST: exact concordance with independently generated profiles.5. SNP phylogenomics: core SNP counts, pairwise SNP distances and tree topology.6. Reproducibility: rerun identical inputs with the same image and databases and compare checksums where outputs are deterministic.7. Performance: wall-clock time, peak RAM, disk use and failure rate as the number of isolates grows.
The **Output concordance** tab performs the table comparison. The same function is available from the command line:
```bashpython app.py compare woloji_mlst.tsv direct_mlst.tsv --keys Sample_ID --json-out mlst_concordance.json```
It matches rows on the key columns, reports key precision, recall and F1, and lists up to 100 value disagreements. Numeric columns are compared with `--numeric-tolerance` (default 1e-8).
Use at least one established bacterial WGS workflow as an external comparator, and report biological concordance, computational performance and usability as separate outcomes. Do not claim better accuracy only because more modules are available through a graphical interface.
## Citation and licence
WOLOJI coordinates other programs. Publications should cite WOLOJI and every underlying program that was executed in the chosen workflow, together with the database release dates and versions. The command manifest and run manifest list what was run.
The WOLOJI application code is released under the MIT License. Each external tool and reference database keeps its own licence and terms; check them before redistribution or commercial use.
## Changelog
**2.1.0*** Consolidated the repository into four files: `app.py`, `Dockerfile`, `requirements.txt` and `README.md`.* Merged the output comparison script into `app.py`, as an interface tab and as `python app.py compare`.* Merged the full and lite Dockerfiles into one file with a `WOLOJI_TOOLSET` switch (`lite`, `standard`, `full`). Removed Prokka and cd-hit, which this build no longer uses, and added the pipeline tools it does use.* Moved the app to port 7860 and a non-root user, as required by Hugging Face Spaces.* Added the missing `requirements.txt` with tested, pinned versions.* Dry run now records every intended command even when tools are not installed.* Automatic sample pairing now stops on ambiguous file names instead of overwriting them; metadata that names a missing file now raises an error.* Empty metadata cells no longer become the text "nan".* Results and download buttons now persist after a download click (PhyloForge previously lost the tree after the first download).* PhyloForge checks for duplicate sequence IDs and at least four sequences before running IQ-TREE.* Core SNP tree uses `+ASC` on the SNP-only alignment; GTDB-Tk runs with `--skip_ani_screen`.* Command timeouts are recorded instead of stopping the whole run; schema ZIPs are extracted safely.* The methods note now lists only the modules that were selected, and the version number comes from one place.
**2.0.1*** Timezone-aware run names, explicit `check=False` on subprocess calls, and removal of unused dependencies.
**2.0.0*** First unified bacterial WGS workflow from raw reads or assemblies, with SHA256 provenance, command manifests and publication outputs.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290"""WOLOJI Comprehensive Bacterial Genomics Suite (trimmed single-file build)
This one file replaces the former woloji/ package, app.py andvalidation/compare_outputs.py.
Pipeline modules: read QC, assembly/polishing, QUAST, CheckM2, taxonomy(GTDB-Tk, Mash, skani), mobileome (MOB-suite, geNomad, IntegronFinder, MinCED),MLST, cgMLST/wgMLST, core SNP phylogenomics and population genomics (PopPUNK).Utilities: primer design, local BLAST, PhyloForge and output concordance.
Removed from this build (covered by separate dedicated tools): Genome annotation (Bakta/Prokka), composition and codon usage, AMR detection, virulence screening, secondary metabolites, eggNOG-mapper and Panaroo.
Two ways to run: streamlit run app.py python app.py compare OBSERVED EXPECTED --keys Sample_ID [--numeric-tolerance 1e-8] [--json-out out.json]"""from __future__ import annotations
import argparseimport gzipimport hashlibimport ioimport jsonimport mathimport osimport reimport shutilimport subprocessimport sysimport tempfileimport zipfilefrom collections.abc import Callable, Sequencefrom dataclasses import asdict, dataclassfrom datetime import UTC, datetimefrom pathlib import Path
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as plt # noqa: E402import pandas as pd # noqa: E402
__version__ = "2.1.0"SUITE_NAME = "WOLOJI Comprehensive Bacterial Genomics Suite"
# =============================================================================# Data model# =============================================================================@dataclassclass Sample: sample_id: str read1: Path | None = None read2: Path | None = None long_reads: Path | None = None assembly: Path | None = None genus: str = "" species: str = ""
# =============================================================================# Filesystem, hashing and command execution helpers# =============================================================================def utc_now() -> str: return datetime.now(UTC).isoformat()
def safe_name(value: str) -> str: value = re.sub(r"[^A-Za-z0-9._-]+", "_", str(value)).strip("._") return value or "sample"
def sha256_file(path: Path, block: int = 1024 * 1024) -> str: h = hashlib.sha256() with open(path, "rb") as fh: while chunk := fh.read(block): h.update(chunk) return h.hexdigest()
def command_exists(name: str) -> bool: return shutil.which(name) is not None
def get_version(command: Sequence[str]) -> str: try: cp = subprocess.run(command, capture_output=True, text=True, timeout=30, check=False) text = (cp.stdout or cp.stderr or "").strip().splitlines() return text[0][:300] if text else "unknown" except (OSError, subprocess.SubprocessError) as exc: return f"unavailable: {exc}"
def open_text(path: Path): if str(path).lower().endswith(".gz"): return gzip.open(path, "rt", encoding="utf-8", errors="ignore") return open(path, encoding="utf-8", errors="ignore")
def fasta_stats(path: Path) -> dict: lengths: list[int] = [] a = c = g = t = n = 0 with open_text(path) as fh: cur = 0 for raw in fh: line = raw.strip() if not line: continue if line.startswith(">"): if cur: lengths.append(cur) cur = 0 continue s = line.upper() cur += len(s) ca, cc, cg, ct = s.count("A"), s.count("C"), s.count("G"), s.count("T") a += ca; c += cc; g += cg; t += ct n += len(s) - (ca + cc + cg + ct) if cur: lengths.append(cur) seq_len = sum(lengths) canonical = a + c + g + t gc = 100.0 * (g + c) / canonical if canonical else float("nan") n_pct = 100.0 * n / seq_len if seq_len else float("nan") n50 = l50 = 0 cum = 0 for i, length in enumerate(sorted(lengths, reverse=True), start=1): cum += length if cum >= seq_len / 2.0: n50, l50 = length, i break return { "assembly": path.name, "total_length_bp": int(seq_len), "contigs": len(lengths), "largest_contig_bp": int(max(lengths) if lengths else 0), "N50_bp": int(n50), "L50": int(l50), "GC_percent": None if math.isnan(gc) else round(gc, 5), "ambiguous_percent": None if math.isnan(n_pct) else round(n_pct, 5), "A": a, "C": c, "G": g, "T": t, "ambiguous_bases": n, }
@dataclassclass CmdResult: name: str command: list[str] returncode: int started_at: str finished_at: str stdout_path: str stderr_path: str skipped: bool = False reason: str = ""
def to_dict(self): return asdict(self)
class Runner: """Runs external commands, logs stdout/stderr and records every call."""
def __init__(self, log_dir: Path, dry_run: bool = False, timeout: int = 14400): self.log_dir = Path(log_dir) self.log_dir.mkdir(parents=True, exist_ok=True) self.dry_run = dry_run self.timeout = timeout self.records: list[CmdResult] = []
def skip(self, name: str, command: Sequence[str], reason: str) -> CmdResult: now = utc_now() rec = CmdResult(name, [str(x) for x in command], 0, now, now, "", "", True, reason) self.records.append(rec) return rec
def run(self, name: str, command: Sequence[str], cwd: Path | None = None, stdout_file: Path | None = None, env: dict | None = None, check: bool = False) -> CmdResult: command = [str(x) for x in command] exe = command[0] # Dry run is checked first, so the intended command is always recorded, # even on a machine without the external tools. if self.dry_run: reason = "dry run" if command_exists(exe) else f"dry run (executable not installed: {exe})" return self.skip(name, command, reason) if not command_exists(exe): if check: raise RuntimeError(f"{name} failed: executable not found on PATH: {exe}") return self.skip(name, command, f"Executable not found on PATH: {exe}") started = utc_now() out_path = self.log_dir / f"{safe_name(name)}.stdout.txt" err_path = self.log_dir / f"{safe_name(name)}.stderr.txt" proc_env = os.environ.copy() if env: proc_env.update({k: str(v) for k, v in env.items()}) target = stdout_file or out_path target.parent.mkdir(parents=True, exist_ok=True) try: with open(target, "w", encoding="utf-8") as out, open(err_path, "w", encoding="utf-8") as err: cp = subprocess.run(command, cwd=cwd, stdout=out, stderr=err, text=True, timeout=self.timeout, env=proc_env, check=False) code = int(cp.returncode) except subprocess.TimeoutExpired: with open(err_path, "a", encoding="utf-8") as err: err.write(f"\nTerminated after timeout of {self.timeout} s\n") code = -9 rec = CmdResult(name, command, code, started, utc_now(), str(target), str(err_path)) self.records.append(rec) if check and code != 0: tail = err_path.read_text(encoding="utf-8", errors="ignore")[-1500:] if err_path.exists() else "" raise RuntimeError(f"{name} failed (exit {code}). {tail}") return rec
def write_manifest(self, path: Path): path.write_text(json.dumps([r.to_dict() for r in self.records], indent=2), encoding="utf-8")
def safe_extract_zip(zip_path: Path, dest: Path): """Extract a ZIP while refusing entries that would escape the destination.""" dest = dest.resolve() with zipfile.ZipFile(zip_path) as zf: for info in zf.infolist(): target = (dest / info.filename).resolve() if not str(target).startswith(str(dest) + os.sep) and target != dest: raise ValueError(f"Unsafe path in ZIP: {info.filename}") zf.extractall(dest)
# =============================================================================# Sample discovery from uploads or metadata# =============================================================================FASTA_EXT = (".fa", ".fasta", ".fna", ".fas", ".fa.gz", ".fasta.gz", ".fna.gz", ".fas.gz")FASTQ_EXT = (".fastq", ".fq", ".fastq.gz", ".fq.gz")
def save_uploads(uploaded_files, input_dir: Path) -> dict[str, Path]: input_dir.mkdir(parents=True, exist_ok=True) mapping: dict[str, Path] = {} for uploaded in uploaded_files or []: name = os.path.basename(uploaded.name) target = input_dir / name target.write_bytes(uploaded.getvalue()) if name.lower().endswith(".zip"): with zipfile.ZipFile(target) as zf: for info in zf.infolist(): base = os.path.basename(info.filename) if info.is_dir() or not base or base.startswith("."): continue out = input_dir / base out.write_bytes(zf.read(info.filename)) mapping[base] = out else: mapping[name] = target return mapping
def _clean_cell(value) -> str: if value is None or (isinstance(value, float) and pd.isna(value)): return "" return str(value).strip()
def _find_name(mapping: dict[str, Path], value) -> Path | None: value = _clean_cell(value) if not value: return None found = mapping.get(value) or mapping.get(os.path.basename(value)) if found is None: raise ValueError(f"File named in metadata was not uploaded: {value}") return found
def samples_from_metadata(metadata_path: Path, mapping: dict[str, Path]) -> list[Sample]: df = pd.read_csv(metadata_path, sep=None, engine="python") if "Sample_ID" not in df.columns: raise ValueError("Metadata must contain Sample_ID. Optional columns: " "Read_1, Read_2, Long_Reads, Assembly, Genus, Species") samples, seen = [], set() for _, row in df.iterrows(): sid = safe_name(row["Sample_ID"]) if sid in seen: raise ValueError(f"Duplicate Sample_ID in metadata: {sid}") seen.add(sid) samples.append(Sample( sample_id=sid, read1=_find_name(mapping, row.get("Read_1")), read2=_find_name(mapping, row.get("Read_2")), long_reads=_find_name(mapping, row.get("Long_Reads")), assembly=_find_name(mapping, row.get("Assembly")), genus=_clean_cell(row.get("Genus")), species=_clean_cell(row.get("Species")), )) return samples
def _stem_without_ext(name: str) -> str: for ext in sorted(FASTQ_EXT + FASTA_EXT, key=len, reverse=True): if name.lower().endswith(ext): return name[:-len(ext)] return Path(name).stem
_PAIR_PATTERNS = [ (re.compile(r"(.+?)_R?1(?:_\d+)?$", re.IGNORECASE), "read1"), (re.compile(r"(.+?)_R?2(?:_\d+)?$", re.IGNORECASE), "read2"),]
def auto_samples(mapping: dict[str, Path]) -> list[Sample]: """Pair files by name. Ambiguous duplicate assignments raise an error instead of being overwritten.""" samples: dict[str, Sample] = {}
def assign(sid: str, field: str, path: Path): s = samples.setdefault(sid, Sample(sample_id=sid)) current = getattr(s, field) if current is not None and current != path: raise ValueError(f"Ambiguous input for sample {sid}: both {current.name} and {path.name} " f"map to {field}. Use a metadata table.") setattr(s, field, path)
for name, path in sorted(mapping.items()): low = name.lower() if low.endswith(FASTQ_EXT): stem = _stem_without_ext(name) for pat, field in _PAIR_PATTERNS: m = pat.match(stem) if m: assign(safe_name(m.group(1)), field, path) break else: # An unpaired FASTQ is interpreted as long-read input. assign(safe_name(stem), "long_reads", path) elif low.endswith(FASTA_EXT): assign(safe_name(_stem_without_ext(name)), "assembly", path) for s in samples.values(): if s.read2 and not s.read1: raise ValueError(f"Sample {s.sample_id} has an R2 file without a matching R1 file.") return sorted(samples.values(), key=lambda s: s.sample_id)
# =============================================================================# External tool and database status# =============================================================================TOOLS = { "fastp": ["fastp", "--version"], "FastQC": ["fastqc", "--version"], "MultiQC": ["multiqc", "--version"], "SPAdes": ["spades.py", "--version"], "Flye": ["flye", "--version"], "Unicycler": ["unicycler", "--version"], "BWA": ["bwa"], "Polypolish": ["polypolish", "--version"], "QUAST": ["quast.py", "--version"], "CheckM2": ["checkm2", "--version"], "GTDB-Tk": ["gtdbtk", "--version"], "Mash": ["mash", "--version"], "skani": ["skani", "--version"], "MOB-suite": ["mob_recon", "--version"], "geNomad": ["genomad", "--version"], "IntegronFinder": ["integron_finder", "--version"], "MinCED": ["minced", "--version"], "mlst": ["mlst", "--version"], "chewBBACA": ["chewBBACA.py", "--version"], "Snippy": ["snippy", "--version"], "Gubbins": ["run_gubbins.py", "--version"], "MAFFT": ["mafft", "--version"], "IQ-TREE 2": ["iqtree2", "--version"], "PopPUNK": ["poppunk", "--version"], "BLAST+": ["blastn", "-version"],}
DATABASES = { "GTDB-Tk": "GTDBTK_DATA_PATH", "CheckM2": "CHECKM2DB", "geNomad": "GENOMAD_DB", "MOB-suite": "MOB_SUITE_DB",}
def status_rows(): rows = [] for display, cmd in TOOLS.items(): ok = command_exists(cmd[0]) rows.append({"tool": display, "executable": cmd[0], "available": ok, "version": get_version(cmd) if ok else "not installed"}) return rows
def database_rows(): rows = [] for name, envvar in DATABASES.items(): value = os.getenv(envvar, "") rows.append({"database": name, "environment_variable": envvar, "path": value, "detected": bool(value) and Path(value).exists()}) return rows
# =============================================================================# Publication figures# =============================================================================def _bar_or_scatter(df: pd.DataFrame, column: str, ylabel: str, title: str, out: Path, kind: str): if df.empty or column not in df: return fig, ax = plt.subplots(figsize=(8, 4.8)) x = list(range(len(df))) y = pd.to_numeric(df[column], errors="coerce") if kind == "bar": ax.bar(x, y) else: ax.scatter(x, y, s=42) ax.set_xticks(x) ax.set_xticklabels(df["sample"], rotation=45, ha="right") ax.set_ylabel(ylabel) ax.set_title(title) fig.tight_layout() fig.savefig(out, dpi=600, bbox_inches="tight") plt.close(fig)
def assembly_summary_plot(df: pd.DataFrame, out: Path): _bar_or_scatter(df, "N50_bp", "N50 (bp)", "Assembly contiguity across isolates", out, "bar")
def gc_plot(df: pd.DataFrame, out: Path): _bar_or_scatter(df, "GC_percent", "GC (%)", "Genome GC content", out, "scatter")
# =============================================================================# Utilities: primer design, local BLAST, PhyloForge# =============================================================================def read_fasta_bytes(file_bytes: bytes) -> list[tuple[str, str]]: from Bio import SeqIO text = file_bytes.decode("utf-8", errors="ignore") return [(rec.id, str(rec.seq).upper()) for rec in SeqIO.parse(io.StringIO(text), "fasta")]
def fasta_first_sequence(file_bytes: bytes) -> tuple[str, str]: records = read_fasta_bytes(file_bytes) if not records: raise ValueError("No FASTA record was found in the file.") return records[0]
def design_primers(sequence: str, target_start: int = 0, target_length: int = 0, product_min: int = 100, product_max: int = 600, num_return: int = 5) -> pd.DataFrame: import primer3 seq = re.sub(r"\s+", "", sequence).upper() if product_min >= product_max: raise ValueError("Minimum product size must be smaller than the maximum product size.") if len(seq) < product_min: raise ValueError(f"Template ({len(seq)} bp) is shorter than the minimum product size ({product_min} bp).") args = {"SEQUENCE_ID": "target", "SEQUENCE_TEMPLATE": seq} if target_length > 0: args["SEQUENCE_TARGET"] = [int(target_start), int(target_length)] global_args = { "PRIMER_OPT_SIZE": 20, "PRIMER_MIN_SIZE": 18, "PRIMER_MAX_SIZE": 25, "PRIMER_OPT_TM": 60.0, "PRIMER_MIN_TM": 57.0, "PRIMER_MAX_TM": 63.0, "PRIMER_MIN_GC": 35.0, "PRIMER_MAX_GC": 65.0, "PRIMER_PRODUCT_SIZE_RANGE": [[int(product_min), int(product_max)]], "PRIMER_NUM_RETURN": int(num_return), } res = primer3.bindings.design_primers(args, global_args) rows = [] for i in range(int(res.get("PRIMER_PAIR_NUM_RETURNED", 0))): rows.append({ "pair": i + 1, "left_primer": res.get(f"PRIMER_LEFT_{i}_SEQUENCE", ""), "right_primer": res.get(f"PRIMER_RIGHT_{i}_SEQUENCE", ""), "left_tm": res.get(f"PRIMER_LEFT_{i}_TM"), "right_tm": res.get(f"PRIMER_RIGHT_{i}_TM"), "left_gc": res.get(f"PRIMER_LEFT_{i}_GC_PERCENT"), "right_gc": res.get(f"PRIMER_RIGHT_{i}_GC_PERCENT"), "product_size": res.get(f"PRIMER_PAIR_{i}_PRODUCT_SIZE"), "pair_penalty": res.get(f"PRIMER_PAIR_{i}_PENALTY"), }) return pd.DataFrame(rows)
def local_blast(query_bytes: bytes, subject_bytes: bytes, task: str = "blastn", evalue: float = 1e-10, threads: int = 2) -> pd.DataFrame: fields = "qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore qcovs" cols = fields.split() with tempfile.TemporaryDirectory() as td: td = Path(td) q, s = td / "query.fasta", td / "subject.fasta" q.write_bytes(query_bytes) s.write_bytes(subject_bytes) runner = Runner(td / "logs") runner.run("makeblastdb", ["makeblastdb", "-in", s, "-dbtype", "nucl", "-out", td / "db"], check=True) out = td / "blast.tsv" runner.run("blastn", ["blastn", "-task", task, "-query", q, "-db", td / "db", "-evalue", evalue, "-num_threads", threads, "-outfmt", f"6 {fields}", "-out", out], check=True) if out.exists() and out.stat().st_size: return pd.read_csv(out, sep="\t", names=cols) return pd.DataFrame(columns=cols)
def phyloforge(files, threads: int = 2, model: str = "MFP", bootstrap: int = 1000) -> tuple[str, str, str]: """MAFFT alignment followed by IQ-TREE 2 with ultrafast bootstrap. Returns alignment, Newick tree and log.""" records: list[tuple[str, str]] = [] for f in files: records.extend(read_fasta_bytes(f.getvalue())) ids = [r[0] for r in records] dups = sorted({x for x in ids if ids.count(x) > 1}) if dups: raise ValueError(f"Duplicate sequence IDs across the uploaded files: {', '.join(dups[:10])}") if len(records) < 4: raise ValueError(f"IQ-TREE with ultrafast bootstrap needs at least 4 sequences; {len(records)} found.") with tempfile.TemporaryDirectory() as td: td = Path(td) inp = td / "input.fasta" inp.write_text("".join(f">{i}\n{s}\n" for i, s in records), encoding="utf-8") runner = Runner(td / "logs") aln = td / "aligned.fasta" runner.run("mafft", ["mafft", "--auto", "--thread", threads, inp], stdout_file=aln, check=True) prefix = td / "tree" runner.run("iqtree", ["iqtree2", "-s", aln, "-m", model, "-B", bootstrap, "-T", threads, "--prefix", prefix], check=True) tree = Path(f"{prefix}.treefile") log = Path(f"{prefix}.iqtree") return (aln.read_text() if aln.exists() else "", tree.read_text() if tree.exists() else "", log.read_text() if log.exists() else "")
# =============================================================================# Output concordance (formerly validation/compare_outputs.py)# =============================================================================def read_table(path_or_buffer, name: str | None = None) -> pd.DataFrame: label = (name or str(path_or_buffer)).lower() if label.endswith((".tsv", ".txt", ".tab")): return pd.read_csv(path_or_buffer, sep="\t") return pd.read_csv(path_or_buffer)
def compare_tables(observed: pd.DataFrame, expected: pd.DataFrame, keys: list[str], numeric_tolerance: float = 1e-8) -> dict[str, object]: """Compare a WOLOJI table with a direct-tool reference table on shared key columns.""" missing = [k for k in keys if k not in observed.columns or k not in expected.columns] if missing: raise ValueError(f"Missing key columns: {', '.join(missing)}") merged = observed.merge(expected, how="outer", on=keys, suffixes=("_observed", "_expected"), indicator=True) only_observed = merged[merged["_merge"] == "left_only"] only_expected = merged[merged["_merge"] == "right_only"] shared = merged[merged["_merge"] == "both"].copy()
compared_columns: list[str] = [] disagreements: list[dict[str, object]] = [] disagreement_count = 0 for column in sorted((set(observed.columns) & set(expected.columns)) - set(keys)): left, right = f"{column}_observed", f"{column}_expected" if left not in shared.columns or right not in shared.columns: continue compared_columns.append(column) lv, rv = shared[left], shared[right] if pd.api.types.is_numeric_dtype(lv) and pd.api.types.is_numeric_dtype(rv): lnum, rnum = pd.to_numeric(lv, errors="coerce"), pd.to_numeric(rv, errors="coerce") mismatch = ((lnum - rnum).abs() > numeric_tolerance) | (lnum.isna() ^ rnum.isna()) else: mismatch = lv.astype(object).where(lv.notna(), "<NA>").astype(str) != \ rv.astype(object).where(rv.notna(), "<NA>").astype(str) disagreement_count += int(mismatch.sum()) for _, row in shared.loc[mismatch, keys + [left, right]].iterrows(): if len(disagreements) >= 100: break record = {k: row[k] for k in keys} record.update({"column": column, "observed": row[left], "expected": row[right]}) disagreements.append(record)
tp, fp, fn = len(shared), len(only_observed), len(only_expected) precision = tp / (tp + fp) if tp + fp else math.nan recall = tp / (tp + fn) if tp + fn else math.nan f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else math.nan return { "observed_rows": int(len(observed)), "expected_rows": int(len(expected)), "matched_key_rows": int(tp), "only_observed_rows": int(fp), "only_expected_rows": int(fn), "key_precision": precision, "key_recall": recall, "key_f1": f1, "compared_columns": compared_columns, "value_disagreement_count": disagreement_count, "value_disagreements_first_100": disagreements, }
def compare_cli(argv: list[str]) -> int: parser = argparse.ArgumentParser(prog="python app.py compare", description="Compare WOLOJI tabular output with a direct-tool reference output.") parser.add_argument("observed", type=Path, help="WOLOJI output CSV/TSV") parser.add_argument("expected", type=Path, help="Direct-tool reference CSV/TSV") parser.add_argument("--keys", required=True, help="Comma-separated key columns used to match records") parser.add_argument("--numeric-tolerance", type=float, default=1e-8) parser.add_argument("--json-out", type=Path, default=None) args = parser.parse_args(argv) result = compare_tables(read_table(args.observed), read_table(args.expected), [k.strip() for k in args.keys.split(",") if k.strip()], args.numeric_tolerance) payload = json.dumps(result, indent=2, default=str) print(payload) if args.json_out: args.json_out.write_text(payload + "\n", encoding="utf-8") return 0
# =============================================================================# End-to-end analysis pipeline# =============================================================================DEFAULTS = { "threads": 4, "memory_gb": 12, "fastp_quality": 20, "fastp_length": 50, "fastp_n_limit": 5, "assembly_mode": "Auto", "genome_size": "5m", "iqtree_model": "MFP", "iqtree_bootstrap": 1000, "dry_run": False, "timeout": 14400,}
def _emit(cb: Callable[[str], None] | None, text: str): if cb: cb(text)
def _copy_or_link(src: Path, dst: Path): dst.parent.mkdir(parents=True, exist_ok=True) if dst.exists() or dst.is_symlink(): dst.unlink() try: dst.symlink_to(Path(src).resolve()) except OSError: shutil.copy2(src, dst)
def _run_fastp(sample: Sample, out: Path, runner: Runner, p: dict): qc = out / "01_read_qc" / sample.sample_id qc.mkdir(parents=True, exist_ok=True) r1 = qc / f"{sample.sample_id}.clean_R1.fastq.gz" r2 = qc / f"{sample.sample_id}.clean_R2.fastq.gz" if sample.read2 else None cmd = ["fastp", "-i", sample.read1, "-o", r1, "--qualified_quality_phred", p["fastp_quality"], "--length_required", p["fastp_length"], "--n_base_limit", p["fastp_n_limit"], "--thread", p["threads"], "--json", qc / "fastp.json", "--html", qc / "fastp.html"] if sample.read2: cmd += ["-I", sample.read2, "-O", r2, "--detect_adapter_for_pe"] result = runner.run(f"{sample.sample_id}_fastp", cmd) if result.skipped or result.returncode != 0: return sample.read1, sample.read2 runner.run(f"{sample.sample_id}_fastqc", ["fastqc", "-t", p["threads"], "-o", qc, *[x for x in (r1, r2) if x]]) return r1, r2
def _polypolish(sample_id: str, draft: Path, r1: Path, r2: Path, out: Path, runner: Runner, threads: int): pol = out / "03_polishing" / sample_id pol.mkdir(parents=True, exist_ok=True) draft_copy = pol / "draft.fasta" if draft.exists(): shutil.copy2(draft, draft_copy) runner.run(f"{sample_id}_bwa_index", ["bwa", "index", draft_copy]) a1, a2 = pol / "alignments_1.sam", pol / "alignments_2.sam" runner.run(f"{sample_id}_bwa_r1", ["bwa", "mem", "-t", threads, "-a", draft_copy, r1], stdout_file=a1) runner.run(f"{sample_id}_bwa_r2", ["bwa", "mem", "-t", threads, "-a", draft_copy, r2], stdout_file=a2) f1, f2 = pol / "filtered_1.sam", pol / "filtered_2.sam" runner.run(f"{sample_id}_polypolish_filter", ["polypolish", "filter", "--in1", a1, "--in2", a2, "--out1", f1, "--out2", f2]) polished = pol / "polished.fasta" rec = runner.run(f"{sample_id}_polypolish", ["polypolish", "polish", draft_copy, f1, f2], stdout_file=polished) if not runner.dry_run and (rec.skipped or rec.returncode != 0): return draft # fall back to the unpolished Flye assembly return polished
def _assemble(sample: Sample, r1: Path | None, r2: Path | None, out: Path, runner: Runner, p: dict): if sample.assembly: return sample.assembly asm_root = out / "02_assembly" / sample.sample_id asm_root.mkdir(parents=True, exist_ok=True) threads, mem, mode = p["threads"], p["memory_gb"], p["assembly_mode"] long_ok = mode in {"Auto", "Long-read: Flye"} hybrid_ok = mode in {"Auto", "Hybrid: Unicycler"} short_ok = mode in {"Auto", "Short-read: SPAdes"}
if sample.long_reads and r1 and r2 and hybrid_ok: runner.run(f"{sample.sample_id}_unicycler", ["unicycler", "-1", r1, "-2", r2, "-l", sample.long_reads, "-o", asm_root, "-t", threads]) return asm_root / "assembly.fasta" if sample.long_reads and long_ok: runner.run(f"{sample.sample_id}_flye", ["flye", "--nano-hq", sample.long_reads, "--out-dir", asm_root, "--threads", threads, "--genome-size", p["genome_size"]]) draft = asm_root / "assembly.fasta" if r1 and r2: return _polypolish(sample.sample_id, draft, r1, r2, out, runner, threads) return draft if r1 and short_ok: cmd = ["spades.py", "--isolate", "-1", r1, "-2", r2] if r2 else ["spades.py", "--isolate", "-s", r1] runner.run(f"{sample.sample_id}_spades", cmd + ["-o", asm_root, "-t", threads, "-m", mem]) return asm_root / "contigs.fasta" runner.skip(f"{sample.sample_id}_assembly", [mode], f"Assembly strategy '{mode}' does not match the available reads for this sample") return None
def _quast(sample_id, assembly, out, runner, threads): runner.run(f"{sample_id}_quast", ["quast.py", assembly, "-o", out / "04_assembly_qc" / "quast" / sample_id, "-t", threads])
def _checkm2(sample_id, assembly, out, runner, threads): qout = out / "04_assembly_qc" / "checkm2" / sample_id indir = qout / "input" indir.mkdir(parents=True, exist_ok=True) _copy_or_link(assembly, indir / f"{sample_id}.fasta") cmd = ["checkm2", "predict", "--threads", threads, "--input", indir, "--output-directory", qout / "results", "--extension", "fasta"] db = os.getenv("CHECKM2DB", "") if db: cmd += ["--database_path", db] runner.run(f"{sample_id}_checkm2", cmd)
def _mobileome(sample_id, assembly, out, runner, threads): root = out / "12_mobileome" / sample_id root.mkdir(parents=True, exist_ok=True) cmd = ["mob_recon", "--infile", assembly, "--outdir", root / "mob_suite", "--num_threads", threads] mob_db = os.getenv("MOB_SUITE_DB", "") if mob_db: cmd += ["--database_directory", mob_db] runner.run(f"{sample_id}_mob_recon", cmd) gdb = os.getenv("GENOMAD_DB", "") if gdb and Path(gdb).exists(): runner.run(f"{sample_id}_genomad", ["genomad", "end-to-end", "--cleanup", "--splits", threads, assembly, root / "genomad", gdb]) else: runner.skip(f"{sample_id}_genomad", ["genomad", "end-to-end", assembly, root / "genomad", "$GENOMAD_DB"], "GENOMAD_DB is not configured") runner.run(f"{sample_id}_integronfinder", ["integron_finder", "--local-max", "--cpu", min(int(threads), 4), "--outdir", root / "integrons", assembly]) runner.run(f"{sample_id}_minced", ["minced", assembly, root / "crispr.txt", root / "crispr.gff"])
def _mlst(sample_id, assembly, out, runner): root = out / "13_typing" / "mlst" root.mkdir(parents=True, exist_ok=True) runner.run(f"{sample_id}_mlst", ["mlst", "--full", assembly], stdout_file=root / f"{sample_id}.tsv")
def _gtdbtk(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int): if not assemblies: return root = out / "05_taxonomy" / "gtdbtk" inp = root / "input" inp.mkdir(parents=True, exist_ok=True) for sid, asm in assemblies.items(): _copy_or_link(asm, inp / f"{sid}.fasta") cmd = ["gtdbtk", "classify_wf", "--genome_dir", inp, "--out_dir", root / "results", "--extension", "fasta", "--cpus", threads, "--skip_ani_screen"] db = os.getenv("GTDBTK_DATA_PATH", "") if not db or not Path(db).exists(): runner.skip("gtdbtk_classify", cmd, "GTDBTK_DATA_PATH is not configured") return runner.run("gtdbtk_classify", cmd)
def _mash_skani(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int): if len(assemblies) < 2: runner.skip("mash_skani", ["mash", "skani"], "Pairwise distance and ANI need at least two genomes") return root = out / "05_taxonomy" / "comparative" root.mkdir(parents=True, exist_ok=True) paths = list(assemblies.values()) runner.run("mash_sketch", ["mash", "sketch", "-o", root / "genomes", *paths]) runner.run("mash_dist", ["mash", "dist", root / "genomes.msh", root / "genomes.msh"], stdout_file=root / "mash_dist.tsv") runner.run("skani_triangle", ["skani", "triangle", "-s", "90", "-t", threads, "-E", *paths], stdout_file=root / "skani_triangle.tsv")
def _chewbbaca(assemblies: dict[str, Path], schema_dir: Path | None, out: Path, runner: Runner, threads: int): if len(assemblies) < 2 or not schema_dir: runner.skip("chewbbaca", ["chewBBACA.py", "AlleleCall"], "cgMLST/wgMLST requires at least two genomes and a schema directory") return root = out / "13_typing" / "chewbbaca" inp = root / "genomes" inp.mkdir(parents=True, exist_ok=True) for sid, asm in assemblies.items(): _copy_or_link(asm, inp / f"{sid}.fasta") runner.run("chewbbaca_allelecall", ["chewBBACA.py", "AlleleCall", "-i", inp, "-g", schema_dir, "-o", root / "allelecall", "--cpu", threads])
def _phylogenomics(samples: list[Sample], assemblies: dict[str, Path], reference: Path | None, out: Path, runner: Runner, p: dict): if len(assemblies) < 3 or reference is None: runner.skip("core_snp_phylogeny", ["snippy"], "Core SNP phylogeny requires at least three samples and a reference genome") return root = out / "16_phylogenomics" snippy_dirs = [] for s in samples: asm = assemblies.get(s.sample_id) if asm is None: continue od = root / "snippy" / s.sample_id snippy_dirs.append(od) base = ["snippy", "--cpus", p["threads"], "--outdir", od, "--ref", reference, "--force"] if s.read1: cmd = base + ["--R1", s.read1] + (["--R2", s.read2] if s.read2 else []) else: cmd = base + ["--ctgs", asm] runner.run(f"{s.sample_id}_snippy", cmd) core = root / "core" core.mkdir(parents=True, exist_ok=True) runner.run("snippy_core", ["snippy-core", "--ref", reference, "--prefix", core / "core", *snippy_dirs]) aln = core / "core.full.aln" gub = root / "gubbins" gub.mkdir(parents=True, exist_ok=True) rec = runner.run("gubbins", ["run_gubbins.py", "--prefix", gub / "gubbins", "--threads", p["threads"], aln]) filt = gub / "gubbins.filtered_polymorphic_sites.fasta" iqdir = root / "iqtree" iqdir.mkdir(parents=True, exist_ok=True) if filt.exists() or (runner.dry_run and rec.skipped): # Only polymorphic sites remain, so ascertainment-bias correction (+ASC) is applied. model = p["iqtree_model"] if "+ASC" in p["iqtree_model"] else f"{p['iqtree_model']}+ASC" iq_input = filt else: model, iq_input = p["iqtree_model"], aln runner.run("iqtree", ["iqtree2", "-s", iq_input, "-m", model, "-B", p["iqtree_bootstrap"], "-T", p["threads"], "--prefix", iqdir / "tree"])
def _poppunk(assemblies: dict[str, Path], out: Path, runner: Runner, threads: int): if len(assemblies) < 3: runner.skip("poppunk", ["poppunk", "--create-db"], "PopPUNK model fitting needs at least three genomes (many more for stable clusters)") return root = out / "17_population" / "poppunk" root.mkdir(parents=True, exist_ok=True) rlist = root / "rlist.txt" rlist.write_text("".join(f"{sid}\t{path}\n" for sid, path in assemblies.items())) runner.run("poppunk_create_db", ["poppunk", "--create-db", "--output", root / "database", "--r-files", rlist, "--threads", threads]) runner.run("poppunk_fit", ["poppunk", "--fit-model", "bgmm", "--K", "2", "--ref-db", root / "database", "--output", root / "database", "--threads", threads])
def _publication_report(run_dir: Path, samples: list[Sample], assemblies: dict[str, Path], runner: Runner, modules: dict): report = run_dir / "20_publication_report" tables, figs = report / "tables", report / "figures" tables.mkdir(parents=True, exist_ok=True) figs.mkdir(parents=True, exist_ok=True) rows = [] for sid, asm in assemblies.items(): if Path(asm).exists(): d = fasta_stats(Path(asm)) d["sample"] = sid rows.append(d) df = pd.DataFrame(rows) if not df.empty: df.to_csv(tables / "assembly_summary.csv", index=False) assembly_summary_plot(df, figs / "assembly_n50.png") gc_plot(df, figs / "genome_gc.png") used = [k for k, v in modules.items() if v] methods = [ f"{SUITE_NAME} v{__version__} was used to coordinate the following analysis modules: {', '.join(used)}.", "The exact commands, software versions, parameters, input SHA256 checksums and database paths are " "recorded in run_manifest.json, command_manifest.json and input_manifest.tsv.", "Taxonomic assignments, mobile genetic element predictions, sequence types and population clusters " "should be interpreted in the context of genome quality and the reference database release used. " "Cite each underlying program that was executed.", ] (report / "methods_note.txt").write_text("\n\n".join(methods) + "\n", encoding="utf-8") summary = { "samples": len(samples), "assemblies_available": len(assemblies), "commands_total": len(runner.records), "commands_skipped": sum(r.skipped for r in runner.records), "commands_failed": sum((not r.skipped and r.returncode != 0) for r in runner.records), } (report / "run_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
def _zip_run(run_dir: Path) -> Path: target = run_dir.parent / f"{run_dir.name}.zip" with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as zf: for path in run_dir.rglob("*"): if path.is_file(): zf.write(path, path.relative_to(run_dir)) return target
def run_pipeline(samples: list[Sample], run_dir: Path, modules: dict, params: dict, reference: Path | None = None, schema_dir: Path | None = None, progress_cb: Callable[[str], None] | None = None): p = DEFAULTS | (params or {}) run_dir.mkdir(parents=True, exist_ok=True) runner = Runner(run_dir / "logs", dry_run=bool(p["dry_run"]), timeout=int(p["timeout"])) assemblies: dict[str, Path] = {}
input_manifest = [] for s in samples: for label, path in [("Read_1", s.read1), ("Read_2", s.read2), ("Long_Reads", s.long_reads), ("Assembly", s.assembly)]: if path and Path(path).exists(): input_manifest.append({"sample": s.sample_id, "type": label, "file": Path(path).name, "sha256": sha256_file(Path(path))}) if reference and reference.exists(): input_manifest.append({"sample": "", "type": "Reference", "file": reference.name, "sha256": sha256_file(reference)}) pd.DataFrame(input_manifest).to_csv(run_dir / "input_manifest.tsv", sep="\t", index=False)
for i, sample in enumerate(samples, start=1): _emit(progress_cb, f"[{i}/{len(samples)}] {sample.sample_id}: read QC and assembly") r1, r2 = sample.read1, sample.read2 if modules.get("read_qc") and sample.read1: r1, r2 = _run_fastp(sample, run_dir, runner, p) asm = _assemble(sample, r1, r2, run_dir, runner, p) if modules.get("assembly") else sample.assembly if not asm: continue asm = Path(asm) if not runner.dry_run and not asm.exists(): runner.skip(f"{sample.sample_id}_downstream", [str(asm)], "Assembly was not produced; downstream modules skipped for this sample") continue assemblies[sample.sample_id] = asm _emit(progress_cb, f"[{i}/{len(samples)}] {sample.sample_id}: assembly QC, mobileome and MLST") if modules.get("quast"): _quast(sample.sample_id, asm, run_dir, runner, p["threads"]) if modules.get("checkm2"): _checkm2(sample.sample_id, asm, run_dir, runner, p["threads"]) if modules.get("mobileome"): _mobileome(sample.sample_id, asm, run_dir, runner, p["threads"]) if modules.get("mlst"): _mlst(sample.sample_id, asm, run_dir, runner)
if modules.get("read_qc") and (run_dir / "01_read_qc").exists(): runner.run("multiqc", ["multiqc", run_dir / "01_read_qc", "-o", run_dir / "01_read_qc" / "multiqc"]) _emit(progress_cb, "Cohort analyses: taxonomy, typing, phylogenomics and population structure") if modules.get("taxonomy"): _gtdbtk(assemblies, run_dir, runner, p["threads"]) _mash_skani(assemblies, run_dir, runner, p["threads"]) if modules.get("cgmlst"): _chewbbaca(assemblies, schema_dir, run_dir, runner, p["threads"]) if modules.get("phylogenomics"): _phylogenomics(samples, assemblies, reference, run_dir, runner, p) if modules.get("population"): _poppunk(assemblies, run_dir, runner, p["threads"])
_emit(progress_cb, "Writing publication report and manifests") _publication_report(run_dir, samples, assemblies, runner, modules) runner.write_manifest(run_dir / "command_manifest.json") run_manifest = { "suite": SUITE_NAME, "version": __version__, "created_at": utc_now(), "parameters": p, "modules": modules, "database_paths": {v: os.getenv(v, "") for v in DATABASES.values()}, "samples": [s.sample_id for s in samples], "software_versions": status_rows(), } (run_dir / "run_manifest.json").write_text(json.dumps(run_manifest, indent=2, default=str), encoding="utf-8") return _zip_run(run_dir), run_manifest, runner.records
# =============================================================================# Streamlit interface# =============================================================================def _store_upload(uploaded, folder: Path) -> Path: path = folder / os.path.basename(uploaded.name) path.write_bytes(uploaded.getvalue()) return path
def render_app(): import streamlit as st
st.set_page_config(page_title=SUITE_NAME, page_icon="🧬", layout="wide") st.title(f"🧬 {SUITE_NAME}") st.caption(f"Version {__version__} | Raw reads to publication-ready bacterial whole-genome analysis")
with st.expander("Scope and interpretation", expanded=False): st.write( "WOLOJI is designed for bacterial isolate whole-genome analysis. It coordinates read quality control, " "assembly, assembly quality, taxonomy, mobile genetic elements, sequence typing, SNP phylogenomics, " "population genomics and reproducibility reporting. Genome annotation, codon usage analysis, AMR " "detection, virulence screening and secondary metabolite prediction are handled by separate dedicated " "tools and are out of scope here. Database-dependent modules run only when the corresponding database " "path is configured. Prediction-based outputs do not replace phenotypic or experimental validation." )
with st.sidebar: st.header("Workflow modules") modules = { "read_qc": st.checkbox("1. Raw read QC", True), "assembly": st.checkbox("2. Genome assembly / polishing", True), "quast": st.checkbox("3. QUAST assembly QC", True), "checkm2": st.checkbox("4. CheckM2 completeness", False), "taxonomy": st.checkbox("5. Taxonomy + ANI", True), "mobileome": st.checkbox("6. Mobileome / plasmids / prophages / CRISPR", True), "mlst": st.checkbox("7. Classical MLST", True), "cgmlst": st.checkbox("8. cgMLST / wgMLST", False), "phylogenomics": st.checkbox("9. Core SNP phylogenomics", False), "population": st.checkbox("10. Population genomics", False), } st.header("Core parameters") cpu = max(1, os.cpu_count() or 2) threads = st.slider("CPU threads", 1, cpu, min(4, cpu)) memory_gb = st.number_input("Assembly memory limit (GB)", 2, 256, 12, 1) assembly_mode = st.selectbox("Assembly strategy", ["Auto", "Hybrid: Unicycler", "Long-read: Flye", "Short-read: SPAdes"]) genome_size = st.text_input("Expected genome size for Flye", "5m", help="For example 2.8m for Staphylococcus aureus, 5m for Escherichia coli.") fastp_quality = st.slider("fastp minimum Phred", 10, 35, 20) fastp_length = st.number_input("fastp minimum read length", 20, 300, 50, 5) fastp_n_limit = st.number_input("fastp maximum N bases per read", 0, 50, 5, 1, help="fastp --n_base_limit is an absolute count, not a percentage.") iqtree_model = st.text_input("IQ-TREE model", "MFP", help="MFP runs ModelFinder Plus.") dry_run = st.checkbox("Dry run: record commands without executing", False)
run_tab, utilities_tab, status_tab, help_tab = st.tabs( ["Run complete analysis", "Woloji sequence utilities", "Tools & databases", "User guide"])
# ---------------------------------------------------------------- pipeline with run_tab: st.subheader("1. Upload data") files = st.file_uploader("Upload FASTQ/FASTQ.GZ, FASTA/FASTA.GZ, or a ZIP containing them", accept_multiple_files=True, type=["fastq", "fq", "gz", "fa", "fasta", "fna", "fas", "zip"]) meta = st.file_uploader("Optional metadata CSV/TSV", type=["csv", "tsv", "txt"], key="meta") st.caption("Metadata columns: Sample_ID (required), Read_1, Read_2, Long_Reads, Assembly, Genus, Species") reference = st.file_uploader("Optional reference genome for core SNP analysis", type=["fa", "fasta", "fna", "gbk", "gbff"], key="ref") schema_zip = st.file_uploader("Optional chewBBACA cgMLST/wgMLST schema ZIP", type=["zip"], key="schema") run_name = st.text_input("Run name", value=f"woloji_{datetime.now(UTC).strftime('%Y%m%d_%H%M%S')}")
if st.button("Run WOLOJI analysis", type="primary", width="stretch"): st.session_state.pop("pipeline_result", None) if not files: st.error("Upload at least one sequencing or assembly file.") else: work_root = Path(tempfile.gettempdir()) / "woloji_runs" run_dir = work_root / safe_name(run_name) if run_dir.exists(): shutil.rmtree(run_dir) input_dir = run_dir / "00_input" input_dir.mkdir(parents=True, exist_ok=True) samples: list[Sample] = [] try: mapping = save_uploads(files, input_dir) samples = (samples_from_metadata(_store_upload(meta, input_dir), mapping) if meta else auto_samples(mapping)) except Exception as exc: # UI boundary st.error(f"Input parsing failed: {exc}") if not samples: st.error("No valid samples were detected. Use a metadata table if automatic pairing is unclear.") else: ref_path = _store_upload(reference, input_dir) if reference else None schema_dir = None if schema_zip: schema_dir = input_dir / "cgmlst_schema" schema_dir.mkdir(parents=True, exist_ok=True) safe_extract_zip(_store_upload(schema_zip, input_dir), schema_dir) children = [c for c in schema_dir.iterdir() if c.is_dir()] if len(children) == 1: schema_dir = children[0] st.write("Detected samples") st.dataframe(pd.DataFrame([{ "Sample_ID": s.sample_id, "Read_1": s.read1.name if s.read1 else "", "Read_2": s.read2.name if s.read2 else "", "Long_Reads": s.long_reads.name if s.long_reads else "", "Assembly": s.assembly.name if s.assembly else "", } for s in samples]), width="stretch", hide_index=True) status, progress = st.empty(), st.progress(0) events: list[str] = [] expected_events = 2 * len(samples) + 2
def cb(msg): events.append(msg) status.info(msg) progress.progress(min(95, int(95 * len(events) / expected_events)))
params = {"threads": threads, "memory_gb": int(memory_gb), "assembly_mode": assembly_mode, "genome_size": genome_size.strip() or "5m", "fastp_quality": fastp_quality, "fastp_length": int(fastp_length), "fastp_n_limit": int(fastp_n_limit), "iqtree_model": iqtree_model.strip() or "MFP", "dry_run": dry_run} try: zip_path, manifest, records = run_pipeline(samples, run_dir, modules, params, reference=ref_path, schema_dir=schema_dir, progress_cb=cb) progress.progress(100) status.success("Analysis finished") st.session_state["pipeline_result"] = { "zip": str(zip_path), "manifest": manifest, "records": [r.to_dict() for r in records]} except Exception as exc: # UI boundary progress.empty() status.error(f"Pipeline failed: {exc}")
result = st.session_state.get("pipeline_result") if result and Path(result["zip"]).exists(): st.subheader("Execution summary") cdf = pd.DataFrame(result["records"]) if not cdf.empty: cdf["status"] = cdf.apply(lambda r: "skipped" if r["skipped"] else ("ok" if r["returncode"] == 0 else "failed"), axis=1) st.dataframe(cdf[["name", "status", "returncode", "reason"]], width="stretch", hide_index=True) with st.expander("Run manifest"): st.json(result["manifest"]) zp = Path(result["zip"]) st.download_button("Download complete WOLOJI result package", data=zp.read_bytes(), file_name=zp.name, mime="application/zip", width="stretch")
# --------------------------------------------------------------- utilities with utilities_tab: u1, u2, u3, u4 = st.tabs(["Primer design", "GeneClean-BLAST", "PhyloForge", "Output concordance"]) with u1: st.markdown("#### Primer Design Tool (Primer3)") primer_file = st.file_uploader("Target FASTA", type=["fa", "fasta", "fna"], key="primer_file") primer_text = st.text_area("Or paste target DNA sequence", height=120, key="primer_text") pc1, pc2, pc3 = st.columns(3) prod_min = pc1.number_input("Minimum product size", 50, 5000, 100, 10) prod_max = pc2.number_input("Maximum product size", 60, 10000, 600, 10) n_pairs = pc3.number_input("Primer pairs to return", 1, 20, 5, 1) if st.button("Design primers", key="design_primers"): try: seq = fasta_first_sequence(primer_file.getvalue())[1] if primer_file else primer_text seq = re.sub(r"\s+", "", seq or "") if not seq: st.error("Provide a FASTA file or DNA sequence.") else: st.session_state["primer_df"] = design_primers( seq, product_min=int(prod_min), product_max=int(prod_max), num_return=int(n_pairs)) except Exception as exc: # UI boundary st.error(f"Primer design failed: {exc}") if "primer_df" in st.session_state: pdf = st.session_state["primer_df"] if pdf.empty: st.warning("Primer3 returned no pairs. Relax the product size range or check the template.") else: st.dataframe(pdf, width="stretch", hide_index=True) st.download_button("Download primer table", pdf.to_csv(index=False).encode(), "woloji_primers.csv", "text/csv") with u2: st.markdown("#### GeneClean-BLAST (local BLAST+)") q = st.file_uploader("Query FASTA", type=["fa", "fasta", "fna"], key="blast_q") subj = st.file_uploader("Subject/reference FASTA", type=["fa", "fasta", "fna"], key="blast_s") bc1, bc2 = st.columns(2) task = bc1.selectbox("blastn task", ["megablast", "dc-megablast", "blastn", "blastn-short"], index=2) evalue = bc2.number_input("E-value threshold", 0.0, 10.0, 1e-10, format="%.1e") if st.button("Run local BLAST", key="run_blast"): if not q or not subj: st.error("Upload query and subject FASTA files.") else: try: st.session_state["blast_df"] = local_blast(q.getvalue(), subj.getvalue(), task=task, evalue=evalue, threads=threads) except Exception as exc: # UI boundary st.error(f"BLAST failed: {exc}") if "blast_df" in st.session_state: bdf = st.session_state["blast_df"] st.dataframe(bdf, width="stretch", hide_index=True) st.download_button("Download BLAST table", bdf.to_csv(index=False).encode(), "woloji_blast.csv", "text/csv") with u3: st.markdown("#### PhyloForge (MAFFT + IQ-TREE 2)") pf = st.file_uploader("Upload homologous FASTA sequences (at least 4 sequences in total)", type=["fa", "fasta", "fna", "fas"], accept_multiple_files=True, key="phylo_files") pf_model = st.text_input("Substitution model", "MFP", key="pf_model") if st.button("Align and infer tree", key="run_phylo"): if not pf: st.error("Upload at least one FASTA file.") else: try: st.session_state["phylo"] = phyloforge(pf, threads=threads, model=pf_model.strip() or "MFP") except Exception as exc: # UI boundary st.error(f"PhyloForge failed: {exc}") if "phylo" in st.session_state: aln, tree, log = st.session_state["phylo"] st.text_area("MAFFT alignment", aln, height=250) st.code(tree, language="text") d1, d2, d3 = st.columns(3) d1.download_button("Download alignment", aln.encode(), "woloji_alignment.fasta", "text/plain") d2.download_button("Download Newick tree", tree.encode(), "woloji_tree.nwk", "text/plain") d3.download_button("Download IQ-TREE report", log.encode(), "woloji_iqtree_report.txt", "text/plain") with u4: st.markdown("#### Output concordance (WOLOJI versus direct-tool run)") st.caption("Matches rows on key columns, then reports key precision, recall, F1 and value disagreements.") obs = st.file_uploader("WOLOJI output table (CSV/TSV)", type=["csv", "tsv", "txt", "tab"], key="cmp_obs") exp = st.file_uploader("Direct-tool reference table (CSV/TSV)", type=["csv", "tsv", "txt", "tab"], key="cmp_exp") keys = st.text_input("Key columns (comma separated)", "Sample_ID") tol = st.number_input("Numeric tolerance", 0.0, 1e6, 1e-8, format="%.1e") if st.button("Compare tables", key="run_compare"): if not obs or not exp: st.error("Upload both tables.") else: try: st.session_state["compare"] = compare_tables( read_table(io.BytesIO(obs.getvalue()), obs.name), read_table(io.BytesIO(exp.getvalue()), exp.name), [k.strip() for k in keys.split(",") if k.strip()], tol) except Exception as exc: # UI boundary st.error(f"Comparison failed: {exc}") if "compare" in st.session_state: res = st.session_state["compare"] m1, m2, m3 = st.columns(3) fmt = lambda v: "n/a" if isinstance(v, float) and math.isnan(v) else f"{v:.3f}" # noqa: E731 m1.metric("Key precision", fmt(res["key_precision"])) m2.metric("Key recall", fmt(res["key_recall"])) m3.metric("Key F1", fmt(res["key_f1"])) st.write(f"Value disagreements: {res['value_disagreement_count']}") if res["value_disagreements_first_100"]: st.dataframe(pd.DataFrame(res["value_disagreements_first_100"]), width="stretch", hide_index=True) st.download_button("Download concordance JSON", json.dumps(res, indent=2, default=str).encode(), "woloji_concordance.json", "application/json")
# ------------------------------------------------------------------ status with status_tab: st.subheader("Installed command-line tools") if st.button("Refresh tool status") or "tool_status" not in st.session_state: st.session_state["tool_status"] = status_rows() st.session_state["db_status"] = database_rows() st.dataframe(pd.DataFrame(st.session_state["tool_status"]), width="stretch", hide_index=True) st.subheader("Reference database configuration") st.dataframe(pd.DataFrame(st.session_state["db_status"]), width="stretch", hide_index=True) st.info("Mount large reference databases on persistent storage (for example /data) and expose them " "through the environment variables shown above.")
# -------------------------------------------------------------------- help with help_tab: st.markdown("""### Input namingFor paired Illumina files without metadata, use names such as `Sample01_R1.fastq.gz` and `Sample01_R2.fastq.gz`(`_1/_2` and lane suffixes such as `_R1_001` are also recognised). Unpaired FASTQ files are interpreted as long reads.FASTA files are treated as finished assemblies. For mixed or non-standard names, use the metadata table.
### Recommended analysis modes**Routine isolate WGS:** read QC, assembly, QUAST, taxonomy/ANI, mobileome, MLST and report.
**Comparative genomics:** analyse multiple assemblies and enable cgMLST/wgMLST and population genomics.
**Outbreak/phylogenomic analysis:** provide a reference genome, at least three isolates, and enable core SNPphylogenomics. WOLOJI calls Snippy, snippy-core, Gubbins and IQ-TREE 2 (with +ASC on the SNP-only alignment).
### Out of scopeGenome annotation, codon usage, AMR detection, virulence screening and secondary metabolite prediction.
### Database variables`GTDBTK_DATA_PATH`, `CHECKM2DB`, `GENOMAD_DB`, `MOB_SUITE_DB`.
### Reproducibility outputsEvery run records input SHA256 hashes, parameters, database paths, exact command lines, command logs,software versions, assembly summary tables, figures and a methods note.""")
# =============================================================================# Entry point# =============================================================================def _running_in_streamlit() -> bool: try: from streamlit.runtime.scriptrunner import get_script_run_ctx return get_script_run_ctx(suppress_warning=True) is not None except (ImportError, TypeError): return False
if _running_in_streamlit(): render_app()elif __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "compare": raise SystemExit(compare_cli(sys.argv[2:])) print(__doc__) print("Start the web interface with: streamlit run app.py")123456789# Python packages for the WOLOJI Streamlit application (app.py).# Pinned to the versions tested with this build on Python 3.11.# Command-line bioinformatics tools are installed by the Dockerfile, not by pip.streamlit==1.64.0pandas==3.0.6numpy==2.4.6matplotlib==3.11.2biopython==1.88primer3-py==2.3.1DockerfileAdded+117
README.mdAdded+201
app.pyAdded+1290
requirements.txtAdded+9