diff --git "a/app.R" "b/app.R"
--- "a/app.R"
+++ "b/app.R"
@@ -1,1258 +1,1614 @@
-import { useState, useEffect, useRef, useCallback } from "react";
-
-// ─── CONSTANTS ────────────────────────────────────────────────────────────────
-const GROQ_MODELS = [
- { id: "llama-3.1-8b-instant", label: "Llama 3.1 8B (Fast)" },
- { id: "llama-3.3-70b-versatile", label: "Llama 3.3 70B (Smart)" },
- { id: "mixtral-8x7b-32768", label: "Mixtral 8x7B" },
- { id: "gemma2-9b-it", label: "Gemma2 9B" },
-];
-
-// ─── API HELPERS ──────────────────────────────────────────────────────────────
-const API = {
- async fetchPDB(id) {
- const r = await fetch(`https://files.rcsb.org/download/${id.toUpperCase()}.pdb`);
- if (!r.ok) throw new Error("PDB not found");
- return r.text();
- },
- async fetchPDBMeta(id) {
- const r = await fetch(`https://data.rcsb.org/rest/v1/core/entry/${id.toUpperCase()}`);
- if (!r.ok) return null;
- return r.json();
- },
- async searchPDB(query) {
- const body = {
- query: { type: "terminal", service: "full_text", parameters: { value: query } },
- return_type: "entry",
- request_options: { paginate: { start: 0, rows: 8 } },
- };
- const r = await fetch("https://search.rcsb.org/rcsbsearch/v2/query", {
- method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
- });
- if (!r.ok) return [];
- const d = await r.json();
- return d.result_set || [];
- },
- async fetchAlphaFold(uid) {
- const r = await fetch(`https://alphafold.ebi.ac.uk/api/prediction/${uid}`);
- if (!r.ok) throw new Error("UniProt ID not found in AlphaFold");
- const d = await r.json();
- if (!d.length) throw new Error("No prediction available");
- return d[0];
- },
- async fetchAlphaFoldPDB(url) {
- const r = await fetch(url);
- if (!r.ok) throw new Error("Failed to download AlphaFold PDB");
- return r.text();
- },
- async searchPubChem(query, type = "name") {
- const enc = encodeURIComponent(query);
- const r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/${type}/${enc}/JSON`);
- if (!r.ok) throw new Error("Compound not found");
- const d = await r.json();
- return d.PC_Compounds || [];
- },
- async getPubChemProps(cid) {
- const props = "MolecularFormula,MolecularWeight,CanonicalSMILES,InChIKey,XLogP,TPSA,HBondDonorCount,HBondAcceptorCount,RotatableBondCount,HeavyAtomCount,Complexity,Charge";
- const r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/property/${props}/JSON`);
- if (!r.ok) throw new Error("Properties not found");
- const d = await r.json();
- return d.PropertyTable?.Properties?.[0] || null;
- },
- async getPubChemSDF(cid) {
- // Try 3D first, then 2D
- let r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/SDF?record_type=3d`);
- if (!r.ok) r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/${cid}/SDF`);
- if (!r.ok) throw new Error("SDF not found");
- return r.text();
- },
- async iupacToSMILES(name) {
- const r = await fetch(`https://cactus.nci.nih.gov/chemical/structure/${encodeURIComponent(name)}/smiles`);
- if (!r.ok) throw new Error("IUPAC conversion failed");
- return (await r.text()).trim();
- },
- async smilesToCID(smiles) {
- const r = await fetch(`https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/${encodeURIComponent(smiles)}/cids/JSON`);
- if (!r.ok) throw new Error("SMILES lookup failed");
- const d = await r.json();
- return d.IdentifierList?.CID?.[0] || null;
- },
- async callGroq(apiKey, model, messages, maxTokens = 1200) {
- const r = await fetch("https://api.groq.com/openai/v1/chat/completions", {
- method: "POST",
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
- body: JSON.stringify({ model, messages, max_tokens: maxTokens, temperature: 0.7 }),
- });
- if (!r.ok) {
- const err = await r.json().catch(() => ({}));
- throw new Error(err.error?.message || `HTTP ${r.status}`);
+# ============================================================
+# QTL-Mapper v3 — Composite Interval Mapping (CIM) + Fixed Flanking
+#
+# KEY FIXES:
+# 1. REPLACED Random Forest QTL mapping with Composite Interval Mapping (CIM)
+# - CIM fits lm(pheno ~ marker + cofactors) at each marker position
+# - Cofactors = top markers from initial RF screen (controls background)
+# - LOD = -log10(p-value of marker term)
+# - PVE computed from FULL model including cofactors → MUCH higher PVE
+#
+# 2. FIXED flanking markers
+# - Flanking search now uses the FULL marker list (not post-NZV subset)
+# - Correctly finds adjacent markers on same chromosome by sorted position
+#
+# 3. PVE FORMULA (unchanged, still correct):
+# Full model: lm(phenotype ~ a + d) [additive + dominance]
+# PVE (%) = R²_full × 100
+# Additive_Effect = beta_a, Dominance_Effect = beta_d
+# Reference: Falconer & Mackay (1996); Lynch & Walsh (1998)
+# ============================================================
+
+options(repos = c(CRAN = "https://cloud.r-project.org"))
+
+required_packages <- c(
+ "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
+ "writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
+ "shinyjs", "markdown", "base64enc"
+)
+
+for (pkg in required_packages) {
+ if (!require(pkg, character.only = TRUE)) {
+ install.packages(pkg, dependencies = TRUE)
+ library(pkg, character.only = TRUE)
+ }
+}
+
+# ============================================================
+# TOKEN / API SETUP
+# ============================================================
+token <- Sys.getenv("GROQ_API_KEY")
+token_exists <- token != ""
+token_length <- if (token_exists) nchar(token) else 0
+
+cat("=== GROQ API TOKEN DEBUG ===\n")
+cat("Token exists:", token_exists, "\n")
+cat("Token length:", token_length, "\n")
+if (token_exists) cat("Token starts with:", substr(token, 1, 10), "\n")
+cat("===================================\n")
+
+HF_API_TOKEN <- token
+HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions"
+default_model <- "llama-3.1-8b-instant"
+
+available_models <- list(
+ list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"),
+ list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"),
+ list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"),
+ list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free")
+)
+
+model_choices <- setNames(
+ sapply(available_models, function(m) m$id),
+ sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]"))
+)
+
+# ============================================================
+# CIM CORE FUNCTION
+# ============================================================
+#
+# Composite Interval Mapping (Zeng 1993, 1994):
+# For each marker m:
+# 1. Select cofactors = top K markers from RF (excluding nearby markers on same chr)
+# 2. Fit: Y ~ marker_m + cofactors (additive model)
+# 3. LOD = -log10( p-value of marker_m term )
+# 4. PVE = R²_full × 100 (full model including cofactors)
+#
+# This gives HIGHER PVE because:
+# - Cofactors absorb background genetic variance
+# - Each marker's contribution is estimated after controlling for rest
+# - Much more powerful than single-marker regression
+# ============================================================
+
+run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
+ n_cofactors = 10, window_size = 10,
+ lod_threshold = 2.0) {
+
+ markers <- colnames(genotype_matrix)
+ n_markers <- length(markers)
+ n_samples <- length(phenotype_vector)
+
+ cat("CIM: Starting with", n_markers, "markers,", n_samples, "samples\n")
+
+ # ---- Step 1: Select cofactors via RF ----
+ valid_rows <- !is.na(phenotype_vector)
+ X_valid <- genotype_matrix[valid_rows, , drop = FALSE]
+ y_valid <- phenotype_vector[valid_rows]
+
+ # Remove zero-variance markers before RF
+ nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2)
+ X_valid <- X_valid[, !nzv, drop = FALSE]
+
+ rf_model <- tryCatch(
+ randomForest(x = X_valid, y = y_valid, ntree = 500, importance = TRUE),
+ error = function(e) NULL
+ )
+
+ if (!is.null(rf_model)) {
+ imp_scores <- importance(rf_model, type = 1)[, 1]
+ top_cofactors <- names(sort(imp_scores, decreasing = TRUE))[1:min(n_cofactors * 2, length(imp_scores))]
+ } else {
+ # Fallback: single-marker regression ranking
+ p_vals <- sapply(colnames(X_valid), function(m) {
+ fit <- lm(y_valid ~ X_valid[, m])
+ coef(summary(fit))[2, 4]
+ })
+ top_cofactors <- names(sort(p_vals))[1:min(n_cofactors * 2, length(p_vals))]
+ }
+
+ cat("CIM: Selected", length(top_cofactors), "candidate cofactors\n")
+
+ # ---- Step 2: Scan each marker with CIM ----
+ results_list <- list()
+
+ for (i in seq_along(markers)) {
+ m <- markers[i]
+
+ geno <- genotype_matrix[, m]
+ valid_idx <- !is.na(geno) & !is.na(phenotype_vector)
+ geno_v <- geno[valid_idx]
+ pheno_v <- phenotype_vector[valid_idx]
+
+ if (length(unique(geno_v)) < 2 || length(pheno_v) < 5) next
+
+ # Get marker info
+ m_info <- marker_info[marker_info$Marker == m, ]
+ if (nrow(m_info) == 0) next
+ m_chr <- m_info$Chromosome[1]
+ m_pos <- m_info$Position[1]
+
+ # ---- Exclude cofactors within window_size positions on same chromosome ----
+ chr_markers <- marker_info[marker_info$Chromosome == m_chr, ]
+ chr_markers <- chr_markers[order(chr_markers$Position), ]
+ m_idx <- which(chr_markers$Marker == m)
+
+ if (length(m_idx) > 0) {
+ nearby_range <- max(1, m_idx - window_size):min(nrow(chr_markers), m_idx + window_size)
+ nearby_mks <- chr_markers$Marker[nearby_range]
+ } else {
+ nearby_mks <- m
+ }
+
+ active_cofactors <- setdiff(top_cofactors, c(m, nearby_mks))
+ active_cofactors <- active_cofactors[active_cofactors %in% colnames(genotype_matrix)]
+ active_cofactors <- head(active_cofactors, n_cofactors)
+
+ # ---- Build data frame for model ----
+ df_model <- data.frame(y = pheno_v, focal = geno_v[valid_idx])
+
+ # Add cofactors
+ if (length(active_cofactors) > 0) {
+ cof_mat <- genotype_matrix[valid_idx, active_cofactors, drop = FALSE]
+ # Handle NAs in cofactors
+ cof_mat[is.na(cof_mat)] <- 0
+ df_model <- cbind(df_model, cof_mat)
}
- const d = await r.json();
- return d.choices?.[0]?.message?.content || "";
- },
- async groqVision(apiKey, model, imageData, mimeType) {
- const messages = [{
- role: "user",
- content: [
- { type: "text", text: "This is a 2D chemical structure image. Extract and return ONLY the SMILES string for this molecule, nothing else." },
- { type: "image_url", image_url: { url: `data:${mimeType};base64,${imageData}` } },
- ],
- }];
- return this.callGroq(apiKey, model, messages, 200);
- },
- async submitITasser(apiKey, sequence, jobName) {
- const form = new FormData();
- form.append("api_key", apiKey);
- form.append("sequence", sequence);
- form.append("job_name", jobName || "MolExplorer_Job");
- const r = await fetch("https://zhanggroup.org/I-TASSER/submission/api/submit/", {
- method: "POST", body: form,
- });
- const text = await r.text();
- try { return JSON.parse(text); } catch { return { raw: text }; }
- },
- async checkITasser(apiKey, jobId) {
- const r = await fetch(`https://zhanggroup.org/I-TASSER/submission/api/status/?api_key=${apiKey}&job_id=${jobId}`);
- return r.json();
- },
-};
-
-// ─── LIPINSKI CHECK ───────────────────────────────────────────────────────────
-function checkLipinski(props) {
- if (!props) return null;
- return [
- { label: "MW ≤ 500 Da", val: props.MolecularWeight, pass: props.MolecularWeight <= 500 },
- { label: "LogP ≤ 5", val: props.XLogP, pass: props.XLogP <= 5 },
- { label: "HBD ≤ 5", val: props.HBondDonorCount, pass: props.HBondDonorCount <= 5 },
- { label: "HBA ≤ 10", val: props.HBondAcceptorCount, pass: props.HBondAcceptorCount <= 10 },
- ];
+
+ df_model <- df_model[complete.cases(df_model), ]
+ if (nrow(df_model) < 5) next
+
+ # ---- Fit CIM model ----
+ tryCatch({
+ if (length(active_cofactors) > 0) {
+ cof_formula <- paste(active_cofactors, collapse = " + ")
+ full_formula <- as.formula(paste("y ~ focal +", cof_formula))
+ } else {
+ full_formula <- as.formula("y ~ focal")
+ }
+
+ fit <- lm(full_formula, data = df_model)
+ sm <- summary(fit)
+ coef_t <- sm$coefficients
+
+ if (!"focal" %in% rownames(coef_t)) next
+
+ p_val <- coef_t["focal", "Pr(>|t|)"]
+ lod <- -log10(p_val + 1e-300) # avoid log(0)
+ r2_full <- sm$r.squared
+
+ # ---- Additive + Dominance effects (on this marker) ----
+ a_code <- df_model$focal
+ d_code <- as.numeric(a_code == 1)
+ has_het <- length(unique(d_code)) > 1
+
+ if (has_het) {
+ lm_eff <- lm(y ~ a_code + d_code, data = df_model)
+ sm_eff <- summary(lm_eff)
+ pve_ad <- sm_eff$r.squared * 100 # PVE from add+dom ALONE (marker only)
+ c_eff <- coef(lm_eff)
+ a_eff <- c_eff["a_code"]
+ d_eff <- c_eff["d_code"]
+ se_t <- sm_eff$coefficients
+ se_a <- se_t["a_code", "Std. Error"]
+ se_d <- se_t["d_code", "Std. Error"]
+ d_rat <- if (!is.na(a_eff) && a_eff != 0) abs(d_eff / a_eff) else NA
+ } else {
+ lm_eff <- lm(y ~ a_code, data = df_model)
+ sm_eff <- summary(lm_eff)
+ pve_ad <- sm_eff$r.squared * 100
+ c_eff <- coef(lm_eff)
+ a_eff <- c_eff["a_code"]
+ d_eff <- NA; se_a <- NA; se_d <- NA; d_rat <- NA
+ }
+
+ # PVE from full CIM model (marker + cofactors) — this is the HIGH PVE
+ pve_cim <- r2_full * 100
+
+ dom_class <- if (is.na(d_rat)) "Additive"
+ else if (d_rat > 1) "Overdominance"
+ else if (d_rat > 0.5) "Dominance"
+ else if (d_rat > 0.2) "Partial Dom."
+ else "Additive"
+
+ results_list[[m]] <- data.frame(
+ Marker = m,
+ Chromosome = m_chr,
+ Position = m_pos,
+ LOD = lod,
+ P_Value = p_val,
+ PVE_Marker_Percent = pve_ad, # PVE of marker alone (add+dom)
+ PVE_CIM_Percent = pve_cim, # PVE of full CIM model (marker + cofactors)
+ Additive_Effect = a_eff,
+ SE_Additive = se_a,
+ CI_Lower = ifelse(is.na(se_a), NA, a_eff - 1.96 * se_a),
+ CI_Upper = ifelse(is.na(se_a), NA, a_eff + 1.96 * se_a),
+ Dominance_Effect = d_eff,
+ SE_Dominance = se_d,
+ Dominance_Ratio = d_rat,
+ Dominance_Class = dom_class,
+ N_Cofactors = length(active_cofactors),
+ N_Samples = nrow(df_model),
+ N_Heterozygotes = sum(df_model$focal == 1),
+ stringsAsFactors = FALSE
+ )
+
+ }, error = function(e) {
+ cat("CIM error at marker", m, ":", e$message, "\n")
+ })
+ }
+
+ if (length(results_list) == 0) {
+ return(data.frame(Message = "CIM produced no results — check data format"))
+ }
+
+ cim_result <- do.call(rbind, results_list)
+ cim_result <- cim_result[order(-cim_result$LOD), ]
+ cat("CIM: Completed scan,", nrow(cim_result), "markers evaluated\n")
+ return(cim_result)
}
-// ─── VINA PREPARATION STEPS ───────────────────────────────────────────────────
-const VINA_PROTEIN_STEPS = [
- "Remove water molecules (HETATM HOH records)",
- "Remove non-standard ligands/cofactors",
- "Add missing hydrogen atoms (e.g., reduce/pdb4amber)",
- "Assign Gasteiger charges with AutoDockTools",
- "Define active site box coordinates (center_x, center_y, center_z)",
- "Convert to PDBQT format: python prepare_receptor4.py -r protein.pdb",
-];
-const VINA_LIGAND_STEPS = [
- "Obtain or draw SMILES / SDF structure",
- "Generate 3D coordinates (RDKit / OpenBabel)",
- "Add hydrogens at physiological pH: obabel -h",
- "Minimize geometry (MMFF94 / UFF force field)",
- "Assign partial charges: obabel --partialcharge gasteiger",
- "Convert to PDBQT: python prepare_ligand4.py -l ligand.sdf",
-];
-const ABINITIO_STEPS = [
- "Input: amino acid sequence (FASTA format)",
- "Fragment library generation (Rosetta ab initio)",
- "Monte Carlo sampling of conformational space",
- "Energy landscape exploration with full-atom refinement",
- "Cluster low-energy decoys → select representative structure",
- "Validate with PROCHECK / MolProbity Ramachandran analysis",
-];
-
-// ─── MOLECULE DRAW CANVAS ─────────────────────────────────────────────────────
-function MolDrawCanvas({ onSmiles }) {
- const canvasRef = useRef();
- const [drawing, setDrawing] = useState(false);
- const [paths, setPaths] = useState([]);
- const [currentPath, setCurrentPath] = useState([]);
- const [mode, setMode] = useState("draw"); // draw | erase
- const [smilesInput, setSmilesInput] = useState("");
- const [status, setStatus] = useState("");
- const [loading, setLoading] = useState(false);
-
- const getPos = (e) => {
- const rect = canvasRef.current.getBoundingClientRect();
- const clientX = e.touches ? e.touches[0].clientX : e.clientX;
- const clientY = e.touches ? e.touches[0].clientY : e.clientY;
- return { x: clientX - rect.left, y: clientY - rect.top };
- };
-
- const onDown = (e) => {
- e.preventDefault();
- setDrawing(true);
- const p = getPos(e);
- setCurrentPath([p]);
- };
- const onMove = (e) => {
- if (!drawing) return;
- e.preventDefault();
- setCurrentPath(prev => [...prev, getPos(e)]);
- };
- const onUp = () => {
- if (!drawing) return;
- setDrawing(false);
- if (mode === "erase") {
- setPaths([]);
+# ============================================================
+# FLANKING MARKER FUNCTION — FIXED
+# Uses the FULL all_markers table (not post-NZV subset)
+# ============================================================
+
+add_flanking_markers <- function(sig_df, all_markers_df) {
+ sig_df$Low_Flank <- NA_character_
+ sig_df$High_Flank <- NA_character_
+
+ for (i in 1:nrow(sig_df)) {
+ focal_marker <- sig_df$Marker[i]
+ focal_chr <- sig_df$Chromosome[i]
+ focal_pos <- sig_df$Position[i]
+
+ # Get ALL markers on same chromosome, sorted by position
+ chr_markers <- all_markers_df[all_markers_df$Chromosome == focal_chr, ]
+ chr_markers <- chr_markers[order(chr_markers$Position), ]
+
+ if (nrow(chr_markers) == 0) next
+
+ # Find position of focal marker in sorted list
+ idx <- which(chr_markers$Marker == focal_marker)
+
+ if (length(idx) > 0) {
+ sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker
+ sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker
} else {
- setPaths(prev => [...prev, currentPath]);
+ # Marker not found by name — find by closest position
+ dists <- abs(chr_markers$Position - focal_pos)
+ idx <- which.min(dists)
+ sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker
+ sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker
}
- setCurrentPath([]);
- };
-
- useEffect(() => {
- const canvas = canvasRef.current;
- const ctx = canvas.getContext("2d");
- ctx.fillStyle = "#0d1117";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- ctx.strokeStyle = "#00e5ff";
- ctx.lineWidth = 2.5;
- ctx.lineCap = "round";
- ctx.lineJoin = "round";
- [...paths, currentPath].forEach(path => {
- if (path.length < 2) return;
- ctx.beginPath();
- ctx.moveTo(path[0].x, path[0].y);
- path.slice(1).forEach(p => ctx.lineTo(p.x, p.y));
- ctx.stroke();
- });
- }, [paths, currentPath]);
-
- const predictFromDrawing = async () => {
- if (paths.length === 0) { setStatus("Draw a molecule first."); return; }
- setLoading(true); setStatus("Converting drawing to base64...");
- const canvas = canvasRef.current;
- const dataUrl = canvas.toDataURL("image/png");
- const b64 = dataUrl.split(",")[1];
- setSmilesInput(b64.substring(0, 20) + "…");
- setStatus("⚠️ Vision prediction requires Groq API key in AI tab.");
- setLoading(false);
- onSmiles && onSmiles({ type: "drawing", b64, mimeType: "image/png" });
- };
-
- const lookupSmiles = async () => {
- if (!smilesInput.trim()) return;
- setLoading(true); setStatus("Looking up SMILES in PubChem…");
- try {
- const cid = await API.smilesToCID(smilesInput.trim());
- if (!cid) throw new Error("Not found");
- setStatus(`✓ Found CID: ${cid}`);
- onSmiles && onSmiles({ type: "smiles", smiles: smilesInput.trim(), cid });
- } catch (e) {
- setStatus("✗ " + e.message);
- } finally { setLoading(false); }
- };
-
- return (
-
-
- {["draw","erase"].map(m => (
- setMode(m)} style={{
- padding: "6px 14px", borderRadius: 6, border: "none", cursor: "pointer",
- background: mode === m ? "#00e5ff" : "#1e2736", color: mode === m ? "#0d1117" : "#8892a4",
- fontWeight: 600, fontSize: 12, textTransform: "uppercase",
- }}>{m === "draw" ? "✏️ Draw" : "🗑 Clear"}
- ))}
-
-
-
- Draw a 2D structural formula above, then predict its 3D structure
-
-
- {loading ? "⏳ Processing…" : "🔮 Predict 3D from Drawing"}
-
-
- setSmilesInput(e.target.value)}
- placeholder="Or enter SMILES directly…"
- style={{ ...inputStyle, flex: 1, fontSize: 12 }} />
-
- Lookup
-
-
- {status &&
{status}
}
-
- );
+ }
+
+ return(sig_df)
+}
+
+# ============================================================
+# API / AI FUNCTIONS (unchanged)
+# ============================================================
+
+test_api_connection <- function(model_id = default_model) {
+ if (!token_exists) return(list(success = FALSE, error = "No token found"))
+ tryCatch({
+ response <- POST(
+ url = HF_API_URL,
+ add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"),
+ body = toJSON(list(model = model_id, messages = list(list(role = "user", content = "Hi")), max_tokens = 10L), auto_unbox = TRUE),
+ encode = "json", timeout(15))
+ if (status_code(response) == 200) return(list(success = TRUE))
+ err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response)))
+ list(success = FALSE, error = paste("Status:", status_code(response), "-", substr(err, 1, 200)))
+ }, error = function(e) list(success = FALSE, error = e$message))
}
-// ─── STYLE HELPERS ────────────────────────────────────────────────────────────
-const inputStyle = {
- background: "#1e2736", border: "1px solid #2d3748", borderRadius: 8,
- color: "#e2e8f0", padding: "9px 12px", fontSize: 13, outline: "none", width: "100%", boxSizing: "border-box",
-};
-const btnStyle = (bg = "#00e5ff", col = "#0d1117") => ({
- background: bg, color: col, border: "none", borderRadius: 8, padding: "9px 16px",
- cursor: "pointer", fontWeight: 700, fontSize: 13, width: "100%",
-});
-const cardStyle = { background: "#111827", border: "1px solid #1e2736", borderRadius: 12, padding: 16, marginBottom: 12 };
-const labelStyle = { fontSize: 11, color: "#8892a4", textTransform: "uppercase", letterSpacing: 1, marginBottom: 6, display: "block" };
-const propRow = { display: "flex", justifyContent: "space-between", padding: "5px 0", borderBottom: "1px solid #1a2233", fontSize: 12 };
-
-// ─── NOTIFICATION ──────────────────────────────────────────────────────────────
-function Toast({ msg, type, onClose }) {
- useEffect(() => { const t = setTimeout(onClose, 4000); return () => clearTimeout(t); }, [msg]);
- const colors = { success: "#4ade80", error: "#f87171", warning: "#f59e0b", info: "#60a5fa" };
- if (!msg) return null;
- return (
-
- {msg}
- ✕
-
- );
+api_test <- test_api_connection(default_model)
+use_hf_api <- token_exists && api_test$success
+
+cat("API Test:", if (api_test$success) "SUCCESS" else paste("FAILED -", api_test$error), "\n")
+
+query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
+ if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
+ tryCatch({
+ response <- POST(
+ url = HF_API_URL,
+ add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"),
+ body = toJSON(list(
+ model = model_id,
+ messages = list(
+ list(role = "system", content = "You are an expert bioinformatics assistant specializing in QTL analysis using Composite Interval Mapping. Be concise and helpful."),
+ list(role = "user", content = prompt)),
+ max_tokens = as.integer(max_length), temperature = temperature), auto_unbox = TRUE),
+ encode = "json", timeout(60))
+ if (status_code(response) == 200) {
+ result <- content(response, as = "parsed", encoding = "UTF-8")
+ return(list(success = TRUE, text = result$choices[[1]]$message$content))
+ }
+ err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response)))
+ list(success = FALSE, error = paste("API error:", status_code(response), "-", substr(err, 1, 200)))
+ }, error = function(e) list(success = FALSE, error = e$message))
}
-// ─── VIEWER PLACEHOLDER ───────────────────────────────────────────────────────
-function Viewer3D({ pdbText, sdfText, label }) {
- // Embed NGL/3Dmol via iframe with postMessage since we can't import them directly
- const iframeRef = useRef();
- const [loaded, setLoaded] = useState(false);
-
- const htmlContent = `
-
-
-
-
-
-`;
-
- const srcUrl = `data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`;
-
- useEffect(() => {
- if (!loaded) return;
- const iframe = iframeRef.current;
- const sendMsg = (msg) => iframe?.contentWindow?.postMessage(msg, "*");
- if (pdbText && sdfText) sendMsg({ type: "loadBoth", pdb: pdbText, sdf: sdfText });
- else if (pdbText) sendMsg({ type: "loadPDB", data: pdbText });
- else if (sdfText) sendMsg({ type: "loadSDF", data: sdfText });
- }, [pdbText, sdfText, loaded]);
-
- useEffect(() => {
- const handler = (e) => { if (e.data?.type === "ready") setLoaded(true); };
- window.addEventListener("message", handler);
- return () => window.removeEventListener("message", handler);
- }, []);
-
- return (
-
-
- {!loaded && (
-
- Loading 3Dmol.js viewer…
-
- )}
- {loaded && !pdbText && !sdfText && (
-
-
🧬
-
{label || "Load a structure to visualize"}
-
- )}
-
- );
+
+ paste0("👋 Vanakam! TerraByte-AI here (CIM mode).\n\n",
+ "Ask me about:\n• **PVE / CIM** — how variance is explained\n",
+ "• **Top QTLs** — flanking markers included\n• **Model performance**\n",
+ "• **What is CIM?** — Composite Interval Mapping explained\n\n",
+ "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
}
-// ═══════════════════════════════════════════════════════════════════════════════
-// MAIN APP
-// ═══════════════════════════════════════════════════════════════════════════════
-export default function MolExplorer() {
- const [activeTab, setActiveTab] = useState("protein");
-
- // ─── State ─────────────────────────────────────────────────────────────────
- const [protein, setProtein] = useState({ pdb: null, meta: null, id: null, source: null });
- const [ligand, setLigand] = useState({ sdf: null, props: null, cid: null, name: null });
- const [groqKey, setGroqKey] = useState("");
- const [groqKeyInput, setGroqKeyInput] = useState("");
- const [groqModel, setGroqModel] = useState("llama-3.1-8b-instant");
- const [apiStatus, setApiStatus] = useState("unchecked");
- const [chatHistory, setChatHistory] = useState([]);
- const [chatInput, setChatInput] = useState("");
- const [chatLoading, setChatLoading] = useState(false);
- const [itasserKey, setItasserKey] = useState("");
- const [itasserSeq, setItasserSeq] = useState("");
- const [itasserJobName, setItasserJobName] = useState("");
- const [itasserJobId, setItasserJobId] = useState("");
- const [itasserStatus, setItasserStatus] = useState(null);
- const [toast, setToast] = useState({ msg: "", type: "info" });
- const [loading, setLoading] = useState({});
- const chatEndRef = useRef();
-
- // Protein sub-state
- const [pdbInput, setPdbInput] = useState("");
- const [pdbSearch, setPdbSearch] = useState("");
- const [pdbResults, setPdbResults] = useState([]);
- const [afInput, setAfInput] = useState("");
- const [afInfo, setAfInfo] = useState(null);
-
- // Ligand sub-state
- const [pubQuery, setPubQuery] = useState("");
- const [pubType, setPubType] = useState("name");
- const [pubResults, setPubResults] = useState([]);
- const [iupacInput, setIupacInput] = useState("");
- const [molImageFile, setMolImageFile] = useState(null);
- const [smileDraw, setSmileDraw] = useState(null);
-
- // Docking state
- const [dockBox, setDockBox] = useState({ cx: 0, cy: 0, cz: 0, sx: 20, sy: 20, sz: 20, exhaustiveness: 8 });
- const [dockResult, setDockResult] = useState(null);
-
- const notify = (msg, type = "info") => setToast({ msg, type });
-
- const setLoad = (key, val) => setLoading(prev => ({ ...prev, [key]: val }));
-
- // ─── PROTEIN: Load PDB ──────────────────────────────────────────────────────
- const loadPDB = async (id) => {
- if (!id) return;
- setLoad("pdb", true);
- try {
- const [pdb, meta] = await Promise.all([API.fetchPDB(id), API.fetchPDBMeta(id)]);
- setProtein({ pdb, meta, id: id.toUpperCase(), source: "PDB" });
- notify(`✓ Loaded PDB: ${id.toUpperCase()}`, "success");
- } catch (e) { notify("✗ " + e.message, "error"); }
- finally { setLoad("pdb", false); }
- };
-
- // ─── PROTEIN: AlphaFold ─────────────────────────────────────────────────────
- const loadAlphaFold = async () => {
- if (!afInput.trim()) return;
- setLoad("af", true);
- try {
- const info = await API.fetchAlphaFold(afInput.trim());
- const pdb = await API.fetchAlphaFoldPDB(info.pdbUrl);
- setAfInfo(info);
- setProtein({ pdb, meta: { alphafold: info }, id: afInput.trim().toUpperCase(), source: "AlphaFold" });
- notify(`✓ AlphaFold structure loaded: ${afInput.trim()}`, "success");
- } catch (e) { notify("✗ " + e.message, "error"); }
- finally { setLoad("af", false); }
- };
-
- // ─── PROTEIN: Search PDB ────────────────────────────────────────────────────
- const searchPDB = async () => {
- if (!pdbSearch.trim()) return;
- setLoad("pdbSearch", true);
- try {
- const res = await API.searchPDB(pdbSearch);
- setPdbResults(res);
- } catch (e) { notify("Search failed: " + e.message, "error"); }
- finally { setLoad("pdbSearch", false); }
- };
-
- // ─── LIGAND: PubChem search ─────────────────────────────────────────────────
- const searchPubChem = async () => {
- if (!pubQuery.trim()) return;
- setLoad("pub", true);
- try {
- const res = await API.searchPubChem(pubQuery, pubType);
- setPubResults(res);
- notify(`Found ${res.length} compound(s)`, "success");
- } catch (e) { notify("✗ " + e.message, "error"); }
- finally { setLoad("pub", false); }
- };
-
- const loadCompoundByCID = async (cid) => {
- setLoad(`cid_${cid}`, true);
- try {
- const [props, sdf] = await Promise.all([API.getPubChemProps(cid), API.getPubChemSDF(cid)]);
- setLigand({ sdf, props, cid, name: props?.MolecularFormula || cid });
- notify(`✓ Loaded CID: ${cid}`, "success");
- } catch (e) { notify("✗ " + e.message, "error"); }
- finally { setLoad(`cid_${cid}`, false); }
- };
-
- // ─── LIGAND: IUPAC to 3D ────────────────────────────────────────────────────
- const iupacTo3D = async () => {
- if (!iupacInput.trim()) return;
- setLoad("iupac", true);
- try {
- const smiles = await API.iupacToSMILES(iupacInput);
- const cid = await API.smilesToCID(smiles);
- if (!cid) throw new Error("Compound not found in PubChem");
- await loadCompoundByCID(cid);
- } catch (e) { notify("✗ " + e.message, "error"); }
- finally { setLoad("iupac", false); }
- };
-
- // ─── LIGAND: Image → 3D ─────────────────────────────────────────────────────
- const predictFromImage = async () => {
- if (!molImageFile) { notify("Upload an image first", "warning"); return; }
- if (!groqKey) { notify("Set Groq API key in AI tab first", "warning"); return; }
- setLoad("imgPredict", true);
- try {
- const b64 = await new Promise((res, rej) => {
- const fr = new FileReader();
- fr.onload = () => res(fr.result.split(",")[1]);
- fr.onerror = rej;
- fr.readAsDataURL(molImageFile);
+generate_ai_response <- function(user_message, rv, model_id = default_model) {
+ if (token_exists) {
+ context <- build_system_prompt(rv)
+ prompt <- paste("CONTEXT:", context, "\n\nUSER:", user_message,
+ "\n\nAnswer specifically using the context above. Be concise.")
+ result <- query_hf_api(prompt, model_id = model_id)
+ if (result$success) return(result$text)
+ }
+ enhanced_rule_response(user_message, rv)
+}
+
+# ============================================================
+# UI
+# ============================================================
+
+ui <- fluidPage(
+ shinyjs::useShinyjs(),
+ tags$head(
+ tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
+ tags$link(rel = "stylesheet", href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"),
+ tags$script(HTML("
+ function simulateQTLDiscovery() {
+ setTimeout(function() {
+ const markers = document.querySelectorAll('.chromosome-marker');
+ let delay = 0;
+ markers.forEach(function(marker) {
+ setTimeout(function() {
+ marker.classList.add('highlighted');
+ setTimeout(function() { marker.classList.add('pulse'); }, 300);
+ }, delay);
+ delay += 100;
+ });
+ }, 100);
+ }
+ function resetAnimation() {
+ const markers = document.querySelectorAll('.chromosome-marker');
+ markers.forEach(function(marker) {
+ marker.classList.remove('highlighted', 'pulse');
+ });
+ }
+ Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(m) { simulateQTLDiscovery(); });
+ Shiny.addCustomMessageHandler('resetAnimation', function(m) { resetAnimation(); });
+ Shiny.addCustomMessageHandler('scrollChatBottom', function(m) {
+ setTimeout(function() {
+ var cb = document.getElementById('chat_messages');
+ if (cb) cb.scrollTop = cb.scrollHeight;
+ }, 100);
});
- const smiles = await API.groqVision(groqKey, "meta-llama/llama-4-maverick-17b-128e-instruct", b64, molImageFile.type);
- const cleaned = smiles.trim().replace(/[^A-Za-z0-9@+\-=\/\\()[\]#.%]/g, "");
- notify(`Extracted SMILES: ${cleaned.substring(0, 40)}…`, "info");
- const cid = await API.smilesToCID(cleaned);
- if (!cid) throw new Error("Could not match SMILES to PubChem compound");
- await loadCompoundByCID(cid);
- notify("✓ 3D structure predicted from image!", "success");
- } catch (e) { notify("✗ " + e.message, "error"); }
- finally { setLoad("imgPredict", false); }
- };
-
- // ─── LIGAND: Draw SMILES lookup ─────────────────────────────────────────────
- const handleDrawSmiles = async (data) => {
- if (data.type === "smiles" && data.cid) {
- await loadCompoundByCID(data.cid);
- } else if (data.type === "drawing" && data.b64) {
- if (!groqKey) { notify("Set Groq API key in AI tab for vision prediction", "warning"); return; }
- setLoad("drawPredict", true);
- try {
- const smiles = await API.groqVision(groqKey, "meta-llama/llama-4-maverick-17b-128e-instruct", data.b64, data.mimeType);
- const cleaned = smiles.trim().replace(/[^A-Za-z0-9@+\-=\/\\()[\]#.%]/g, "");
- const cid = await API.smilesToCID(cleaned);
- if (!cid) throw new Error("Could not map to PubChem");
- await loadCompoundByCID(cid);
- notify("✓ Structure predicted from drawing!", "success");
- } catch (e) { notify("✗ " + e.message, "error"); }
- finally { setLoad("drawPredict", false); }
+ $(document).on('keydown', '#chat_input', function(e) {
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('#send_chat').click(); }
+ });
+ ")),
+ tags$style(HTML("
+ :root {
+ --bg-primary:#0d1117;--bg-secondary:#161b22;--bg-tertiary:#21262d;
+ --border:#30363d;--text-primary:#e6edf3;--text-secondary:#8b949e;
+ --text-muted:#6e7681;--accent:#58a6ff;--accent-hover:#79c0ff;
+ --success:#3fb950;--warning:#d29922;--danger:#f85149;
+ --purple:#bc8cff;--teal:#39d353;
+ --font-mono:'IBM Plex Mono',monospace;--font-sans:'IBM Plex Sans',sans-serif;
+ }
+ *{box-sizing:border-box;margin:0;padding:0;}
+ body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;}
+ .navbar{background:var(--bg-secondary)!important;border-bottom:1px solid var(--border);}
+ .navbar-brand{color:var(--text-primary)!important;font-family:var(--font-mono);font-weight:600;}
+ .navbar-nav>li>a{color:var(--text-secondary)!important;font-size:13px;}
+ .navbar-nav>li.active>a,.navbar-nav>li>a:hover{color:var(--accent)!important;background:transparent!important;}
+ .main-header{background:linear-gradient(135deg,#1c2b3a,#0d1117);border:1px solid var(--border);border-left:3px solid var(--accent);padding:20px 24px;border-radius:6px;margin-bottom:20px;}
+ .main-header h2{font-family:var(--font-mono);font-size:1.3rem;font-weight:600;color:var(--accent);}
+ .main-header p{color:var(--text-secondary);margin-top:6px;font-size:13px;}
+ .cim-box{background:#0d1a0d;border:1px solid var(--success);border-left:3px solid var(--success);border-radius:6px;padding:12px 16px;margin:10px 0;font-family:var(--font-mono);font-size:12px;color:#7ee787;}
+ .cim-box .box-title{font-weight:600;color:var(--success);margin-bottom:6px;}
+ .card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;margin-bottom:20px;}
+ .card-header{background:var(--bg-tertiary);border-bottom:1px solid var(--border);padding:12px 16px;font-family:var(--font-mono);font-size:12px;color:var(--text-secondary);letter-spacing:.5px;text-transform:uppercase;}
+ .card-body{padding:16px;}
+ .form-control,.selectize-input{background:var(--bg-tertiary)!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:4px;font-size:13px;}
+ .form-control:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px rgba(88,166,255,.2)!important;}
+ label{color:var(--text-secondary);font-size:12px;margin-bottom:4px;}
+ .btn{border-radius:4px;font-family:var(--font-mono);font-size:12px;font-weight:600;transition:all .15s;border:1px solid;}
+ .btn-primary{background:var(--accent);border-color:var(--accent);color:#0d1117;}
+ .btn-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:#0d1117;}
+ .btn-info{background:transparent;border-color:var(--teal);color:var(--teal);}
+ .btn-info:hover{background:var(--teal);color:#0d1117;}
+ .btn-danger{background:transparent;border-color:var(--danger);color:var(--danger);}
+ .btn-danger:hover{background:var(--danger);color:white;}
+ .help-block{color:var(--text-muted);font-size:11px;margin-top:4px;}
+ .dataTables_wrapper{color:var(--text-secondary)!important;}
+ table.dataTable{background:var(--bg-secondary)!important;color:var(--text-primary)!important;border-color:var(--border)!important;}
+ table.dataTable thead th{background:var(--bg-tertiary)!important;color:var(--text-secondary)!important;border-bottom:1px solid var(--border)!important;font-family:var(--font-mono);font-size:11px;letter-spacing:.5px;}
+ table.dataTable tbody tr:hover{background:var(--bg-tertiary)!important;}
+ table.dataTable tbody td{border-bottom:1px solid var(--border)!important;font-size:12px;}
+ .dataTables_info,.dataTables_length,.dataTables_filter,.dataTables_paginate{color:var(--text-muted)!important;font-size:12px;}
+ .dataTables_filter input,.dataTables_length select{background:var(--bg-tertiary)!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;}
+ .paginate_button{color:var(--text-secondary)!important;}
+ .paginate_button.current{background:var(--accent)!important;color:#0d1117!important;border-color:var(--accent)!important;}
+ .chromosome-container{margin:12px 0;padding:12px 16px;background:var(--bg-tertiary);border-radius:4px;border:1px solid var(--border);}
+ .chromosome{height:24px;background:linear-gradient(to right,var(--bg-primary),var(--border));border-radius:12px;margin:8px 0;position:relative;overflow:hidden;border:1px solid var(--border);}
+ .chromosome-marker{position:absolute;height:34px;width:6px;background:var(--text-muted);border-radius:3px;top:-5px;transform:translateX(-50%);transition:all .3s ease;}
+ .chromosome-marker.significant{background:var(--danger)!important;height:40px!important;width:8px!important;top:-8px!important;}
+ .chromosome-marker.flanking{background:var(--accent)!important;height:30px!important;width:5px!important;top:-3px!important;}
+ .chromosome-marker.selection{background:var(--success)!important;}
+ .chromosome-marker.highlighted{background:var(--warning)!important;box-shadow:0 0 10px rgba(210,153,34,.6);}
+ .chromosome-marker.pulse{animation:pulse 1.5s infinite;}
+ @keyframes pulse{0%,100%{transform:translateX(-50%) scale(1);}50%{transform:translateX(-50%) scale(1.3);opacity:.7;}}
+ .chromosome-legend{display:flex;justify-content:space-between;font-size:10px;color:var(--text-muted);font-family:var(--font-mono);margin-top:2px;}
+ .chromosome-title{font-family:var(--font-mono);font-size:11px;color:var(--accent);margin-bottom:4px;}
+ #chat-panel{position:fixed;bottom:20px;right:20px;z-index:9999;width:440px;display:flex;flex-direction:column;}
+ #chat-toggle-btn{align-self:flex-end;width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--purple));border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 20px rgba(88,166,255,.4);transition:all .2s;color:#0d1117;font-size:24px;}
+ #chat-toggle-btn:hover{transform:scale(1.05);}
+ #chat-window{display:none;flex-direction:column;background:var(--bg-secondary);border:1px solid var(--accent);border-radius:12px;overflow:hidden;box-shadow:0 8px 40px rgba(0,0,0,.5);margin-bottom:10px;height:640px;}
+ #chat-window.open{display:flex;}
+ #chat-header{background:linear-gradient(135deg,var(--bg-tertiary),#1c2b3a);border-bottom:1px solid var(--border);padding:12px 16px;display:flex;flex-direction:column;gap:8px;}
+ .chat-header-top{display:flex;align-items:center;justify-content:space-between;}
+ .chat-title{display:flex;align-items:center;gap:10px;}
+ .chat-avatar{width:32px;height:32px;background:linear-gradient(135deg,var(--accent),var(--purple));border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:16px;color:#0d1117;font-weight:bold;flex-shrink:0;}
+ #chat-header h4{font-family:var(--font-mono);font-size:13px;font-weight:600;color:var(--text-primary);margin:0;}
+ #chat-header p{font-size:11px;color:var(--text-muted);margin:0;}
+ #chat-header p.ai-mode{color:var(--success);}
+ #chat-close-btn{background:none;border:none;color:var(--text-muted);cursor:pointer;font-size:18px;padding:4px;transition:color .15s;}
+ #chat-close-btn:hover{color:var(--text-primary);}
+ .chat-model-selector{display:flex;align-items:center;gap:8px;padding:4px 0;}
+ .chat-model-selector label{color:var(--text-muted);font-size:10px;font-family:var(--font-mono);white-space:nowrap;margin:0;}
+ .chat-model-selector select{flex:1;background:var(--bg-primary)!important;border:1px solid var(--border)!important;color:var(--text-secondary)!important;border-radius:4px;font-size:11px;font-family:var(--font-mono);padding:3px 6px;}
+ .model-status-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0;}
+ .model-status-dot.online{background:var(--success);box-shadow:0 0 6px var(--success);}
+ .model-status-dot.offline{background:var(--warning);box-shadow:0 0 6px var(--warning);}
+ .test-model-btn{background:transparent;border:1px solid var(--border);color:var(--text-muted);border-radius:3px;padding:2px 7px;font-size:10px;font-family:var(--font-mono);cursor:pointer;transition:all .15s;white-space:nowrap;}
+ .test-model-btn:hover{border-color:var(--accent);color:var(--accent);}
+ #chat_messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;background:var(--bg-primary);}
+ .chat-msg{max-width:92%;animation:fadeIn .3s ease;}
+ @keyframes fadeIn{from{opacity:0;transform:translateY(10px);}to{opacity:1;transform:translateY(0);}}
+ .chat-msg.user{align-self:flex-end;}
+ .chat-msg.assistant{align-self:flex-start;}
+ .chat-bubble{padding:12px 16px;border-radius:16px;font-size:13px;line-height:1.6;word-wrap:break-word;white-space:pre-wrap;}
+ .chat-msg.user .chat-bubble{background:linear-gradient(135deg,var(--accent),#3a7bd5);color:#0d1117;border-bottom-right-radius:4px;}
+ .chat-msg.assistant .chat-bubble{background:var(--bg-tertiary);color:var(--text-primary);border:1px solid var(--border);border-bottom-left-radius:4px;}
+ .chat-bubble strong{color:var(--accent);}
+ .chat-meta{font-size:10px;color:var(--text-muted);margin-top:4px;font-family:var(--font-mono);padding:0 4px;display:flex;align-items:center;gap:6px;}
+ .chat-meta .model-tag{color:var(--purple);font-size:9px;}
+ .typing-indicator{display:flex;gap:4px;padding:12px 16px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:16px;border-bottom-left-radius:4px;width:fit-content;}
+ .typing-dot{width:8px;height:8px;background:var(--text-muted);border-radius:50%;animation:typingBounce 1.4s infinite;}
+ .typing-dot:nth-child(2){animation-delay:.2s;}
+ .typing-dot:nth-child(3){animation-delay:.4s;}
+ @keyframes typingBounce{0%,60%,100%{transform:translateY(0);}30%{transform:translateY(-8px);}}
+ .quick-questions{padding:8px 16px;display:flex;flex-wrap:wrap;gap:6px;border-bottom:1px solid var(--border);background:var(--bg-secondary);}
+ .quick-q-btn{background:var(--bg-tertiary);border:1px solid var(--border);color:var(--text-secondary);border-radius:16px;padding:4px 12px;font-size:11px;cursor:pointer;transition:all .15s;}
+ .quick-q-btn:hover{border-color:var(--accent);color:var(--accent);background:rgba(88,166,255,.1);}
+ #chat-footer{padding:12px 16px;border-top:1px solid var(--border);background:var(--bg-tertiary);}
+ #chat_input{width:100%;background:var(--bg-secondary)!important;border:1px solid var(--border)!important;border-radius:8px;color:var(--text-primary)!important;font-size:13px;resize:none;padding:10px 12px;font-family:var(--font-sans);margin-bottom:8px;}
+ #chat_input:focus{border-color:var(--accent)!important;outline:none;}
+ .chat-actions{display:flex;gap:8px;}
+ #send_chat{flex:1;background:linear-gradient(135deg,var(--accent),#3a7bd5);color:#0d1117;border:none;border-radius:6px;padding:8px 16px;font-family:var(--font-mono);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;display:flex;align-items:center;justify-content:center;gap:6px;}
+ #send_chat:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 4px 12px rgba(88,166,255,.4);}
+ #send_chat:disabled{opacity:.5;cursor:not-allowed;}
+ #clear_chat{background:transparent;color:var(--text-muted);border:1px solid var(--border);border-radius:6px;padding:8px 12px;font-family:var(--font-mono);font-size:12px;cursor:pointer;transition:all .15s;}
+ #clear_chat:hover{border-color:var(--danger);color:var(--danger);}
+ "))
+ ),
+
+ navbarPage(
+ title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px;color:#58a6ff;"), "QTL-Mapper CIM"),
+ id = "nav",
+
+ # ---- DATA UPLOAD ----
+ tabPanel("Data Upload", icon = icon("upload"),
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload — CIM Mode"),
+ p("Composite Interval Mapping: higher power, correct flanking markers, better PVE estimation")
+ ),
+ fluidRow(
+ column(12,
+ div(class = "cim-box",
+ div(class = "box-title", tags$i(class = "fas fa-chart-line", style = "margin-right:6px;"), "CIM Method + PVE Formula"),
+ tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;",
+ "Composite Interval Mapping (Zeng 1993, 1994):\n",
+ " For each marker m:\n",
+ " 1. Cofactors = top K markers from RF (excluding nearby markers ±window on same chr)\n",
+ " 2. Fit: lm(Y ~ marker_m + cofactors) → LOD = -log10(p_marker)\n",
+ " 3. PVE_CIM (%) = R²_full × 100 [marker + cofactors — higher than single-marker PVE]\n",
+ " 4. PVE_marker (%) = R² from lm(Y ~ a + d) [marker alone, add+dom model]\n\n",
+ "Flanking fix: uses FULL marker table (not post-NZV subset)\n",
+ "Ref: Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)")
+ )
+ )
+ ),
+ fluidRow(
+ column(4,
+ div(class = "card",
+ div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"),
+ div(class = "card-body",
+ fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("Row1=header(id,markers), Row2=chromosomes, Row3=positions, rest=samples. Coded 0/1/2."),
+ fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("id column + numeric trait columns."),
+ selectInput("phenotype_column", "Select Phenotype Column", choices = NULL)
+ )
+ )
+ ),
+ column(4,
+ div(class = "card",
+ div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px;color:#bc8cff;"), "CIM Parameters"),
+ div(class = "card-body",
+ sliderInput("test_size", "Validation Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
+ numericInput("lod_threshold","LOD Threshold", value = 2.0, min = 0.5, max = 10.0, step = 0.1),
+ numericInput("n_cofactors", "CIM Cofactors (K)", value = 10, min = 1, max = 30, step = 1),
+ helpText("More cofactors = better background control, slower. Try 5-15."),
+ numericInput("window_size", "Exclusion Window (±markers)", value = 10, min = 1, max = 30, step = 1),
+ helpText("Nearby markers excluded from cofactors to avoid collinearity."),
+ actionButton("run_analysis", "Run CIM Analysis", class = "btn-primary btn-block", icon = icon("play"))
+ )
+ )
+ ),
+ column(4,
+ div(class = "card",
+ div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px;color:#3fb950;"), "Test Data (Optional)"),
+ div(class = "card-body",
+ fileInput("test_genotype_file", "Test Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("Same format as training genotype."),
+ tags$br(),
+ fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("Columns: id, population (e.g. Domesticated/Wild)."),
+ actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
+ )
+ )
+ )
+ ),
+ fluidRow(
+ column(12,
+ div(class = "card",
+ div(class = "card-header", "Data Preview"),
+ div(class = "card-body",
+ tabsetPanel(
+ tabPanel("Training Genotype", DTOutput("geno_preview")),
+ tabPanel("Training Phenotype", DTOutput("pheno_preview")),
+ tabPanel("Test Genotype", DTOutput("test_geno_preview")),
+ tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview"))
+ )
+ )
+ )
+ )
+ )
+ ),
+
+ # ---- RESULTS ----
+ tabPanel("Results", icon = icon("chart-line"),
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "CIM Results"),
+ p("LOD genome scan, flanking markers, additive + dominance PVE, model performance")
+ ),
+ fluidRow(
+ column(6, div(class = "card", div(class = "card-header", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
+ column(6, div(class = "card",
+ div(class = "card-header", "Chromosome Visualization"),
+ div(class = "card-body",
+ uiOutput("chromosome_viz"),
+ div(style = "margin:12px 0;display:flex;gap:8px;",
+ actionButton("simulate_btn", "Simulate Discovery", class = "btn-info"),
+ actionButton("reset_btn", "Reset", class = "btn-danger")
+ )
+ )
+ ))
+ ),
+ fluidRow(
+ column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
+ column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
+ column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
+ ),
+ fluidRow(
+ column(12, div(class = "card",
+ div(class = "card-header", "CIM QTL Effects — All markers scanned (Additive + Dominance PVE)"),
+ div(class = "card-body",
+ DTOutput("qtl_effects_table_train"),
+ tags$br(),
+ downloadButton("download_train_results", "Download CIM Results (.xlsx)")
+ )
+ ))
+ ),
+ fluidRow(
+ column(12, div(class = "card",
+ div(class = "card-header", "Epistasis Analysis"),
+ div(class = "card-body",
+ DTOutput("epistasis_table"),
+ plotlyOutput("epistasis_heatmap", height = "400px")
+ )
+ ))
+ )
+ ),
+
+ # ---- DOMESTICATION ----
+ tabPanel("Domestication", icon = icon("leaf"),
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
+ p("Fst, Tajima's D, nucleotide diversity — needs population metadata")
+ ),
+ fluidRow(
+ column(4,
+ div(class = "card",
+ div(class = "card-header", "Parameters"),
+ div(class = "card-body",
+ numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
+ numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
+ actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
+ )
+ )
+ ),
+ column(8,
+ div(class = "card",
+ div(class = "card-header", "Population Data Preview"),
+ div(class = "card-body", DTOutput("pop_preview"))
+ )
+ )
+ ),
+ fluidRow(
+ column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
+ column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"),div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
+ ),
+ fluidRow(
+ column(12,
+ div(class = "card",
+ div(class = "card-header", "Selection Signatures"),
+ div(class = "card-body",
+ DTOutput("selection_table"),
+ tags$br(),
+ downloadButton("download_selection", "Download Selection Results")
+ )
+ )
+ )
+ )
+ ),
+
+ # ---- INTERPRETATION ----
+ tabPanel("Interpretation", icon = icon("lightbulb"),
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
+ p("CIM QTL interpretation: PVE_marker vs PVE_CIM, flanking regions, dominance class")
+ ),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
+ fluidRow(
+ column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
+ column(6, div(class = "card", div(class = "card-header", "Effect Sizes (Add + Dom)"), div(class = "card-body", uiOutput("effect_interpretation"))))
+ ),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
+ ),
+
+ # ---- ABOUT ----
+ tabPanel("About", icon = icon("info-circle"),
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper CIM v3")
+ ),
+ fluidRow(
+ column(8, offset = 2,
+ div(class = "card",
+ div(class = "card-body",
+ h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin-bottom:12px;", "What Changed in v3"),
+ div(class = "cim-box",
+ tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;",
+ "FIX 1 — PVE now reports two values:\n",
+ " PVE_Marker_% = R² from lm(y ~ a + d) [marker alone]\n",
+ " PVE_CIM_% = R² from lm(y ~ marker + cofactors) [full CIM model]\n",
+ " → PVE_CIM is always ≥ PVE_Marker; often much higher\n\n",
+ "FIX 2 — Flanking markers fixed:\n",
+ " OLD: used colnames(X_train) after NZV removal → flanking lookup FAILED\n",
+ " NEW: uses all_markers table (full set before NZV removal)\n",
+ " Position-based fallback if marker not found by name\n\n",
+ "METHOD — Composite Interval Mapping (Zeng 1993, PNAS):\n",
+ " For each marker: fit lm(Y ~ focal_marker + K_cofactors)\n",
+ " Cofactors selected by RF importance, excluding nearby markers\n",
+ " LOD = -log10(p-value of focal marker term)\n",
+ " This controls background genetic variance → higher power & PVE")
+ ),
+ h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin:16px 0 8px;", "Thresholds"),
+ tags$ul(style = "color:#8b949e;line-height:2;",
+ tags$li("LOD > 2: Suggestive QTL | LOD > 3: Significant | LOD > 5: Highly significant"),
+ tags$li("PVE_CIM > 20%: Major QTL | 10-20%: Moderate | <10%: Minor"),
+ tags$li("|d/a| > 1: Overdominance | ~1: Complete dominance | <0.5: Additive"),
+ tags$li("Fst > 0.2: Strong differentiation | Tajima's D < -2: Selective sweep")
+ )
+ )
+ )
+ )
+ )
+ )
+ ),
+
+ # ============================================================
+ # FLOATING CHAT
+ # ============================================================
+ tags$div(id = "chat-panel",
+ tags$div(id = "chat-window",
+ tags$div(id = "chat-header",
+ tags$div(class = "chat-header-top",
+ tags$div(class = "chat-title",
+ tags$div(class = "chat-avatar", "AI"),
+ tags$div(
+ tags$h4("QTL-CIM AI Assistant"),
+ tags$p(id = "model_status_text",
+ if (token_exists) "AI mode ready" else "Rule-based mode",
+ class = if (token_exists) "ai-mode" else "")
+ )
+ ),
+ tags$button(id = "chat-close-btn",
+ onclick = "document.getElementById('chat-window').classList.remove('open');",
+ tags$i(class = "fas fa-times"))
+ ),
+ tags$div(class = "chat-model-selector",
+ tags$label(tags$i(class = "fas fa-robot"), " Model:"),
+ tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")),
+ selectInput("selected_model", label = NULL, choices = model_choices, selected = default_model, width = "100%"),
+ actionButton("test_model_btn", "Test", class = "test-model-btn")
+ )
+ ),
+ tags$div(class = "quick-questions",
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE in CIM?',{priority:'event'});", "PVE / CIM"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show top QTLs',{priority:'event'});", "Top QTLs"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show flanking markers',{priority:'event'});", "Flanking"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R²")
+ ),
+ tags$div(id = "chat_messages", uiOutput("chat_display")),
+ tags$div(id = "chat-footer",
+ tags$textarea(id = "chat_input", placeholder = "Ask about CIM results... (Enter to send)", rows = "2"),
+ tags$div(class = "chat-actions",
+ actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
+ actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
+ )
+ )
+ ),
+ tags$button(id = "chat-toggle-btn",
+ onclick = "document.getElementById('chat-window').classList.toggle('open');",
+ tags$i(class = "fas fa-robot"))
+ )
+)
+
+# ============================================================
+# SERVER
+# ============================================================
+
+server <- function(input, output, session) {
+
+ values <- reactiveValues(
+ genotype_data = NULL,
+ phenotype_data = NULL,
+ test_genotype_data = NULL,
+ predicted_test_phenotype_data = NULL,
+ all_markers = NULL,
+ chromosome_info = NULL,
+ position_info = NULL,
+ cim_all = NULL, # Full CIM scan results
+ qtl_effects_train = NULL, # Significant QTLs with flanking
+ performance_metrics = NULL,
+ train_predictions = NULL,
+ test_predictions = NULL,
+ epistasis_all = NULL,
+ epistasis_sig = NULL,
+ pop_data = NULL,
+ selection_metrics = NULL,
+ model_fit = NULL,
+ chat_messages = list(),
+ is_typing = FALSE,
+ lod_threshold = 2,
+ current_model = default_model
+ )
+
+ # ---- Model selector ----
+ observe({
+ req(input$selected_model)
+ values$current_model <- input$selected_model
+ })
+
+ observeEvent(input$test_model_btn, {
+ req(input$selected_model)
+ add_message("assistant", paste0("⏳ Testing model: **", input$selected_model, "**..."))
+ result <- test_api_connection(input$selected_model)
+ if (result$success) {
+ add_message("assistant", paste0("✅ **", input$selected_model, "** is working!"))
+ shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot online';")
+ } else {
+ add_message("assistant", paste0("❌ Failed: ", result$error))
+ shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot offline';")
+ }
+ })
+
+ # ---- Chat helpers ----
+ add_message <- function(role, content, model_used = NULL) {
+ values$chat_messages <- c(values$chat_messages,
+ list(list(role = role, content = content,
+ time = format(Sys.time(), "%H:%M"), model = model_used)))
+ if (length(values$chat_messages) > 100)
+ values$chat_messages <- tail(values$chat_messages, 100)
+ session$sendCustomMessage("scrollChatBottom", list())
+ }
+
+ process_message <- function(user_text) {
+ if (nchar(trimws(user_text)) == 0) return()
+ add_message("user", user_text)
+ values$is_typing <- TRUE
+ model_id <- isolate(values$current_model)
+ response <- generate_ai_response(user_text, values, model_id = model_id)
+ values$is_typing <- FALSE
+ add_message("assistant", response, model_used = if (token_exists) gsub(".*/", "", model_id) else NULL)
+ }
+
+ observeEvent(input$send_chat, {
+ user_text <- trimws(input$chat_input)
+ if (nchar(user_text) == 0) return()
+ updateTextAreaInput(session, "chat_input", value = "")
+ process_message(user_text)
+ })
+
+ observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
+ observeEvent(input$clear_chat, {
+ values$chat_messages <- list()
+ add_message("assistant", "Chat cleared. How can I help?")
+ })
+
+ observe({
+ if (length(values$chat_messages) == 0) {
+ add_message("assistant", paste0(
+ "👋 Vanakam! TerraByte-AI (CIM v3)\n\n",
+ "**What's new:**\n",
+ "• CIM (Composite Interval Mapping) — higher PVE, better power\n",
+ "• Flanking markers fixed — uses full marker table\n",
+ "• Two PVE values: PVE_marker (add+dom alone) & PVE_CIM (full model)\n\n",
+ "Upload data and run CIM analysis to get started!\n",
+ "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org"
+ ))
}
- };
-
- // ─── AI: Save & test Groq key ───────────────────────────────────────────────
- const saveGroqKey = async () => {
- if (!groqKeyInput.trim()) return;
- setLoad("apiTest", true);
- try {
- const res = await API.callGroq(groqKeyInput.trim(), "llama-3.1-8b-instant",
- [{ role: "user", content: "Reply with just: OK" }], 5);
- if (res) {
- setGroqKey(groqKeyInput.trim());
- setApiStatus("ok");
- notify("✓ Groq API key verified!", "success");
+ })
+
+ output$chat_display <- renderUI({
+ msgs <- values$chat_messages
+ if (length(msgs) == 0) return(NULL)
+ elems <- lapply(msgs, function(msg) {
+ content_html <- HTML(gsub("\n", " ", htmltools::htmlEscape(msg$content)))
+ div(class = paste("chat-msg", msg$role),
+ div(class = "chat-bubble", content_html),
+ div(class = "chat-meta",
+ span(msg$time),
+ if (!is.null(msg$model) && msg$role == "assistant")
+ span(class = "model-tag", paste0("[", msg$model, "]"))
+ )
+ )
+ })
+ if (values$is_typing) {
+ elems <- c(elems, list(div(class = "chat-msg assistant",
+ div(class = "typing-indicator",
+ div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")))))
+ }
+ do.call(tagList, elems)
+ })
+
+ # ============================================================
+ # DATA LOADING
+ # ============================================================
+
+ observeEvent(input$genotype_file, {
+ req(input$genotype_file)
+ tryCatch({
+ all_data <- readLines(input$genotype_file$datapath)
+ if (length(all_data) < 4) { showNotification("Need ≥4 rows", type = "error"); return() }
+ header <- strsplit(all_data[1], ",")[[1]]
+ chromosome_row <- strsplit(all_data[2], ",")[[1]]
+ position_row <- strsplit(all_data[3], ",")[[1]]
+ genotype_data <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), header = FALSE)
+ colnames(genotype_data) <- header
+ rownames(genotype_data) <- genotype_data[, 1]
+ genotype_data <- genotype_data[, -1]
+ for (col in colnames(genotype_data))
+ genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
+ values$genotype_data <- genotype_data
+ values$chromosome_info <- chromosome_row[-1]
+ values$position_info <- suppressWarnings(as.numeric(position_row[-1]))
+ values$all_markers <- data.frame(
+ Marker = colnames(genotype_data),
+ Chromosome = chromosome_row[-1],
+ Position = suppressWarnings(as.numeric(position_row[-1])),
+ stringsAsFactors = FALSE)
+ showNotification(paste("Loaded", ncol(genotype_data), "markers,", nrow(genotype_data), "samples"), type = "message")
+ add_message("assistant", paste0("✅ Genotype: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
+ }, error = function(e) showNotification(paste("Geno error:", e$message), type = "error"))
+ })
+
+ observeEvent(input$phenotype_file, {
+ req(input$phenotype_file)
+ tryCatch({
+ pd <- read.csv(input$phenotype_file$datapath)
+ rownames(pd) <- pd[, 1]; pd <- pd[, -1]
+ for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]]))
+ values$phenotype_data <- pd
+ updateSelectInput(session, "phenotype_column", choices = colnames(pd), selected = colnames(pd)[1])
+ showNotification(paste("Loaded", ncol(pd), "traits"), type = "message")
+ add_message("assistant", paste0("✅ Phenotype: **", ncol(pd), " traits**, **", nrow(pd), " samples**"))
+ }, error = function(e) showNotification(paste("Pheno error:", e$message), type = "error"))
+ })
+
+ observeEvent(input$pop_file, {
+ req(input$pop_file)
+ tryCatch({
+ pd <- read.csv(input$pop_file$datapath)
+ if (!all(c("id", "population") %in% colnames(pd))) {
+ showNotification("Need 'id' and 'population' columns", type = "error"); return()
+ }
+ values$pop_data <- pd
+ showNotification(paste("Population data:", nrow(pd), "samples"), type = "message")
+ }, error = function(e) showNotification(paste("Pop error:", e$message), type = "error"))
+ })
+
+ observeEvent(input$test_genotype_file, {
+ req(input$test_genotype_file)
+ tryCatch({
+ all_data <- readLines(input$test_genotype_file$datapath)
+ header <- strsplit(all_data[1], ",")[[1]]
+ gd <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), header = FALSE)
+ colnames(gd) <- header; rownames(gd) <- gd[, 1]; gd <- gd[, -1]
+ for (col in colnames(gd)) gd[[col]] <- as.numeric(as.character(gd[[col]]))
+ values$test_genotype_data <- gd
+ showNotification("Test genotype loaded", type = "message")
+ }, error = function(e) showNotification(paste("Test geno error:", e$message), type = "error"))
+ })
+
+ output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
+
+ # ============================================================
+ # MAIN CIM ANALYSIS
+ # ============================================================
+
+ observeEvent(input$run_analysis, {
+ req(values$genotype_data, values$phenotype_data, input$phenotype_column)
+ showNotification("Starting CIM analysis...", type = "message")
+ values$lod_threshold <- input$lod_threshold
+
+ tryCatch({
+ common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
+ if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
+
+ X <- values$genotype_data[common_samples, , drop = FALSE]
+ y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
+
+ set.seed(123)
+ train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
+ X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
+ y_train <- y[train_index]; y_val <- y[-train_index]
+
+ # ---- Run CIM scan ----
+ withProgress(message = "Running CIM genome scan...", value = 0.1, {
+ cim_results <- run_cim(
+ genotype_matrix = X_train,
+ phenotype_vector = y_train,
+ marker_info = values$all_markers, # FULL marker table — key fix
+ n_cofactors = input$n_cofactors,
+ window_size = input$window_size,
+ lod_threshold = input$lod_threshold
+ )
+ incProgress(0.7)
+ })
+
+ values$cim_all <- cim_results
+
+ # ---- Extract significant QTLs and add FIXED flanking ----
+ if (!"Message" %in% colnames(cim_results)) {
+ sig_qtls <- cim_results[cim_results$LOD >= input$lod_threshold, ]
+
+ if (nrow(sig_qtls) > 0) {
+ # Add flanking using FULL all_markers table
+ sig_qtls <- add_flanking_markers(sig_qtls, values$all_markers)
+ values$qtl_effects_train <- sig_qtls[order(-sig_qtls$LOD), ]
+ } else {
+ values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
+ }
+ } else {
+ values$qtl_effects_train <- cim_results
}
- } catch (e) { setApiStatus("error"); notify("✗ API key invalid: " + e.message, "error"); }
- finally { setLoad("apiTest", false); }
- };
-
- // ─── AI: Chat ───────────────────────────────────────────────────────────────
- const sendChat = async () => {
- if (!chatInput.trim() || !groqKey || chatLoading) return;
- const userMsg = chatInput.trim();
- setChatInput("");
- setChatHistory(prev => [...prev, { role: "user", content: userMsg }]);
- setChatLoading(true);
- try {
- const systemPrompt = [
- "You are MolExplorer AI, an expert assistant in structural biology, drug discovery, cheminformatics, and bioinformatics.",
- "Be precise, scientific, and concise. Use markdown for structure.",
- protein.id ? `Loaded protein: ${protein.source} — ${protein.id}` : "",
- ligand.cid ? `Loaded ligand: CID ${ligand.cid}, Formula: ${ligand.props?.MolecularFormula || "N/A"}, MW: ${ligand.props?.MolecularWeight || "N/A"} Da, LogP: ${ligand.props?.XLogP ?? "N/A"}` : "",
- ].filter(Boolean).join("\n");
-
- const messages = [
- { role: "system", content: systemPrompt },
- ...chatHistory.slice(-12),
- { role: "user", content: userMsg },
- ];
- const response = await API.callGroq(groqKey, groqModel, messages, 1200);
- setChatHistory(prev => [...prev, { role: "assistant", content: response }]);
- } catch (e) { notify("Chat error: " + e.message, "error"); }
- finally { setChatLoading(false); }
- };
-
- useEffect(() => { chatEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [chatHistory]);
-
- // ─── I-TASSER ───────────────────────────────────────────────────────────────
- const submitITasser = async () => {
- if (!itasserSeq.trim() || !itasserKey.trim()) return;
- setLoad("itasser", true);
- try {
- const res = await API.submitITasser(itasserKey, itasserSeq.replace(/^>.*\n/, "").replace(/\s/g, ""), itasserJobName);
- const jobId = res.job_id || res.jobId || JSON.stringify(res);
- setItasserJobId(jobId);
- notify(`✓ Submitted! Job ID: ${jobId}`, "success");
- } catch (e) { notify("✗ I-TASSER: " + e.message, "error"); }
- finally { setLoad("itasser", false); }
- };
-
- const checkITasserStatus = async () => {
- if (!itasserJobId.trim() || !itasserKey.trim()) return;
- setLoad("itasserCheck", true);
- try {
- const res = await API.checkITasser(itasserKey, itasserJobId);
- setItasserStatus(res);
- } catch (e) { notify("✗ Status check failed: " + e.message, "error"); }
- finally { setLoad("itasserCheck", false); }
- };
-
- // ─── DOCKING ─────────────────────────────────────────────────────────────────
- const runDocking = () => {
- if (!protein.pdb || !ligand.sdf) {
- notify("Load both protein and ligand first", "warning");
- return;
+
+ # ---- RF model for prediction (separate from CIM mapping) ----
+ nzv <- nearZeroVar(X_train)
+ X_tr_rf <- if (length(nzv) > 0) X_train[, -nzv, drop = FALSE] else X_train
+ X_v_rf <- X_val[, colnames(X_tr_rf), drop = FALSE]
+
+ model <- tryCatch(
+ train(x = X_tr_rf, y = y_train, method = "rf",
+ trControl = trainControl(method = "cv", number = 5),
+ importance = TRUE, tuneLength = 3),
+ error = function(e) {
+ train(x = X_tr_rf, y = y_train, method = "lm",
+ trControl = trainControl(method = "cv", number = 5))
+ })
+ values$model_fit <- model
+
+ y_train_pred <- predict(model, X_tr_rf)
+ y_val_pred <- predict(model, X_v_rf)
+ train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
+ val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
+
+ values$performance_metrics <- data.frame(
+ Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"),
+ Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
+ stringsAsFactors = FALSE)
+
+ values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
+ values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
+
+ # ---- Epistasis ----
+ if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
+ sig_markers <- values$qtl_effects_train$Marker
+ all_markers_v <- colnames(X_train)
+ epi_list <- list()
+
+ withProgress(message = "Calculating epistasis...", value = 0, {
+ for (m1 in sig_markers) {
+ for (m2 in all_markers_v) {
+ if (m1 == m2) next
+ tryCatch({
+ d <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2])
+ d <- na.omit(d)
+ if (nrow(d) < 10) next
+ fit <- lm(y ~ m1 * m2, data = d)
+ ct <- summary(fit)$coefficients
+ if ("m1:m2" %in% rownames(ct)) {
+ epi_list[[length(epi_list) + 1]] <- data.frame(
+ QTL1 = m1, QTL2 = m2,
+ Interaction_p = ct["m1:m2", "Pr(>|t|)"],
+ Effect_Size = coef(fit)["m1:m2"],
+ stringsAsFactors = FALSE)
+ }
+ }, error = function(e) {})
+ }
+ }
+ })
+
+ if (length(epi_list) > 0) {
+ ea <- do.call(rbind, epi_list)
+ values$epistasis_all <- ea
+ values$epistasis_sig <- ea[ea$Interaction_p < 0.05, ]
+ } else {
+ values$epistasis_all <- data.frame(Message = "No epistatic interactions found")
+ values$epistasis_sig <- data.frame(Message = "No epistatic interactions found")
+ }
+ }
+
+ n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
+ max_pve_cim <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_CIM_Percent), 1) else 0
+
+ showNotification("CIM analysis completed!", type = "message")
+ add_message("assistant", paste0(
+ "✅ **CIM analysis complete!**\n\n",
+ "• Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n",
+ "• Top QTL PVE_CIM: **", max_pve_cim, "%** (full CIM model)\n",
+ "• Validation R²: **", round(val_r2, 3), "**\n",
+ "• Flanking markers: ✅ fixed (uses full marker table)\n\n",
+ "Ask me about PVE, flanking markers, or top QTLs!"
+ ))
+ updateTabsetPanel(session, "nav", selected = "Results")
+
+ }, error = function(e) {
+ showNotification(paste("CIM Error:", e$message), type = "error")
+ cat("CIM ERROR:", e$message, "\n")
+ })
+ })
+
+ # ============================================================
+ # PREDICT TEST PHENOTYPES
+ # ============================================================
+
+ observeEvent(input$predict_test_phenotype, {
+ req(values$model_fit, values$test_genotype_data)
+ tryCatch({
+ common_m <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
+ if (length(common_m) == 0) { showNotification("No common markers", type = "error"); return() }
+ X_test <- values$test_genotype_data[, common_m, drop = FALSE]
+ preds <- predict(values$model_fit, newdata = X_test)
+ values$predicted_test_phenotype_data <- data.frame(
+ id = rownames(X_test), Predicted_Phenotype = as.numeric(preds), stringsAsFactors = FALSE)
+ showNotification("Predictions done!", type = "message")
+ }, error = function(e) showNotification(paste("Predict error:", e$message), type = "error"))
+ })
+
+ # ============================================================
+ # DOMESTICATION
+ # ============================================================
+
+ calculate_selection_metrics <- function(geno_mat, pop_data, marker_info) {
+ metrics_list <- list()
+ for (marker in colnames(geno_mat)) {
+ geno <- geno_mat[, marker]
+ pop <- pop_data$population[match(rownames(geno_mat), pop_data$id)]
+ valid_idx <- !is.na(geno) & !is.na(pop)
+ geno <- geno[valid_idx]; pop <- pop[valid_idx]
+ if (length(unique(pop)) < 2) next
+ gd <- geno[pop == "Domesticated"]; gw <- geno[pop == "Wild"]
+ if (length(gd) < 3 || length(gw) < 3) next
+ fd <- mean(gd, na.rm = TRUE) / 2; fw <- mean(gw, na.rm = TRUE) / 2
+ pa <- (fd + fw) / 2
+ fst <- if (pa > 0 && pa < 1) { f <- (fd - fw)^2 / (pa * (1 - pa)); f / (1 + f) } else 0
+ pi_d <- 2 * fd * (1 - fd); pi_w <- 2 * fw * (1 - fw)
+ td_d <- tryCatch((pi_d - 1/length(gd)) / sqrt(var(gd)/length(gd)), error = function(e) NA)
+ td_w <- tryCatch((pi_w - 1/length(gw)) / sqrt(var(gw)/length(gw)), error = function(e) NA)
+ mr <- marker_info[marker_info$Marker == marker, ]
+ metrics_list[[marker]] <- data.frame(
+ Marker = marker,
+ Chromosome = ifelse(nrow(mr) > 0, mr$Chromosome[1], NA),
+ Position = ifelse(nrow(mr) > 0, mr$Position[1], NA),
+ Fst = fst, Pi_Dom = pi_d, Pi_Wild = pi_w,
+ Tajima_D_Dom = td_d, Tajima_D_Wild = td_w,
+ stringsAsFactors = FALSE)
}
- // Parse rough center from PDB (centroid of CA atoms)
- const lines = protein.pdb.split("\n").filter(l => l.startsWith("ATOM") && l.substring(12,16).trim() === "CA");
- let cx=0, cy=0, cz=0, n=lines.length||1;
- lines.forEach(l => { cx+=parseFloat(l.substring(30,38)); cy+=parseFloat(l.substring(38,46)); cz+=parseFloat(l.substring(46,54)); });
- const auto = { cx: (cx/n).toFixed(2), cy: (cy/n).toFixed(2), cz: (cz/n).toFixed(2) };
- setDockBox(b => ({ ...b, ...auto }));
- setDockResult({
- protein: protein.id, ligand: ligand.cid || ligand.name,
- center: auto, box: { sx: dockBox.sx, sy: dockBox.sy, sz: dockBox.sz },
- exhaustiveness: dockBox.exhaustiveness,
- cmd: `vina --receptor protein.pdbqt --ligand ligand.pdbqt --center_x ${auto.cx} --center_y ${auto.cy} --center_z ${auto.cz} --size_x ${dockBox.sx} --size_y ${dockBox.sy} --size_z ${dockBox.sz} --exhaustiveness ${dockBox.exhaustiveness} --out docked.pdbqt`,
- });
- notify("✓ Docking config prepared. Vina command generated.", "success");
- };
-
- // ─── LIPINSKI ────────────────────────────────────────────────────────────────
- const lipinskiRules = checkLipinski(ligand.props);
-
- // ─── TABS ─────────────────────────────────────────────────────────────────────
- const tabs = [
- { id: "protein", label: "🧬 Protein" },
- { id: "ligand", label: "⚗️ Molecule" },
- { id: "draw", label: "✏️ Draw" },
- { id: "docking", label: "🎯 Docking" },
- { id: "sequence", label: "🔬 Sequence" },
- { id: "ai", label: "🤖 AI" },
- ];
-
- // ═══════ RENDER ═══════════════════════════════════════════════════════════════
- return (
-
- {/* HEADER */}
-
-
🧪
-
-
MolExplorer
-
STRUCTURAL BIOLOGY & DRUG DISCOVERY PLATFORM
-
-
- {protein.id && {protein.source}: {protein.id} }
- {ligand.cid && CID: {ligand.cid} }
-
- {apiStatus === "ok" ? "AI ✓" : "AI ○"}
-
-
-
-
- {/* TABS */}
-
- {tabs.map(t => (
- setActiveTab(t.id)} style={{
- background: "none", border: "none", padding: "12px 16px", cursor: "pointer", fontSize: 12, fontWeight: 600,
- color: activeTab === t.id ? "#00e5ff" : "#8892a4",
- borderBottom: `2px solid ${activeTab === t.id ? "#00e5ff" : "transparent"}`,
- whiteSpace: "nowrap", fontFamily: "inherit",
- }}>{t.label}
- ))}
-
-
- {/* MAIN CONTENT */}
-
-
- {/* ── PROTEIN TAB ─────────────────────────────────────────────────── */}
- {activeTab === "protein" && <>
-
- {/* Load by PDB ID */}
-
-
Load by PDB ID
-
- setPdbInput(e.target.value.toUpperCase())}
- placeholder="e.g. 1HHO, 6LU7, 3HTB…"
- onKeyDown={e => e.key === "Enter" && loadPDB(pdbInput)}
- style={{ ...inputStyle, flex: 1 }} />
- loadPDB(pdbInput)} disabled={loading.pdb} style={{ ...btnStyle("#00e5ff", "#0d1117"), width: "auto", padding: "9px 16px" }}>
- {loading.pdb ? "⏳" : "Load"}
-
-
-
- {["1HHO","6LU7","3HTB","1AKE","2HHB"].map(id => (
- loadPDB(id)} style={{ background: "#1e2736", border: "1px solid #2d3748", color: "#8892a4", borderRadius: 6, padding: "4px 10px", fontSize: 11, cursor: "pointer" }}>{id}
- ))}
-
-
-
- {/* Search PDB */}
-
-
Search RCSB PDB
-
- setPdbSearch(e.target.value)} placeholder="Protein name, keyword…"
- onKeyDown={e => e.key === "Enter" && searchPDB()} style={{ ...inputStyle, flex: 1 }} />
-
- {loading.pdbSearch ? "⏳" : "Search"}
-
-
- {pdbResults.length > 0 && (
-
- {pdbResults.slice(0, 8).map((r, i) => (
-
loadPDB(r.identifier)} style={{
- display: "flex", alignItems: "center", gap: 10, padding: "7px 10px", borderRadius: 8,
- background: "#1e2736", marginBottom: 4, cursor: "pointer", transition: "background 0.15s",
- }}
- onMouseOver={e => e.currentTarget.style.background = "#263040"}
- onMouseOut={e => e.currentTarget.style.background = "#1e2736"}>
- {r.identifier}
- {r.identifier}
-
- ))}
-
- )}
-
-
- {/* AlphaFold */}
-
-
AlphaFold2 by UniProt ID
-
- setAfInput(e.target.value)} placeholder="e.g. P69905, Q8IYD8, P04637"
- onKeyDown={e => e.key === "Enter" && loadAlphaFold()} style={{ ...inputStyle, flex: 1 }} />
-
- {loading.af ? "⏳" : "Fetch"}
-
-
-
- {[["P69905","α-Hemoglobin"],["P04637","TP53"],["Q8IYD8","SARS-CoV-2 Spike"]].map(([id,name]) => (
- { setAfInput(id); }} style={{ background: "#1a1226", border: "1px solid #7c3aed44", color: "#a78bfa", borderRadius: 6, padding: "4px 10px", fontSize: 11, cursor: "pointer" }}>{name}
- ))}
-
- {afInfo && (
-
- {[["UniProt", afInfo.uniprotAccession], ["Gene", afInfo.gene], ["Organism", afInfo.organismScientificName], ["pLDDT", Number(afInfo.plddt||0).toFixed(1)]].map(([k,v]) => (
-
{k} {v||"N/A"}
- ))}
-
- )}
-
-
- {/* Protein meta */}
- {protein.meta && protein.source === "PDB" && (
-
-
Structure Info
- {[
- ["PDB ID", protein.id],
- ["Title", (protein.meta?.struct?.title||"N/A").substring(0,60)],
- ["Method", protein.meta?.exptl?.[0]?.method || "N/A"],
- ["Resolution", protein.meta?.rcsb_entry_info?.resolution_combined?.[0] ? protein.meta.rcsb_entry_info.resolution_combined[0] + " Å" : "N/A"],
- ].map(([k,v]) => (
-
{k} {v}
- ))}
-
- )}
-
-
- {/* Right: 3D Viewer */}
-
-
- {protein.pdb && (
-
- Download
- {
- const a = document.createElement("a");
- a.href = "data:text/plain;charset=utf-8," + encodeURIComponent(protein.pdb);
- a.download = `${protein.id}.pdb`; a.click();
- }} style={{ ...btnStyle("#1e2736", "#e2e8f0"), border: "1px solid #2d3748" }}>⬇ Download {protein.id}.pdb
-
- )}
-
- >}
-
- {/* ── LIGAND TAB ─────────────────────────────────────────────────── */}
- {activeTab === "ligand" && <>
-
- {/* PubChem Search */}
-
-
Search PubChem
-
- setPubType(e.target.value)} style={{ ...inputStyle, width: 120, flex: "none" }}>
- Name
- SMILES
- InChIKey
- CID
-
- setPubQuery(e.target.value)} placeholder="aspirin, CC(O)=O, …"
- onKeyDown={e => e.key === "Enter" && searchPubChem()} style={{ ...inputStyle, flex: 1 }} />
-
- {loading.pub ? "⏳" : "Search"}
-
-
-
- {[["aspirin","Aspirin"],["ibuprofen","Ibuprofen"],["caffeine","Caffeine"],["paracetamol","Paracetamol"]].map(([q,l]) => (
- { setPubQuery(q); setPubType("name"); }} style={{ background: "#0e3b4d", border: "1px solid #00e5ff33", color: "#00e5ff", borderRadius: 6, padding: "4px 10px", fontSize: 11, cursor: "pointer" }}>{l}
- ))}
-
- {pubResults.length > 0 && (
-
- {pubResults.slice(0, 6).map((c, i) => {
- const cid = c.id?.id?.cid;
- const nameRow = c.props?.find(p => p.urn?.label === "IUPAC Name" && p.urn?.name === "Preferred");
- const name = nameRow?.value?.sval || `CID: ${cid}`;
- return (
-
loadCompoundByCID(cid)} style={{
- display: "flex", gap: 10, padding: "7px 10px", borderRadius: 8,
- background: "#1e2736", marginBottom: 4, cursor: "pointer",
- }}
- onMouseOver={e => e.currentTarget.style.background = "#263040"}
- onMouseOut={e => e.currentTarget.style.background = "#1e2736"}>
- CID {cid}
- {name.substring(0, 50)}
-
- );
- })}
-
- )}
-
-
- {/* IUPAC */}
-
-
IUPAC Name → 3D Structure
-
- setIupacInput(e.target.value)} placeholder="2-acetoxybenzoic acid"
- onKeyDown={e => e.key === "Enter" && iupacTo3D()} style={{ ...inputStyle, flex: 1 }} />
-
- {loading.iupac ? "⏳" : "Convert"}
-
-
-
-
- {/* Image upload */}
-
-
Image → 3D (Groq Vision)
-
Upload a 2D structural formula image. Requires Groq API key.
-
setMolImageFile(e.target.files[0])}
- style={{ ...inputStyle, padding: "7px 10px", cursor: "pointer" }} />
- {molImageFile && (
-
Selected: {molImageFile.name}
- )}
-
- {loading.imgPredict ? "⏳ Analyzing image…" : "🔮 Predict from Image"}
-
-
-
- {/* Molecule props */}
- {ligand.props && (
-
-
Molecular Properties
- {[
- ["Formula", ligand.props.MolecularFormula],
- ["MW", ligand.props.MolecularWeight + " Da"],
- ["LogP (XLogP)", ligand.props.XLogP],
- ["TPSA", ligand.props.TPSA + " Ų"],
- ["HBD", ligand.props.HBondDonorCount],
- ["HBA", ligand.props.HBondAcceptorCount],
- ["Rotatable Bonds", ligand.props.RotatableBondCount],
- ["Heavy Atoms", ligand.props.HeavyAtomCount],
- ["Complexity", ligand.props.Complexity],
- ["SMILES", (ligand.props.CanonicalSMILES||"").substring(0, 40) + "…"],
- ].map(([k,v]) => (
-
{k} {v ?? "N/A"}
- ))}
-
- )}
-
- {/* Lipinski */}
- {lipinskiRules && (
-
-
Lipinski Rule of Five
- {lipinskiRules.map(r => (
-
- {r.pass ? "✓" : "✗"} {r.label}
- {r.val ?? "N/A"}
-
- ))}
-
r.pass) ? "#1a3320" : "#2d1a1a", color: lipinskiRules.every(r=>r.pass) ? "#4ade80" : "#f59e0b", fontSize: 12 }}>
- {lipinskiRules.filter(r=>!r.pass).length === 0 ? "✓ Drug-like (0 violations)" : `⚠ ${lipinskiRules.filter(r=>!r.pass).length} violation(s)`}
-
-
- )}
-
-
-
-
- {ligand.sdf && (
-
- {
- const a = document.createElement("a");
- a.href = "data:chemical/x-mdl-sdfile;charset=utf-8," + encodeURIComponent(ligand.sdf);
- a.download = `molecule_${ligand.cid||"compound"}.sdf`; a.click();
- }} style={{ ...btnStyle("#1e2736", "#e2e8f0"), border: "1px solid #2d3748" }}>⬇ Download SDF
-
- )}
-
- >}
-
- {/* ── DRAW TAB ──────────────────────────────────────────────────── */}
- {activeTab === "draw" && <>
-
-
- Draw Molecule (2D Sketch)
-
-
-
-
SMILES Library
-
Click a common molecule to load it directly:
-
- {[
- ["Aspirin", "CC(=O)Oc1ccccc1C(=O)O"],
- ["Caffeine", "Cn1cnc2c1c(=O)n(c(=O)n2C)C"],
- ["Glucose", "OC[C@H]1OC(O)[C@H](O)[C@@H](O)[C@@H]1O"],
- ["Paclitaxel", "CC1=C2C(C(=O)[C@@]3([C@H](CC4=C([C@@H](OC(=O)c5ccccc5)[C@H]([C@H]([C@@]3(C2=C1)O)OC(=O)C)O)CO4)OC(=O)C)C)=O"],
- ["ATP", "c1nc(c2c(n1)n(cn2)[C@H]3[C@@H]([C@@H]([C@H](O3)COP(=O)(O)OP(=O)(O)OP(=O)(O)O)O)O)N"],
- ].map(([name, smiles]) => (
-
{
- try {
- const cid = await API.smilesToCID(smiles);
- if (cid) await loadCompoundByCID(cid);
- else notify("Not found in PubChem", "warning");
- } catch(e) { notify(e.message, "error"); }
- }} style={{ display: "flex", gap: 12, padding: "8px 12px", background: "#1e2736", borderRadius: 8, cursor: "pointer" }}
- onMouseOver={e => e.currentTarget.style.background="#263040"}
- onMouseOut={e => e.currentTarget.style.background="#1e2736"}>
- {name}
- {smiles.substring(0,50)}
-
- ))}
-
-
-
-
-
- {ligand.props && (
-
-
Current Molecule
- {[["Formula", ligand.props.MolecularFormula], ["CID", ligand.cid], ["MW", ligand.props.MolecularWeight + " Da"]].map(([k,v]) => (
-
{k} {v}
- ))}
-
- )}
-
- >}
-
- {/* ── DOCKING TAB ───────────────────────────────────────────────── */}
- {activeTab === "docking" && <>
-
-
-
Protein Status
-
- {protein.pdb ? `✓ Ready: ${protein.source} — ${protein.id}` : "⚠ No protein loaded. Go to Protein tab."}
-
-
-
-
Ligand Status
-
- {ligand.sdf ? `✓ Ready: CID ${ligand.cid} (${ligand.props?.MolecularFormula || "?"})` : "⚠ No ligand loaded. Go to Molecule tab."}
-
-
-
- {/* Protein prep steps */}
-
-
Protein Preparation (AutoDock Vina)
- {VINA_PROTEIN_STEPS.map((s,i) => (
-
- {i+1}.
- {s}
-
- ))}
-
-
- {/* Ligand prep steps */}
-
-
Ligand Preparation (AutoDock Vina)
- {VINA_LIGAND_STEPS.map((s,i) => (
-
- {i+1}.
- {s}
-
- ))}
-
-
- {/* Ab initio steps */}
-
-
Ab Initio Structure Prediction Pipeline
- {ABINITIO_STEPS.map((s,i) => (
-
- {i+1}.
- {s}
-
- ))}
-
-
-
-
-
-
Docking Box Configuration
-
-
-
Exhaustiveness (1–32)
-
setDockBox(b => ({...b, exhaustiveness: Number(e.target.value)}))}
- style={{ width: "100%", accentColor: "#00e5ff" }} />
-
{dockBox.exhaustiveness}
-
-
- ⚙️ Prepare Docking Config
-
-
-
- {dockResult && (
-
-
Vina Command
-
- {dockResult.cmd}
-
-
navigator.clipboard.writeText(dockResult.cmd).then(() => notify("Copied!", "success"))}
- style={{ ...btnStyle("#1e2736", "#e2e8f0"), border: "1px solid #2d3748", fontSize: 11 }}>📋 Copy Command
-
- {[["Protein", dockResult.protein], ["Ligand CID", dockResult.ligand],
- ["Center", Object.values(dockResult.center).join(", ")],
- ["Box", `${dockResult.box.sx}×${dockResult.box.sy}×${dockResult.box.sz}`]].map(([k,v]) => (
-
{k} {v}
- ))}
-
-
- )}
-
-
-
- >}
-
- {/* ── SEQUENCE TAB ─────────────────────────────────────────────── */}
- {activeTab === "sequence" && <>
-
- {/* I-TASSER */}
-
-
I-TASSER Ab Initio Prediction
-
- Get your free API key at zhanggroup.org/I-TASSER/register
-
-
- I-TASSER API Key
- setItasserKey(e.target.value)} placeholder="Your I-TASSER API key" type="password" style={inputStyle} />
-
-
- Job Name
- setItasserJobName(e.target.value)} placeholder="MyProtein_Job" style={inputStyle} />
-
-
- Amino Acid Sequence (FASTA or plain)
-
-
- {loading.itasser ? "⏳ Submitting…" : "🚀 Submit to I-TASSER"}
-
-
-
- {/* Check status */}
-
-
Check Job Status
-
- setItasserJobId(e.target.value)} placeholder="Job ID from submission" style={{ ...inputStyle, flex: 1 }} />
-
- {loading.itasserCheck ? "⏳" : "Check"}
-
-
- {itasserStatus && (
-
- {Object.entries(itasserStatus).map(([k,v]) => (
-
{k} {String(v)}
- ))}
-
- )}
-
-
- {/* Sequence tools */}
-
-
Analysis Tools (Coming Soon)
- {["Sequence Alignment (BLAST)", "2° Structure (DSSP/PSIPRED)", "Ramachandran Plot", "Binding Site Detection (fpocket)"].map(t => (
-
notify("Requires server-side integration: " + t, "info")} style={{
- padding: "8px 12px", borderRadius: 7, background: "#1e2736", marginBottom: 5, cursor: "pointer",
- fontSize: 12, color: "#8892a4", display: "flex", justifyContent: "space-between",
- }}>
- {t} →
-
- ))}
-
-
-
-
- {/* FASTA from loaded protein */}
- {protein.pdb && (
-
- Extract Sequence from PDB
- {
- const lines = protein.pdb.split("\n").filter(l => l.startsWith("ATOM") && l.substring(12,16).trim() === "CA");
- const aa = {"ALA":"A","ARG":"R","ASN":"N","ASP":"D","CYS":"C","GLN":"Q","GLU":"E","GLY":"G","HIS":"H","ILE":"I","LEU":"L","LYS":"K","MET":"M","PHE":"F","PRO":"P","SER":"S","THR":"T","TRP":"W","TYR":"Y","VAL":"V"};
- const seq = lines.map(l => aa[l.substring(17,20).trim()] || "X").join("");
- setItasserSeq(`>${protein.id}\n${seq}`);
- setActiveTab("sequence");
- notify("Sequence extracted! Scroll down to submit.", "success");
- }} style={btnStyle("#1e2736", "#e2e8f0")}>Extract Sequence → I-TASSER
-
- )}
-
-
-
I-TASSER Quality Metrics
-
After job completion, results include:
- {[["C-score", "Confidence score (-5 to 2). Higher is better."],
- ["TM-score", "Template Modeling score (0–1). >0.5 = correct topology."],
- ["RMSD", "Root Mean Square Deviation from native (Å)."],
- ["I-score", "Estimated accuracy of the predicted model."]].map(([k,v]) => (
-
- {k}
- {v}
-
- ))}
-
-
- >}
-
- {/* ── AI TAB ────────────────────────────────────────────────────── */}
- {activeTab === "ai" && <>
-
-
-
Groq API Configuration
-
- setGroqKeyInput(e.target.value)}
- placeholder="gsk_…" onKeyDown={e => e.key === "Enter" && saveGroqKey()} style={{ ...inputStyle, flex: 1 }} />
-
- {loading.apiTest ? "⏳" : "Save & Test"}
-
-
-
- {apiStatus === "ok" ? "✓ Connected — Groq API ready" : apiStatus === "error" ? "✗ API key invalid or network error" : "ℹ Enter API key and click Save & Test"}
-
-
- Model
- setGroqModel(e.target.value)} style={inputStyle}>
- {GROQ_MODELS.map(m => {m.label} )}
-
-
-
- Free API keys at console.groq.com
-
-
-
- {/* Quick prompts */}
-
- Quick Prompts
- {[
- ["🔗 Binding Mechanism", "What is the binding mechanism and key active site residues of the currently loaded protein?"],
- ["💊 ADMET Properties", "Predict and explain the ADMET properties of the current molecule based on its structure."],
- ["📋 Lipinski Assessment", "Assess drug-likeness using Lipinski Ro5 and Veber rules for the current ligand."],
- ["🧬 Key Mutations", "What are the most clinically important mutations in this protein and their effects?"],
- ["⚡ Interactions", "Describe the key molecular interactions (H-bonds, hydrophobic, π-π) between loaded protein and ligand."],
- ["🎯 Docking Guidance", "What docking box parameters and scoring function would you recommend for this protein-ligand pair?"],
- ].map(([label, prompt]) => (
- {
- if (!groqKey) { notify("Set Groq API key first", "warning"); return; }
- setChatInput(prompt); setActiveTab("ai");
- }} style={{ ...btnStyle("#1e2736", "#e2e8f0"), border: "1px solid #2d3748", marginBottom: 5, textAlign: "left", fontSize: 11 }}>
- {label}
-
- ))}
-
-
- {/* Chat stats */}
-
-
Session Info
- {[["Messages", chatHistory.length], ["Model", groqModel.split("/").pop()], ["Protein", protein.id || "none"], ["Ligand", ligand.cid ? `CID ${ligand.cid}` : "none"]].map(([k,v]) => (
-
{k} {v}
- ))}
-
{ setChatHistory([]); notify("Chat cleared", "info"); }}
- style={{ ...btnStyle("#1e2736", "#f87171"), border: "1px solid #f8717133", marginTop: 8, fontSize: 11 }}>🗑 Clear Chat
-
-
-
- {/* Chat panel */}
-
-
- {chatHistory.length === 0 && (
-
-
🤖
-
MolExplorer AI is ready.
-
Set your Groq API key and ask about loaded structures.
-
- )}
- {chatHistory.map((msg, i) => (
-
- {msg.content}
-
- ))}
- {chatLoading && (
-
- ⏳ Thinking…
-
- )}
-
-
-
- setChatInput(e.target.value)}
- onKeyDown={e => e.key === "Enter" && !e.shiftKey && sendChat()}
- placeholder={groqKey ? "Ask about proteins, molecules, docking…" : "Set Groq API key to chat"}
- disabled={!groqKey} style={{ ...inputStyle, flex: 1 }} />
- Send
-
-
- >}
-
-
-
setToast({ msg: "" })} />
-
- );
-}
\ No newline at end of file
+ if (length(metrics_list) == 0) return(NULL)
+ do.call(rbind, metrics_list)
+ }
+
+ observeEvent(input$run_domestication, {
+ req(values$genotype_data, values$pop_data, values$all_markers)
+ tryCatch({
+ cs <- intersect(rownames(values$genotype_data), values$pop_data$id)
+ if (length(cs) == 0) { showNotification("No common samples", type = "error"); return() }
+ X <- values$genotype_data[cs, , drop = FALSE]
+ ps <- values$pop_data[values$pop_data$id %in% cs, ]
+ sel <- calculate_selection_metrics(X, ps, values$all_markers)
+ if (is.null(sel)) { showNotification("No selection metrics", type = "error"); return() }
+ sel$Significant <- sel$Fst > input$fst_threshold | sel$Tajima_D_Dom < input$tajima_threshold
+ values$selection_metrics <- sel
+ showNotification(paste("Domestication done:", sum(sel$Significant, na.rm = TRUE), "signatures"), type = "message")
+ }, error = function(e) showNotification(paste("Dom error:", e$message), type = "error"))
+ })
+
+ # ============================================================
+ # MANHATTAN HELPER
+ # ============================================================
+
+ create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
+ if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
+ return(plot_ly() %>% layout(title = "No data — run analysis first",
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+ pd <- data[!is.na(data[[y_col]]) & !is.na(data$Chromosome), ]
+ if (nrow(pd) == 0) return(plot_ly() %>% layout(title = "No valid data",
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+ chroms <- unique(pd$Chromosome)
+ chrom_pos <- data.frame()
+ for (i in seq_along(chroms)) {
+ cd <- pd[pd$Chromosome == chroms[i], ]
+ if (nrow(cd) > 0) {
+ cd$ChromIndex <- i
+ cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1)
+ chrom_pos <- rbind(chrom_pos, cd)
+ }
+ }
+ p <- plot_ly() %>%
+ add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
+ type = "scatter", mode = "markers", color = ~factor(Chromosome),
+ colors = viridis(length(chroms)), marker = list(size = 6, opacity = 0.7),
+ text = ~paste("Marker:", Marker, " Chr:", Chromosome, " Pos:", Position,
+ " ", y_label, ":", round(get(y_col), 3)),
+ hoverinfo = "text", showlegend = FALSE)
+ if (!is.null(threshold) && !is.na(threshold))
+ p <- p %>% add_segments(
+ x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
+ y = threshold, yend = threshold,
+ line = list(color = "red", dash = "dash", width = 1))
+ p %>% layout(title = title,
+ xaxis = list(title = "Chromosome",
+ ticktext = chroms,
+ tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
+ tickangle = 45),
+ yaxis = list(title = y_label),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ }
+
+ # ============================================================
+ # PLOTS
+ # ============================================================
+
+ output$lod_plot_2d <- renderPlotly({
+ req(values$cim_all)
+ create_manhattan(values$cim_all, "LOD", "CIM Manhattan Plot (LOD Scores)", input$lod_threshold, "LOD Score")
+ })
+
+ output$fst_plot <- renderPlotly({ req(values$selection_metrics); create_manhattan(values$selection_metrics, "Fst", "Fst Plot", input$fst_threshold, "Fst") })
+
+ output$tajima_plot <- renderPlotly({
+ req(values$selection_metrics)
+ if ("Message" %in% colnames(values$selection_metrics))
+ return(plot_ly() %>% layout(title = "No data", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+ d <- values$selection_metrics
+ chroms <- unique(d$Chromosome)
+ cp <- data.frame()
+ for (i in seq_along(chroms)) {
+ cd <- d[d$Chromosome == chroms[i], ]
+ if (nrow(cd) > 0) { cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1); cp <- rbind(cp, cd) }
+ }
+ plot_ly() %>%
+ add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers", name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = .7)) %>%
+ add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Wild, type = "scatter", mode = "markers", name = "Wild", marker = list(size = 5, color = "#f97316", opacity = .7)) %>%
+ add_segments(x = min(cp$PosScaled, na.rm = TRUE), xend = max(cp$PosScaled, na.rm = TRUE), y = input$tajima_threshold, yend = input$tajima_threshold, line = list(color = "red", dash = "dash", width = 1)) %>%
+ layout(title = "Tajima's D", xaxis = list(title = "Chromosome", ticktext = chroms, tickvals = tapply(cp$PosScaled, cp$Chromosome, median, na.rm = TRUE), tickangle = 45), yaxis = list(title = "Tajima's D"),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ })
+
+ output$performance_plot <- renderPlotly({
+ req(values$performance_metrics)
+ plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
+ marker = list(color = c("#58a6ff","#58a6ff","#3fb950","#3fb950")),
+ text = ~round(Value, 3), textposition = "outside") %>%
+ layout(title = "Model Performance (RF for Prediction)", yaxis = list(title = "Value", range = c(0, 1.1)),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ })
+
+ output$regression_plot_train <- renderPlotly({
+ req(values$train_predictions)
+ plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
+ type = "scatter", mode = "markers", marker = list(size = 6, color = "#58a6ff", opacity = .7)) %>%
+ add_trace(x = range(values$train_predictions$Observed), y = range(values$train_predictions$Observed),
+ type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
+ layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ })
+
+ output$regression_plot_test <- renderPlotly({
+ req(values$test_predictions)
+ plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
+ type = "scatter", mode = "markers", marker = list(size = 6, color = "#3fb950", opacity = .7)) %>%
+ add_trace(x = range(values$test_predictions$Observed), y = range(values$test_predictions$Observed),
+ type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
+ layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ })
+
+ output$epistasis_heatmap <- renderPlotly({
+ req(values$epistasis_all)
+ if ("Message" %in% colnames(values$epistasis_all))
+ return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+ qtls <- unique(values$epistasis_all$QTL1)
+ mks <- unique(values$epistasis_all$QTL2)
+ pm <- matrix(NA, nrow = length(qtls), ncol = length(mks), dimnames = list(qtls, mks))
+ for (i in 1:nrow(values$epistasis_all))
+ pm[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <- -log10(values$epistasis_all$Interaction_p[i])
+ plot_ly(x = colnames(pm), y = rownames(pm), z = pm, type = "heatmap", colorscale = "Viridis") %>%
+ layout(title = "Epistatic Interactions (-log10 p)", xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ })
+
+ # ============================================================
+ # TABLES
+ # ============================================================
+
+ output$qtl_effects_table_train <- renderDT({
+ req(values$qtl_effects_train)
+ if ("Message" %in% colnames(values$qtl_effects_train))
+ return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
+
+ display_cols <- intersect(
+ c("Marker", "Chromosome", "Position", "LOD", "P_Value",
+ "PVE_Marker_Percent", "PVE_CIM_Percent",
+ "Additive_Effect", "SE_Additive", "CI_Lower", "CI_Upper",
+ "Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "Dominance_Class",
+ "N_Cofactors", "N_Samples", "N_Heterozygotes",
+ "Low_Flank", "High_Flank"),
+ colnames(values$qtl_effects_train))
+
+ datatable(values$qtl_effects_train[, display_cols],
+ options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE,
+ caption = "PVE_Marker = R²(lm(y~a+d))×100 | PVE_CIM = R²(lm(y~marker+cofactors))×100") %>%
+ formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent",
+ "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
+ "Dominance_Effect","SE_Dominance","Dominance_Ratio"), display_cols), 3) %>%
+ formatSignif(intersect(c("P_Value"), display_cols), digits = 3)
+ })
+
+ output$epistasis_table <- renderDT({
+ req(values$epistasis_sig)
+ if ("Message" %in% colnames(values$epistasis_sig))
+ return(datatable(data.frame(Status = values$epistasis_sig$Message[1]), options = list(dom = "t")))
+ datatable(values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
+ options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
+ formatSignif(c("Interaction_p", "Effect_Size"), digits = 4)
+ })
+
+ output$selection_table <- renderDT({
+ req(values$selection_metrics)
+ if ("Message" %in% colnames(values$selection_metrics))
+ return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
+ df <- values$selection_metrics
+ if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
+ df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
+ dc <- intersect(c("Marker","Chromosome","Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom","Significant","QTL_Overlap"), colnames(df))
+ datatable(df[order(-df$Fst), dc], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
+ formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"), 3)
+ })
+
+ # ============================================================
+ # CHROMOSOME VISUALIZATION (uses FULL all_markers — flanking fixed)
+ # ============================================================
+
+ output$chromosome_viz <- renderUI({
+ req(values$qtl_effects_train, values$all_markers)
+ if ("Message" %in% colnames(values$qtl_effects_train))
+ return(div(class = "alert alert-info", values$qtl_effects_train$Message[1]))
+
+ chromosomes <- unique(values$qtl_effects_train$Chromosome)
+ tagList(lapply(chromosomes, function(chr) {
+ # Use FULL all_markers (not post-NZV subset)
+ chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
+ chr_markers <- chr_markers[order(chr_markers$Position), ]
+ chr_qtls <- values$qtl_effects_train[values$qtl_effects_train$Chromosome == chr, ]
+
+ sel_markers <- NULL
+ if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
+ sel_markers <- values$selection_metrics[
+ values$selection_metrics$Chromosome == chr & isTRUE(values$selection_metrics$Significant), ]
+
+ min_pos <- min(chr_markers$Position, na.rm = TRUE)
+ max_pos <- max(chr_markers$Position, na.rm = TRUE)
+ range_pos <- max_pos - min_pos
+
+ flanking_markers <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank)
+ flanking_markers <- flanking_markers[!is.na(flanking_markers)]
+
+ div(class = "chromosome-container",
+ div(class = "chromosome-title", paste("Chromosome", chr, " —", nrow(chr_markers), "markers,", nrow(chr_qtls), "QTLs")),
+ div(class = "chromosome",
+ lapply(1:nrow(chr_markers), function(i) {
+ marker <- chr_markers[i, ]
+ left <- if (range_pos > 0 && !is.na(range_pos))
+ ((marker$Position - min_pos) / range_pos) * 100
+ else (i / nrow(chr_markers)) * 100
+
+ mclass <- "chromosome-marker"
+ if (marker$Marker %in% chr_qtls$Marker) {
+ mclass <- paste(mclass, "significant")
+ } else if (!is.null(sel_markers) && nrow(sel_markers) > 0 && marker$Marker %in% sel_markers$Marker) {
+ mclass <- paste(mclass, "selection")
+ } else if (marker$Marker %in% flanking_markers) {
+ mclass <- paste(mclass, "flanking")
+ }
+ div(class = mclass, style = paste0("left:", round(left, 2), "%;"),
+ title = paste0(marker$Marker, " pos:", marker$Position))
+ })
+ ),
+ div(class = "chromosome-legend",
+ span(paste(format(min_pos, big.mark = ","), "bp")),
+ span(paste(format(max_pos, big.mark = ","), "bp"))
+ )
+ )
+ }))
+ })
+
+ observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
+ observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
+
+ # ============================================================
+ # INTERPRETATION
+ # ============================================================
+
+ output$analysis_summary <- renderUI({
+ has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
+ has_perf <- !is.null(values$performance_metrics)
+ n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
+ val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
+ max_pve <- if (has_qtl) round(max(values$qtl_effects_train$PVE_CIM_Percent), 1) else NA
+ div(
+ tags$h5("CIM Analysis Summary"),
+ tags$p(paste(n_qtl, "QTLs detected above LOD", input$lod_threshold, "| Validation R²:", val_r2)),
+ if (!is.na(max_pve)) tags$p(paste("Max PVE_CIM:", max_pve, "% (marker + cofactors)")),
+ tags$p(style = "color:#3fb950;font-size:12px;",
+ tags$i(class = "fas fa-check-circle"), " CIM: flanking markers use full marker table ✓")
+ )
+ })
+
+ output$qtl_interpretation <- renderUI({
+ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
+ return(div(tags$h5("QTL Significance"), tags$p("No significant QTLs. Try lower LOD threshold.")))
+ top <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
+ div(
+ tags$h5("Top QTL"),
+ tags$p(paste(top$Marker, "— Chr", top$Chromosome, "— LOD =", round(top$LOD, 2))),
+ tags$p(paste("Flanking:", top$Low_Flank, "↔", top$High_Flank)),
+ tags$p(paste("PVE_marker:", round(top$PVE_Marker_Percent, 1), "% | PVE_CIM:", round(top$PVE_CIM_Percent, 1), "%"))
+ )
+ })
+
+ output$effect_interpretation <- renderUI({
+ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
+ return(div(tags$h5("Effect Sizes"), tags$p("No QTL effects yet.")))
+ top <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_CIM_Percent), ]
+ dom <- if (!is.na(top$Dominance_Effect)) paste0("Dominance = ", round(top$Dominance_Effect, 3), " (", top$Dominance_Class, ")") else "No heterozygotes (additive model)"
+ div(
+ tags$h5("Largest PVE_CIM QTL"),
+ tags$p(paste(top$Marker, "—", round(top$PVE_CIM_Percent, 1), "% PVE (CIM model)")),
+ tags$p(paste("Additive effect =", round(top$Additive_Effect, 3))),
+ tags$p(dom)
+ )
+ })
+
+ output$epistasis_interpretation <- renderUI({
+ if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
+ return(div(tags$h5("Epistasis"), tags$p("No significant interactions.")))
+ top <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
+ div(tags$h5("Epistasis"),
+ tags$p(paste(nrow(values$epistasis_sig), "interactions. Strongest:", top$QTL1, "×", top$QTL2, "(p =", format.pval(top$Interaction_p), ")")))
+ })
+
+ output$recommendations <- renderUI({
+ has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
+ recs <- if (has_qtl) {
+ n_ovdom <- sum(values$qtl_effects_train$Dominance_Class == "Overdominance", na.rm = TRUE)
+ r <- c("Validate top CIM QTLs in independent populations",
+ "Use Low_Flank / High_Flank for fine-mapping intervals",
+ "Annotate QTL regions for candidate genes")
+ if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) — consider heterosis breeding"))
+ r <- c(r, "PVE_CIM includes cofactor variance — use PVE_Marker for single-QTL estimates")
+ r
+ } else {
+ c("Upload genotype + phenotype CSV files", "Click 'Run CIM Analysis'", "Try LOD threshold = 2 to start")
+ }
+ div(tags$h5("Recommendations"), tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
+ })
+
+ # ============================================================
+ # DOWNLOADS
+ # ============================================================
+
+ output$download_train_results <- downloadHandler(
+ filename = function() paste0("cim_results_", Sys.Date(), ".xlsx"),
+ content = function(file) {
+ sheets <- list()
+ if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
+ sheets[["CIM_QTL_Results"]] <- values$qtl_effects_train
+ if (!is.null(values$cim_all) && !"Message" %in% colnames(values$cim_all))
+ sheets[["CIM_Full_Scan"]] <- values$cim_all
+ if (!is.null(values$performance_metrics))
+ sheets[["Performance"]] <- values$performance_metrics
+ sheets[["Method_Documentation"]] <- data.frame(
+ Item = c("Method","Cofactor selection","LOD formula","PVE_Marker","PVE_CIM",
+ "Additive_Effect","Dominance_Effect","Flanking fix","Reference"),
+ Description = c(
+ "Composite Interval Mapping (CIM)",
+ "Top K markers by RF importance, excluding ±window on same chromosome",
+ "-log10(p-value of focal marker in lm(Y ~ marker + cofactors))",
+ "R² from lm(Y ~ additive_code + dominance_code) × 100 — marker alone",
+ "R² from full CIM model (marker + cofactors) × 100 — includes background",
+ "beta_a from lm(Y ~ a + d) — allele substitution effect",
+ "beta_d from lm(Y ~ a + d) — heterozygote deviation from midparent",
+ "Uses full all_markers table (not post-NZV subset)",
+ "Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)"),
+ stringsAsFactors = FALSE)
+ write_xlsx(sheets, file)
+ }
+ )
+
+ output$download_selection <- downloadHandler(
+ filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
+ content = function(file) {
+ if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
+ write_xlsx(list(Selection = values$selection_metrics), file)
+ else
+ write_xlsx(list(Message = data.frame(msg = "No results yet")), file)
+ }
+ )
+}
+
+shinyApp(ui = ui, server = server)
\ No newline at end of file