from __future__ import annotations import os import shutil import traceback import uuid import zipfile from datetime import datetime from pathlib import Path from typing import Dict, Optional, Sequence, Tuple import gradio as gr import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import stats from sklearn.ensemble import RandomForestClassifier from sklearn.inspection import permutation_importance from 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 from sklearn.preprocessing import LabelEncoder from statsmodels.stats.multitest import multipletests try: import shap SHAP_AVAILABLE = True except Exception: shap = None SHAP_AVAILABLE = False APP_TITLE = os.getenv("APP_TITLE", "Bulamarwa Metagenomics Tool 2") APP_VERSION = "2.0.0" WORK_ROOT = Path(os.getenv("WORK_ROOT", "/tmp/metagenome_stats_runs")).resolve() WORK_ROOT.mkdir(parents=True, exist_ok=True) class PipelineError(RuntimeError): pass 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 _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 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) 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: from scipy.spatial.distance import pdist, squareform 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]: 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) 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) 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 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_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) 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 make_zip(run_dir: Path, name: Optional[str] = None) -> Path: zip_path = run_dir.parent / f"{name or run_dir.name}.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 build_publication_package(work: Path, params: dict, notes: list, n_samples: int, n_features: int) -> Path: """Reorganise raw analysis output into a clean, publication ready package. tables/ holds every TSV produced by the analysis. figures/ holds every PNG and SVG produced by the analysis, at 300 dpi. methods.txt is wording that can be pasted into a manuscript Methods section. README.txt explains what each file is and, where relevant, which figure or table number it is likely to become in a manuscript. """ package = work / "publication_package" tables_dir = package / "tables" figures_dir = package / "figures" tables_dir.mkdir(parents=True, exist_ok=True) figures_dir.mkdir(parents=True, exist_ok=True) for tsv in work.glob("*.tsv"): shutil.copy2(tsv, tables_dir / tsv.name) for fig in list(work.glob("*.png")) + list(work.glob("*.svg")): shutil.copy2(fig, figures_dir / fig.name) methods_text = f"""# Statistical methods, Tool 2: statistics and reporting Species relative abundance data ({n_samples} samples, {n_features} features after filtering) were analysed with {APP_TITLE} v{APP_VERSION}. Alpha diversity was summarised as observed richness, the Shannon index, and the Simpson index; the Chao1 estimator was calculated only when a validated integer count matrix was supplied, otherwise it is reported as not available. Group comparisons of alpha diversity used the Mann-Whitney U test for two groups or the Kruskal-Wallis test for more than two groups, with Benjamini-Hochberg false discovery rate correction. Beta diversity used {params['distance_metric'].replace('_', ' ')} distance with principal coordinates analysis. Where at least two valid groups with four or more labelled samples were present, PERMANOVA and PERMDISP were run with {params['permutations']} label permutations. Exploratory differential abundance applied a {params['prevalence_threshold']}% prevalence filter and a {params['mean_abundance_threshold']}% minimum mean relative abundance filter, followed by centred log ratio transformation, two-sided Mann-Whitney testing, and Benjamini-Hochberg correction at a {params['fdr_threshold']} false discovery rate threshold. This procedure is exploratory and is not presented as a covariate-adjusted substitute for ANCOM-BC2 or MaAsLin2. {"A Random Forest classifier was trained on centred log ratio transformed features; performance was estimated only from stratified out-of-fold predictions, and the primary feature ranking used held-out permutation importance. SHAP values, when available, were generated from the final model fit on all data as a post-hoc explanation and are not an independent validation." if params.get('run_ml') else "Machine learning classification was not run for this dataset."} Notes on this run: {chr(10).join('- ' + n for n in notes)} All tables in tables/ and figures in figures/ are produced directly by the analysis. No values in this package have been rounded, cherry picked, or edited by hand. """ (package / "methods.txt").write_text(methods_text, encoding="utf-8") readme_lines = [ f"{APP_TITLE} v{APP_VERSION}", "Publication package contents", "", "tables/", " relative_abundance.tsv Samples x taxa relative abundance matrix used for every downstream test", " validated_count_matrix.tsv Integer counts, present only if you supplied count data (enables Chao1)", " alpha_diversity.tsv Per sample richness, Shannon, Simpson, Chao1 -> usually a supplementary table", " alpha_diversity_group_tests.tsv Group comparison test results for alpha diversity, if groups were supplied", " _distance.tsv Full pairwise beta diversity distance matrix", " pcoa_.tsv Sample coordinates on the first two PCoA axes -> usually a main figure", " _permanova_permdisp.tsv PERMANOVA and PERMDISP statistics and p values, if groups were supplied", " exploratory_clr_differential.tsv Per feature CLR mean difference, p value, and BH adjusted p value", " exploratory_ml_metrics.tsv Out-of-fold classification performance, if machine learning was run", " cv_permutation_feature_importance.tsv Held-out permutation importance per feature, if machine learning was run", " posthoc_shap_importance.tsv Post-hoc SHAP importance from the final model fit, if available", "", "figures/", " alpha_diversity.png / .svg Boxplots or bar charts of alpha diversity", " pcoa_.png / .svg PCoA ordination plot, coloured by group when available", " exploratory_differential_volcano.png/.svg Volcano plot of CLR mean difference against adjusted p value", " exploratory_ml_roc.png / .svg Out-of-fold ROC curve", " exploratory_ml_pr_curve.png / .svg Out-of-fold precision-recall curve", " cv_permutation_feature_importance.png/.svg Top features by held-out permutation importance", "", "methods.txt Wording that can be adapted directly for a manuscript Methods section.", "", "All figures are exported at 300 dpi as PNG, with an editable SVG alongside for figure preparation in Illustrator, Inkscape, or similar software.", ] (package / "README.txt").write_text("\n".join(readme_lines), encoding="utf-8") return make_zip(package, name="publication_package") 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 (for example species_relative_abundance.tsv from Tool 1).", 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) params = { "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), "run_ml": bool(run_ml_flag), } 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 the abundance table and the metadata file.") 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") raw_zip_path = make_zip(work, name=f"{work.name}_raw_results") report_zip_path = build_publication_package(work, params, notes, len(rel), rel.shape[1]) 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 = ( "Statistics completed and publication package built. " + " ".join(notes[:4]) + f" Publication package: {report_zip_path.name}" ) 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(report_zip_path) except Exception as exc: (work / "ERROR.txt").write_text(traceback.format_exc(), encoding="utf-8") try: zip_path = make_zip(work, name=f"{work.name}_error") except Exception: zip_path = None return f"Analysis stopped: {type(exc).__name__}: {exc}", None, None, None, None, (str(zip_path) if zip_path else None) DESCRIPTION = """ **Tool 2 of 2.** Upload an abundance table and metadata, typically `species_relative_abundance.tsv` (or `species_estimated_reads.tsv` for count based Chao1) and `samplesheet_resolved.csv` produced by Tool 1. This tool also accepts abundance tables from other pipelines, such as MetaPhlAn or HUMAnN, in either counts or relative abundance form. The tool runs alpha and beta diversity, permutation based PERMANOVA and PERMDISP, exploratory CLR differential abundance with FDR correction, and optional cross-validated Random Forest classification with SHAP explanation. Every run finishes by rebuilding the outputs into a `publication_package.zip` containing a `tables/` folder, a `figures/` folder, a `methods.txt` you can adapt for a manuscript, and a `README.txt` describing every file. """ with gr.Blocks(title=APP_TITLE) as demo: gr.Markdown(f"# {APP_TITLE}\n**Version {APP_VERSION}**\n\n{DESCRIPTION}") with gr.Tab("Run statistics and build report"): with gr.Row(): stats_abundance = gr.File(label="Abundance table CSV/TSV (e.g. species_relative_abundance.tsv from Tool 1)", file_types=[".csv", ".tsv", ".txt"], type="filepath") stats_metadata = gr.File(label="Metadata CSV/TSV (e.g. samplesheet_resolved.csv from Tool 1)", 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="Samples as rows, taxa as columns", label="Table orientation" ) stats_input_type = gr.Dropdown(choices=["Relative abundance", "Counts"], value="Relative abundance", 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 statistics and build publication package", 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 publication_package.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("Output structure"): gr.Markdown(""" ``` publication_package/ ├── tables/ │ ├── relative_abundance.tsv │ ├── validated_count_matrix.tsv (only if counts were supplied) │ ├── alpha_diversity.tsv │ ├── alpha_diversity_group_tests.tsv (only if groups were supplied) │ ├── _distance.tsv │ ├── pcoa_.tsv │ ├── _permanova_permdisp.tsv (only if groups were supplied) │ ├── exploratory_clr_differential.tsv │ ├── exploratory_ml_metrics.tsv (only if machine learning was run) │ ├── cv_permutation_feature_importance.tsv │ └── posthoc_shap_importance.tsv (only if SHAP is installed) ├── figures/ │ ├── alpha_diversity.png / .svg │ ├── pcoa_.png / .svg │ ├── exploratory_differential_volcano.png / .svg │ ├── exploratory_ml_roc.png / .svg │ ├── exploratory_ml_pr_curve.png / .svg │ └── cv_permutation_feature_importance.png / .svg ├── methods.txt └── README.txt ``` """) 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", "7861")), show_error=True, )