softwareDevelopment commited on
Commit
b0778c0
·
verified ·
1 Parent(s): ab0b446

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +1231 -6
app.R CHANGED
@@ -1462,16 +1462,1241 @@ make_idiogram_ggplot <- function(qtl_list, all_markers_df, lod_threshold = 2.0)
1462
  }
1463
 
1464
  # ============================================================
1465
- # UI - Same as before (keeping it concise here)
1466
  # ============================================================
1467
- # [UI code remains identical to previous version - omitted for brevity]
1468
- # In production, include the full UI code from the original
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1469
 
1470
  # ============================================================
1471
- # SERVER with progress bar fixes
1472
  # ============================================================
1473
- # [Server code with progress bar fixes remains as in previous version]
1474
- # In production, include the full server code from the original
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1475
 
1476
  # ============================================================
1477
  # Run the app
 
1462
  }
1463
 
1464
  # ============================================================
1465
+ # UI
1466
  # ============================================================
1467
+ ui <- fluidPage(
1468
+ shinyjs::useShinyjs(),
1469
+ tags$head(
1470
+ tags$link(rel="stylesheet",
1471
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"),
1472
+ tags$style(HTML("
1473
+ *{box-sizing:border-box;}
1474
+ body{font-family:'Inter',sans-serif;background:#f8f9fa;color:#212529;font-size:14px;margin:0;}
1475
+ .navbar{background:#ffffff!important;border-bottom:2px solid #dee2e6!important;box-shadow:0 2px 6px rgba(0,0,0,0.08);}
1476
+ .navbar-brand{font-weight:700;color:#FF006E!important;font-size:18px;}
1477
+ .navbar-nav>li>a{color:#495057!important;font-size:13px;font-weight:500;}
1478
+ .navbar-nav>li.active>a{color:#FF006E!important;background:transparent!important;border-bottom:2px solid #FF006E;}
1479
+ .card{background:#ffffff;border:1px solid #dee2e6;border-radius:10px;margin-bottom:20px;box-shadow:0 2px 8px rgba(0,0,0,0.06);overflow:hidden;}
1480
+ .card-hd{background:linear-gradient(90deg,#f8f9fa,#fff);border-bottom:2px solid #FF006E;padding:10px 16px;font-size:12px;color:#212529;letter-spacing:.4px;text-transform:uppercase;font-weight:700;}
1481
+ .card-bd{padding:16px;}
1482
+ .info-box{background:#e8f4fd;border:1px solid #90caf9;border-left:4px solid #3A86FF;border-radius:6px;padding:10px 14px;margin:6px 0;font-size:13px;}
1483
+ .warn-box{background:#fff8e1;border:1px solid #ffe082;border-left:4px solid #FFBE0B;border-radius:6px;padding:10px 14px;margin:6px 0;font-size:13px;}
1484
+ .good-box{background:#e8f5e9;border:1px solid #a5d6a7;border-left:4px solid #06D6A0;border-radius:6px;padding:10px 14px;margin:6px 0;font-size:13px;}
1485
+ .err-box{background:#fce4ec;border:1px solid #f48fb1;border-left:4px solid #FF006E;border-radius:6px;padding:10px 14px;margin:6px 0;font-size:13px;}
1486
+ .btn{border-radius:7px;font-size:13px;font-weight:500;padding:7px 15px;transition:all .2s;}
1487
+ .btn-primary{background:#FF006E;border-color:#FF006E;color:#fff;}
1488
+ .btn-primary:hover{background:#cc0059;border-color:#cc0059;transform:translateY(-1px);}
1489
+ .btn-success{background:#06D6A0;border-color:#06D6A0;color:#fff;}
1490
+ .btn-success:hover{background:#05b085;border-color:#05b085;transform:translateY(-1px);}
1491
+ .btn-info{background:#3A86FF;border-color:#3A86FF;color:#fff;}
1492
+ .btn-info:hover{background:#2563eb;border-color:#2563eb;transform:translateY(-1px);}
1493
+ .btn-warning{background:#FFBE0B;border-color:#FFBE0B;color:#212529;}
1494
+ .form-control,.selectize-input{background:#ffffff!important;border:1px solid #ced4da!important;color:#212529!important;font-size:13px;border-radius:6px;}
1495
+ label{font-size:12px;color:#6c757d;font-weight:500;}
1496
+ .stat-box{background:#ffffff;border:1px solid #dee2e6;border-radius:8px;padding:14px 18px;text-align:center;}
1497
+ .stat-value{font-size:30px;font-weight:700;color:#FF006E;}
1498
+ .stat-label{font-size:11px;color:#6c757d;text-transform:uppercase;letter-spacing:1px;}
1499
+ table.dataTable thead th{background:#f1f3f5!important;font-weight:600;font-size:12px;color:#FF006E;}
1500
+ table.dataTable tbody td{color:#212529;}
1501
+ table.dataTable tbody tr:hover{background:#f8f9fa!important;}
1502
+ .model-badge{display:inline-block;background:#e8f4fd;border:1px solid #90caf9;border-radius:20px;padding:3px 10px;font-size:11px;font-weight:600;color:#3A86FF;margin:2px;}
1503
+ .perm-info{background:linear-gradient(135deg,#e8f4fd,#f0f8ff);border:1px solid #90caf9;border-left:4px solid #8338EC;border-radius:8px;padding:12px 16px;margin:8px 0;font-size:13px;}
1504
+ .speed-badge{background:#8338EC;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
1505
+ .fix-badge{background:#06D6A0;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
1506
+ .diag-box{background:#fff3cd;border:1px solid #ffc107;border-left:4px solid #fd7e14;border-radius:6px;padding:10px 14px;margin:6px 0;font-size:12px;font-family:monospace;}
1507
+ .progress-bar-custom{height:6px;background:#e9ecef;border-radius:3px;overflow:hidden;margin:10px 0;}
1508
+ .progress-fill{width:0%;height:100%;background:#06D6A0;transition:width 0.3s ease;}
1509
+ "))
1510
+ ),
1511
+
1512
+ navbarPage(
1513
+ title = "QTL-Mapper v12",
1514
+ id = "nav",
1515
+
1516
+ # ── 1. DATA UPLOAD ──────────────────────────────────────
1517
+ tabPanel("📁 Data Upload", icon = icon("upload"),
1518
+ fluidRow(column(12,
1519
+ div(class="info-box",
1520
+ tags$b("QTL-Mapper v12 — Precision QTL Interval Mapping"),
1521
+ tags$br(),
1522
+ "Format: Row1 = header (id, marker1, …) | Row2 = chromosomes | ",
1523
+ "Row3 = positions (cM) | Rows 4+ = samples. Genotypes coded 0/1/2.",
1524
+ tags$br(),
1525
+ tags$span(style="color:#06D6A0;font-weight:600;",
1526
+ "v12 FIXES: LASSO/ENET LOD & PVE use model fitted values (not per-marker OLS) | ",
1527
+ "RF LOD & PVE use OOB predictions | P-values from OLS t-test (not 10^-LOD) | ",
1528
+ "Eliminates LOD=0 / P≈1 / PVE=49.26% locked bug in LASSO/ENET/RF output")
1529
+ )
1530
+ )),
1531
+ fluidRow(
1532
+ column(4,
1533
+ div(class="card",
1534
+ div(class="card-hd","Training Data"),
1535
+ div(class="card-bd",
1536
+ fileInput("geno_file", "Genotype CSV", accept=".csv"),
1537
+ fileInput("pheno_file", "Phenotype CSV", accept=".csv"),
1538
+ selectInput("pheno_col","Select Trait", choices=NULL),
1539
+ tags$hr(style="margin:10px 0;"),
1540
+ fileInput("test_geno_file","Test Genotype CSV (optional)",accept=".csv"),
1541
+ fileInput("pop_file","Population Metadata CSV (optional)",accept=".csv"),
1542
+ helpText("Pop CSV needs columns: 'id' and 'population' (Domesticated / Wild)")
1543
+ )
1544
+ )
1545
+ ),
1546
+ column(4,
1547
+ div(class="card",
1548
+ div(class="card-hd","Mapping Parameters"),
1549
+ div(class="card-bd",
1550
+ selectInput("mapping_method","Mapping Method",
1551
+ choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")),
1552
+ selected = "CIM"),
1553
+ uiOutput("method_desc_ui"),
1554
+
1555
+ sliderInput("lod_threshold","LOD Threshold (manual)",
1556
+ min=0.1, max=10, value=2.0, step=0.1),
1557
+
1558
+ sliderInput("val_prop","Validation Proportion",
1559
+ min=0.1, max=0.4, value=0.2, step=0.05),
1560
+
1561
+ conditionalPanel("input.mapping_method == 'CIM' || input.mapping_method == 'MQM'",
1562
+ numericInput("n_cofactors","Max Cofactors (K)", value=10, min=1, max=30),
1563
+ numericInput("window_size","Exclusion Window (±markers)", value=10, min=1, max=30)
1564
+ ),
1565
+ numericInput("lod_drop","LOD Drop for Support Interval", value=1.5, min=0.5, max=3.0, step=0.1),
1566
+ numericInput("min_peak_distance","Min Distance Between QTL Peaks (cM)", value=5, min=0, max=20, step=1),
1567
+ actionButton("run_btn","▶ Run QTL Analysis",
1568
+ class="btn btn-primary btn-block",
1569
+ style="margin-top:10px;width:100%;"),
1570
+ tags$hr(style="margin:10px 0;"),
1571
+
1572
+ checkboxInput("run_permutation","Estimate LOD threshold by permutation",value=FALSE),
1573
+ conditionalPanel("input.run_permutation",
1574
+ div(class="perm-info",
1575
+ tags$span(class="speed-badge","FAST"),
1576
+ tags$b(" Parallel Permutations"),
1577
+ tags$br(),
1578
+ tags$small("Uses SIM on ≤200 marker subsample. Result shown below. Click 'Apply' to use it."),
1579
+ tags$br(),tags$br(),
1580
+ numericInput("n_perm","Number of Permutations",value=100,min=50,max=1000,step=50),
1581
+ numericInput("perm_alpha","Alpha (significance)",value=0.05,min=0.01,max=0.20,step=0.01),
1582
+ uiOutput("perm_result_ui"),
1583
+ actionButton("apply_perm_thr","Apply Permutation Threshold to Slider",
1584
+ class="btn btn-warning btn-block",style="margin-top:6px;")
1585
+ )
1586
+ )
1587
+ )
1588
+ )
1589
+ ),
1590
+ column(4,
1591
+ div(class="card",
1592
+ div(class="card-hd","Dataset Summary & Diagnostics"),
1593
+ div(class="card-bd",uiOutput("dataset_info_ui"))
1594
+ ),
1595
+ div(class="card",
1596
+ div(class="card-hd","Predict Test Phenotypes"),
1597
+ div(class="card-bd",
1598
+ actionButton("pred_btn","Predict Test Samples",class="btn btn-info btn-block"),
1599
+ tags$br(),
1600
+ downloadButton("dl_pred","Download Predictions (.xlsx)",
1601
+ class="btn btn-success btn-block",style="margin-top:6px;")
1602
+ )
1603
+ )
1604
+ )
1605
+ ),
1606
+ fluidRow(column(12,
1607
+ div(class="card",
1608
+ div(class="card-hd","Data Preview"),
1609
+ div(class="card-bd",
1610
+ tabsetPanel(
1611
+ tabPanel("Training Genotype", DTOutput("prev_geno")),
1612
+ tabPanel("Training Phenotype", DTOutput("prev_pheno")),
1613
+ tabPanel("Marker Map", DTOutput("prev_marker_info")),
1614
+ tabPanel("Test Genotype", DTOutput("prev_test_geno")),
1615
+ tabPanel("Predicted Phenotype", DTOutput("prev_pred"))
1616
+ )
1617
+ )
1618
+ )
1619
+ ))
1620
+ ),
1621
+
1622
+ # ── 2. RESULTS ──────────────────────────────────────────
1623
+ tabPanel("📊 Results", icon=icon("chart-line"),
1624
+ fluidRow(column(12,
1625
+ div(style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px;",
1626
+ downloadButton("dl_manhattan","Manhattan Plot (PNG)",class="btn btn-info"),
1627
+ downloadButton("dl_idiogram", "Chromosome Map (PNG)",class="btn btn-info"),
1628
+ downloadButton("dl_results", "Full Results (.xlsx)", class="btn btn-success")
1629
+ )
1630
+ )),
1631
+ fluidRow(
1632
+ column(7,
1633
+ div(class="card",
1634
+ div(class="card-hd","Manhattan Plot — LOD Scores Across Genome"),
1635
+ div(class="card-bd",plotlyOutput("manhattan_plot",height="480px"))
1636
+ )
1637
+ ),
1638
+ column(5,
1639
+ div(class="card",
1640
+ div(class="card-hd","Chromosome Idiogram — QTL Positions"),
1641
+ div(class="card-bd",plotOutput("idiogram_plot",height="480px"))
1642
+ )
1643
+ )
1644
+ ),
1645
+ fluidRow(
1646
+ column(4,
1647
+ div(class="card",
1648
+ div(class="card-hd","Model Performance Metrics"),
1649
+ div(class="card-bd",plotlyOutput("perf_plot",height="270px"))
1650
+ )
1651
+ ),
1652
+ column(4,
1653
+ div(class="card",
1654
+ div(class="card-hd","Training: Predicted vs Observed"),
1655
+ div(class="card-bd",plotlyOutput("reg_train",height="270px"))
1656
+ )
1657
+ ),
1658
+ column(4,
1659
+ div(class="card",
1660
+ div(class="card-hd","Validation: Predicted vs Observed"),
1661
+ div(class="card-bd",plotlyOutput("reg_val",height="270px"))
1662
+ )
1663
+ )
1664
+ ),
1665
+ fluidRow(column(12,
1666
+ div(class="card",
1667
+ div(class="card-hd","Significant QTL Peaks — Above LOD Threshold"),
1668
+ div(class="card-bd",DTOutput("qtl_peaks_table"))
1669
+ )
1670
+ )),
1671
+ fluidRow(column(12,
1672
+ div(class="card",
1673
+ div(class="card-hd","Full Genome Scan Results"),
1674
+ div(class="card-bd",DTOutput("full_scan_table"))
1675
+ )
1676
+ ))
1677
+ ),
1678
+
1679
+ # ── 3. COMPARE MODELS ───────────────────────────────────
1680
+ tabPanel("⚖️ Compare Models", icon=icon("balance-scale"),
1681
+ fluidRow(column(12,
1682
+ div(class="card",
1683
+ div(class="card-hd","Multi-Model Comparison"),
1684
+ div(class="card-bd",
1685
+ div(class="info-box",
1686
+ "Select methods, click Run. PVE is comparable across all methods (SST denominator)."),
1687
+ checkboxGroupInput("compare_methods","Methods to Compare:",
1688
+ choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")),
1689
+ selected = c("SIM","CIM","LASSO"), inline=TRUE),
1690
+ actionButton("run_compare","Run Selected Models",class="btn btn-primary"),
1691
+ tags$br(),tags$br(),
1692
+ uiOutput("compare_status_ui")
1693
+ )
1694
+ )
1695
+ )),
1696
+ fluidRow(
1697
+ column(6,
1698
+ div(class="card",
1699
+ div(class="card-hd","Multi-Model Chromosome Map"),
1700
+ div(class="card-bd",plotOutput("compare_idiogram",height="500px"))
1701
+ )
1702
+ ),
1703
+ column(6,
1704
+ div(class="card",
1705
+ div(class="card-hd","QTL Count by Method & Chromosome"),
1706
+ div(class="card-bd",plotlyOutput("compare_bar",height="500px"))
1707
+ )
1708
+ )
1709
+ ),
1710
+ fluidRow(column(12,
1711
+ div(class="card",
1712
+ div(class="card-hd","All Significant QTL Peaks — All Models"),
1713
+ div(class="card-bd",DTOutput("compare_table"))
1714
+ )
1715
+ ))
1716
+ ),
1717
+
1718
+ # ── 4. COMMON QTL ───────────────────────────────────────
1719
+ tabPanel("🎯 Common QTL", icon=icon("bullseye"),
1720
+ fluidRow(column(12,
1721
+ div(class="card",
1722
+ div(class="card-hd","Common QTL — Markers Significant Across Multiple Models"),
1723
+ div(class="card-bd",
1724
+ fluidRow(
1725
+ column(4, sliderInput("min_models","Minimum Models Agreeing",min=2,max=6,value=2,step=1)),
1726
+ column(4, div(style="margin-top:26px;",
1727
+ downloadButton("dl_common_qtl","Download Common QTL (.xlsx)",
1728
+ class="btn btn-success btn-block"))),
1729
+ column(4, div(style="margin-top:10px;",uiOutput("common_qtl_summary_ui")))
1730
+ )
1731
+ )
1732
+ )
1733
+ )),
1734
+ fluidRow(
1735
+ column(6,
1736
+ div(class="card",
1737
+ div(class="card-hd","Common QTL — Chromosome Map"),
1738
+ div(class="card-bd",plotOutput("common_idiogram",height="480px"))
1739
+ )
1740
+ ),
1741
+ column(6,
1742
+ div(class="card",
1743
+ div(class="card-hd","Model Agreement by Chromosome"),
1744
+ div(class="card-bd",plotlyOutput("common_bar",height="480px"))
1745
+ )
1746
+ )
1747
+ ),
1748
+ fluidRow(column(12,
1749
+ div(class="card",
1750
+ div(class="card-hd","Common QTL Details"),
1751
+ div(class="card-bd",
1752
+ div(class="good-box","Run the Compare Models tab first, then return here."),
1753
+ tags$br(), DTOutput("common_qtl_table"))
1754
+ )
1755
+ ))
1756
+ ),
1757
+
1758
+ # ── 5. DOMESTICATION ────────────────────────────────────
1759
+ tabPanel("🌾 Domestication", icon=icon("leaf"),
1760
+ fluidRow(
1761
+ column(4,
1762
+ div(class="card",
1763
+ div(class="card-hd","Selection Parameters"),
1764
+ div(class="card-bd",
1765
+ numericInput("fst_thr", "Fst Threshold", value=0.1, min=0.01,max=0.5, step=0.01),
1766
+ numericInput("tajima_thr","Tajima's D Threshold", value=-1.0,min=-5, max=0, step=0.1),
1767
+ actionButton("run_dom","Run Domestication Analysis",class="btn btn-primary btn-block")
1768
+ )
1769
+ )
1770
+ ),
1771
+ column(8,
1772
+ div(class="card",
1773
+ div(class="card-hd","Population Metadata"),
1774
+ div(class="card-bd",DTOutput("prev_pop"))
1775
+ )
1776
+ )
1777
+ ),
1778
+ fluidRow(
1779
+ column(6,
1780
+ div(class="card",
1781
+ div(class="card-hd","Fst Manhattan Plot"),
1782
+ div(class="card-bd",plotlyOutput("fst_plot",height="380px"))
1783
+ )
1784
+ ),
1785
+ column(6,
1786
+ div(class="card",
1787
+ div(class="card-hd","Tajima's D Manhattan Plot"),
1788
+ div(class="card-bd",plotlyOutput("tajima_plot",height="380px"))
1789
+ )
1790
+ )
1791
+ ),
1792
+ fluidRow(column(12,
1793
+ div(class="card",
1794
+ div(class="card-hd","Selection Signatures"),
1795
+ div(class="card-bd",
1796
+ DTOutput("sel_table"),tags$br(),
1797
+ downloadButton("dl_sel","Download Selection Results (.xlsx)",class="btn btn-success")
1798
+ )
1799
+ )
1800
+ ))
1801
+ ),
1802
+
1803
+ # ── 6. ABOUT ────────────────────────────────────────────
1804
+ tabPanel("ℹ️ About", icon=icon("info-circle"),
1805
+ fluidRow(column(10, offset=1,
1806
+ div(class="card",
1807
+ div(class="card-bd",
1808
+ tags$h4(style="color:#FF006E;","QTL-Mapper v12 — Precision QTL Interval Mapping"),
1809
+ div(class="info-box",
1810
+ tags$b("v12 Bug Fixes (LASSO / ENET / RF):"), tags$br(),tags$br(),
1811
+
1812
+ tags$span(class="fix-badge","FIXED"),
1813
+ tags$b(" LASSO/ENET LOD = 0 bug:"),
1814
+ " Root cause: v11 computed LOD per-marker using simple OLS on scaled predictors,
1815
+ but many markers had near-zero effects after penalization causing LOD → 0.
1816
+ Fix: Global LOD now uses LASSO/ENET fitted values:
1817
+ LOD = (n/2)*log10(SST / RSS_model). Per-marker LOD from individual OLS.",
1818
+ tags$br(),tags$br(),
1819
+
1820
+ tags$span(class="fix-badge","FIXED"),
1821
+ tags$b(" P-value ≈ 1.0 bug (LASSO/ENET/RF):"),
1822
+ " Root cause: v11 set P_Value = 10^(-LOD). When global LOD ≈ 0, P ≈ 1.
1823
+ Fix: P-values now come from individual OLS t-test (coef[2,4]) per marker.",
1824
+ tags$br(),tags$br(),
1825
+
1826
+ tags$span(class="fix-badge","FIXED"),
1827
+ tags$b(" PVE locked at 49.255% bug (LASSO/ENET):"),
1828
+ " Root cause: per-marker OLS on many near-null markers consistently
1829
+ explains ~49% when RSS ≈ SST/2 (intercept-only behaviour).
1830
+ Fix: LASSO/ENET PVE uses model-level fitted values vs SST.",
1831
+ tags$br(),tags$br(),
1832
+
1833
+ tags$span(class="fix-badge","FIXED"),
1834
+ tags$b(" RF LOD/PVE bug:"),
1835
+ " Fix: RF global LOD and PVE use OOB predictions:
1836
+ LOD = (n/2)*log10(SST/RSS_oob). Per-marker LOD still uses individual OLS.",
1837
+ tags$br(),tags$br(),
1838
+
1839
+ tags$span(class="fix-badge","RETAINED"),
1840
+ tags$b(" All v11 fixes retained:"),
1841
+ " find_interval_boundary seq() crash, safe_partition(), sample ID matching,
1842
+ PVE SST denominator for SIM/CIM/MQM, permutation threshold storage."
1843
+ ),
1844
+ div(class="info-box",style="margin-top:12px;",
1845
+ tags$b("Statistical Formulas (v12):"), tags$br(),
1846
+ tags$b("SIM/CIM/MQM:"), tags$br(),
1847
+ tags$code("LOD = (n/2) × log10(RSS_null / RSS_full)"), tags$br(),
1848
+ tags$code("PVE = (SST - RSS_full) / SST × 100"), tags$br(),tags$br(),
1849
+ tags$b("LASSO/ENET — Global model:"), tags$br(),
1850
+ tags$code("LOD_global = (n/2) × log10(SST / RSS_model_fitted)"), tags$br(),
1851
+ tags$code("PVE_global = (SST - RSS_model_fitted) / SST × 100"), tags$br(),
1852
+ tags$code("LOD_marker = (n/2) × log10(RSS_null / RSS_ols_marker) [per-marker OLS]"), tags$br(),
1853
+ tags$code("P_marker from OLS t-test"), tags$br(),tags$br(),
1854
+ tags$b("RF — Global model:"), tags$br(),
1855
+ tags$code("LOD_global = (n/2) × log10(SST / RSS_oob)"), tags$br(),
1856
+ tags$code("PVE_global = (SST - RSS_oob) / SST × 100"), tags$br(),
1857
+ tags$code("LOD_marker = per-marker OLS LOD [for Manhattan/peak detection]")
1858
+ ),
1859
+ tags$h5(style="margin-top:18px;font-weight:600;color:#3A86FF;","References"),
1860
+ tags$ul(
1861
+ tags$li("Lander & Botstein (1989) Genetics 121:185 — Interval mapping"),
1862
+ tags$li("Zeng (1993) PNAS 90:10972; Zeng (1994) Genetics 136:1457 — CIM"),
1863
+ tags$li("Tibshirani (1996) JRSS-B 58:267 — LASSO"),
1864
+ tags$li("Zou & Hastie (2005) JRSS-B 67:301 — Elastic Net"),
1865
+ tags$li("Breiman (2001) Machine Learning 45:5 — Random Forest")
1866
+ ),
1867
+ tags$hr(),
1868
+ tags$p(style="text-align:center;color:#6c757d;font-size:12px;",
1869
+ "Contact: ashmithamganesan@gmail.com | P.sinha@cgiar.org",
1870
+ tags$br(), "QTL-Mapper v12 © 2025")
1871
+ )
1872
+ )
1873
+ ))
1874
+ )
1875
+ )
1876
+ )
1877
 
1878
  # ============================================================
1879
+ # SERVER
1880
  # ============================================================
1881
+ server <- function(input, output, session) {
1882
+
1883
+ rv <- reactiveValues(
1884
+ geno = NULL, pheno = NULL,
1885
+ test_geno = NULL, pop_data = NULL,
1886
+ marker_info = NULL,
1887
+ scan_all = NULL,
1888
+ qtl_peaks = NULL,
1889
+ perf = NULL, tr_pred = NULL, val_pred = NULL,
1890
+ model_fit = NULL, model_cols = NULL,
1891
+ pred_test = NULL,
1892
+ sel_metrics = NULL,
1893
+ compare_res = list(),
1894
+ compare_peaks = list(),
1895
+ perm_threshold = NULL,
1896
+ diag_info = NULL,
1897
+ analysis_running = FALSE
1898
+ )
1899
+
1900
+ lod_thr <- reactive({ input$lod_threshold })
1901
+
1902
+ output$method_desc_ui <- renderUI({
1903
+ m <- input$mapping_method
1904
+ if (is.null(m) || !m %in% names(MAPPING_MODELS)) return(NULL)
1905
+ div(class="info-box",style="font-size:12px;", MAPPING_MODELS[[m]]$desc)
1906
+ })
1907
+
1908
+ output$perm_result_ui <- renderUI({
1909
+ if (is.null(rv$perm_threshold)) return(NULL)
1910
+ div(class="good-box",style="margin-top:8px;",
1911
+ tags$span(class="fix-badge","RESULT"),
1912
+ tags$b(" Permutation LOD threshold: "),
1913
+ strong(round(rv$perm_threshold, 3)),
1914
+ tags$br(),
1915
+ tags$small(style="color:#555;","Click 'Apply' above to set the slider to this value.")
1916
+ )
1917
+ })
1918
+
1919
+ observeEvent(input$apply_perm_thr, {
1920
+ req(rv$perm_threshold)
1921
+ thr <- round(rv$perm_threshold, 2)
1922
+ thr <- max(0.1, min(10, thr))
1923
+ updateSliderInput(session, "lod_threshold", value = thr)
1924
+ showNotification(paste0("LOD threshold set to ", thr,
1925
+ " (permutation, alpha=", input$perm_alpha, ")"),
1926
+ type = "message", duration = 4)
1927
+ })
1928
+
1929
+ output$dataset_info_ui <- renderUI({
1930
+ if (is.null(rv$geno))
1931
+ return(div(class="warn-box","Upload genotype and phenotype files to begin."))
1932
+
1933
+ diag_msgs <- character(0)
1934
+ n_geno <- nrow(rv$geno)
1935
+ n_pheno <- if (!is.null(rv$pheno)) nrow(rv$pheno) else 0
1936
+
1937
+ if (!is.null(rv$pheno) && !is.null(input$pheno_col) && nchar(input$pheno_col) > 0) {
1938
+ cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
1939
+ n_cs <- length(cs)
1940
+ if (n_cs == 0) {
1941
+ diag_msgs <- c(diag_msgs,
1942
+ paste0("⚠ 0 common samples! Geno IDs: '",
1943
+ paste(head(rownames(rv$geno), 3), collapse="', '"), "'... | Pheno IDs: '",
1944
+ paste(head(rownames(rv$pheno), 3), collapse="', '"), "'..."))
1945
+ } else {
1946
+ y_cs <- as.numeric(rv$pheno[cs, input$pheno_col])
1947
+ n_na <- sum(is.na(y_cs))
1948
+ n_valid <- n_cs - n_na
1949
+ if (n_valid < 10)
1950
+ diag_msgs <- c(diag_msgs,
1951
+ paste0("⚠ Only ", n_valid, " non-NA phenotype values. Need ≥10 to run analysis."))
1952
+ if (n_valid >= 2 && var(y_cs, na.rm=TRUE) < 1e-10)
1953
+ diag_msgs <- c(diag_msgs, "⚠ Phenotype has zero variance — check your data.")
1954
+ if (n_na > 0)
1955
+ diag_msgs <- c(diag_msgs, paste0("ℹ ", n_na, " samples have NA phenotype (will be excluded)."))
1956
+ }
1957
+ } else {
1958
+ n_cs <- 0
1959
+ }
1960
+
1961
+ tagList(
1962
+ fluidRow(
1963
+ column(6, div(class="stat-box",
1964
+ tags$div(class="stat-value", n_geno),
1965
+ tags$div(class="stat-label","Geno Samples"))),
1966
+ column(6, div(class="stat-box",
1967
+ tags$div(class="stat-value", ncol(rv$geno)),
1968
+ tags$div(class="stat-label","Markers")))
1969
+ ),
1970
+ fluidRow(
1971
+ column(6, div(class="stat-box",
1972
+ tags$div(class="stat-value", length(unique(rv$marker_info$Chromosome))),
1973
+ tags$div(class="stat-label","Chromosomes"))),
1974
+ column(6, div(class="stat-box",
1975
+ tags$div(class="stat-value", if (n_cs > 0) n_cs else "—"),
1976
+ tags$div(class="stat-label","Common Samples")))
1977
+ ),
1978
+ if (length(diag_msgs) > 0)
1979
+ div(class="diag-box", tags$b("Diagnostics:"), tags$br(),
1980
+ lapply(diag_msgs, function(m) tagList(m, tags$br()))),
1981
+ if (!is.null(rv$perm_threshold))
1982
+ div(class="perm-info",style="margin-top:8px;",
1983
+ tags$span(class="speed-badge","FAST"),
1984
+ tags$b(" Permutation LOD: "), round(rv$perm_threshold,3),
1985
+ tags$br(),
1986
+ tags$small("Use 'Apply Permutation Threshold' button to set slider."))
1987
+ )
1988
+ })
1989
+
1990
+ observeEvent(input$geno_file, {
1991
+ req(input$geno_file)
1992
+ tryCatch({
1993
+ res <- load_genotype_file(input$geno_file$datapath)
1994
+ rv$geno <- res$geno; rv$marker_info <- res$marker_info
1995
+ showNotification(paste("Loaded", res$n_markers,"markers,", res$n_samples,"samples"),
1996
+ type="message", duration=4)
1997
+ }, error=function(e) showNotification(paste("Genotype error:", e$message), type="error"))
1998
+ })
1999
+
2000
+ observeEvent(input$pheno_file, {
2001
+ req(input$pheno_file)
2002
+ tryCatch({
2003
+ pd <- read.csv(input$pheno_file$datapath)
2004
+ rownames(pd) <- make.unique(normalize_id(as.character(pd[,1])))
2005
+ pd <- pd[,-1,drop=FALSE]
2006
+ for (col in colnames(pd)) pd[[col]] <- suppressWarnings(as.numeric(as.character(pd[[col]])))
2007
+ rv$pheno <- pd
2008
+ updateSelectInput(session,"pheno_col",choices=colnames(pd),selected=colnames(pd)[1])
2009
+ showNotification(paste("Loaded",ncol(pd),"traits,",nrow(pd),"samples"),type="message",duration=3)
2010
+ }, error=function(e) showNotification(paste("Phenotype error:", e$message), type="error"))
2011
+ })
2012
+
2013
+ observeEvent(input$pop_file, {
2014
+ req(input$pop_file)
2015
+ tryCatch({
2016
+ rv$pop_data <- read.csv(input$pop_file$datapath)
2017
+ showNotification(paste("Population data:",nrow(rv$pop_data),"samples"),type="message")
2018
+ }, error=function(e) showNotification(paste("Pop error:", e$message), type="error"))
2019
+ })
2020
+
2021
+ observeEvent(input$test_geno_file, {
2022
+ req(input$test_geno_file)
2023
+ tryCatch({
2024
+ res <- load_genotype_file(input$test_geno_file$datapath)
2025
+ rv$test_geno <- res$geno
2026
+ showNotification(paste("Test genotype:",nrow(res$geno),"samples"),type="message")
2027
+ }, error=function(e) showNotification(paste("Test geno error:", e$message), type="error"))
2028
+ })
2029
+
2030
+ output$prev_geno <- renderDT({ req(rv$geno); datatable(head(rv$geno,10), options=list(scrollX=TRUE,pageLength=5,dom="t")) })
2031
+ output$prev_pheno <- renderDT({ req(rv$pheno); datatable(head(rv$pheno,10), options=list(scrollX=TRUE,pageLength=5,dom="t")) })
2032
+ output$prev_marker_info <- renderDT({ req(rv$marker_info); datatable(rv$marker_info, options=list(scrollX=TRUE,pageLength=10)) })
2033
+ output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno,10), options=list(scrollX=TRUE,pageLength=5,dom="t")) })
2034
+ output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test, options=list(scrollX=TRUE,pageLength=10)) })
2035
+ output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data,20), options=list(scrollX=TRUE,pageLength=10)) })
2036
+
2037
+ # ---- MAIN ANALYSIS with PROGRESS BAR ----
2038
+ observeEvent(input$run_btn, {
2039
+ req(rv$geno, rv$pheno, input$pheno_col)
2040
+
2041
+ if (rv$analysis_running) {
2042
+ showNotification("Analysis already running. Please wait...", type = "warning")
2043
+ return()
2044
+ }
2045
+
2046
+ rv$analysis_running <- TRUE
2047
+ shinyjs::disable("run_btn")
2048
+
2049
+ showNotification(paste("Starting", input$mapping_method, "analysis..."), type = "message")
2050
+
2051
+ tryCatch({
2052
+ cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
2053
+ cat("Common samples:", length(cs), "\n")
2054
+
2055
+ if (length(cs) == 0) {
2056
+ showNotification(
2057
+ paste0("No common samples between genotype and phenotype files. ",
2058
+ "Geno example: '", rownames(rv$geno)[1], "' | ",
2059
+ "Pheno example: '", rownames(rv$pheno)[1], "'"),
2060
+ type="error", duration=10)
2061
+ rv$analysis_running <- FALSE
2062
+ shinyjs::enable("run_btn")
2063
+ return()
2064
+ }
2065
+
2066
+ X <- rv$geno[cs, , drop=FALSE]
2067
+ y_raw <- rv$pheno[cs, input$pheno_col]
2068
+ y <- suppressWarnings(as.numeric(as.character(y_raw)))
2069
+
2070
+ if (sum(!is.na(y)) < 10) {
2071
+ showNotification(
2072
+ paste0("Only ", sum(!is.na(y)), " non-NA phenotype values. Need at least 10."),
2073
+ type="error", duration=10)
2074
+ rv$analysis_running <- FALSE
2075
+ shinyjs::enable("run_btn")
2076
+ return()
2077
+ }
2078
+
2079
+ if (var(y, na.rm=TRUE) < 1e-10) {
2080
+ showNotification("Phenotype has zero variance.", type="error", duration=8)
2081
+ rv$analysis_running <- FALSE
2082
+ shinyjs::enable("run_btn")
2083
+ return()
2084
+ }
2085
+
2086
+ partition <- tryCatch(safe_partition(y, val_prop = input$val_prop),
2087
+ error = function(e) { showNotification(e$message, type="error", duration=10); NULL })
2088
+ if (is.null(partition)) {
2089
+ rv$analysis_running <- FALSE
2090
+ shinyjs::enable("run_btn")
2091
+ return()
2092
+ }
2093
+
2094
+ tr_idx <- partition$train; val_idx <- partition$val
2095
+
2096
+ X_tr <- X[tr_idx, , drop=FALSE]; y_tr <- y[tr_idx]
2097
+ X_v <- X[val_idx, , drop=FALSE]; y_v <- y[val_idx]
2098
+
2099
+ tr_ok <- !is.na(y_tr); X_tr <- X_tr[tr_ok, , drop=FALSE]; y_tr <- y_tr[tr_ok]
2100
+ val_ok <- !is.na(y_v); X_v <- X_v[val_ok, , drop=FALSE]; y_v <- y_v[val_ok]
2101
+
2102
+ cat(" Final train N:", length(y_tr), " val N:", length(y_v), "\n")
2103
+
2104
+ withProgress(message = paste("Running", input$mapping_method, "analysis..."), value = 0, {
2105
+
2106
+ incProgress(0.05, detail = "Preparing data...")
2107
+
2108
+ if (isTRUE(input$run_permutation)) {
2109
+ incProgress(0, detail = "Running parallel permutations...")
2110
+ rv$perm_threshold <- permutation_threshold(
2111
+ X_tr, y_tr, rv$marker_info,
2112
+ method = input$mapping_method, n_perm = input$n_perm,
2113
+ alpha = input$perm_alpha, n_cofactors = input$n_cofactors,
2114
+ window_size = input$window_size)
2115
+ showNotification(
2116
+ paste0("Permutation done. LOD threshold = ", round(rv$perm_threshold, 3),
2117
+ " — click 'Apply Permutation Threshold' to use it."),
2118
+ type="message", duration=6)
2119
+ }
2120
+
2121
+ incProgress(0.2, detail = "Running QTL scan...")
2122
+
2123
+ rv$scan_all <- qtl_scan(X_tr, y_tr, rv$marker_info,
2124
+ method = input$mapping_method,
2125
+ n_cofactors = input$n_cofactors,
2126
+ window_size = input$window_size)
2127
+
2128
+ incProgress(0.4, detail = "Detecting QTL peaks...")
2129
+
2130
+ rv$qtl_peaks <- find_qtl_peaks(rv$scan_all, lod_thr(), input$min_peak_distance)
2131
+ if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) {
2132
+ rv$qtl_peaks <- add_precision_support_intervals(rv$qtl_peaks, rv$scan_all, input$lod_drop)
2133
+ cat("Found", nrow(rv$qtl_peaks), "QTL peaks\n")
2134
+ }
2135
+
2136
+ incProgress(0.1, detail = "Building prediction model...")
2137
+
2138
+ nzv_i <- tryCatch(caret::nearZeroVar(X_tr), error=function(e) integer(0))
2139
+ Xtr_rf <- if (length(nzv_i) > 0) X_tr[,-nzv_i,drop=FALSE] else X_tr
2140
+ Xv_rf <- X_v[, intersect(colnames(Xtr_rf), colnames(X_v)), drop=FALSE]
2141
+ missing_cols <- setdiff(colnames(Xtr_rf), colnames(Xv_rf))
2142
+ if (length(missing_cols) > 0) {
2143
+ for (mc in missing_cols) Xv_rf[[mc]] <- 0
2144
+ Xv_rf <- Xv_rf[, colnames(Xtr_rf), drop=FALSE]
2145
+ }
2146
+ rv$model_cols <- colnames(Xtr_rf)
2147
+
2148
+ use_rf <- nrow(Xtr_rf) >= 20 && ncol(Xtr_rf) >= 2
2149
+ fit <- if (use_rf) {
2150
+ tryCatch(
2151
+ caret::train(x=Xtr_rf, y=y_tr, method="rf",
2152
+ trControl=caret::trainControl(method="cv",number=min(5,floor(nrow(Xtr_rf)/5))),
2153
+ tuneLength=3),
2154
+ error=function(e) {
2155
+ cat("RF train failed:", e$message, "— falling back to lm\n")
2156
+ tryCatch(
2157
+ caret::train(x=Xtr_rf, y=y_tr, method="lm",
2158
+ trControl=caret::trainControl(method="cv",number=min(5,floor(nrow(Xtr_rf)/5)))),
2159
+ error=function(e2) NULL)
2160
+ })
2161
+ } else {
2162
+ tryCatch(
2163
+ caret::train(x=Xtr_rf, y=y_tr, method="lm",
2164
+ trControl=caret::trainControl(method="cv",number=min(5,floor(nrow(Xtr_rf)/5)))),
2165
+ error=function(e) NULL)
2166
+ }
2167
+
2168
+ if (is.null(fit)) {
2169
+ showNotification("Prediction model failed — QTL results still available", type="warning")
2170
+ rv$perf <- data.frame(Metric=c("R² Train","R Train","R² Validation","R Validation"),
2171
+ Value=rep(NA_real_,4))
2172
+ rv$tr_pred <- data.frame(Observed=y_tr, Predicted=rep(NA_real_,length(y_tr)))
2173
+ rv$val_pred<- data.frame(Observed=y_v, Predicted=rep(NA_real_,length(y_v)))
2174
+ } else {
2175
+ rv$model_fit <- fit
2176
+ ytr_p <- predict(fit, Xtr_rf); yv_p <- predict(fit, Xv_rf)
2177
+ tr_r2 <- max(0, 1 - sum((y_tr-ytr_p)^2)/sum((y_tr-mean(y_tr))^2))
2178
+ v_r2 <- max(0, 1 - sum((y_v-yv_p)^2) /sum((y_v-mean(y_v))^2))
2179
+ rv$perf <- data.frame(
2180
+ Metric = c("R² Train","R Train","R² Validation","R Validation"),
2181
+ Value = c(tr_r2, cor(y_tr,ytr_p), v_r2, cor(y_v,yv_p)))
2182
+ rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_p)
2183
+ rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_p)
2184
+ }
2185
+
2186
+ incProgress(0.1, detail = "Finalizing...")
2187
+ })
2188
+
2189
+ n_sig <- if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) nrow(rv$qtl_peaks) else 0
2190
+ showNotification(paste(input$mapping_method,"done —",n_sig,"QTL peaks detected"),
2191
+ type="message")
2192
+ updateTabsetPanel(session,"nav",selected="📊 Results")
2193
+
2194
+ }, error=function(e) {
2195
+ showNotification(paste("Analysis error:", e$message), type="error", duration=10)
2196
+ cat("ERROR:", e$message, "\n")
2197
+ })
2198
+
2199
+ rv$analysis_running <- FALSE
2200
+ shinyjs::enable("run_btn")
2201
+ })
2202
+
2203
+ # ---- COMPARE MODELS with PROGRESS BAR ----
2204
+ output$compare_status_ui <- renderUI({
2205
+ if (length(rv$compare_res) == 0) return(NULL)
2206
+ div(class="good-box",
2207
+ tags$b("Completed: "), paste(names(rv$compare_res), collapse=", "),
2208
+ tags$br(),
2209
+ lapply(names(rv$compare_res), function(m) {
2210
+ r <- rv$compare_res[[m]]
2211
+ n <- if (!is.null(r) && !"Message" %in% colnames(r)) {
2212
+ peaks <- find_qtl_peaks(r, lod_thr(), input$min_peak_distance)
2213
+ if (!is.null(peaks)) nrow(peaks) else 0
2214
+ } else 0
2215
+ tags$span(class="model-badge", paste0(m,": ",n," QTLs"))
2216
+ }))
2217
+ })
2218
+
2219
+ observeEvent(input$run_compare, {
2220
+ req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
2221
+ if (length(input$compare_methods) == 0) {
2222
+ showNotification("Select at least one method", type="warning")
2223
+ return()
2224
+ }
2225
+
2226
+ cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
2227
+ if (length(cs) == 0) {
2228
+ showNotification("No common samples — check file IDs match", type="error")
2229
+ return()
2230
+ }
2231
+
2232
+ X <- rv$geno[cs, , drop=FALSE]
2233
+ y <- suppressWarnings(as.numeric(as.character(rv$pheno[cs, input$pheno_col])))
2234
+
2235
+ partition <- tryCatch(safe_partition(y, val_prop=input$val_prop),
2236
+ error=function(e) { showNotification(e$message, type="error"); NULL })
2237
+ if (is.null(partition)) return()
2238
+
2239
+ X_tr <- X[partition$train, , drop=FALSE]
2240
+ y_tr <- y[partition$train]
2241
+ ok <- !is.na(y_tr)
2242
+ X_tr <- X_tr[ok,,drop=FALSE]; y_tr <- y_tr[ok]
2243
+
2244
+ clist <- list(); peaks_list <- list()
2245
+
2246
+ withProgress(message = "Comparing models...", value = 0, {
2247
+ total_methods <- length(input$compare_methods)
2248
+ for (i in seq_along(input$compare_methods)) {
2249
+ mth <- input$compare_methods[i]
2250
+ incProgress(1/total_methods, detail = paste("Running", mth))
2251
+
2252
+ res <- tryCatch(
2253
+ qtl_scan(X_tr, y_tr, rv$marker_info, method=mth,
2254
+ n_cofactors=input$n_cofactors, window_size=input$window_size),
2255
+ error=function(e) { cat("Compare error",mth,":",e$message,"\n"); NULL })
2256
+ if (!is.null(res) && !"Message" %in% colnames(res)) {
2257
+ clist[[mth]] <- res
2258
+ peaks <- find_qtl_peaks(res, lod_thr(), input$min_peak_distance)
2259
+ if (!is.null(peaks) && nrow(peaks) > 0) {
2260
+ peaks <- add_precision_support_intervals(peaks, res, input$lod_drop)
2261
+ peaks_list[[mth]] <- peaks
2262
+ }
2263
+ }
2264
+ }
2265
+ })
2266
+
2267
+ rv$compare_res <- clist
2268
+ rv$compare_peaks <- peaks_list
2269
+ showNotification(paste("Compared", length(clist),"models"), type="message")
2270
+ })
2271
+
2272
+ output$compare_idiogram <- renderPlot({
2273
+ req(length(rv$compare_peaks) > 0, rv$marker_info)
2274
+ make_idiogram_ggplot(rv$compare_peaks, rv$marker_info, lod_thr())
2275
+ }, bg="white")
2276
+
2277
+ output$compare_bar <- renderPlotly({
2278
+ req(length(rv$compare_peaks) > 0)
2279
+ rows <- list()
2280
+ for (mth in names(rv$compare_peaks)) {
2281
+ peaks <- rv$compare_peaks[[mth]]
2282
+ if (is.null(peaks) || nrow(peaks) == 0) next
2283
+ for (ch in unique(peaks$Chromosome))
2284
+ rows <- c(rows, list(data.frame(Method=mth, Chromosome=as.character(ch),
2285
+ Count=sum(peaks$Chromosome==ch))))
2286
+ }
2287
+ if (length(rows) == 0)
2288
+ return(plot_ly() %>% layout(title="No significant QTLs",
2289
+ paper_bgcolor="white",plot_bgcolor="white"))
2290
+ df <- do.call(rbind, rows)
2291
+ df$Chromosome <- factor(df$Chromosome, levels=sort(unique(df$Chromosome)))
2292
+ vivid <- c("#FF006E","#3A86FF","#06D6A0","#FFBE0B","#FB5607","#8338EC")
2293
+ plot_ly(df, x=~Chromosome, y=~Count, color=~Method, type="bar",
2294
+ colors=vivid[seq_len(length(unique(df$Method)))]) %>%
2295
+ layout(barmode="group",
2296
+ title=list(text="QTL Count by Method & Chromosome",font=list(size=14,color="grey10")),
2297
+ xaxis=list(title="Chromosome",tickangle=45,gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2298
+ yaxis=list(title="# Significant QTLs",gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2299
+ paper_bgcolor="white",plot_bgcolor="white",
2300
+ legend=list(font=list(color="grey20")))
2301
+ })
2302
+
2303
+ output$compare_table <- renderDT({
2304
+ req(length(rv$compare_peaks) > 0)
2305
+ rows <- list()
2306
+ for (mth in names(rv$compare_peaks)) {
2307
+ peaks <- rv$compare_peaks[[mth]]
2308
+ if (is.null(peaks) || nrow(peaks) == 0) next
2309
+ peaks$Model_Used <- mth
2310
+ keep <- intersect(c("Marker","Chromosome","Position","LOD","PVE_Percent",
2311
+ "Additive_Effect","Interval_Start_cM","Interval_End_cM",
2312
+ "Interval_Size_cM","Left_Flanking_Marker",
2313
+ "Right_Flanking_Marker","Model_Used"), colnames(peaks))
2314
+ rows <- c(rows, list(peaks[, keep]))
2315
+ }
2316
+ if (length(rows) == 0) return(datatable(data.frame(Status="No QTLs found")))
2317
+ df <- do.call(rbind, rows)
2318
+ datatable(df[order(-df$LOD),],
2319
+ options=list(scrollX=TRUE,pageLength=15,dom="Blfrtip"),
2320
+ rownames=FALSE, class="cell-border stripe hover") %>%
2321
+ formatRound(intersect(c("LOD","PVE_Percent","Position","Additive_Effect",
2322
+ "Interval_Start_cM","Interval_End_cM","Interval_Size_cM"),
2323
+ colnames(df)), 2)
2324
+ })
2325
+
2326
+ # ---- COMMON QTL ----
2327
+ common_qtl_data <- reactive({
2328
+ req(length(rv$compare_peaks) > 0)
2329
+ find_common_qtl(rv$compare_peaks, lod_thr(), min_models=input$min_models)
2330
+ })
2331
+
2332
+ output$common_qtl_summary_ui <- renderUI({
2333
+ cq <- common_qtl_data()
2334
+ if (is.null(cq) || nrow(cq) == 0)
2335
+ return(div(class="warn-box","No common QTLs. Run Compare Models first."))
2336
+ n_all <- nrow(cq)
2337
+ n_max <- sum(cq$N_Models_Detected == length(rv$compare_peaks), na.rm=TRUE)
2338
+ div(class="good-box",
2339
+ tags$b(n_all)," common QTLs | ", tags$b(n_max)," in ALL models",
2340
+ tags$br(),
2341
+ tags$small("Chromosomes: ", paste(sort(unique(cq$Chromosome)), collapse=", ")))
2342
+ })
2343
+
2344
+ output$common_qtl_table <- renderDT({
2345
+ cq <- common_qtl_data()
2346
+ if (is.null(cq) || nrow(cq) == 0)
2347
+ return(datatable(data.frame(Status="Run Compare Models tab first"),
2348
+ options=list(dom="t")))
2349
+ num_cols <- intersect(
2350
+ c("Position","Mean_LOD","Max_LOD","Mean_PVE","Mean_Add_Eff",
2351
+ paste0("LOD_",names(rv$compare_res))), colnames(cq))
2352
+ datatable(cq, options=list(scrollX=TRUE,pageLength=15,dom="Blfrtip"),
2353
+ rownames=FALSE, class="cell-border stripe hover") %>%
2354
+ formatRound(num_cols, 3) %>%
2355
+ formatStyle("N_Models_Detected",
2356
+ background=styleColorBar(range(cq$N_Models_Detected,na.rm=TRUE),"#06D6A0"),
2357
+ backgroundSize="100% 80%",backgroundRepeat="no-repeat",backgroundPosition="center") %>%
2358
+ formatStyle("Max_LOD",
2359
+ background=styleColorBar(range(cq$Max_LOD,na.rm=TRUE),"#FF006E"),
2360
+ backgroundSize="100% 80%",backgroundRepeat="no-repeat",backgroundPosition="center")
2361
+ })
2362
+
2363
+ output$common_idiogram <- renderPlot({
2364
+ cq <- common_qtl_data()
2365
+ req(!is.null(cq), nrow(cq) > 0, rv$marker_info)
2366
+ n_levels <- sort(unique(cq$N_Models_Detected), decreasing=TRUE)
2367
+ qtl_list_cq <- setNames(lapply(n_levels, function(nl) {
2368
+ sub <- cq[cq$N_Models_Detected == nl,
2369
+ c("Marker","Chromosome","Position","Max_LOD","Mean_PVE","Mean_Add_Eff")]
2370
+ colnames(sub)[colnames(sub)=="Max_LOD"] <- "LOD"
2371
+ colnames(sub)[colnames(sub)=="Mean_PVE"] <- "PVE_Percent"
2372
+ colnames(sub)[colnames(sub)=="Mean_Add_Eff"] <- "Additive_Effect"
2373
+ sub
2374
+ }), paste0(n_levels," model(s)"))
2375
+ make_idiogram_ggplot(qtl_list_cq, rv$marker_info, lod_thr())
2376
+ }, bg="white")
2377
+
2378
+ output$common_bar <- renderPlotly({
2379
+ cq <- common_qtl_data()
2380
+ if (is.null(cq) || nrow(cq) == 0)
2381
+ return(plot_ly() %>% layout(title="No common QTLs",
2382
+ paper_bgcolor="white",plot_bgcolor="white"))
2383
+ df <- cq %>%
2384
+ dplyr::group_by(Chromosome, N_Models_Detected) %>%
2385
+ dplyr::summarise(Count=dplyr::n(), .groups="drop")
2386
+ df$Label <- paste0(df$N_Models_Detected," model(s)")
2387
+ df$Chromosome <- factor(df$Chromosome, levels=sort(unique(as.character(df$Chromosome))))
2388
+ plot_ly(df, x=~Chromosome, y=~Count, color=~Label, type="bar",
2389
+ colors=c("#FF006E","#FB5607","#FFBE0B","#06D6A0","#3A86FF","#8338EC")) %>%
2390
+ layout(barmode="stack",
2391
+ title=list(text="Common QTL Count by Chromosome",font=list(size=14,color="grey10")),
2392
+ xaxis=list(title="Chromosome",tickangle=45,gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2393
+ yaxis=list(title="# Common QTLs",gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2394
+ paper_bgcolor="white",plot_bgcolor="white",
2395
+ legend=list(orientation="h",y=-0.18,font=list(color="grey20")))
2396
+ })
2397
+
2398
+ # ---- MAIN PLOTS ----
2399
+ output$manhattan_plot <- renderPlotly({
2400
+ req(rv$scan_all)
2401
+ make_plotly_manhattan(rv$scan_all, lod_thr(), rv$qtl_peaks,
2402
+ paste(input$mapping_method,"Manhattan Plot"))
2403
+ })
2404
+
2405
+ output$idiogram_plot <- renderPlot({
2406
+ req(rv$marker_info)
2407
+ valid_peaks <- if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0)
2408
+ list(setNames(list(rv$qtl_peaks), input$mapping_method)) else list()
2409
+ if (length(valid_peaks) == 0) ggplot() + labs(title="Run analysis first") + theme_bw()
2410
+ else make_idiogram_ggplot(valid_peaks, rv$marker_info, lod_thr())
2411
+ }, bg="white")
2412
+
2413
+ output$perf_plot <- renderPlotly({
2414
+ req(rv$perf)
2415
+ clrs <- c("#FF006E","#06D6A0","#FF006E","#06D6A0")
2416
+ plot_ly(rv$perf, x=~Metric, y=~Value, type="bar",
2417
+ marker=list(color=clrs),
2418
+ text=~round(Value,3), textposition="outside",
2419
+ textfont=list(size=11, color="grey20")) %>%
2420
+ layout(title=list(text="Model Performance",font=list(size=13,color="grey10")),
2421
+ yaxis=list(range=c(0,1.2),title="Value",
2422
+ gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2423
+ xaxis=list(title="",tickangle=15,color="grey20"),
2424
+ paper_bgcolor="white",plot_bgcolor="white")
2425
+ })
2426
+
2427
+ output$reg_train <- renderPlotly({
2428
+ req(rv$tr_pred)
2429
+ rng <- range(c(rv$tr_pred$Observed, rv$tr_pred$Predicted), na.rm=TRUE)
2430
+ plot_ly(rv$tr_pred, x=~Observed, y=~Predicted,
2431
+ type="scatter", mode="markers",
2432
+ marker=list(size=7, color="#FF006E", opacity=0.7)) %>%
2433
+ add_trace(x=rng, y=rng, type="scatter", mode="lines",
2434
+ line=list(color="#3A86FF",dash="dash",width=2), showlegend=FALSE) %>%
2435
+ layout(title=list(text="Training Set",font=list(size=13,color="grey10")),
2436
+ xaxis=list(title="Observed", gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2437
+ yaxis=list(title="Predicted",gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2438
+ paper_bgcolor="white",plot_bgcolor="white")
2439
+ })
2440
+
2441
+ output$reg_val <- renderPlotly({
2442
+ req(rv$val_pred)
2443
+ rng <- range(c(rv$val_pred$Observed, rv$val_pred$Predicted), na.rm=TRUE)
2444
+ plot_ly(rv$val_pred, x=~Observed, y=~Predicted,
2445
+ type="scatter", mode="markers",
2446
+ marker=list(size=7, color="#06D6A0", opacity=0.7)) %>%
2447
+ add_trace(x=rng, y=rng, type="scatter", mode="lines",
2448
+ line=list(color="#FF006E",dash="dash",width=2), showlegend=FALSE) %>%
2449
+ layout(title=list(text="Validation Set",font=list(size=13,color="grey10")),
2450
+ xaxis=list(title="Observed", gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2451
+ yaxis=list(title="Predicted",gridcolor="rgba(0,0,0,0.08)",color="grey20"),
2452
+ paper_bgcolor="white",plot_bgcolor="white")
2453
+ })
2454
+
2455
+ # ---- QTL TABLES ----
2456
+ output$qtl_peaks_table <- renderDT({
2457
+ req(rv$qtl_peaks)
2458
+ if (is.null(rv$qtl_peaks) || nrow(rv$qtl_peaks) == 0)
2459
+ return(datatable(data.frame(Status=paste("No QTL peaks above LOD",lod_thr())),
2460
+ options=list(dom="t")))
2461
+ show_cols <- c("Marker","Chromosome","Position","LOD","P_Value",
2462
+ "PVE_Percent","Additive_Effect","SE_Additive",
2463
+ "CI_Lower","CI_Upper","Dominance_Class",
2464
+ "Interval_Start_cM","Interval_End_cM","Interval_Size_cM",
2465
+ "Left_Flanking_Marker","Right_Flanking_Marker",
2466
+ "Left_Interval_Marker","Right_Interval_Marker","N_Samples",
2467
+ "Global_LOD","Global_PVE")
2468
+ show_cols <- intersect(show_cols, colnames(rv$qtl_peaks))
2469
+ round_cols <- intersect(c("LOD","PVE_Percent","Position","Additive_Effect",
2470
+ "SE_Additive","CI_Lower","CI_Upper",
2471
+ "Interval_Start_cM","Interval_End_cM","Interval_Size_cM",
2472
+ "Global_LOD","Global_PVE"), show_cols)
2473
+ dt <- datatable(rv$qtl_peaks[, show_cols],
2474
+ options=list(scrollX=TRUE,pageLength=10,dom="Blfrtip"),
2475
+ rownames=FALSE, class="cell-border stripe hover")
2476
+ if (length(round_cols) > 0) dt <- dt %>% formatRound(round_cols, 2)
2477
+ if ("P_Value" %in% show_cols) dt <- dt %>% formatSignif("P_Value", digits=3)
2478
+ dt
2479
+ })
2480
+
2481
+ output$full_scan_table <- renderDT({
2482
+ req(rv$scan_all)
2483
+ if ("Message" %in% colnames(rv$scan_all))
2484
+ return(datatable(data.frame(Status=rv$scan_all$Message[1]),options=list(dom="t")))
2485
+ round_cols <- intersect(c("LOD","PVE_Percent","Additive_Effect",
2486
+ "Global_LOD","Global_PVE"), colnames(rv$scan_all))
2487
+ dt <- datatable(rv$scan_all,
2488
+ options=list(scrollX=TRUE,pageLength=15,dom="Blfrtip",
2489
+ order=list(list(4,"desc"))),
2490
+ rownames=FALSE, class="cell-border stripe hover")
2491
+ if (length(round_cols) > 0) dt <- dt %>% formatRound(round_cols, 3)
2492
+ if ("P_Value" %in% colnames(rv$scan_all)) dt <- dt %>% formatSignif("P_Value", digits=3)
2493
+ dt
2494
+ })
2495
+
2496
+ # ---- PREDICT TEST ----
2497
+ observeEvent(input$pred_btn, {
2498
+ if (is.null(rv$model_fit)) { showNotification("Run analysis first",type="error"); return() }
2499
+ if (is.null(rv$test_geno)) { showNotification("Upload test genotype first",type="error"); return() }
2500
+
2501
+ withProgress(message="Predicting test samples...", value=0.3, {
2502
+ incProgress(0.1, detail="Preparing data...")
2503
+ train_cols <- rv$model_cols
2504
+ Xpred <- as.data.frame(matrix(0, nrow=nrow(rv$test_geno), ncol=length(train_cols),
2505
+ dimnames=list(rownames(rv$test_geno), train_cols)))
2506
+ for (col in intersect(train_cols, colnames(rv$test_geno))) {
2507
+ v <- suppressWarnings(as.numeric(as.character(rv$test_geno[[col]])))
2508
+ v[is.na(v)] <- 0; Xpred[[col]] <- v
2509
+ }
2510
+ incProgress(0.4, detail="Running predictions...")
2511
+ preds <- tryCatch(as.numeric(predict(rv$model_fit, newdata=Xpred)),
2512
+ error=function(e) rep(NA, nrow(Xpred)))
2513
+ incProgress(0.5, detail="Finalizing...")
2514
+ rv$pred_test <- data.frame(Sample_ID=rownames(rv$test_geno),
2515
+ Predicted_Phenotype=round(preds,4))
2516
+ })
2517
+ showNotification(paste("Predicted",nrow(rv$pred_test),"samples"),type="message")
2518
+ })
2519
+
2520
+ # ---- DOMESTICATION ----
2521
+ observeEvent(input$run_dom, {
2522
+ req(rv$geno, rv$pop_data, rv$marker_info)
2523
+
2524
+ withProgress(message="Running domestication analysis...", value=0, {
2525
+ incProgress(0.2, detail="Matching samples...")
2526
+
2527
+ tryCatch({
2528
+ cs <- intersect(rownames(rv$geno), rv$pop_data$id)
2529
+ X <- rv$geno[cs, , drop=FALSE]
2530
+ ps <- rv$pop_data[rv$pop_data$id %in% cs, ]
2531
+
2532
+ incProgress(0.4, detail="Calculating Fst and Tajima's D...")
2533
+ sel <- calc_selection_metrics(X, ps, rv$marker_info)
2534
+
2535
+ if (is.null(sel)) {
2536
+ showNotification("No selection metrics computed",type="error")
2537
+ incProgress(1)
2538
+ return()
2539
+ }
2540
+
2541
+ incProgress(0.3, detail="Identifying signatures...")
2542
+ sel$Significant <- (!is.na(sel$Fst) & sel$Fst > input$fst_thr) |
2543
+ (!is.na(sel$Tajima_D_Dom) & sel$Tajima_D_Dom < input$tajima_thr)
2544
+ rv$sel_metrics <- sel
2545
+
2546
+ incProgress(0.1, detail="Done")
2547
+ showNotification(paste("Found",sum(sel$Significant,na.rm=TRUE),"selection signatures"),
2548
+ type="message")
2549
+ }, error=function(e) showNotification(paste("Domestication error:",e$message),type="error"))
2550
+ })
2551
+ })
2552
+
2553
+ make_dom_plotly <- function(data, y_col, title, threshold, y_lab=y_col) {
2554
+ blank <- plot_ly() %>% layout(title=title, paper_bgcolor="white", plot_bgcolor="white")
2555
+ if (is.null(data) || nrow(data) == 0) return(blank)
2556
+ pd <- data[!is.na(data[[y_col]]) & !is.na(data$Chromosome), ]
2557
+ if (nrow(pd) == 0) return(blank)
2558
+ pd$Chromosome <- as.character(pd$Chromosome)
2559
+ chroms <- sort(unique(pd$Chromosome), method="radix")
2560
+ offsets <- setNames(numeric(length(chroms)), chroms)
2561
+ for (i in seq_along(chroms)) {
2562
+ if (i == 1) { offsets[chroms[1]] <- 0; next }
2563
+ offsets[chroms[i]] <- offsets[chroms[i-1]] +
2564
+ max(pd$Position[pd$Chromosome == chroms[i-1]], na.rm=TRUE) * 1.05
2565
+ }
2566
+ pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
2567
+ chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm=TRUE)
2568
+ chr_clrs <- rep(c("#3A86FF","#FB5607"), length.out=length(chroms))
2569
+ names(chr_clrs) <- chroms
2570
+ pl <- plot_ly()
2571
+ for (ch in chroms) {
2572
+ sub <- pd[pd$Chromosome == ch, ]
2573
+ pl <- pl %>% add_trace(
2574
+ data=sub, x=~cum_pos, y=as.formula(paste0("~",y_col)),
2575
+ type="scatter", mode="markers", name=paste("Chr",ch), showlegend=FALSE,
2576
+ marker=list(size=6, color=chr_clrs[ch], opacity=0.75),
2577
+ text=paste0("<b>",sub$Marker,"</b><br>Chr: ",sub$Chromosome,
2578
+ "<br>Pos: ",round(sub$Position,1),
2579
+ "<br>",y_lab,": ",round(sub[[y_col]],4)),
2580
+ hoverinfo="text")
2581
+ }
2582
+ if (!is.null(threshold))
2583
+ pl <- pl %>% add_segments(
2584
+ x=min(pd$cum_pos,na.rm=TRUE), xend=max(pd$cum_pos,na.rm=TRUE),
2585
+ y=threshold, yend=threshold,
2586
+ line=list(color="#FF006E",dash="dash",width=1.8), showlegend=FALSE)
2587
+ pl %>% layout(
2588
+ title=list(text=title, font=list(size=14,color="grey10")),
2589
+ xaxis=list(title="Chromosome", tickvals=as.list(chr_mids[chroms]),
2590
+ ticktext=as.list(paste0("Chr ",chroms)), tickangle=45,
2591
+ gridcolor="rgba(0,0,0,0.08)", color="grey20", zeroline=FALSE),
2592
+ yaxis=list(title=y_lab, gridcolor="rgba(0,0,0,0.08)", color="grey20", zeroline=FALSE),
2593
+ paper_bgcolor="white", plot_bgcolor="white")
2594
+ }
2595
+
2596
+ output$fst_plot <- renderPlotly({ req(rv$sel_metrics); make_dom_plotly(rv$sel_metrics,"Fst", "Fst Manhattan Plot", input$fst_thr, "Fst") })
2597
+ output$tajima_plot <- renderPlotly({ req(rv$sel_metrics); make_dom_plotly(rv$sel_metrics,"Tajima_D_Dom","Tajima's D Manhattan Plot", input$tajima_thr,"Tajima D") })
2598
+
2599
+ output$sel_table <- renderDT({
2600
+ req(rv$sel_metrics)
2601
+ datatable(rv$sel_metrics[order(-rv$sel_metrics$Fst),],
2602
+ options=list(scrollX=TRUE,pageLength=10,dom="Blfrtip"),
2603
+ rownames=FALSE, class="cell-border stripe hover") %>%
2604
+ formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"), 4)
2605
+ })
2606
+
2607
+ # ---- DOWNLOADS ----
2608
+ output$dl_manhattan <- downloadHandler(
2609
+ filename=function() paste0("manhattan_",Sys.Date(),".png"),
2610
+ content=function(file) {
2611
+ req(rv$scan_all)
2612
+ p <- make_manhattan_ggplot(rv$scan_all, lod_thr(), rv$qtl_peaks,
2613
+ paste(input$mapping_method,"Manhattan Plot"))
2614
+ ggsave(file, plot=p, width=14, height=6, dpi=200, bg="white")
2615
+ }
2616
+ )
2617
+
2618
+ output$dl_idiogram <- downloadHandler(
2619
+ filename=function() paste0("idiogram_",Sys.Date(),".png"),
2620
+ content=function(file) {
2621
+ req(rv$marker_info)
2622
+ res_list <- list()
2623
+ if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0)
2624
+ res_list[[input$mapping_method]] <- rv$qtl_peaks
2625
+ for (m in names(rv$compare_peaks)) {
2626
+ if (!is.null(rv$compare_peaks[[m]]) && nrow(rv$compare_peaks[[m]]) > 0)
2627
+ res_list[[m]] <- rv$compare_peaks[[m]]
2628
+ }
2629
+ if (length(res_list) == 0) return()
2630
+ p <- make_idiogram_ggplot(res_list, rv$marker_info, lod_thr())
2631
+ ggsave(file, plot=p, width=12, height=8, dpi=200, bg="white")
2632
+ }
2633
+ )
2634
+
2635
+ output$dl_results <- downloadHandler(
2636
+ filename=function() paste0("qtl_results_",Sys.Date(),".xlsx"),
2637
+ content=function(file) {
2638
+ sheets <- list()
2639
+ if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0)
2640
+ sheets[["QTL_Peaks"]] <- rv$qtl_peaks
2641
+ if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
2642
+ sheets[["Full_Scan"]] <- rv$scan_all
2643
+ if (!is.null(rv$perf)) sheets[["Performance"]] <- rv$perf
2644
+ for (m in names(rv$compare_peaks)) {
2645
+ if (!is.null(rv$compare_peaks[[m]]) && nrow(rv$compare_peaks[[m]]) > 0)
2646
+ sheets[[paste0("Peaks_",m)]] <- rv$compare_peaks[[m]]
2647
+ }
2648
+ cq <- tryCatch(find_common_qtl(rv$compare_peaks, lod_thr(), isolate(input$min_models)),
2649
+ error=function(e) NULL)
2650
+ if (!is.null(cq) && nrow(cq) > 0) sheets[["Common_QTL"]] <- cq
2651
+ sheets[["Methods"]] <- data.frame(
2652
+ Method = names(MAPPING_MODELS),
2653
+ Label = sapply(MAPPING_MODELS,`[[`,"label"),
2654
+ Description = sapply(MAPPING_MODELS,`[[`,"desc"))
2655
+ if (!is.null(rv$sel_metrics) && nrow(rv$sel_metrics) > 0)
2656
+ sheets[["Selection_Signatures"]] <- rv$sel_metrics
2657
+ if (!is.null(rv$perm_threshold))
2658
+ sheets[["Permutation_Info"]] <- data.frame(
2659
+ Method = input$mapping_method,
2660
+ N_Perm = if (isTRUE(input$run_permutation)) input$n_perm else NA,
2661
+ Alpha = if (isTRUE(input$run_permutation)) input$perm_alpha else NA,
2662
+ LOD_Threshold = rv$perm_threshold)
2663
+ if (length(sheets) == 0) sheets[["Empty"]] <- data.frame(msg="Run analysis first")
2664
+ writexl::write_xlsx(sheets, file)
2665
+ }
2666
+ )
2667
+
2668
+ output$dl_pred <- downloadHandler(
2669
+ filename=function() paste0("predictions_",Sys.Date(),".xlsx"),
2670
+ content=function(file) {
2671
+ req(rv$pred_test)
2672
+ writexl::write_xlsx(list(Predictions=rv$pred_test), file)
2673
+ }
2674
+ )
2675
+
2676
+ output$dl_common_qtl <- downloadHandler(
2677
+ filename=function() paste0("common_qtl_",Sys.Date(),".xlsx"),
2678
+ content=function(file) {
2679
+ cq <- tryCatch(find_common_qtl(rv$compare_peaks, lod_thr(), isolate(input$min_models)),
2680
+ error=function(e) NULL)
2681
+ if (!is.null(cq) && nrow(cq) > 0)
2682
+ writexl::write_xlsx(list(Common_QTL=cq), file)
2683
+ else
2684
+ writexl::write_xlsx(
2685
+ list(Empty=data.frame(msg="No common QTLs or run Compare Models first")), file)
2686
+ }
2687
+ )
2688
+
2689
+ output$dl_sel <- downloadHandler(
2690
+ filename=function() paste0("selection_",Sys.Date(),".xlsx"),
2691
+ content=function(file) {
2692
+ if (!is.null(rv$sel_metrics))
2693
+ writexl::write_xlsx(list(Selection=rv$sel_metrics), file)
2694
+ else
2695
+ writexl::write_xlsx(
2696
+ list(Empty=data.frame(msg="Run domestication analysis first")), file)
2697
+ }
2698
+ )
2699
+ }
2700
 
2701
  # ============================================================
2702
  # Run the app