Delete app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673from __future__ import annotations
import csvimport gzipimport hashlibimport jsonimport mathimport osimport platformimport reimport shutilimport subprocessimport sysimport timeimport tracebackimport uuidimport zipfilefrom dataclasses import asdict, dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Dict, Iterable, List, Optional, Sequence, Tuple
import gradio as grimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport psutilimport yamlfrom scipy import statsfrom scipy.spatial.distance import braycurtis, pdist, squareformfrom sklearn.decomposition import PCAfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.inspection import permutation_importancefrom sklearn.metrics import ( accuracy_score, average_precision_score, brier_score_loss, balanced_accuracy_score, confusion_matrix, f1_score, matthews_corrcoef, precision_score, precision_recall_curve, recall_score, roc_curve, roc_auc_score,)from sklearn.model_selection import StratifiedKFold, cross_val_predictfrom sklearn.preprocessing import LabelEncoderfrom statsmodels.stats.multitest import multipletests
try: import shap SHAP_AVAILABLE = Trueexcept Exception: shap = None SHAP_AVAILABLE = False
APP_TITLE = os.getenv("APP_TITLE", "Bulamarwa Metagenomics Suite")APP_VERSION = "1.0.0"WORK_ROOT = Path(os.getenv("WORK_ROOT", "/tmp/metagenome_runs")).resolve()WORK_ROOT.mkdir(parents=True, exist_ok=True)MAX_UPLOAD_GB = float(os.getenv("MAX_UPLOAD_GB", "20"))DEFAULT_THREADS = max(1, min(int(os.getenv("DEFAULT_THREADS", "4")), os.cpu_count() or 2))
DB_ENV = { "Kraken2 / Bracken": "KRAKEN2_DB", "CheckM2": "CHECKM2DB", "GTDB-Tk": "GTDBTK_DATA_PATH", "eggNOG-mapper": "EGGNOG_DATA_DIR", "geNomad": "GENOMAD_DB",}
SPECIAL_ENVS = { "checkm2": "checkm2", "gtdbtk": "gtdbtk", "genomad": "genomad", "emapper.py": "eggnog", "amrfinder": "amrfinder",}
CORE_TOOLS = [ "fastp", "fastqc", "multiqc", "bowtie2", "bowtie2-build", "samtools", "kraken2", "bracken", "megahit", "quast.py", "metabat2", "jgi_summarize_bam_contig_depths", "prodigal", "dRep", "seqkit",]OPTIONAL_TOOLS = ["checkm2", "gtdbtk", "genomad", "emapper.py", "amrfinder"]
@dataclassclass Sample: sample_id: str read1: Path read2: Optional[Path] = None group: str = "NA" condition: str = "NA" location: str = "NA" time_point: str = "NA" replicate: str = "NA" sequencing_platform: str = "Illumina" library_type: str = "Shotgun"
class PipelineError(RuntimeError): pass
def now_iso() -> str: return datetime.now(timezone.utc).isoformat()
def safe_name(value: str) -> str: value = re.sub(r"[^A-Za-z0-9._-]+", "_", str(value).strip()) return value[:120] or "sample"
def human_bytes(n: int) -> str: units = ["B", "KB", "MB", "GB", "TB"] value = float(n) for unit in units: if value < 1024 or unit == units[-1]: return f"{value:.2f} {unit}" value /= 1024 return f"{value:.2f} TB"
def sha256sum(path: Path, chunk_size: int = 1024 * 1024) -> str: h = hashlib.sha256() with path.open("rb") as fh: while True: chunk = fh.read(chunk_size) if not chunk: break h.update(chunk) return h.hexdigest()
def tool_cmd(tool: str, *args: str) -> List[str]: env_name = SPECIAL_ENVS.get(tool) if env_name: return ["micromamba", "run", "-n", env_name, tool, *map(str, args)] return [tool, *map(str, args)]
def tool_available(tool: str) -> bool: if shutil.which(tool): return True env_name = SPECIAL_ENVS.get(tool) if env_name and shutil.which("micromamba"): proc = subprocess.run( ["micromamba", "run", "-n", env_name, tool, "--help"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20, ) return proc.returncode in (0, 1, 2) return False
def tool_version(tool: str) -> str: candidates = [ tool_cmd(tool, "--version"), tool_cmd(tool, "-version"), tool_cmd(tool, "-v"), ] for cmd in candidates: try: p = subprocess.run(cmd, capture_output=True, text=True, timeout=15) text = (p.stdout + "\n" + p.stderr).strip() if text: return text.splitlines()[0][:250] except Exception: pass return "available" if tool_available(tool) else "not available"
def run_command( cmd: Sequence[str], log_path: Path, cwd: Optional[Path] = None, env: Optional[dict] = None, dry_run: bool = False,) -> None: command_string = " ".join(map(str, cmd)) with log_path.open("a", encoding="utf-8") as log: log.write(f"\n[{now_iso()}] COMMAND: {command_string}\n") log.flush() if dry_run: log.write("DRY RUN: command not executed.\n") return proc = subprocess.Popen( list(map(str, cmd)), cwd=str(cwd) if cwd else None, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, ) assert proc.stdout is not None for line in proc.stdout: log.write(line) rc = proc.wait() if rc != 0: raise PipelineError(f"Command failed with exit code {rc}: {command_string}")
def copy_upload(src: str | Path, dst_dir: Path) -> Path: src = Path(src) dst = dst_dir / safe_name(src.name) shutil.copy2(src, dst) return dst
def parse_metadata(metadata_path: Path, upload_map: Dict[str, Path]) -> List[Sample]: sep = "\t" if metadata_path.suffix.lower() in {".tsv", ".txt"} else "," df = pd.read_csv(metadata_path, sep=sep, dtype=str).fillna("") normalized = {c.lower().strip(): c for c in df.columns} required = ["sample_id", "read_1"] missing = [x for x in required if x not in normalized] if missing: raise PipelineError( "Metadata must contain Sample_ID and Read_1 columns. " f"Missing: {', '.join(missing)}" )
if df[normalized["sample_id"]].duplicated().any(): dups = df.loc[df[normalized["sample_id"]].duplicated(), normalized["sample_id"]].tolist() raise PipelineError(f"Duplicate Sample_ID values detected: {dups[:10]}")
def field(row, name: str, default: str = "NA") -> str: col = normalized.get(name) value = str(row[col]).strip() if col else "" return value or default
def resolve_read(name: str) -> Path: base = Path(name).name if base in upload_map: return upload_map[base] if name in upload_map: return upload_map[name] raise PipelineError( f"Metadata references '{name}', but that FASTQ file was not uploaded. " "Use matching file names in Read_1 and Read_2." )
samples: List[Sample] = [] for _, row in df.iterrows(): sid = safe_name(field(row, "sample_id", "sample")) r1 = resolve_read(field(row, "read_1", "")) r2_name = field(row, "read_2", "") if "read_2" in normalized else "" r2 = resolve_read(r2_name) if r2_name and r2_name != "NA" else None samples.append( Sample( sample_id=sid, read1=r1, read2=r2, group=field(row, "group"), condition=field(row, "condition"), location=field(row, "location"), time_point=field(row, "time_point"), replicate=field(row, "replicate"), sequencing_platform=field(row, "sequencing_platform", "Illumina"), library_type=field(row, "library_type", "Shotgun"), ) ) return samples
def infer_samples(uploaded: List[Path]) -> List[Sample]: if len(uploaded) == 1: return [Sample(sample_id=safe_name(uploaded[0].name.split(".")[0]), read1=uploaded[0])] if len(uploaded) == 2: names = [p.name.lower() for p in uploaded] r1_idx = next((i for i, n in enumerate(names) if any(t in n for t in ["_r1", "_1.", "-r1"])), 0) r2_idx = 1 - r1_idx sid = re.sub(r"([._-]r?1).*", "", uploaded[r1_idx].name, flags=re.I) return [Sample(sample_id=safe_name(sid), read1=uploaded[r1_idx], read2=uploaded[r2_idx])] raise PipelineError("For more than two FASTQ files, upload a metadata CSV/TSV describing each sample.")
def validate_inputs(samples: List[Sample]) -> List[str]: warnings: List[str] = [] ids = [s.sample_id for s in samples] if len(ids) != len(set(ids)): raise PipelineError("Sample IDs must be unique.") for s in samples: for read in [s.read1, s.read2]: if read is None: continue if not read.exists() or read.stat().st_size == 0: raise PipelineError(f"Missing or empty FASTQ: {read}") n = read.name.lower() if not any(n.endswith(ext) for ext in (".fastq", ".fq", ".fastq.gz", ".fq.gz")): warnings.append(f"{read.name}: extension is not a standard FASTQ extension.") return warnings
def fastq_open(path: Path): return gzip.open(path, "rt", encoding="utf-8", errors="replace") if path.suffix == ".gz" else path.open("r", encoding="utf-8", errors="replace")
def estimate_read_length(path: Path, max_reads: int = 1000) -> int: lengths = [] try: with fastq_open(path) as fh: i = 0 while i < max_reads: header = fh.readline() seq = fh.readline().strip() plus = fh.readline() qual = fh.readline() if not header or not seq or not plus or not qual: break lengths.append(len(seq)) i += 1 except Exception: return 150 return int(round(float(np.median(lengths)))) if lengths else 150
def module_status_dataframe() -> pd.DataFrame: rows = [] for tool in CORE_TOOLS + OPTIONAL_TOOLS: rows.append({"Tool": tool, "Available": "Yes" if tool_available(tool) else "No", "Version": tool_version(tool)}) for label, env_name in DB_ENV.items(): path = os.getenv(env_name, "") rows.append({"Tool": f"Database: {label}", "Available": "Yes" if path and Path(path).exists() else "No", "Version": path or f"Set {env_name}"}) return pd.DataFrame(rows)
def make_manifest(run_dir: Path, samples: List[Sample], params: dict, input_files: List[Path]) -> dict: manifest = { "application": APP_TITLE, "application_version": APP_VERSION, "run_id": run_dir.name, "created_utc": now_iso(), "platform": platform.platform(), "python": sys.version, "cpu_count": os.cpu_count(), "memory_total_gb": round(psutil.virtual_memory().total / (1024 ** 3), 2), "parameters": params, "samples": [ { **asdict(s), "read1": s.read1.name, "read2": s.read2.name if s.read2 else None, } for s in samples ], "inputs": [], "databases": {env: os.getenv(env, "") for env in DB_ENV.values()}, } for p in input_files: manifest["inputs"].append({ "file": p.name, "size_bytes": p.stat().st_size, "sha256": sha256sum(p), }) (run_dir / "run_manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8") return manifest
def write_versions(run_dir: Path) -> None: rows = [] for tool in CORE_TOOLS + OPTIONAL_TOOLS: rows.append({"software": tool, "version": tool_version(tool)}) pd.DataFrame(rows).to_csv(run_dir / "software_versions.tsv", sep="\t", index=False) db_rows = [] for label, env_name in DB_ENV.items(): db_rows.append({"database": label, "environment_variable": env_name, "path": os.getenv(env_name, "")}) pd.DataFrame(db_rows).to_csv(run_dir / "database_versions.tsv", sep="\t", index=False)
def fastp_step(sample: Sample, out_dir: Path, log: Path, threads: int, min_q: int, min_len: int, max_n_bases: int, trim_poly_g: bool, dry_run: bool) -> Tuple[Path, Optional[Path]]: """Run fastp with an absolute N-base limit. fastp --n_base_limit is a count, not a proportion.""" out_dir.mkdir(parents=True, exist_ok=True) r1 = out_dir / f"{sample.sample_id}_clean_R1.fastq.gz" r2 = out_dir / f"{sample.sample_id}_clean_R2.fastq.gz" if sample.read2 else None json_out = out_dir / f"{sample.sample_id}_fastp.json" html_out = out_dir / f"{sample.sample_id}_fastp.html" if not tool_available("fastp"): raise PipelineError("fastp is not installed in the container.") cmd = [ "fastp", "-i", str(sample.read1), "-o", str(r1), "-q", str(min_q), "-l", str(min_len), "--n_base_limit", str(max(0, int(max_n_bases))), "-w", str(threads), "-j", str(json_out), "-h", str(html_out) ] if trim_poly_g: cmd.append("--trim_poly_g") if sample.read2: cmd.extend(["-I", str(sample.read2), "-O", str(r2), "--detect_adapter_for_pe"]) run_command(cmd, log, dry_run=dry_run) if dry_run: return sample.read1, sample.read2 return r1, r2
def fastqc_multiqc_step(reads: List[Path], out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: if not tool_available("fastqc") or not tool_available("multiqc"): return fq_dir = out_dir / "fastqc" fq_dir.mkdir(parents=True, exist_ok=True) run_command(["fastqc", "-t", str(threads), "-o", str(fq_dir), *map(str, reads)], log, dry_run=dry_run) run_command(["multiqc", str(out_dir), "-o", str(out_dir / "multiqc"), "--force"], log, dry_run=dry_run)
def host_remove_step(sample_id: str, r1: Path, r2: Optional[Path], host_fasta: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> Tuple[Path, Optional[Path]]: out_dir.mkdir(parents=True, exist_ok=True) if not tool_available("bowtie2") or not tool_available("bowtie2-build"): raise PipelineError("Bowtie2 is required for host removal.") index_prefix = out_dir / "host_index" if not dry_run: run_command(["bowtie2-build", str(host_fasta), str(index_prefix)], log) else: run_command(["bowtie2-build", str(host_fasta), str(index_prefix)], log, dry_run=True) if r2: prefix = out_dir / f"{sample_id}_nonhost_R%.fastq.gz" cmd = ["bowtie2", "-x", str(index_prefix), "-1", str(r1), "-2", str(r2), "--very-sensitive", "-p", str(threads), "--un-conc-gz", str(prefix), "-S", "/dev/null"] run_command(cmd, log, dry_run=dry_run) if dry_run: return r1, r2 return out_dir / f"{sample_id}_nonhost_R1.fastq.gz", out_dir / f"{sample_id}_nonhost_R2.fastq.gz" out_single = out_dir / f"{sample_id}_nonhost.fastq.gz" cmd = ["bowtie2", "-x", str(index_prefix), "-U", str(r1), "--very-sensitive", "-p", str(threads), "--un-gz", str(out_single), "-S", "/dev/null"] run_command(cmd, log, dry_run=dry_run) return (r1 if dry_run else out_single), None
def kraken_step(sample_id: str, r1: Path, r2: Optional[Path], out_dir: Path, log: Path, threads: int, confidence: float, bracken_level: str, min_reads: int, dry_run: bool) -> Optional[Path]: db = os.getenv("KRAKEN2_DB", "") if not db or not Path(db).exists() or not tool_available("kraken2"): with log.open("a", encoding="utf-8") as fh: fh.write(f"\nSKIP taxonomy for {sample_id}: set KRAKEN2_DB to a valid database path.\n") return None out_dir.mkdir(parents=True, exist_ok=True) report = out_dir / f"{sample_id}_kraken_report.tsv" classified = out_dir / f"{sample_id}_kraken_output.tsv" cmd = ["kraken2", "--db", db, "--threads", str(threads), "--confidence", str(confidence), "--use-names", "--report", str(report), "--output", str(classified)] if r2: cmd.extend(["--paired", str(r1), str(r2)]) else: cmd.append(str(r1)) run_command(cmd, log, dry_run=dry_run) if dry_run or not tool_available("bracken"): return report if not dry_run else None read_len = estimate_read_length(r1) bracken = out_dir / f"{sample_id}_bracken_{bracken_level}.tsv" run_command(["bracken", "-d", db, "-i", str(report), "-o", str(bracken), "-r", str(read_len), "-l", bracken_level, "-t", str(min_reads)], log, dry_run=dry_run) return bracken
def megahit_step(sample_id: str, r1: Path, r2: Optional[Path], out_dir: Path, log: Path, threads: int, min_contig: int, dry_run: bool) -> Optional[Path]: if not tool_available("megahit"): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP assembly: MEGAHIT is not installed.\n") return None sample_out = out_dir / sample_id cmd = ["megahit", "-o", str(sample_out), "-t", str(threads), "--min-contig-len", str(min_contig)] if r2: cmd.extend(["-1", str(r1), "-2", str(r2)]) else: cmd.extend(["-r", str(r1)]) run_command(cmd, log, dry_run=dry_run) return sample_out / "final.contigs.fa"
def quast_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, threads: int, min_contig: int, dry_run: bool) -> None: if not tool_available("quast.py"): return run_command(["quast.py", str(contigs), "-o", str(out_dir / sample_id), "-t", str(threads), "--min-contig", str(min_contig)], log, dry_run=dry_run)
def mapping_binning_step(sample_id: str, contigs: Path, r1: Path, r2: Optional[Path], out_dir: Path, log: Path, threads: int, dry_run: bool) -> Optional[Path]: needed = ["bowtie2", "bowtie2-build", "samtools", "metabat2", "jgi_summarize_bam_contig_depths"] if not all(tool_available(x) for x in needed): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP binning: required mapping/MetaBAT2 tools are not installed.\n") return None sdir = out_dir / sample_id sdir.mkdir(parents=True, exist_ok=True) idx = sdir / "assembly_index" sam = sdir / "mapping.sam" bam = sdir / "mapping.sorted.bam" depth = sdir / "depth.tsv" bins = sdir / "bins" bins.mkdir(exist_ok=True) run_command(["bowtie2-build", str(contigs), str(idx)], log, dry_run=dry_run) mapcmd = ["bowtie2", "-x", str(idx), "-p", str(threads)] if r2: mapcmd.extend(["-1", str(r1), "-2", str(r2)]) else: mapcmd.extend(["-U", str(r1)]) mapcmd.extend(["-S", str(sam)]) run_command(mapcmd, log, dry_run=dry_run) run_command(["samtools", "sort", "-@", str(threads), "-o", str(bam), str(sam)], log, dry_run=dry_run) if not dry_run and sam.exists(): sam.unlink(missing_ok=True) run_command(["samtools", "index", str(bam)], log, dry_run=dry_run) run_command(["jgi_summarize_bam_contig_depths", "--outputDepth", str(depth), str(bam)], log, dry_run=dry_run) run_command(["metabat2", "-i", str(contigs), "-a", str(depth), "-o", str(bins / "bin"), "-m", "1500", "-t", str(threads)], log, dry_run=dry_run) return bins
def checkm2_step(bins: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("CHECKM2DB", "") if not tool_available("checkm2") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP CheckM2: install tool and set CHECKM2DB.\n") return cmd = tool_cmd("checkm2", "predict", "--threads", str(threads), "--input", str(bins), "--output-directory", str(out_dir), "--database_path", db) run_command(cmd, log, dry_run=dry_run)
def gtdbtk_step(bins: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("GTDBTK_DATA_PATH", "") if not tool_available("gtdbtk") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP GTDB-Tk: install tool and set GTDBTK_DATA_PATH.\n") return env = os.environ.copy() env["GTDBTK_DATA_PATH"] = db cmd = tool_cmd("gtdbtk", "classify_wf", "--genome_dir", str(bins), "--out_dir", str(out_dir), "--cpus", str(threads), "-x", "fa") run_command(cmd, log, env=env, dry_run=dry_run)
def prodigal_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, dry_run: bool) -> Optional[Path]: if not tool_available("prodigal"): return None sdir = out_dir / sample_id sdir.mkdir(parents=True, exist_ok=True) proteins = sdir / "proteins.faa" genes = sdir / "genes.fna" gff = sdir / "genes.gff" run_command(["prodigal", "-i", str(contigs), "-a", str(proteins), "-d", str(genes), "-o", str(gff), "-p", "meta", "-f", "gff", "-q"], log, dry_run=dry_run) return proteins
def eggnog_step(sample_id: str, proteins: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("EGGNOG_DATA_DIR", "") if not tool_available("emapper.py") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write(f"\nSKIP eggNOG for {sample_id}: set EGGNOG_DATA_DIR.\n") return cmd = tool_cmd("emapper.py", "-i", str(proteins), "--itype", "proteins", "-o", sample_id, "--output_dir", str(out_dir / sample_id), "--cpu", str(threads), "--data_dir", db, "--override") run_command(cmd, log, dry_run=dry_run)
def amrfinder_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, dry_run: bool) -> None: if not tool_available("amrfinder"): with log.open("a", encoding="utf-8") as fh: fh.write("\nSKIP AMRFinderPlus: tool is not installed.\n") return out_dir.mkdir(parents=True, exist_ok=True) out = out_dir / f"{sample_id}_amrfinder.tsv" cmd = tool_cmd("amrfinder", "-n", str(contigs), "--plus", "-o", str(out)) run_command(cmd, log, dry_run=dry_run)
def genomad_step(sample_id: str, contigs: Path, out_dir: Path, log: Path, threads: int, dry_run: bool) -> None: db = os.getenv("GENOMAD_DB", "") if not tool_available("genomad") or not db or not Path(db).exists(): with log.open("a", encoding="utf-8") as fh: fh.write(f"\nSKIP geNomad for {sample_id}: set GENOMAD_DB.\n") return splits = max(1, min(threads, 8)) cmd = tool_cmd("genomad", "end-to-end", "--cleanup", "--splits", str(splits), str(contigs), str(out_dir / sample_id), db) run_command(cmd, log, dry_run=dry_run)
def parse_bracken(path: Path) -> pd.Series: df = pd.read_csv(path, sep="\t") name_col = next((c for c in ["name", "taxonomy_name"] if c in df.columns), None) value_col = next((c for c in ["fraction_total_reads", "new_est_reads", "estimated_reads"] if c in df.columns), None) if name_col is None or value_col is None: raise PipelineError(f"Unexpected Bracken columns in {path.name}") s = pd.Series(pd.to_numeric(df[value_col], errors="coerce").fillna(0).values, index=df[name_col].astype(str)) if value_col != "fraction_total_reads": total = s.sum() if total > 0: s = s / total return s.groupby(level=0).sum()
# ==========================================================================# MERGED ADVANCED STATISTICS AND EXPLAINABILITY (v2)# ==========================================================================
def _normalise_rows(matrix: pd.DataFrame) -> pd.DataFrame: x = matrix.astype(float).clip(lower=0) return x.div(x.sum(axis=1).replace(0, np.nan), axis=0).fillna(0.0)
def _bh_adjust(p_values: Sequence[float]) -> np.ndarray: p = np.asarray(p_values, dtype=float) p = np.where(np.isfinite(p), p, 1.0) return multipletests(p, method="fdr_bh")[1]
def parse_bracken_counts(path: Path) -> pd.Series: """Return estimated read counts from a Bracken table.""" df = pd.read_csv(path, sep="\t") name_col = next((c for c in ["name", "taxonomy_name"] if c in df.columns), None) value_col = next((c for c in ["new_est_reads", "estimated_reads", "kraken_assigned_reads"] if c in df.columns), None) if name_col is None or value_col is None: raise PipelineError(f"Bracken count columns were not found in {path.name}") s = pd.Series(pd.to_numeric(df[value_col], errors="coerce").fillna(0).values, index=df[name_col].astype(str)) return s.groupby(level=0).sum()
def build_abundance_matrix(bracken_files: Dict[str, Path], out_dir: Path) -> Optional[pd.DataFrame]: """Build both estimated-read count and relative-abundance matrices.
Returned matrix is samples x taxa relative abundance. The estimated-read count matrix is saved separately so Chao1 is never calculated from proportions. """ if not bracken_files: return None rel_series, count_series = [], [] for sid, path in bracken_files.items(): if not path.exists(): continue s_rel = parse_bracken(path) s_rel.name = sid rel_series.append(s_rel) try: s_count = parse_bracken_counts(path) s_count.name = sid count_series.append(s_count) except Exception: pass if not rel_series: return None rel = pd.concat(rel_series, axis=1).fillna(0).T rel = _normalise_rows(rel) rel.index.name = "Sample_ID" rel.to_csv(out_dir / "species_relative_abundance.tsv", sep="\t") if count_series: counts = pd.concat(count_series, axis=1).fillna(0).T counts.index.name = "Sample_ID" counts.to_csv(out_dir / "species_estimated_reads.tsv", sep="\t") return rel
def _chao1_from_counts(values: np.ndarray) -> float: counts = np.asarray(values, dtype=float) if counts.size == 0 or not np.all(np.isfinite(counts)) or np.any(counts < 0): return np.nan # Chao1 singleton/doubleton logic requires discrete count data. if not np.allclose(counts, np.round(counts), atol=1e-8): return np.nan counts = np.round(counts).astype(int) s_obs = int(np.sum(counts > 0)) f1 = int(np.sum(counts == 1)) f2 = int(np.sum(counts == 2)) if f2 == 0: return float(s_obs + f1 * (f1 - 1) / 2.0) return float(s_obs + (f1 * f1) / (2.0 * f2))
def alpha_diversity(matrix: pd.DataFrame, metadata: pd.DataFrame, out_dir: Path, count_matrix: Optional[pd.DataFrame] = None) -> pd.DataFrame: """Alpha diversity from samples x taxa data.
Shannon and Simpson use proportions. Chao1 is calculated only from a discrete count matrix. If counts are unavailable, Chao1 is reported as NA. """ p = _normalise_rows(matrix) observed = (p > 0).sum(axis=1) shannon = -(p.where(p > 0, 1).apply(np.log) * p).sum(axis=1) simpson = 1 - (p ** 2).sum(axis=1) chao = [] if count_matrix is not None: count_matrix = count_matrix.reindex(index=matrix.index, columns=matrix.columns).fillna(0) chao = [_chao1_from_counts(count_matrix.loc[sid].values) for sid in matrix.index] else: chao = [np.nan] * len(matrix) alpha = pd.DataFrame({ "Sample_ID": matrix.index, "Observed_richness": observed.values, "Shannon": shannon.values, "Simpson": simpson.values, "Chao1": chao, }) if metadata is not None and "Group" in metadata.columns: alpha = alpha.merge(metadata[["Sample_ID", "Group"]], on="Sample_ID", how="left") alpha.to_csv(out_dir / "alpha_diversity.tsv", sep="\t", index=False)
metrics = ["Observed_richness", "Shannon", "Simpson"] if np.isfinite(alpha["Chao1"]).any(): metrics.append("Chao1") stats_rows = [] if "Group" in alpha.columns and alpha["Group"].notna().sum() >= 4: valid_groups = [g for g in alpha["Group"].dropna().astype(str).unique() if g not in {"", "NA", "nan"}] for metric in metrics: vals = [alpha.loc[alpha["Group"].astype(str) == g, metric].dropna().values for g in valid_groups] vals = [v for v in vals if len(v) > 0] if len(vals) == 2: st, pv = stats.mannwhitneyu(vals[0], vals[1], alternative="two-sided") test = "Mann-Whitney U" elif len(vals) > 2: st, pv = stats.kruskal(*vals) test = "Kruskal-Wallis" else: continue stats_rows.append({"Metric": metric, "Test": test, "Statistic": st, "P_value": pv}) if stats_rows: stat_df = pd.DataFrame(stats_rows) stat_df["FDR_BH"] = _bh_adjust(stat_df["P_value"]) stat_df.to_csv(out_dir / "alpha_diversity_group_tests.tsv", sep="\t", index=False)
fig, axes = plt.subplots(1, len(metrics), figsize=(5 * len(metrics), 4.8), squeeze=False) for ax, metric in zip(axes[0], metrics): if "Group" in alpha.columns and alpha["Group"].nunique(dropna=True) > 1: groups = [(str(g), d[metric].dropna().values) for g, d in alpha.groupby("Group")] groups = [(g, v) for g, v in groups if len(v)] ax.boxplot([v for _, v in groups], tick_labels=[g for g, _ in groups]) for i, (_, vals) in enumerate(groups, 1): jitter = np.linspace(-0.06, 0.06, len(vals)) if len(vals) > 1 else np.array([0.0]) ax.scatter(np.full(len(vals), i) + jitter, vals, s=24) ax.set_xlabel("Group") else: ax.bar(alpha["Sample_ID"], alpha[metric]) ax.tick_params(axis="x", rotation=70) ax.set_ylabel(metric.replace("_", " ")) ax.set_title(metric.replace("_", " ")) fig.tight_layout() fig.savefig(out_dir / "alpha_diversity.png", dpi=300, bbox_inches="tight") fig.savefig(out_dir / "alpha_diversity.svg", bbox_inches="tight") plt.close(fig) return alpha
def pcoa_from_distance(distance_matrix: np.ndarray, n_components: Optional[int] = None) -> Tuple[np.ndarray, np.ndarray]: """Classical PCoA retaining positive-eigenvalue axes.""" n = distance_matrix.shape[0] h = np.eye(n) - np.ones((n, n)) / n b = -0.5 * h @ (distance_matrix ** 2) @ h eigvals, eigvecs = np.linalg.eigh(b) idx = np.argsort(eigvals)[::-1] eigvals, eigvecs = eigvals[idx], eigvecs[:, idx] positive = eigvals > 1e-12 eigvals, eigvecs = eigvals[positive], eigvecs[:, positive] total_positive = eigvals.sum() explained_all = eigvals / total_positive if total_positive > 0 else np.zeros_like(eigvals) if n_components is not None: eigvals = eigvals[:n_components] eigvecs = eigvecs[:, :n_components] explained = explained_all[:n_components] else: explained = explained_all coords = eigvecs * np.sqrt(eigvals) if eigvals.size else np.zeros((n, 1)) return coords, explained
def _distance_matrix(matrix: pd.DataFrame, metric: str) -> np.ndarray: rel = _normalise_rows(matrix).values if metric == "jaccard": return squareform(pdist((rel > 0).astype(int), metric="jaccard")) if metric == "aitchison": pseudo = rel + 1e-6 clr = np.log(pseudo) - np.log(pseudo).mean(axis=1, keepdims=True) return squareform(pdist(clr, metric="euclidean")) return squareform(pdist(rel, metric="braycurtis"))
def permanova_test(distance_matrix: np.ndarray, groups: Sequence[str], permutations: int = 999, random_seed: int = 42) -> Tuple[float, float]: groups = np.asarray(groups, dtype=str) n = len(groups) unique = np.unique(groups) if n < 3 or len(unique) < 2: return np.nan, np.nan
def pseudo_f(grp: np.ndarray) -> float: ss_total = (distance_matrix ** 2).sum() / (2.0 * n) ss_within = 0.0 for g in np.unique(grp): idx = np.where(grp == g)[0] ng = len(idx) if ng > 1: sub = distance_matrix[np.ix_(idx, idx)] ss_within += (sub ** 2).sum() / (2.0 * ng) ss_among = ss_total - ss_within df_a = len(np.unique(grp)) - 1 df_w = n - len(np.unique(grp)) if df_a <= 0 or df_w <= 0 or ss_within <= 0: return np.nan return float((ss_among / df_a) / (ss_within / df_w))
observed = pseudo_f(groups) if not np.isfinite(observed): return observed, np.nan rng = np.random.default_rng(random_seed) exceed = 0 valid = 0 for _ in range(int(permutations)): f = pseudo_f(rng.permutation(groups)) if np.isfinite(f): valid += 1 exceed += int(f >= observed) p = (exceed + 1) / (valid + 1) if valid else np.nan return observed, float(p)
def _permdisp_f(distance_matrix: np.ndarray, groups: np.ndarray) -> Tuple[float, np.ndarray]: # Use all positive PCoA axes to approximate distances in the original metric space. coords, _ = pcoa_from_distance(distance_matrix, n_components=None) dists = np.zeros(len(groups), dtype=float) vals = [] for g in np.unique(groups): idx = np.where(groups == g)[0] if len(idx) == 0: continue centroid = coords[idx].mean(axis=0) dists[idx] = np.linalg.norm(coords[idx] - centroid, axis=1) vals.append(dists[idx]) if len(vals) < 2 or any(len(v) < 2 for v in vals): return np.nan, dists f, _ = stats.f_oneway(*vals) return float(f), dists
def permdisp_test(distance_matrix: np.ndarray, groups: Sequence[str], permutations: int = 999, random_seed: int = 42) -> Tuple[float, float]: """Permutation-based dispersion test.
The observed F statistic compares distances to group centroids in PCoA space. Group labels are permuted and centroid distances are recomputed for every permutation, rather than reporting a parametric ANOVA p value as a permutation p value. """ groups = np.asarray(groups, dtype=str) observed, _ = _permdisp_f(distance_matrix, groups) if not np.isfinite(observed): return observed, np.nan rng = np.random.default_rng(random_seed) exceed = 0 valid = 0 for _ in range(int(permutations)): f, _ = _permdisp_f(distance_matrix, rng.permutation(groups)) if np.isfinite(f): valid += 1 exceed += int(f >= observed) p = (exceed + 1) / (valid + 1) if valid else np.nan return observed, float(p)
def beta_diversity(matrix: pd.DataFrame, metadata: pd.DataFrame, out_dir: Path, metric: str = "bray_curtis", permutations: int = 999, random_seed: int = 42) -> Optional[pd.DataFrame]: if len(matrix) < 2: return None metric = metric if metric in {"bray_curtis", "jaccard", "aitchison"} else "bray_curtis" dist = _distance_matrix(matrix, metric) pd.DataFrame(dist, index=matrix.index, columns=matrix.index).to_csv( out_dir / f"{metric}_distance.tsv", sep="\t") coords, explained = pcoa_from_distance(dist, n_components=2) pcoa = pd.DataFrame({ "Sample_ID": matrix.index, "PCo1": coords[:, 0] if coords.shape[1] > 0 else 0.0, "PCo2": coords[:, 1] if coords.shape[1] > 1 else 0.0, }) if metadata is not None and "Group" in metadata.columns: pcoa = pcoa.merge(metadata[["Sample_ID", "Group"]], on="Sample_ID", how="left") pcoa.to_csv(out_dir / f"pcoa_{metric}.tsv", sep="\t", index=False)
tests = [] if "Group" in pcoa.columns: labels = pcoa["Group"].astype(str).values valid = ~pd.Series(labels).isin(["", "NA", "nan"]).values if valid.sum() >= 4 and len(np.unique(labels[valid])) >= 2: dsub = dist[np.ix_(valid, valid)] gsub = labels[valid] pf, pp = permanova_test(dsub, gsub, permutations=permutations, random_seed=random_seed) df, dp = permdisp_test(dsub, gsub, permutations=permutations, random_seed=random_seed) tests = [ {"Test": "PERMANOVA", "Statistic": pf, "P_value": pp, "Permutations": permutations}, {"Test": "PERMDISP", "Statistic": df, "P_value": dp, "Permutations": permutations}, ] pd.DataFrame(tests).to_csv(out_dir / f"{metric}_permanova_permdisp.tsv", sep="\t", index=False)
fig, ax = plt.subplots(figsize=(7, 5.5)) if "Group" in pcoa.columns and pcoa["Group"].nunique(dropna=True) > 1: for group, g in pcoa.groupby("Group"): ax.scatter(g["PCo1"], g["PCo2"], label=str(group), s=50) ax.legend(frameon=False) else: ax.scatter(pcoa["PCo1"], pcoa["PCo2"], s=50) e1 = explained[0] * 100 if len(explained) else 0.0 e2 = explained[1] * 100 if len(explained) > 1 else 0.0 ax.set_xlabel(f"PCo1 ({e1:.1f}%)") ax.set_ylabel(f"PCo2 ({e2:.1f}%)") ax.set_title(f"PCoA: {metric.replace('_', ' ')}") fig.tight_layout() fig.savefig(out_dir / f"pcoa_{metric}.png", dpi=300, bbox_inches="tight") fig.savefig(out_dir / f"pcoa_{metric}.svg", bbox_inches="tight") plt.close(fig) return pcoa
def clr_transform(matrix: pd.DataFrame, pseudocount: float = 1e-6) -> pd.DataFrame: """CLR for samples x features data after closure to relative abundance.""" rel = _normalise_rows(matrix) logs = np.log(rel + float(pseudocount)) return logs.sub(logs.mean(axis=1), axis=0)
def exploratory_differential(matrix: pd.DataFrame, metadata: pd.DataFrame, out_dir: Path, prevalence_threshold: float = 10.0, mean_abundance_threshold: float = 0.01, fdr_threshold: float = 0.05) -> Optional[pd.DataFrame]: """Exploratory two-group CLR + Mann-Whitney analysis.
This is explicitly labelled exploratory and is not presented as an ANCOM-BC2 or covariate-adjusted replacement. """ if metadata is None or "Group" not in metadata.columns or len(matrix) < 4: return None md = metadata.set_index("Sample_ID").reindex(matrix.index) keep_samples = md["Group"].notna() & ~md["Group"].astype(str).isin(["", "NA", "nan"]) x = matrix.loc[keep_samples].copy() md = md.loc[keep_samples] groups = list(md["Group"].astype(str).unique()) if len(groups) != 2 or min((md["Group"].astype(str) == g).sum() for g in groups) < 2: return None
rel = _normalise_rows(x) prevalence = (x > 0).mean(axis=0) * 100.0 mean_rel_pct = rel.mean(axis=0) * 100.0 keep_features = (prevalence >= float(prevalence_threshold)) & (mean_rel_pct >= float(mean_abundance_threshold)) x = x.loc[:, keep_features] if x.shape[1] == 0: return None clr = clr_transform(x) rows = [] for feature in clr.columns: a = clr.loc[md["Group"].astype(str) == groups[0], feature].values b = clr.loc[md["Group"].astype(str) == groups[1], feature].values try: stat, p = stats.mannwhitneyu(a, b, alternative="two-sided") except Exception: stat, p = np.nan, 1.0 effect = float(np.nanmean(a) - np.nanmean(b)) rows.append({ "Feature": feature, "Group_A": groups[0], "Group_B": groups[1], "CLR_mean_difference_A_minus_B": effect, "Statistic": stat, "P_value": p, "Prevalence_pct": float(prevalence[feature]), "Mean_relative_abundance_pct": float(mean_rel_pct[feature]), }) res = pd.DataFrame(rows) if res.empty: return None res["Adjusted_P_value"] = _bh_adjust(res["P_value"]) res["Significant"] = res["Adjusted_P_value"] < float(fdr_threshold) res["Direction"] = np.where( res["CLR_mean_difference_A_minus_B"] > 0, f"Higher in {groups[0]}", f"Higher in {groups[1]}" ) res = res.sort_values(["Adjusted_P_value", "P_value"]) res.to_csv(out_dir / "exploratory_clr_differential.tsv", sep="\t", index=False)
# Statistical consistency: y-axis and horizontal threshold both use adjusted p values. fig, ax = plt.subplots(figsize=(7.5, 6)) y = -np.log10(res["Adjusted_P_value"].clip(lower=1e-300)) sig = res["Significant"].values ax.scatter(res.loc[~sig, "CLR_mean_difference_A_minus_B"], y.loc[~sig], alpha=0.65, s=24) ax.scatter(res.loc[sig, "CLR_mean_difference_A_minus_B"], y.loc[sig], alpha=0.85, s=30) ax.axhline(-np.log10(float(fdr_threshold)), linestyle="--", linewidth=1) ax.axvline(0, linestyle=":", linewidth=1) ax.set_xlabel(f"CLR mean difference ({groups[0]} minus {groups[1]})") ax.set_ylabel("-log10(BH adjusted p value)") ax.set_title("Exploratory differential abundance") fig.tight_layout() fig.savefig(out_dir / "exploratory_differential_volcano.png", dpi=300, bbox_inches="tight") fig.savefig(out_dir / "exploratory_differential_volcano.svg", bbox_inches="tight") plt.close(fig) return res
def _specificity(y_true: np.ndarray, y_pred: np.ndarray) -> float: cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) if cm.shape != (2, 2): return np.nan tn, fp, fn, tp = cm.ravel() return float(tn / (tn + fp)) if (tn + fp) else np.nan
def exploratory_ml(matrix: pd.DataFrame, metadata: pd.DataFrame, out_dir: Path, random_seed: int, prevalence_threshold: float = 10.0, n_trees: int = 500, requested_folds: int = 5) -> Optional[pd.DataFrame]: """Binary Random Forest with out-of-fold metrics and held-out importance.
Performance comes only from out-of-fold predictions. Primary feature ranking is averaged permutation importance on held-out folds. SHAP from a final model is produced only as post-hoc explanatory output and is labelled accordingly. """ if metadata is None or "Group" not in metadata.columns or len(matrix) < 10: return None md = metadata.set_index("Sample_ID").reindex(matrix.index) keep = md["Group"].notna() & ~md["Group"].astype(str).isin(["", "NA", "nan"]) x = matrix.loc[keep].copy() y_raw = md.loc[keep, "Group"].astype(str) if y_raw.nunique() != 2 or y_raw.value_counts().min() < 3: return None
# Unsupervised prevalence filtering does not use class labels. prevalence = (x > 0).mean(axis=0) * 100.0 x = x.loc[:, prevalence >= float(prevalence_threshold)] if x.shape[1] < 2: return None x = clr_transform(x) le = LabelEncoder() y = le.fit_transform(y_raw) n_splits = max(2, min(int(requested_folds), int(pd.Series(y).value_counts().min()))) cv = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=int(random_seed))
oof_prob = np.full(len(y), np.nan) oof_pred = np.full(len(y), -1, dtype=int) fold_importances = [] for fold, (tr, te) in enumerate(cv.split(x, y), 1): model = RandomForestClassifier( n_estimators=int(n_trees), class_weight="balanced", random_state=int(random_seed) + fold, n_jobs=1 ) model.fit(x.iloc[tr], y[tr]) prob = model.predict_proba(x.iloc[te])[:, 1] pred = (prob >= 0.5).astype(int) oof_prob[te], oof_pred[te] = prob, pred if len(np.unique(y[te])) == 2: try: pi = permutation_importance( model, x.iloc[te], y[te], scoring="roc_auc", n_repeats=10, random_state=int(random_seed) + fold, n_jobs=1 ) fold_importances.append(pi.importances_mean) except Exception: pass
auc_roc = roc_auc_score(y, oof_prob) auc_pr = average_precision_score(y, oof_prob) metrics = pd.DataFrame([{ "n_samples": len(x), "n_features": x.shape[1], "cross_validation_folds": n_splits, "accuracy": accuracy_score(y, oof_pred), "balanced_accuracy": balanced_accuracy_score(y, oof_pred), "precision": precision_score(y, oof_pred, zero_division=0), "recall_sensitivity": recall_score(y, oof_pred, zero_division=0), "specificity": _specificity(y, oof_pred), "f1": f1_score(y, oof_pred, zero_division=0), "mcc": matthews_corrcoef(y, oof_pred), "roc_auc": auc_roc, "pr_auc": auc_pr, "brier_score": brier_score_loss(y, oof_prob), "class_0": le.classes_[0], "class_1": le.classes_[1], "performance_source": "out-of-fold predictions only", }]) metrics.to_csv(out_dir / "exploratory_ml_metrics.tsv", sep="\t", index=False)
fpr, tpr, _ = roc_curve(y, oof_prob) precision, recall, _ = precision_recall_curve(y, oof_prob) fig, ax = plt.subplots(figsize=(6, 5.5)) ax.plot(fpr, tpr, label=f"ROC AUC = {auc_roc:.3f}") ax.plot([0, 1], [0, 1], linestyle="--") ax.set_xlabel("False positive rate") ax.set_ylabel("True positive rate") ax.set_title(f"Out-of-fold ROC ({n_splits}-fold CV)") ax.legend(frameon=False) fig.tight_layout() fig.savefig(out_dir / "exploratory_ml_roc.png", dpi=300, bbox_inches="tight") fig.savefig(out_dir / "exploratory_ml_roc.svg", bbox_inches="tight") plt.close(fig)
fig, ax = plt.subplots(figsize=(6, 5.5)) ax.plot(recall, precision, label=f"PR AUC = {auc_pr:.3f}") ax.set_xlabel("Recall") ax.set_ylabel("Precision") ax.set_title("Out-of-fold precision-recall curve") ax.legend(frameon=False) fig.tight_layout() fig.savefig(out_dir / "exploratory_ml_pr_curve.png", dpi=300, bbox_inches="tight") fig.savefig(out_dir / "exploratory_ml_pr_curve.svg", bbox_inches="tight") plt.close(fig)
if fold_importances: imp = np.vstack(fold_importances) importance = pd.DataFrame({ "Feature": x.columns, "CV_permutation_importance_mean": imp.mean(axis=0), "CV_permutation_importance_SD": imp.std(axis=0, ddof=1) if imp.shape[0] > 1 else 0.0, }).sort_values("CV_permutation_importance_mean", ascending=False) importance.to_csv(out_dir / "cv_permutation_feature_importance.tsv", sep="\t", index=False) top = importance.head(20).iloc[::-1] fig, ax = plt.subplots(figsize=(8, 7)) ax.barh(top["Feature"], top["CV_permutation_importance_mean"]) ax.set_xlabel("Mean held-out permutation importance (ROC AUC decrease)") ax.set_title("Cross-validated feature importance") fig.tight_layout() fig.savefig(out_dir / "cv_permutation_feature_importance.png", dpi=300, bbox_inches="tight") fig.savefig(out_dir / "cv_permutation_feature_importance.svg", bbox_inches="tight") plt.close(fig)
# Final fit only for post-hoc explanation. It is not used for performance estimates. final_model = RandomForestClassifier( n_estimators=int(n_trees), class_weight="balanced", random_state=int(random_seed), n_jobs=1 ) final_model.fit(x, y) if SHAP_AVAILABLE: try: explainer = shap.TreeExplainer(final_model) sv = explainer.shap_values(x) if isinstance(sv, list): vals = np.asarray(sv[1]) else: vals = np.asarray(sv) if vals.ndim == 3: vals = vals[:, :, 1] if vals.ndim == 2 and vals.shape[1] == x.shape[1]: shap_imp = pd.DataFrame({ "Feature": x.columns, "Mean_abs_SHAP": np.abs(vals).mean(axis=0), }).sort_values("Mean_abs_SHAP", ascending=False) shap_imp["Interpretation"] = "Post-hoc explanation from final model fit; not independent validation" shap_imp.to_csv(out_dir / "posthoc_shap_importance.tsv", sep="\t", index=False) except Exception as exc: (out_dir / "shap_warning.txt").write_text(str(exc), encoding="utf-8") return metrics
def _load_external_abundance(path: str, orientation: str, input_type: str) -> Tuple[pd.DataFrame, Optional[pd.DataFrame]]: p = Path(path) sep = "\t" if p.suffix.lower() in {".tsv", ".txt"} else "," df = pd.read_csv(p, sep=sep, index_col=0) df = df.apply(pd.to_numeric, errors="coerce").fillna(0) # Internal orientation is samples x features. if orientation == "Taxa as rows, samples as columns": df = df.T if (df < 0).any().any(): raise PipelineError("Abundance tables cannot contain negative values.") count_matrix = None if input_type == "Counts": if not np.allclose(df.values, np.round(df.values), atol=1e-8): raise PipelineError("Input type is Counts, but non-integer values were detected.") count_matrix = df.round().astype(int) rel = _normalise_rows(df) return rel, count_matrix
def _load_external_metadata(path: Optional[str]) -> pd.DataFrame: if not path: return pd.DataFrame(columns=["Sample_ID", "Group"]) p = Path(path) sep = "\t" if p.suffix.lower() in {".tsv", ".txt"} else "," md = pd.read_csv(p, sep=sep, dtype=str).fillna("") if "Sample_ID" not in md.columns: raise PipelineError("Metadata must contain Sample_ID.") if md["Sample_ID"].duplicated().any(): raise PipelineError("Metadata contains duplicated Sample_ID values.") return md
def run_advanced_statistics(abundance_file, metadata_file, orientation, input_type, group_column, distance_metric, permutations, prevalence_threshold, mean_abundance_threshold, fdr_threshold, run_ml_flag, n_trees, n_folds, random_seed): if not abundance_file: return "Upload an abundance table.", None, None, None, None, None work = WORK_ROOT / f"stats_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}" work.mkdir(parents=True, exist_ok=True) try: rel, counts = _load_external_abundance(str(abundance_file), str(orientation), str(input_type)) md = _load_external_metadata(str(metadata_file) if metadata_file else None) if group_column and group_column in md.columns and group_column != "Group": md = md.copy() md["Group"] = md[group_column] elif "Group" not in md.columns: md["Group"] = "NA" common = [s for s in rel.index if s in set(md["Sample_ID"])] if not md.empty else [] if common: rel = rel.loc[common] if counts is not None: counts = counts.loc[common] md = md.set_index("Sample_ID").loc[common].reset_index() elif not md.empty: raise PipelineError("No Sample_ID values matched between abundance table and metadata.") else: md = pd.DataFrame({"Sample_ID": rel.index, "Group": "NA"})
rel.to_csv(work / "relative_abundance.tsv", sep="\t") if counts is not None: counts.to_csv(work / "validated_count_matrix.tsv", sep="\t") alpha = alpha_diversity(rel, md, work, count_matrix=counts) beta_diversity(rel, md, work, metric=str(distance_metric), permutations=int(permutations), random_seed=int(random_seed)) da = exploratory_differential( rel, md, work, prevalence_threshold=float(prevalence_threshold), mean_abundance_threshold=float(mean_abundance_threshold), fdr_threshold=float(fdr_threshold), ) ml = None if run_ml_flag: ml = exploratory_ml( rel, md, work, int(random_seed), prevalence_threshold=float(prevalence_threshold), n_trees=int(n_trees), requested_folds=int(n_folds), ) notes = [ f"Samples analysed: {len(rel)}", f"Features analysed: {rel.shape[1]}", f"Input type: {input_type}", f"Distance metric: {distance_metric}", f"Permutations: {int(permutations)}", "Chao1: calculated from integer counts only" if counts is not None else "Chao1: NA because a validated count matrix was not supplied", "Differential abundance: exploratory CLR + Mann-Whitney + BH FDR; not a covariate-adjusted ANCOM-BC2 substitute", "Machine-learning performance: out-of-fold only; SHAP, when present, is post-hoc explanation", ] (work / "STATISTICAL_NOTES.txt").write_text("\n".join(notes), encoding="utf-8") zip_path = make_zip(work) beta_file = work / f"{distance_metric}_permanova_permdisp.tsv" beta_df = pd.read_csv(beta_file, sep="\t") if beta_file.exists() else pd.DataFrame() status = "Advanced statistics completed. " + " ".join(notes[:4]) da_df = da.head(100) if da is not None else pd.DataFrame() ml_df = ml if ml is not None else pd.DataFrame() return status, alpha, beta_df, da_df, ml_df, str(zip_path) except Exception as exc: (work / "ERROR.txt").write_text(traceback.format_exc(), encoding="utf-8") return f"Analysis stopped: {type(exc).__name__}: {exc}", None, None, None, None, str(make_zip(work))
def metadata_dataframe(samples: List[Sample]) -> pd.DataFrame: return pd.DataFrame([ { "Sample_ID": s.sample_id, "Group": s.group, "Condition": s.condition, "Location": s.location, "Time_point": s.time_point, "Replicate": s.replicate, "Sequencing_platform": s.sequencing_platform, "Library_type": s.library_type, } for s in samples ])
def write_methods(run_dir: Path, params: dict, samples: List[Sample], completed: List[str], skipped: List[str]) -> None: db_text = "; ".join(f"{k}={os.getenv(v, 'not configured')}" for k, v in DB_ENV.items()) text = f"""# Automated methods record
Analysis was performed with {APP_TITLE} v{APP_VERSION}. The workflow was executed in {params['analysis_mode']} mode using {params['threads']} CPU threads and random seed {params['random_seed']}. Raw shotgun metagenomic reads were quality filtered with fastp using a minimum Phred score of {params['min_quality']}, a minimum retained read length of {params['min_read_length']} bp, and an absolute maximum of {params['max_n_bases']} ambiguous N bases per read. Poly-G trimming was {'enabled' if params['trim_poly_g'] else 'disabled'}. FastQC and MultiQC were used when available. Host read removal was {'enabled' if params['host_removal'] else 'not requested'}. Read based taxonomic profiling used Kraken2 with confidence {params['kraken_confidence']} and Bracken at taxonomic level {params['bracken_level']} when a Kraken2 database was configured. Assembly used MEGAHIT with a minimum contig length of {params['min_contig_length']} bp. QUAST was used for assembly quality assessment when available. Genome resolved analysis mapped cleaned reads back to contigs with Bowtie2 and SAMtools and performed MetaBAT2 binning. CheckM2 and GTDB-Tk were executed only when their external databases were configured. Gene prediction used Prodigal in metagenomic mode. eggNOG-mapper, AMRFinderPlus, and geNomad were executed when their software and databases were available. Alpha diversity included observed richness, Shannon and Simpson indices; Chao1 was calculated only when discrete estimated read counts were available. Beta diversity used {params['distance_metric'].replace('_', ' ')} distance and PCoA. Where valid groups were available, PERMANOVA and PERMDISP used {params['permutations']} label permutations. Exploratory differential abundance applied a {params['prevalence_threshold']}% prevalence filter and {params['mean_abundance_threshold']}% minimum mean relative abundance, followed by CLR transformation, two-sided Mann-Whitney testing, and Benjamini-Hochberg FDR correction at {params['fdr_threshold']}. This exploratory procedure is not presented as a covariate-adjusted replacement for ANCOM-BC2 or MaAsLin2. Random Forest performance, when run, was estimated only from stratified out-of-fold predictions on CLR-transformed features. Held-out permutation importance was used as the primary feature ranking; SHAP, when available, was generated only as post-hoc explanation from the final fitted model and not as independent validation.
Database configuration: {db_text}.
Completed modules: {', '.join(completed) if completed else 'None'}.
Skipped modules: {', '.join(skipped) if skipped else 'None'}.
All software versions, input checksums, parameter values, and database paths are stored with the run outputs.""" (run_dir / "methods.txt").write_text(text, encoding="utf-8")
def make_zip(run_dir: Path) -> Path: zip_path = run_dir.parent / f"{run_dir.name}_results.zip" with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf: for path in run_dir.rglob("*"): if path.is_file(): zf.write(path, path.relative_to(run_dir.parent)) return zip_path
def tail_log(log: Path, max_chars: int = 18000) -> str: if not log.exists(): return "" text = log.read_text(encoding="utf-8", errors="replace") return text[-max_chars:]
def run_pipeline( fastq_files, metadata_file, host_file, analysis_mode, threads, min_quality, min_read_length, max_n_bases, trim_poly_g, kraken_confidence, bracken_level, min_bracken_reads, min_contig_length, host_removal, run_statistics, run_ml, distance_metric, permutations, prevalence_threshold, mean_abundance_threshold, fdr_threshold, random_seed, dry_run,): started = time.time() run_id = f"run_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}" run_dir = WORK_ROOT / run_id input_dir = run_dir / "00_Input" input_dir.mkdir(parents=True, exist_ok=True) log = run_dir / "pipeline.log" completed: List[str] = [] skipped: List[str] = []
try: if not fastq_files: raise PipelineError("Upload at least one FASTQ or FASTQ.GZ file.") fastq_files = fastq_files if isinstance(fastq_files, list) else [fastq_files] total_upload = sum(Path(f).stat().st_size for f in fastq_files) if total_upload > MAX_UPLOAD_GB * (1024 ** 3): raise PipelineError(f"Uploaded FASTQ files total {human_bytes(total_upload)}, above the configured {MAX_UPLOAD_GB:g} GB limit.")
copied_reads = [copy_upload(f, input_dir) for f in fastq_files] upload_map = {p.name: p for p in copied_reads} copied_metadata = copy_upload(metadata_file, input_dir) if metadata_file else None copied_host = copy_upload(host_file, input_dir) if host_file else None
samples = parse_metadata(copied_metadata, upload_map) if copied_metadata else infer_samples(copied_reads) warnings = validate_inputs(samples) params = { "analysis_mode": analysis_mode, "threads": int(threads), "min_quality": int(min_quality), "min_read_length": int(min_read_length), "max_n_bases": int(max_n_bases), "trim_poly_g": bool(trim_poly_g), "kraken_confidence": float(kraken_confidence), "bracken_level": bracken_level, "min_bracken_reads": int(min_bracken_reads), "min_contig_length": int(min_contig_length), "host_removal": bool(host_removal), "run_statistics": bool(run_statistics), "run_ml": bool(run_ml), "distance_metric": str(distance_metric), "permutations": int(permutations), "prevalence_threshold": float(prevalence_threshold), "mean_abundance_threshold": float(mean_abundance_threshold), "fdr_threshold": float(fdr_threshold), "random_seed": int(random_seed), "dry_run": bool(dry_run), } (run_dir / "parameters.yaml").write_text(yaml.safe_dump(params, sort_keys=False), encoding="utf-8") metadata_df = metadata_dataframe(samples) metadata_df.to_csv(run_dir / "samplesheet_resolved.csv", index=False) input_files = copied_reads + ([copied_metadata] if copied_metadata else []) + ([copied_host] if copied_host else []) make_manifest(run_dir, samples, params, [p for p in input_files if p]) write_versions(run_dir)
cleaned: Dict[str, Tuple[Path, Optional[Path]]] = {} qc_dir = run_dir / "01_QC" all_clean_reads: List[Path] = [] for sample in samples: r1, r2 = fastp_step(sample, qc_dir / "fastp", log, int(threads), int(min_quality), int(min_read_length), int(max_n_bases), bool(trim_poly_g), bool(dry_run)) cleaned[sample.sample_id] = (r1, r2) all_clean_reads.append(r1) if r2: all_clean_reads.append(r2) completed.append("quality trimming") fastqc_multiqc_step(all_clean_reads, qc_dir, log, int(threads), bool(dry_run)) completed.append("FastQC/MultiQC")
if host_removal: if not copied_host: warnings.append("Host removal was requested but no host reference FASTA was uploaded. The step was skipped.") skipped.append("host removal") else: host_out = run_dir / "02_Host_Removal" # Build one index, then use it for all samples. To keep the command implementation simple, # host_remove_step builds per sample; this is slower but robust for small/medium Space jobs. for sid, (r1, r2) in list(cleaned.items()): cleaned[sid] = host_remove_step(sid, r1, r2, copied_host, host_out / sid, log, int(threads), bool(dry_run)) completed.append("host removal")
mode = str(analysis_mode).lower() do_taxonomy = any(k in mode for k in ["basic", "comprehensive", "complete"]) do_assembly = any(k in mode for k in ["comprehensive", "genome", "complete"]) do_genome = any(k in mode for k in ["genome", "complete"]) do_function = any(k in mode for k in ["comprehensive", "complete"])
bracken_files: Dict[str, Path] = {} if do_taxonomy: tax_dir = run_dir / "03_Taxonomy" for sid, (r1, r2) in cleaned.items(): b = kraken_step(sid, r1, r2, tax_dir, log, int(threads), float(kraken_confidence), bracken_level, int(min_bracken_reads), bool(dry_run)) if b: bracken_files[sid] = b if bracken_files: completed.append("Kraken2/Bracken taxonomy") else: skipped.append("Kraken2/Bracken taxonomy")
assemblies: Dict[str, Path] = {} if do_assembly: assembly_dir = run_dir / "04_Assembly" quast_dir = run_dir / "05_Assembly_QC" for sid, (r1, r2) in cleaned.items(): contigs = megahit_step(sid, r1, r2, assembly_dir, log, int(threads), int(min_contig_length), bool(dry_run)) if contigs and (contigs.exists() or dry_run): assemblies[sid] = contigs quast_step(sid, contigs, quast_dir, log, int(threads), int(min_contig_length), bool(dry_run)) if assemblies or dry_run: completed.append("MEGAHIT assembly") else: skipped.append("assembly")
bins_by_sample: Dict[str, Path] = {} if do_genome and assemblies: bin_dir = run_dir / "06_MAGs" for sid, contigs in assemblies.items(): r1, r2 = cleaned[sid] bins = mapping_binning_step(sid, contigs, r1, r2, bin_dir, log, int(threads), bool(dry_run)) if bins and (dry_run or any(bins.glob("*.fa"))): bins_by_sample[sid] = bins checkm2_step(bins, bin_dir / sid / "checkm2", log, int(threads), bool(dry_run)) gtdbtk_step(bins, bin_dir / sid / "gtdbtk", log, int(threads), bool(dry_run)) if bins_by_sample: completed.append("MAG binning and genome quality/taxonomy") else: skipped.append("MAG quality/taxonomy")
if (do_function or do_genome) and assemblies: gene_dir = run_dir / "07_Genes_Function" amr_dir = run_dir / "08_Resistome_Virulome" mobile_dir = run_dir / "09_Viruses_Plasmids" for sid, contigs in assemblies.items(): proteins = prodigal_step(sid, contigs, gene_dir, log, bool(dry_run)) if proteins and (proteins.exists() or dry_run): eggnog_step(sid, proteins, gene_dir / "eggnog", log, int(threads), bool(dry_run)) amrfinder_step(sid, contigs, amr_dir, log, bool(dry_run)) genomad_step(sid, contigs, mobile_dir, log, int(threads), bool(dry_run)) completed.append("gene prediction and optional functional/resistance/mobile element analysis")
abundance = None stats_dir = run_dir / "10_Statistics" stats_dir.mkdir(exist_ok=True) if bracken_files and not dry_run: abundance = build_abundance_matrix(bracken_files, stats_dir) if run_statistics and abundance is not None: count_path = stats_dir / "species_estimated_reads.tsv" count_matrix = pd.read_csv(count_path, sep="\t", index_col=0) if count_path.exists() else None alpha_diversity(abundance, metadata_df, stats_dir, count_matrix=count_matrix) beta_diversity(abundance, metadata_df, stats_dir, metric=str(distance_metric), permutations=int(permutations), random_seed=int(random_seed)) exploratory_differential( abundance, metadata_df, stats_dir, prevalence_threshold=float(prevalence_threshold), mean_abundance_threshold=float(mean_abundance_threshold), fdr_threshold=float(fdr_threshold), ) completed.append("diversity and exploratory comparative statistics") elif run_statistics: skipped.append("diversity/statistics because no Bracken abundance matrix was available")
ml_dir = run_dir / "11_Machine_Learning" ml_dir.mkdir(exist_ok=True) if run_ml and abundance is not None: ml = exploratory_ml( abundance, metadata_df, ml_dir, int(random_seed), prevalence_threshold=float(prevalence_threshold), ) if ml is not None: completed.append("exploratory machine learning") else: skipped.append("machine learning because group/sample requirements were not met") elif run_ml: skipped.append("machine learning because no taxonomic abundance matrix was available")
write_methods(run_dir, params, samples, completed, skipped) summary = { "run_id": run_id, "status": "completed", "elapsed_seconds": round(time.time() - started, 2), "sample_count": len(samples), "completed_modules": completed, "skipped_modules": skipped, "warnings": warnings, } (run_dir / "analysis_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8") zip_path = make_zip(run_dir) status_df = pd.DataFrame([ {"Category": "Run", "Item": "Run ID", "Value": run_id}, {"Category": "Run", "Item": "Samples", "Value": len(samples)}, {"Category": "Run", "Item": "Mode", "Value": analysis_mode}, {"Category": "Run", "Item": "Elapsed", "Value": f"{summary['elapsed_seconds']} s"}, {"Category": "Modules", "Item": "Completed", "Value": "; ".join(completed)}, {"Category": "Modules", "Item": "Skipped", "Value": "; ".join(skipped) or "None"}, {"Category": "Warnings", "Item": "Input/analysis warnings", "Value": "; ".join(warnings) or "None"}, ]) md = f"### Analysis completed\n**Run:** `{run_id}` \n**Samples:** {len(samples)} \n**Mode:** {analysis_mode} \n**Results:** complete run directory packaged as ZIP." return md, status_df, tail_log(log), str(zip_path)
except Exception as exc: with log.open("a", encoding="utf-8") as fh: fh.write("\nERROR\n") fh.write(traceback.format_exc()) try: zip_path = make_zip(run_dir) zip_value = str(zip_path) except Exception: zip_value = None status_df = pd.DataFrame([{"Category": "Error", "Item": type(exc).__name__, "Value": str(exc)}]) return f"### Analysis stopped\n{type(exc).__name__}: {exc}", status_df, tail_log(log), zip_value
def refresh_status(): return module_status_dataframe()
DESCRIPTION = """Upload shotgun metagenomic FASTQ files and optional metadata. The application executes a modular read based, assembly based, genome resolved, functional, resistance, mobile element, diversity, and exploratory machine learning workflow according to the selected analysis mode.
For multiple samples, upload a CSV or TSV containing at least `Sample_ID`, `Read_1`, and optionally `Read_2`, `Group`, `Condition`, `Location`, `Time_point`, `Replicate`, `Sequencing_platform`, and `Library_type`. The FASTQ file names in the metadata must match the uploaded file names.
Database dependent modules are run only when their Space environment variables point to valid mounted database directories. The app never silently downloads large scientific databases during an analysis run."""
with gr.Blocks(title=APP_TITLE) as demo: gr.Markdown(f"# {APP_TITLE}\n**Version {APP_VERSION}**\n\n{DESCRIPTION}")
with gr.Tab("Run analysis"): with gr.Row(): with gr.Column(scale=2): fastq_files = gr.File(label="FASTQ / FASTQ.GZ files", file_count="multiple", file_types=[".fastq", ".fq", ".gz"], type="filepath") metadata_file = gr.File(label="Metadata CSV/TSV (recommended for multiple samples)", file_types=[".csv", ".tsv", ".txt"], type="filepath") host_file = gr.File(label="Optional host reference FASTA", file_types=[".fa", ".fasta", ".fna", ".gz"], type="filepath") with gr.Column(scale=1): analysis_mode = gr.Dropdown( choices=["Basic", "Comprehensive", "Genome resolved", "Complete"], value="Complete", label="Analysis mode", ) threads = gr.Slider(1, max(2, min(16, os.cpu_count() or 2)), value=DEFAULT_THREADS, step=1, label="CPU threads") host_removal = gr.Checkbox(value=False, label="Remove host reads") run_statistics = gr.Checkbox(value=True, label="Run diversity/statistical summaries") run_ml = gr.Checkbox(value=False, label="Run exploratory machine learning") dry_run = gr.Checkbox(value=False, label="Dry run: write commands without executing")
with gr.Accordion("Scientific parameters", open=False): with gr.Row(): min_quality = gr.Slider(10, 35, value=20, step=1, label="Minimum base quality (fastp)") min_read_length = gr.Slider(30, 150, value=50, step=5, label="Minimum retained read length, bp") max_n_bases = gr.Slider(0, 20, value=5, step=1, label="Maximum N bases per read (absolute count)") trim_poly_g = gr.Checkbox(value=True, label="Trim poly-G") kraken_confidence = gr.Slider(0.0, 1.0, value=0.10, step=0.01, label="Kraken2 confidence") with gr.Row(): bracken_level = gr.Dropdown(choices=["P", "C", "O", "F", "G", "S"], value="S", label="Bracken taxonomic level") min_bracken_reads = gr.Slider(1, 100, value=10, step=1, label="Minimum Bracken reads") min_contig_length = gr.Slider(500, 5000, value=1000, step=100, label="Minimum assembly contig length, bp") random_seed = gr.Number(value=42, precision=0, label="Random seed") with gr.Row(): distance_metric = gr.Dropdown(choices=["bray_curtis", "jaccard", "aitchison"], value="bray_curtis", label="Beta diversity metric") permutations = gr.Slider(99, 4999, value=999, step=100, label="PERMANOVA/PERMDISP permutations") prevalence_threshold = gr.Slider(0, 100, value=10, step=1, label="Minimum prevalence, %") mean_abundance_threshold = gr.Number(value=0.01, label="Minimum mean relative abundance, %") fdr_threshold = gr.Slider(0.01, 0.25, value=0.05, step=0.01, label="FDR threshold")
run_button = gr.Button("Run metagenomics workflow", variant="primary") summary_output = gr.Markdown() status_output = gr.Dataframe(label="Run summary", interactive=False) log_output = gr.Textbox(label="Pipeline log", lines=18, max_lines=30) download_output = gr.File(label="Download complete results ZIP")
run_button.click( fn=run_pipeline, inputs=[ fastq_files, metadata_file, host_file, analysis_mode, threads, min_quality, min_read_length, max_n_bases, trim_poly_g, kraken_confidence, bracken_level, min_bracken_reads, min_contig_length, host_removal, run_statistics, run_ml, distance_metric, permutations, prevalence_threshold, mean_abundance_threshold, fdr_threshold, random_seed, dry_run, ], outputs=[summary_output, status_output, log_output, download_output], )
with gr.Tab("Advanced statistics / imported abundance"): gr.Markdown( "Use this mode for Kraken2/Bracken, MetaPhlAn, HUMAnN, functional, ARG, or other abundance tables generated externally. " "It adds corrected alpha/beta diversity, permutation PERMANOVA and PERMDISP, exploratory CLR differential analysis, and cross-validated Random Forest analysis." ) with gr.Row(): stats_abundance = gr.File(label="Abundance table CSV/TSV", file_types=[".csv", ".tsv", ".txt"], type="filepath") stats_metadata = gr.File(label="Metadata CSV/TSV", file_types=[".csv", ".tsv", ".txt"], type="filepath") with gr.Row(): stats_orientation = gr.Dropdown( choices=["Taxa as rows, samples as columns", "Samples as rows, taxa as columns"], value="Taxa as rows, samples as columns", label="Table orientation" ) stats_input_type = gr.Dropdown(choices=["Counts", "Relative abundance"], value="Counts", label="Abundance data type") stats_group = gr.Textbox(value="Group", label="Metadata grouping column") with gr.Row(): stats_distance = gr.Dropdown(choices=["bray_curtis", "jaccard", "aitchison"], value="bray_curtis", label="Beta diversity metric") stats_permutations = gr.Slider(99, 4999, value=999, step=100, label="Permutation count") stats_prev = gr.Slider(0, 100, value=10, step=1, label="Minimum prevalence, %") stats_mean = gr.Number(value=0.01, label="Minimum mean relative abundance, %") stats_fdr = gr.Slider(0.01, 0.25, value=0.05, step=0.01, label="FDR threshold") with gr.Row(): stats_run_ml = gr.Checkbox(value=False, label="Run Random Forest and explainability") stats_trees = gr.Number(value=500, precision=0, label="Random Forest trees") stats_folds = gr.Number(value=5, precision=0, label="CV folds") stats_seed = gr.Number(value=42, precision=0, label="Random seed") stats_btn = gr.Button("Run advanced statistics", variant="primary") stats_status = gr.Textbox(label="Analysis status", lines=5) stats_alpha = gr.Dataframe(label="Alpha diversity", interactive=False) stats_beta = gr.Dataframe(label="PERMANOVA and PERMDISP", interactive=False) stats_da = gr.Dataframe(label="Differential abundance results, top 100", interactive=False) stats_ml = gr.Dataframe(label="Machine learning metrics", interactive=False) stats_zip = gr.File(label="Download complete statistical results ZIP") stats_btn.click( fn=run_advanced_statistics, inputs=[ stats_abundance, stats_metadata, stats_orientation, stats_input_type, stats_group, stats_distance, stats_permutations, stats_prev, stats_mean, stats_fdr, stats_run_ml, stats_trees, stats_folds, stats_seed, ], outputs=[stats_status, stats_alpha, stats_beta, stats_da, stats_ml, stats_zip], )
with gr.Tab("System and database status"): gr.Markdown("This table shows which executables and external databases are available inside the running Space.") status_table = gr.Dataframe(value=module_status_dataframe(), interactive=False, label="Module status") refresh_button = gr.Button("Refresh status") refresh_button.click(fn=refresh_status, outputs=status_table)
with gr.Tab("Output structure"): gr.Markdown("""```run_<timestamp>_<id>/βββ 00_Input/βββ 01_QC/βββ 02_Host_Removal/βββ 03_Taxonomy/βββ 04_Assembly/βββ 05_Assembly_QC/βββ 06_MAGs/βββ 07_Genes_Function/βββ 08_Resistome_Virulome/βββ 09_Viruses_Plasmids/βββ 10_Statistics/βββ 11_Machine_Learning/βββ run_manifest.jsonβββ parameters.yamlβββ software_versions.tsvβββ database_versions.tsvβββ samplesheet_resolved.csvβββ methods.txtβββ analysis_summary.jsonβββ pipeline.log``` """)
if __name__ == "__main__": demo.queue(default_concurrency_limit=1, max_size=8).launch( server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")), show_error=True, )app.pyDeleted-1673