Spaces:
Sleeping
Sleeping
Update app.R
Browse files
app.R
CHANGED
|
@@ -1427,14 +1427,53 @@ server <- function(input, output, session) {
|
|
| 1427 |
observeEvent(input$test_genotype_file, {
|
| 1428 |
req(input$test_genotype_file)
|
| 1429 |
tryCatch({
|
| 1430 |
-
|
| 1431 |
-
|
| 1432 |
-
|
| 1433 |
-
|
| 1434 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1435 |
values$test_genotype_data <- gd
|
| 1436 |
-
|
| 1437 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1438 |
})
|
| 1439 |
|
| 1440 |
output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
|
@@ -1583,105 +1622,150 @@ server <- function(input, output, session) {
|
|
| 1583 |
# ============================================================
|
| 1584 |
observeEvent(input$predict_test_phenotype, {
|
| 1585 |
req(values$model_fit, values$test_genotype_data)
|
| 1586 |
-
tryCatch({
|
| 1587 |
-
withProgress(message = "Predicting test phenotypes...", value = 0, {
|
| 1588 |
|
| 1589 |
-
|
| 1590 |
-
Sys.sleep(0.1)
|
| 1591 |
|
| 1592 |
-
|
| 1593 |
-
|
| 1594 |
-
|
| 1595 |
-
values$model_train_cols
|
| 1596 |
-
} else {
|
| 1597 |
-
colnames(values$genotype_data)
|
| 1598 |
-
}
|
| 1599 |
|
| 1600 |
-
|
| 1601 |
-
|
| 1602 |
-
missing_m <- setdiff(train_cols, test_cols)
|
| 1603 |
|
| 1604 |
-
|
| 1605 |
-
|
| 1606 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1607 |
|
| 1608 |
-
|
| 1609 |
-
|
| 1610 |
-
|
| 1611 |
-
|
| 1612 |
-
|
| 1613 |
-
|
| 1614 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1615 |
|
| 1616 |
-
|
| 1617 |
-
|
| 1618 |
-
|
| 1619 |
-
|
| 1620 |
-
|
| 1621 |
-
|
|
|
|
|
|
|
|
|
|
| 1622 |
|
| 1623 |
-
|
| 1624 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1625 |
|
| 1626 |
-
|
| 1627 |
-
|
| 1628 |
-
X_test <- values$test_genotype_data[, common_m, drop = FALSE]
|
| 1629 |
|
| 1630 |
-
|
| 1631 |
-
|
| 1632 |
-
|
| 1633 |
-
|
|
|
|
|
|
|
| 1634 |
}
|
|
|
|
| 1635 |
|
| 1636 |
-
|
| 1637 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1638 |
|
| 1639 |
-
|
| 1640 |
-
|
|
|
|
| 1641 |
|
| 1642 |
-
|
| 1643 |
-
|
|
|
|
|
|
|
| 1644 |
|
| 1645 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1646 |
|
| 1647 |
-
|
|
|
|
| 1648 |
|
| 1649 |
-
|
| 1650 |
-
id = rownames(X_test),
|
| 1651 |
-
Predicted_Phenotype = round(as.numeric(preds), 4),
|
| 1652 |
-
stringsAsFactors = FALSE
|
| 1653 |
-
)
|
| 1654 |
|
| 1655 |
-
|
| 1656 |
-
|
| 1657 |
-
|
|
|
|
|
|
|
| 1658 |
|
| 1659 |
-
|
| 1660 |
-
|
| 1661 |
-
|
| 1662 |
-
|
| 1663 |
-
|
| 1664 |
-
|
| 1665 |
-
|
| 1666 |
-
|
| 1667 |
-
|
| 1668 |
-
|
| 1669 |
-
|
| 1670 |
-
|
| 1671 |
-
|
| 1672 |
-
)
|
| 1673 |
-
|
| 1674 |
-
showNotification(paste("Prediction error:", e$message), type = "error", duration = 10)
|
| 1675 |
-
cat("PREDICT ERROR:", e$message, "\n")
|
| 1676 |
-
add_message("assistant", paste0(
|
| 1677 |
-
"β **Prediction failed**\n\n",
|
| 1678 |
-
"Error: ", e$message, "\n\n",
|
| 1679 |
-
"Common causes:\n",
|
| 1680 |
-
"β’ Test genotype has different marker names than training\n",
|
| 1681 |
-
"β’ Model not trained yet (run CIM Analysis first)\n",
|
| 1682 |
-
"β’ Test CSV format issue (needs same 3-row header as training)"
|
| 1683 |
-
))
|
| 1684 |
-
})
|
| 1685 |
})
|
| 1686 |
|
| 1687 |
# ============================================================
|
|
|
|
| 1427 |
observeEvent(input$test_genotype_file, {
|
| 1428 |
req(input$test_genotype_file)
|
| 1429 |
tryCatch({
|
| 1430 |
+
# Read raw lines, strip Windows carriage returns
|
| 1431 |
+
all_data <- readLines(input$test_genotype_file$datapath)
|
| 1432 |
+
all_data <- gsub("\r", "", all_data)
|
| 1433 |
+
all_data <- all_data[nchar(trimws(all_data)) > 0] # drop blank lines
|
| 1434 |
+
|
| 1435 |
+
if (length(all_data) < 4) {
|
| 1436 |
+
showNotification("Test genotype needs β₯4 rows (header + chr row + pos row + β₯1 sample)", type = "error")
|
| 1437 |
+
return()
|
| 1438 |
+
}
|
| 1439 |
+
|
| 1440 |
+
# Parse header β strip any quotes and whitespace
|
| 1441 |
+
header <- trimws(gsub('"', '', strsplit(all_data[1], ",")[[1]]))
|
| 1442 |
+
|
| 1443 |
+
# Rows 4+ are sample data
|
| 1444 |
+
sample_lines <- all_data[-(1:3)]
|
| 1445 |
+
gd <- read.csv(text = paste(sample_lines, collapse = "\n"),
|
| 1446 |
+
header = FALSE, stringsAsFactors = FALSE,
|
| 1447 |
+
strip.white = TRUE, quote = '"')
|
| 1448 |
+
|
| 1449 |
+
if (ncol(gd) != length(header)) {
|
| 1450 |
+
showNotification(
|
| 1451 |
+
paste0("Column count mismatch: header has ", length(header),
|
| 1452 |
+
" cols but data has ", ncol(gd), " cols. Check CSV format."),
|
| 1453 |
+
type = "error", duration = 10)
|
| 1454 |
+
return()
|
| 1455 |
+
}
|
| 1456 |
+
|
| 1457 |
+
colnames(gd) <- header
|
| 1458 |
+
rownames(gd) <- trimws(as.character(gd[, 1]))
|
| 1459 |
+
gd <- gd[, -1, drop = FALSE]
|
| 1460 |
+
|
| 1461 |
+
# Convert all to numeric
|
| 1462 |
+
for (col in colnames(gd))
|
| 1463 |
+
gd[[col]] <- suppressWarnings(as.numeric(as.character(gd[[col]])))
|
| 1464 |
+
|
| 1465 |
values$test_genotype_data <- gd
|
| 1466 |
+
|
| 1467 |
+
cat("TEST GENO LOADED:", nrow(gd), "samples,", ncol(gd), "markers\n")
|
| 1468 |
+
cat("TEST GENO first 3 cols:", paste(colnames(gd)[1:3], collapse = ", "), "\n")
|
| 1469 |
+
|
| 1470 |
+
showNotification(
|
| 1471 |
+
paste0("β
Test genotype loaded: ", nrow(gd), " samples, ", ncol(gd), " markers"),
|
| 1472 |
+
type = "message")
|
| 1473 |
+
}, error = function(e) {
|
| 1474 |
+
showNotification(paste("Test geno load error:", e$message), type = "error", duration = 10)
|
| 1475 |
+
cat("TEST GENO LOAD ERROR:", e$message, "\n")
|
| 1476 |
+
})
|
| 1477 |
})
|
| 1478 |
|
| 1479 |
output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
|
|
|
|
| 1622 |
# ============================================================
|
| 1623 |
observeEvent(input$predict_test_phenotype, {
|
| 1624 |
req(values$model_fit, values$test_genotype_data)
|
|
|
|
|
|
|
| 1625 |
|
| 1626 |
+
withProgress(message = "Predicting test phenotypes...", value = 0, {
|
|
|
|
| 1627 |
|
| 1628 |
+
# ββ Step 1: Validate inputs ββββββββββββββββββββββββββββββββββ
|
| 1629 |
+
incProgress(0.05, detail = "Validating inputs...")
|
| 1630 |
+
Sys.sleep(0.08)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1631 |
|
| 1632 |
+
model <- values$model_fit
|
| 1633 |
+
test_raw <- values$test_genotype_data # data.frame, rows = samples
|
|
|
|
| 1634 |
|
| 1635 |
+
# caret stores the exact predictor names it was trained on
|
| 1636 |
+
train_cols <- if (!is.null(values$model_train_cols)) {
|
| 1637 |
+
values$model_train_cols
|
| 1638 |
+
} else if (!is.null(model$finalModel) && !is.null(model$coefnames)) {
|
| 1639 |
+
model$coefnames
|
| 1640 |
+
} else {
|
| 1641 |
+
colnames(values$genotype_data)
|
| 1642 |
+
}
|
| 1643 |
|
| 1644 |
+
test_cols <- colnames(test_raw)
|
| 1645 |
+
common_m <- intersect(train_cols, test_cols)
|
| 1646 |
+
missing_m <- setdiff(train_cols, test_cols)
|
| 1647 |
+
extra_m <- setdiff(test_cols, train_cols)
|
| 1648 |
+
|
| 1649 |
+
cat("PREDICT DEBUG: train_cols =", length(train_cols),
|
| 1650 |
+
"| test_cols =", length(test_cols),
|
| 1651 |
+
"| common =", length(common_m),
|
| 1652 |
+
"| missing =", length(missing_m), "\n")
|
| 1653 |
+
|
| 1654 |
+
# ββ Step 2: Check marker overlap ββββββββββββββββββββββββββββ
|
| 1655 |
+
incProgress(0.10, detail = paste0("Matched ", length(common_m), " / ", length(train_cols), " markers..."))
|
| 1656 |
+
Sys.sleep(0.08)
|
| 1657 |
+
|
| 1658 |
+
if (length(common_m) == 0) {
|
| 1659 |
+
showNotification(
|
| 1660 |
+
paste0("No markers matched between test and training data. ",
|
| 1661 |
+
"Make sure both CSVs use the same marker column names."),
|
| 1662 |
+
type = "error", duration = 12)
|
| 1663 |
+
add_message("assistant", paste0(
|
| 1664 |
+
"β **Prediction failed β no marker overlap**\n\n",
|
| 1665 |
+
"Training has ", length(train_cols), " markers, test has ", length(test_cols), " markers, 0 in common.\n\n",
|
| 1666 |
+
"Fix: Ensure test CSV has identical marker column names to training CSV.\n",
|
| 1667 |
+
"First 5 training markers: ", paste(head(train_cols, 5), collapse = ", ")))
|
| 1668 |
+
return()
|
| 1669 |
+
}
|
| 1670 |
|
| 1671 |
+
if (length(missing_m) > 0) {
|
| 1672 |
+
showNotification(
|
| 1673 |
+
paste0(length(missing_m), " training markers absent from test β imputing with 0."),
|
| 1674 |
+
type = "warning", duration = 6)
|
| 1675 |
+
}
|
| 1676 |
+
|
| 1677 |
+
# ββ Step 3: Build aligned data.frame (caret requires data.frame) ββ
|
| 1678 |
+
incProgress(0.20, detail = paste0("Building aligned matrix (", nrow(test_raw), " samples)..."))
|
| 1679 |
+
Sys.sleep(0.08)
|
| 1680 |
|
| 1681 |
+
# Start with only common columns
|
| 1682 |
+
X_test_df <- as.data.frame(test_raw[, common_m, drop = FALSE])
|
| 1683 |
+
|
| 1684 |
+
# Add missing columns filled with 0
|
| 1685 |
+
if (length(missing_m) > 0) {
|
| 1686 |
+
fill_df <- as.data.frame(
|
| 1687 |
+
matrix(0L, nrow = nrow(X_test_df), ncol = length(missing_m),
|
| 1688 |
+
dimnames = list(rownames(X_test_df), missing_m))
|
| 1689 |
+
)
|
| 1690 |
+
X_test_df <- cbind(X_test_df, fill_df)
|
| 1691 |
+
}
|
| 1692 |
|
| 1693 |
+
# Reorder columns to exactly match training order
|
| 1694 |
+
X_test_df <- X_test_df[, train_cols, drop = FALSE]
|
|
|
|
| 1695 |
|
| 1696 |
+
# Replace any remaining NAs with column means from test data (or 0)
|
| 1697 |
+
for (col in colnames(X_test_df)) {
|
| 1698 |
+
na_idx <- is.na(X_test_df[[col]])
|
| 1699 |
+
if (any(na_idx)) {
|
| 1700 |
+
col_mean <- mean(X_test_df[[col]], na.rm = TRUE)
|
| 1701 |
+
X_test_df[[col]][na_idx] <- if (is.finite(col_mean)) col_mean else 0
|
| 1702 |
}
|
| 1703 |
+
}
|
| 1704 |
|
| 1705 |
+
# Ensure all columns are numeric
|
| 1706 |
+
X_test_df <- as.data.frame(lapply(X_test_df, as.numeric))
|
| 1707 |
+
rownames(X_test_df) <- rownames(test_raw)
|
| 1708 |
+
|
| 1709 |
+
cat("PREDICT DEBUG: X_test_df dims =", nrow(X_test_df), "x", ncol(X_test_df), "\n")
|
| 1710 |
+
cat("PREDICT DEBUG: First 3 cols match training:", all(colnames(X_test_df)[1:3] == train_cols[1:3]), "\n")
|
| 1711 |
+
|
| 1712 |
+
# ββ Step 4: Run prediction βββββββββββββββββββββββββββββββββββ
|
| 1713 |
+
incProgress(0.35, detail = paste0("Running RF model on ", nrow(X_test_df), " samples..."))
|
| 1714 |
+
Sys.sleep(0.05)
|
| 1715 |
+
|
| 1716 |
+
preds <- tryCatch({
|
| 1717 |
+
predict(model, newdata = X_test_df)
|
| 1718 |
+
}, error = function(e) {
|
| 1719 |
+
cat("PREDICT ERROR (caret predict):", e$message, "\n")
|
| 1720 |
+
# Fallback: try predicting from finalModel directly
|
| 1721 |
+
tryCatch({
|
| 1722 |
+
predict(model$finalModel, newdata = X_test_df)
|
| 1723 |
+
}, error = function(e2) {
|
| 1724 |
+
stop(paste("Primary:", e$message, "| Fallback:", e2$message))
|
| 1725 |
+
})
|
| 1726 |
+
})
|
| 1727 |
|
| 1728 |
+
# ββ Step 5: Assemble results βββββββββββββββββββββββββββββββββ
|
| 1729 |
+
incProgress(0.20, detail = "Assembling results table...")
|
| 1730 |
+
Sys.sleep(0.05)
|
| 1731 |
|
| 1732 |
+
sample_ids <- rownames(X_test_df)
|
| 1733 |
+
if (is.null(sample_ids) || all(sample_ids == as.character(seq_len(nrow(X_test_df))))) {
|
| 1734 |
+
sample_ids <- paste0("Sample_", seq_len(nrow(X_test_df)))
|
| 1735 |
+
}
|
| 1736 |
|
| 1737 |
+
values$predicted_test_phenotype_data <- data.frame(
|
| 1738 |
+
id = sample_ids,
|
| 1739 |
+
Predicted_Phenotype = round(as.numeric(preds), 4),
|
| 1740 |
+
stringsAsFactors = FALSE
|
| 1741 |
+
)
|
| 1742 |
|
| 1743 |
+
incProgress(0.10, detail = "Done!")
|
| 1744 |
+
Sys.sleep(0.1)
|
| 1745 |
|
| 1746 |
+
}) # end withProgress
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1747 |
|
| 1748 |
+
# ββ Notify ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1749 |
+
n_pred <- nrow(values$predicted_test_phenotype_data)
|
| 1750 |
+
train_cols <- if (!is.null(values$model_train_cols)) values$model_train_cols else colnames(values$genotype_data)
|
| 1751 |
+
common_m <- intersect(train_cols, colnames(values$test_genotype_data))
|
| 1752 |
+
missing_m <- setdiff(train_cols, colnames(values$test_genotype_data))
|
| 1753 |
|
| 1754 |
+
showNotification(
|
| 1755 |
+
paste0("β
Predicted ", n_pred, " test samples successfully."),
|
| 1756 |
+
type = "message", duration = 5
|
| 1757 |
+
)
|
| 1758 |
+
|
| 1759 |
+
add_message("assistant", paste0(
|
| 1760 |
+
"β
**Test phenotypes predicted successfully!**\n\n",
|
| 1761 |
+
"β’ **", n_pred, "** samples predicted\n",
|
| 1762 |
+
"β’ Training markers: **", length(train_cols), "** β matched: **", length(common_m), "**",
|
| 1763 |
+
if (length(missing_m) > 0) paste0(" (", length(missing_m), " imputed with 0)") else " β all matched",
|
| 1764 |
+
"\nβ’ Range: ", round(min(values$predicted_test_phenotype_data$Predicted_Phenotype), 3),
|
| 1765 |
+
" to ", round(max(values$predicted_test_phenotype_data$Predicted_Phenotype), 3),
|
| 1766 |
+
"\nβ’ Preview: Data Upload β 'Predicted Test Phenotype' tab\n",
|
| 1767 |
+
"β’ Save: click **Download Predicted Phenotypes (.xlsx)**"
|
| 1768 |
+
))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1769 |
})
|
| 1770 |
|
| 1771 |
# ============================================================
|