# GutPath.org & WebR: Single-Cell Architectural Specification ## Leveraging a 1-Million-Cell Gut Infection Atlas in In-Browser WebAssembly This document outlines the technical specification, memory budgets, and implementation plan for integrating the **GutPath.org** 1-million-cell annotated mucosal infection single-cell atlas into an in-browser **WebR workspace**. --- ## 1. Executive Summary & The WebAssembly Scale Challenge ### The Data Asset **GutPath.org** houses a curated single-cell RNA-seq atlas of the gastrointestinal tract during health and parasitic/bacterial/viral infections (*Cryptosporidium*, *Toxoplasma*, *Giardia*, *Salmonella*, helminths, and naive controls). The atlas encompasses approximately **1,000,000 cells** with fine-grained lineage annotations (stem, transit-amplifying, enterocytes, goblet, tuft, enteroendocrine, Paneth, innate lymphoid cells, myeloid subsets, and adaptive lymphocytes). ### The In-Browser Memory Constraint Standard 32-bit WebAssembly runtimes (including WebR) operate under strict memory caps: * **Browser Tab Ceiling:** ~2.0 to 4.0 GB total virtual memory. * **1M-Cell Raw Sparse Matrix (`dgCMatrix`):** $$1{,}000{,}000\text{ cells} \times 1{,}500\text{ detected genes/cell} = 1.5 \times 10^9\text{ non-zero entries}$$ Storing this matrix in R requires at least **18–24 GB of RAM**, making a monolithic in-browser load impossible. * **Network Payload:** An uncompressed 1M-cell matrix exceeds 10 GB; compressed it is ~2–4 GB, creating prohibitive download barriers. ### The Decoupled Solution: The GutPath Continuum Researchers and students rarely need to perform global matrix algebra on 1,000,000 cells simultaneously. By decoupling global visual querying from in-depth statistical computing, the atlas operates in WebR via **four synergistic strategies** spanning observation, annotation, and procedural simulation: ```mermaid flowchart TD Atlas[("GutPath 1M Cell Atlas
1,000,000 Cells / Curated Metadata")] --> WGL["Global WebGL Navigator
(Deck.gl / Regl - 10 MB payload)"] Atlas --> Distill["Atlas Distillation Pipeline
(HPC Pre-computation)"] WGL -->|"Filter: Infection & Lineage
Lasso Select (1.5k - 5k cells)"| S1["Strategy 1: Dynamic Cohort Slicing
Seurat v5 Sandbox (~150 MB RAM)"] Distill -->|"Replicate-Level Summation
(Gene x Mouse x CellType)"| S2["Strategy 2: On-Demand Pseudobulk
limma-voom / edgeR TMM (~30 MB RAM)"] Distill -->|"Generative Model Parameters
(Baselines + Dispersions + Modules)"| S3["Strategy 3: The GutPath Digital Twin
Procedural Synthesis & Power Sim (~45 MB RAM)"] Distill -->|"Centroid / Marker Distillation
(30k Genes x 60 Cell Types)"| S4["Strategy 4: Curated Reference Atlas
SingleR / Azimuth Transfer (~15 MB RAM)"] S1 --> WebR[("WebR Browser Workspace
(Zero Server / Total Privacy)")] S2 --> WebR S3 --> WebR S4 --> WebR ``` --- ## 2. Strategy 1: Dynamic Cohort Slicing & Visual Atlas Bridge ### 2.1 Concept & User Experience Users explore the entire 1M-cell atlas visually in GutPath's web portal using GPU-accelerated WebGL. Once a specific biological question is framed, a targeted cohort of cells is dynamically extracted and dispatched into a live WebR Seurat workspace. ```mermaid flowchart LR A["1. Explore 1M Cells
Global UMAP Canvas"] --> B["2. Metadata Filter / Lasso
e.g. Tuft Cells in Naive vs Toxo"] B --> C["3. Validation Guardrail
Selected: 3,420 cells (~48 MB)"] C --> D["4. Dispatch to WebR
Mount /home/web_user/cohort/"] D --> E["5. Live Seurat Sandbox
QC, PCA, UMAP, Marker DEG"] ``` ### 2.2 Global WebGL Visualization Layer * **Lightweight Coordinate Storage:** The full 1,000,000 cell embedding requires only two single-precision floats per cell ($X, Y$ coordinates = $8\text{ MB}$) plus cluster/infection IDs ($2\text{ MB}$). * **Rendering:** Rendered at 60 FPS using `deck.gl` (`ScatterplotLayer` with binary buffers) or `regl`. * **Selection Tools:** 1. **Faceted Filter Panel:** Select by Organ/Region (Duodenum, Jejunum, Ileum, Cecum, Colon, Mesenteric Lymph Nodes), Pathogen/Condition (*Cryptosporidium*, *Toxoplasma*, *Giardia*, Naive), Lineage, Timepoint, or Mouse Strain. 2. **Spatial Polygon/Lasso Tool:** Freehand drawing directly on the 2D UMAP projection. ### 2.3 Slicing Engine & Virtual Filesystem Mounting When the user clicks **`[ Open Selected Cohort in WebR ]`**: 1. The client-side application queries a static cloud bucket (e.g. Cloudflare R2 / S3) using **HTTP Range Requests** or a lightweight edge worker to retrieve only the binary sparse column slices for the selected cell IDs. 2. The payload (typically 8–35 MB gzipped) is written to the WebR Emscripten Virtual Filesystem: * `/home/web_user/cohort/matrix.mtx.gz` * `/home/web_user/cohort/barcodes.tsv.gz` * `/home/web_user/cohort/features.tsv.gz` * `/home/web_user/cohort/cell_metadata.csv` 3. WebR automatically launches with a tailored single-cell analysis script pre-loaded into the editor. ### 2.4 Default Analysis Script Template (`GUTPATH_COHORT_SEURAT.R`) ```R # ============================================================================== # GutPath.org - Cohort Subcluster Analysis # Cohort: Cryptosporidium vs Naive - Small Intestinal Epithelium # ============================================================================== library(tidyverse) library(Seurat) library(Matrix) library(DT) # 1. Load Filtered Cohort from Virtual Filesystem datadir <- "cohort" counts <- Read10X(data.dir = datadir) meta <- read.csv(file.path(datadir, "cell_metadata.csv"), row.names = 1) # 2. Initialize Seurat Object gut_cohort <- CreateSeuratObject(counts = counts, meta.data = meta, min.cells = 3) # 3. Quality Assessment & Filtering gut_cohort[["percent.mt"]] <- PercentageFeatureSet(gut_cohort, pattern = "^mt-") VlnPlot(gut_cohort, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), group.by = "infection_status", pt.size = 0.1) # 4. Normalization & High-Variance Feature Selection gut_cohort <- NormalizeData(gut_cohort, normalization.method = "LogNormalize", scale.factor = 10000) gut_cohort <- FindVariableFeatures(gut_cohort, selection.method = "vst", nfeatures = 2000) # 5. Dimensional Reduction (PCA & UMAP) gut_cohort <- ScaleData(gut_cohort, features = VariableFeatures(gut_cohort)) gut_cohort <- RunPCA(gut_cohort, npcs = 30, verbose = FALSE) gut_cohort <- RunUMAP(gut_cohort, dims = 1:20) # 6. Visualization Across Experimental Variables DimPlot(gut_cohort, reduction = "umap", group.by = "curated_cell_type", label = TRUE) DimPlot(gut_cohort, reduction = "umap", split.by = "infection_status") # 7. Cluster Marker & Infection Response Discovery Idents(gut_cohort) <- "infection_status" infection_degs <- FindMarkers(gut_cohort, ident.1 = "Cryptosporidium", ident.2 = "Naive", min.pct = 0.25) datatable(infection_degs, caption = "Differentially Expressed Genes: Cryptosporidium vs Naive", options = list(pageLength = 10, searchHighlight = TRUE)) %>% formatRound(columns = c("p_val", "avg_log2FC", "pct.1", "pct.2", "p_val_adj"), digits = 3) ``` ### 2.5 Memory Budget & Guardrails * **Recommended Cohort Limit:** $\le 5{,}000$ cells. * **Typical Memory Consumption:** 120–280 MB RAM. * **Protective Downsampling:** If a user selects $>8{,}000$ cells, the UI prompts: > *"You have selected 14,200 cells. To guarantee responsive WebAssembly performance without browser tab freezing, GutPath will downsample to 4,000 representative cells (stratified across conditions)."* --- ## 3. Strategy 2: On-Demand Sample $\times$ Cell-Type Pseudobulking ### 3.1 Biological & Statistical Rationale While single-cell workflows often default to cell-level Wilcoxon tests, cell-level testing treats individual cells as independent observations, creating severe **pseudoreplication** and inflated false-discovery rates (FDR) in multi-animal studies. **Pseudobulking** aggregates UMI counts across cells belonging to the same cell type within each biological replicate (individual mouse): $$\text{Count}_{g, c, m} = \sum_{k \in \text{Cells}(c, m)} Y_{g, k}$$ where $g$ is the gene, $c$ is the curated cell type, and $m$ is the mouse replicate. This transforms single-cell data into an authentic replicated bulk count matrix, unlocking the gold-standard statistical rigor of **`limma-voom`** and **`edgeR` (TMM normalization)**. ### 3.2 Dimensions & Unbeatable Performance in WebR * **Input Atlas:** 1,000,000 cells across 40 mice and 30 curated cell types. * **Pseudobulk Matrix Dimensions:** $30{,}000\text{ genes} \times (40\text{ mice} \times 30\text{ cell types}) \le 30{,}000 \times 1{,}200$. * **Typical Filtered Contrast Matrix:** When focusing on a specific cell lineage (e.g. Enterocytes across 12 infected vs 12 control mice): $$30{,}000\text{ genes} \times 24\text{ biological samples} \approx \mathbf{5.8\text{ MB uncompressed}}$$ * **Execution Time:** Linear model fitting (`lmFit`), empirical Bayes shrinkage (`eBayes`), and volcano plot rendering execute in $<2.5$ seconds in WebR! ### 3.3 Pseudobulk Data Flow ```mermaid flowchart TD A["GutPath 1M Cell Atlas"] -->|"Offline Pre-aggregation
Matrix.utils / presto"| B[("Pseudobulk Data Store
counts_pseudobulk.parquet / hdf5")] B --> C["User Contrast Selector
1. Cell Type: Tuft Cells
2. Comparison: Salmonella vs Naive"] C --> D["Instant Slice Generation
counts.tsv (24 samples) + studydesign.txt"] D --> E["Mount to WebR VFS
/home/web_user/"] E --> F["Execute Course limma/edgeR Engine
TMM, voom, eBayes, Volcano, DT"] ``` ### 3.4 Integration with Existing WebR Course Shims This strategy has **zero friction** with the existing DIY Transcriptomics architecture. The pseudobulk slice is formatted as standard `counts.tsv` and `studydesign.txt`, directly utilizing: 1. `webr_shims$DGEList` & `webr_shims$calcNormFactors` (TMM normalization). 2. `webr_shims$filterByExpr` (low-count expression filtering). 3. `webr_shims$voom`, `webr_shims$lmFit`, `webr_shims$makeContrasts`, and `webr_shims$eBayes`. 4. High-performance GPU-accelerated volcano plots and interactive `DT::datatable()` widgets. ### 3.5 Default Pseudobulk Analysis Script (`GUTPATH_PSEUDOBULK_LIMMA.R`) ```R # ============================================================================== # GutPath.org - Cell-Type-Specific Pseudobulk Differential Expression # Target: Mature Enterocytes | Comparison: Salmonella enterica vs Naive # ============================================================================== library(tidyverse) library(edgeR) library(limma) library(DT) library(plotly) # 1. Load Count Matrix and Sample Metadata counts <- read.delim("counts.tsv", row.names = 1, check.names = FALSE) targets <- read_tsv("studydesign.txt", show_col_types = FALSE) # 2. Build DGEList Container dge <- DGEList(counts = counts) # 3. Filter Lowly Expressed Genes infection_group <- factor(targets$infection_status) keep <- filterByExpr(dge, group = infection_group) dge <- dge[keep, , keep.lib.sizes = FALSE] # 4. TMM Normalization dge <- calcNormFactors(dge, method = "TMM") # 5. Formulate Linear Model Design Matrix design <- model.matrix(~ 0 + infection_group) colnames(design) <- levels(infection_group) # 6. Empirical Bayes Variance Modeling via Voom v <- voom(dge, design, plot = TRUE) fit <- lmFit(v, design) # 7. Evaluate Statistical Contrast contrast_matrix <- makeContrasts(InfectionEffect = Salmonella - Naive, levels = design) fit_contrast <- contrasts.fit(fit, contrast_matrix) fit_bayes <- eBayes(fit_contrast) # 8. Extract Differential Hits top_hits <- topTable(fit_bayes, coef = "InfectionEffect", number = Inf, sort.by = "P") top_hits_df <- as_tibble(top_hits, rownames = "geneID") # 9. Interactive Volcano Plot p <- ggplot(top_hits_df, aes(x = logFC, y = -log10(adj.P.Val), text = geneID)) + geom_point(aes(color = adj.P.Val < 0.05 & abs(logFC) > 1), alpha = 0.7, size = 1.5) + scale_color_manual(values = c("grey60", "#dc2626")) + theme_bw() + labs(title = "Salmonella Response in Mature Enterocytes (Pseudobulk)", x = "Log2 Fold Change", y = "-Log10 Adjusted P-Value") ggplotly(p, tooltip = "text") # 10. Interactive Searchable DEG Table datatable(top_hits_df %>% filter(adj.P.Val < 0.05), options = list(pageLength = 15, searchHighlight = TRUE)) %>% formatRound(columns = c("logFC", "AveExpr", "t", "P.Value", "adj.P.Val"), digits = 3) ``` --- ## 4. Strategy 3: The GutPath Digital Twin (Procedural Simulation Engine) ### 4.1 Concept & Scientific Grounding Rather than generating abstract synthetic data from arbitrary mathematical equations, **Strategy 3 creates a Digital Twin of GutPath**. An offline parameter distillation script runs on the HPC server holding the 1,000,000 cells. It fits empirical negative binomial, dispersion, and covariance models to real mucosal biology, saving the result as a tiny **~2.8 MB generative recipe** (`gutpath_digital_twin_model.rds`). Inside WebR, this recipe synthesizes arbitrary single-cell cohorts and in-silico experimental trials in **$<60\text{ milliseconds}$** with **zero network lag**. ```mermaid flowchart TD A["GutPath 1M Cell Atlas (HPC)"] -->|"One-time Empirical Extraction
(Fit Splat / Copula / Dispersion)"| B[("GutPath Digital Twin Recipe
gutpath_digital_twin_model.rds (~2.8 MB)")] B --> C["Client Browser (WebR)"] C --> D["In-Silico Single-Cell Cohorts
(4k cells synthesized in 50 ms)"] C --> E["Prospective Power Analysis
(Simulate N=3 vs N=6 mice trials)"] C --> F["Benchmarking & QA Testing
(Known Ground-Truth DEGs)"] ``` ### 4.2 Distilled Biological Components The 2.8 MB Digital Twin model encodes: 1. **Cell-Type Baselines ($\mu_{g, c}$):** Authentic expression means for 30,000 genes across all ~60 gut lineages (*Lgr5* in stem cells, *Muc2* in goblet cells, *Dclk1* in tuft cells, *Reg3g* in enterocytes). 2. **Biological Dispersion Curves ($\phi_{g, c}$):** Empirical gene-wise biological coefficient of variation (BCV) learned from real mice. 3. **Library Size & QC Distributions:** Empirical UMI count distributions (e.g., crypt stem cells ~15,000 UMIs vs. resting T cells ~2,500 UMIs) and authentic mitochondrial percentage profiles. 4. **Gene-Gene Co-Expression Modules:** The top biological correlation modules (Interferon-Stimulated Genes, Wnt/Notch differentiation cascade, antimicrobial defense, cell cycle), ensuring co-regulated genes activate together naturally. 5. **Cluster Manifolds:** Pre-calibrated 2D UMAP cluster centroids and cell spread. ### 4.3 Synergy with Strategy 2: The "Observed Hits $\rightarrow$ Power Simulator" Loop While Strategy 2 allows students to discover observed DEGs in real mice, Strategy 3 allows them to design follow-up experiments: * *"We observed 400 DEGs in Salmonella-infected enterocytes with $N=3$ mice. If we test a therapeutic candidate, what is our statistical power to detect a 50% suppression of the inflammatory signature across $N=4, 6, 8$ mice?"* * The Digital Twin answers this in-browser by procedurally generating 100 virtual cohorts and computing empirical True Positive Rates. ### 4.4 Default Digital Twin Analysis Script (`GUTPATH_DIGITAL_TWIN.R`) ```R # ============================================================================== # GutPath.org - Digital Twin Procedural Synthesis & Power Simulator # Model: GutPath 1M Mucosal Immune & Epithelial Atlas (Empirical Parameters) # ============================================================================== library(tidyverse) library(Seurat) library(limma) library(edgeR) # 1. Synthesize an Authentic Single-Cell Cohort from the Digital Twin # Generates 4,000 cells in <60 ms directly in WebAssembly RAM: gut_sim <- generate_gutpath_cohort( infection = "Cryptosporidium", # Conditions: Naive, Cryptosporidium, Salmonella, Toxoplasma tissue = "Ileum", # Region: Duodenum, Jejunum, Ileum, Colon n_cells = 4000, # Cell budget bcv_scale = 1.0, # 1.0 = exact real biological dispersion seed = 42 # Fully reproducible seed ) # 2. Authentic Seurat Quality Control & Visualization VlnPlot(gut_sim, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"), group.by = "cell_type") DimPlot(gut_sim, reduction = "umap", group.by = "cell_type", label = TRUE) FeaturePlot(gut_sim, features = c("Lgr5", "Muc2", "Dclk1", "Ifng", "Stat1")) # 3. Ground-Truth Marker Validation Idents(gut_sim) <- "cell_type" stem_degs <- FindMarkers(gut_sim, ident.1 = "Stem", min.pct = 0.25) # Compare discovered markers against known programmed ground truth: true_stem_markers <- gut_sim@misc$ground_truth_markers[["Stem"]] discovered_markers <- rownames(stem_degs %>% filter(p_val_adj < 0.05)) sensitivity <- length(intersect(discovered_markers, true_stem_markers)) / length(true_stem_markers) cat(sprintf("\n[Digital Twin Evaluation] Marker Discovery Sensitivity: %.1f%%\n", sensitivity * 100)) # 4. In-Silico Experimental Power Simulator # Test sample size power for Salmonella enterocyte response (N = 3, 5, 8 mice): power_curve <- simulate_gutpath_power( cell_type = "Mature_Enterocyte", contrast = "Salmonella_vs_Naive", n_mice = c(3, 5, 8), n_trials = 50, alpha = 0.05 ) # Plot empirical power curve plot(power_curve, main = "Statistical Power vs. Mouse Replicates (GutPath Twin)") ``` --- ## 5. Strategy 4: GutPath as an Automated Reference Atlas (SingleR / Azimuth) ### 5.1 Concept & Value Proposition Researchers frequently generate their own gut single-cell experiments (e.g. from mouse disease models or biopsies) and face steep annotation bottlenecks. By distilling GutPath’s 1M-cell curated dataset into a lightweight reference profile, external users can upload their own unannotated single-cell matrices into WebR and receive **high-confidence cell-type predictions in $<5$ seconds**. ```mermaid flowchart LR A["User Uploads Own Single-Cell Data
(10X matrix.mtx / counts.tsv)"] --> B["WebR Workspace"] C[("GutPath Curated Reference
30,000 Genes x 60 Cell Types
(~8 MB)")] --> B B --> D["webr_shims$SingleR()
Rank-Correlation Label Transfer"] D --> E["plotScoreHeatmap()
Diagnostic Classification Scores"] D --> F["Annotated User Dataset
SingleR.labels on UMAP"] ``` ### 5.2 Shared Infrastructure with Strategy 3 **The Digital Twin and Strategy 4 share the exact same underlying statistical artifact.** * Computing cell-type centroid vectors ($\mu_{g, c}$) and marker variance across the 1M cells produces the single reference matrix needed for `SingleR` label transfer ($30{,}000\text{ genes} \times 60\text{ cell types} \approx \mathbf{7.2\text{ MB}}$). * One unified distillation pipeline on the GutPath HPC server powers both **automated user classification** (`SingleR`) and **generative cohort simulation** (`Digital Twin`). ### 5.3 WebR Shim Implementation (`webr_shims$GutPathReferenceData`) We register `GutPathReferenceData()` inside `webr_shims` alongside existing `celldex` references (`MonacoImmuneData`, `MouseRNAseqData`): ```R webr_shims$GutPathReferenceData <- function(level = c("fine", "main")) { level <- match.arg(level) ref_path <- file.path("/home/web_user/.webr_lib/references", paste0("gutpath_", level, ".rds")) if (!file.exists(ref_path)) { # Auto-fetch pre-distilled reference profile on first invocation download.file("https://gutpath.org/data/references/gutpath_reference.rds", ref_path, quiet = TRUE) } readRDS(ref_path) } ``` ### 5.4 User Label Transfer Script Template (`GUTPATH_LABEL_TRANSFER.R`) ```R # ============================================================================== # GutPath.org - Automated Reference-Based Cell Type Annotation # Mapping Query scRNA-seq Data to the GutPath 1M Cell Atlas # ============================================================================== library(SingleR) library(SingleCellExperiment) library(DropletUtils) library(pheatmap) library(ggplot2) # 1. Load User's Unannotated Query Dataset query_sce <- read10xCounts("user_query_10x") # 2. Access the Pre-Distilled GutPath Mucosal Reference gutpath_ref <- GutPathReferenceData(level = "fine") # 3. Perform High-Speed Label Transfer predictions <- SingleR(test = query_sce, ref = gutpath_ref, labels = gutpath_ref$cell_type, de.method = "wilcox") # 4. Diagnostic Prediction Score Heatmap plotScoreHeatmap(predictions, main = "SingleR Prediction Confidence Scores (GutPath Reference)") # 5. Project Transferred Labels onto Query Embedding query_sce$GutPath_CellType <- predictions$labels plotUMAP(query_sce, colour_by = "GutPath_CellType") # 6. Cell Type Proportions Table as.data.frame(table(query_sce$GutPath_CellType)) %>% rename(CellType = Var1, CellCount = Freq) %>% arrange(desc(CellCount)) ``` --- ## 6. Comprehensive Architectural & Resource Comparison Matrix | Dimension | Strategy 1: Dynamic Cohort Slicing | Strategy 2: On-Demand Pseudobulk | Strategy 3: GutPath Digital Twin | Strategy 4: Automated Reference Atlas | | :--- | :--- | :--- | :--- | :--- | | **Primary Purpose** | Subclustering & exploration of specific raw cell subsets | Rigorous multi-replicate differential expression (DEG) | In-silico experiment generation & prospective power analysis | Automated cell-type annotation of external user data | | **Data Nature** | Real wet-lab cells | Real wet-lab biological replicates | Procedurally synthesized cells from empirical GutPath parameters | Curated centroids from real GutPath cells | | **Matrix Dimensions** | 30,000 genes $\times$ 1,500–5,000 cells | 30,000 genes $\times$ 12–40 samples | 30,000 genes $\times$ 4,000 cells (on demand) | 30,000 genes $\times$ 60 cell-type profiles | | **Network Transfer** | 8 – 35 MB (compressed MTX / CSV) | 1.5 – 6 MB (TSV) | **~2.8 MB (One-time recipe)** | ~7.2 MB (Pre-cached RDS) | | **WebR Memory** | 120 – 280 MB RAM | 25 – 45 MB RAM | **35 – 55 MB RAM** | 15 – 35 MB RAM | | **Execution Latency** | 10 – 25 seconds (PCA + UMAP) | $< 2.5$ seconds (TMM + eBayes) | **$< 60$ ms (Synthesis) + standard Seurat** | $< 4.0$ seconds (Spearman rank math) | | **Ground Truth** | Unknown | Unknown | **100% Known & Validated** | Pre-annotated ontology | | **Tab Crash Risk** | Zero (capped at $\le 5{,}000$ cells) | Absolutely zero | Absolutely zero | Absolutely zero | --- ## 7. Implementation Roadmap & Phased Delivery ```mermaid timeline title GutPath WebR Implementation Timeline section Phase 1: Distillation & Twin HPC parameter extraction (means, BCV, modules) : Done offline Deploy gutpath_digital_twin_model.rds : Week 1 Integrate SingleR reference & generate_gutpath_cohort() : Week 1 section Phase 2: Pseudobulk Pipeline Generate replicate-level counts across 40 mice : Week 2 Deploy contrast selector UI on GutPath : Week 2 Connect to WebR limma-voom engine : Week 3 section Phase 3: WebGL Cohort Slicing Build WebGL UMAP navigator (Deck.gl) : Week 4 Implement HTTP Range Request slice generator : Week 5 End-to-end integration with Seurat WebR sandbox : Week 6 section Phase 4: SimLab Workbench UI Add SimLab 4th track to track-switcher : Week 7 Interactive power slider controls : Week 7 ``` ### Phase 1: Unified Distillation, SingleR & Digital Twin Engine (Fastest Win) 1. **HPC Matrix Extraction:** Run one-time distillation script on GutPath cluster extracting cell-type baselines, negative binomial dispersions, and gene correlation modules. 2. **Dual-Use Asset:** Package as `gutpath_reference.rds` (for `SingleR`) and `gutpath_digital_twin_model.rds` (for simulation). 3. **WebR Engine Functions:** Register `webr_shims$GutPathReferenceData()` and `webr_shims$generate_gutpath_cohort()` in `js/src/webr/webr-engine.js`. 4. **Validation:** Confirm synthesis of 4,000 cells executes in $<60\text{ ms}$ with authentic marker expression. ### Phase 2: Pseudobulk Pipeline & Contrast Selector 1. **Replicate Pre-Aggregation:** Generate `gutpath_pseudobulk_master.tsv` ($30{,}000 \times 1{,}200$). 2. **GutPath.org Contrast Dropdown:** Allow users to pick cell type and infection comparison. 3. **WebR Handoff:** Launch WebR pre-loaded with the 24-sample slice running `voom` + `eBayes`. ### Phase 3: WebGL Cohort Slicing Bridge 1. **2D Coordinates:** Export binary float buffers for WebGL rendering at 60 FPS. 2. **Range Requests:** Implement client-side sparse matrix column slicing. 3. **Seurat Sandbox:** Connect lasso selections directly to the WebR virtual filesystem. ### Phase 4: SimLab Workbench UI Integration 1. **Track Switcher:** Add `[ 🎲 SimLab ]` alongside `[ Lectures ] [ Labs ] [ My Data ]`. 2. **Interactive Slider Card:** Provide sliders for $N$ replicates, read depth, and effect size. 3. **Contextual Jump Points:** Add *"Simulate Power in SimLab"* buttons directly to Step 5 and My Data. --- ## 8. Architectural Guarantees & Verification Gate 1. **Client-Side Privacy Invariant:** No user data or filtered cohort slices are ever uploaded to an external server; all single-cell algebra and differential modeling execute strictly within local browser memory via WebAssembly. 2. **Tier 1 & Tier 2 Search Path Isolation:** Genuine WASM packages (`Matrix`, `tidyverse`, `DT`, `plotly`) operate natively without `.GlobalEnv` shadowing, while curated shims (`SingleR`, `limma`, `edgeR`, `DigitalTwin`) reside inside `webr_shims`. 3. **Build Gate:** Any client-side code added to support these workflows must satisfy: ```bash npm run build && bundle exec jekyll build ``` with 100% passing invariant checks.