softwareDevelopment commited on
Commit
d98046b
Β·
verified Β·
1 Parent(s): c3e74b5

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +172 -88
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
- all_data <- readLines(input$test_genotype_file$datapath)
1431
- header <- strsplit(all_data[1], ",")[[1]]
1432
- gd <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), header = FALSE)
1433
- colnames(gd) <- header; rownames(gd) <- gd[, 1]; gd <- gd[, -1]
1434
- for (col in colnames(gd)) gd[[col]] <- as.numeric(as.character(gd[[col]]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1435
  values$test_genotype_data <- gd
1436
- showNotification("Test genotype loaded", type = "message")
1437
- }, error = function(e) showNotification(paste("Test geno error:", e$message), type = "error"))
 
 
 
 
 
 
 
 
 
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
- incProgress(0.10, detail = "Checking test genotype data...")
1590
- Sys.sleep(0.1)
1591
 
1592
- # ── Use the exact columns the RF model was trained on (after NZV removal) ──
1593
- # Falling back to full genotype cols if model_train_cols wasn't saved (older session)
1594
- train_cols <- if (!is.null(values$model_train_cols)) {
1595
- values$model_train_cols
1596
- } else {
1597
- colnames(values$genotype_data)
1598
- }
1599
 
1600
- test_cols <- colnames(values$test_genotype_data)
1601
- common_m <- intersect(train_cols, test_cols)
1602
- missing_m <- setdiff(train_cols, test_cols)
1603
 
1604
- incProgress(0.15, detail = paste0("Matched ", length(common_m), " / ",
1605
- length(train_cols), " training markers..."))
1606
- Sys.sleep(0.1)
 
 
 
 
 
1607
 
1608
- if (length(common_m) == 0) {
1609
- showNotification(
1610
- paste0("No markers in common between test genotype and training model. ",
1611
- "Ensure test CSV has the same marker column names as training CSV."),
1612
- type = "error", duration = 10)
1613
- return()
1614
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1615
 
1616
- if (length(missing_m) > 0) {
1617
- showNotification(
1618
- paste0(length(missing_m), " training markers missing from test data β€” ",
1619
- "filling with column mean (0 = major homozygote). Predictions may be less accurate."),
1620
- type = "warning", duration = 8)
1621
- }
 
 
 
1622
 
1623
- incProgress(0.20, detail = paste0("Building aligned test matrix (", nrow(values$test_genotype_data), " samples)..."))
1624
- Sys.sleep(0.1)
 
 
 
 
 
 
 
 
 
1625
 
1626
- # Build test matrix aligned to ALL training columns in the correct order
1627
- # Missing columns get filled with 0 (safe default = major homozygote)
1628
- X_test <- values$test_genotype_data[, common_m, drop = FALSE]
1629
 
1630
- if (length(missing_m) > 0) {
1631
- fill_mat <- matrix(0, nrow = nrow(X_test), ncol = length(missing_m),
1632
- dimnames = list(rownames(X_test), missing_m))
1633
- X_test <- cbind(X_test, fill_mat)
 
 
1634
  }
 
1635
 
1636
- # Reorder to exactly match training column order
1637
- X_test <- X_test[, train_cols, drop = FALSE]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1638
 
1639
- # Replace any NAs in test data with 0
1640
- X_test[is.na(X_test)] <- 0
 
1641
 
1642
- incProgress(0.30, detail = paste0("Running prediction model on ",
1643
- nrow(X_test), " samples..."))
 
 
1644
 
1645
- preds <- predict(values$model_fit, newdata = X_test)
 
 
 
 
1646
 
1647
- incProgress(0.20, detail = "Assembling results table...")
 
1648
 
1649
- values$predicted_test_phenotype_data <- data.frame(
1650
- id = rownames(X_test),
1651
- Predicted_Phenotype = round(as.numeric(preds), 4),
1652
- stringsAsFactors = FALSE
1653
- )
1654
 
1655
- incProgress(0.05, detail = "Done!")
1656
- Sys.sleep(0.15)
1657
- })
 
 
1658
 
1659
- n_pred <- nrow(values$predicted_test_phenotype_data)
1660
- showNotification(
1661
- paste0("βœ… Predicted ", n_pred, " test samples. Use Download button to save."),
1662
- type = "message", duration = 5
1663
- )
1664
- add_message("assistant", paste0(
1665
- "βœ… **Test phenotypes predicted!**\n\n",
1666
- "β€’ **", n_pred, "** samples predicted\n",
1667
- "β€’ Training markers used: **", length(train_cols), "**\n",
1668
- "β€’ Matched from test data: **", length(common_m), "**",
1669
- if (length(missing_m) > 0) paste0(" (", length(missing_m), " missing β†’ filled with 0)") else " βœ“",
1670
- "\nβ€’ Preview in Data Upload β†’ 'Predicted Test Phenotype' tab\n",
1671
- "β€’ Click **Download Predicted Phenotypes (.xlsx)** to save"
1672
- ))
1673
- }, error = function(e) {
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
  # ============================================================