softwareDevelopment commited on
Commit
d57de76
·
verified ·
1 Parent(s): 4650d58

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +57 -1342
app.R CHANGED
@@ -1,1348 +1,63 @@
1
- # ============================================================
2
- # QTL MAPPING SUITE — Full Single-File Shiny Application
3
- # FIXED v2.2: All ggplot2/dplyr/tidyr compatibility patches
4
- # ============================================================
5
-
6
- suppressPackageStartupMessages({
7
- library(shiny)
8
- library(shinyWidgets)
9
- library(shinyjs)
10
- library(shinycssloaders)
11
- library(qtl)
12
- library(ggplot2)
13
- library(plotly)
14
- library(DT)
15
- library(dplyr)
16
- library(tidyr)
17
- library(viridis)
18
- library(circlize)
19
- library(scales)
20
- })
21
-
22
- # ── CSS (Google Fonts removed — safe system fonts only) ────
23
- APP_CSS <- "
24
- *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
25
- :root{
26
- --white:#ffffff;--off:#f8f8f6;--g50:#f4f4f2;--g100:#e8e8e5;--g200:#d0d0cc;
27
- --g400:#9a9a94;--g600:#5c5c58;--g800:#2a2a27;--ink:#1a1a18;
28
- --acc:#1a6b3a;--acclt:#e8f4ed;--accmd:#2d9e58;
29
- --amb:#c47c1a;--amblt:#fef3e2;
30
- --red:#b83232;--redlt:#fdeaea;
31
- --blu:#1a4a8a;--blult:#e8eef8;
32
- --rsm:4px;--r:8px;--rlg:14px;
33
- --sh:0 2px 12px rgba(0,0,0,.09);--shsm:0 1px 3px rgba(0,0,0,.07);
34
- --f:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
35
- --fm:'Courier New',Courier,monospace;
36
- --t:0.18s ease;
37
  }
38
- html,body{height:100%;background:var(--off);font-family:var(--f);color:var(--ink);font-size:14px;line-height:1.5}
39
- body{overflow-x:hidden}
40
- .container-fluid{padding:0!important}
41
- .qtl-top{height:56px;background:var(--white);border-bottom:1.5px solid var(--g100);display:flex;align-items:center;padding:0 24px;gap:16px;position:sticky;top:0;z-index:1000;box-shadow:var(--shsm)}
42
- .tlmark{width:30px;height:30px;background:var(--acc);border-radius:var(--rsm);display:flex;align-items:center;justify-content:center;color:#fff;font-size:15px;font-weight:700}
43
- .tlname{font-size:17px;font-weight:700;color:var(--ink);letter-spacing:-.3px}
44
- .tlver{font-size:10px;color:var(--g400);font-family:var(--fm);background:var(--g50);padding:1px 6px;border-radius:20px;border:1px solid var(--g100)}
45
- .tldiv{width:1px;height:22px;background:var(--g100)}
46
- .stpill{display:flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;background:var(--acclt);border:1px solid #b8dfc6;font-size:11px;font-weight:500;color:var(--acc)}
47
- .stpill .dot{width:6px;height:6px;border-radius:50%;background:var(--accmd);animation:pulse 2s infinite}
48
- @keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}
49
- .tlright{margin-left:auto;display:flex;align-items:center;gap:10px}
50
- .btn-tn{padding:6px 14px;border-radius:var(--rsm);border:1.5px solid var(--g100);background:#fff;color:var(--g600);font-family:var(--f);font-size:12px;font-weight:500;cursor:pointer;transition:var(--t)}
51
- .btn-tn:hover{border-color:var(--acc);color:var(--acc);background:var(--acclt)}
52
- .qtl-lay{display:flex;height:calc(100vh - 56px);overflow:hidden}
53
- .qtl-sb{width:232px;min-width:232px;background:var(--white);border-right:1.5px solid var(--g100);display:flex;flex-direction:column;overflow-y:auto}
54
- .sb-sec{padding:18px 14px 6px}
55
- .sb-sec-t{font-size:9px;font-weight:700;letter-spacing:1.4px;text-transform:uppercase;color:var(--g400);padding:0 8px 7px}
56
- .nv{display:flex;align-items:center;gap:10px;padding:8px 14px;border-radius:var(--rsm);cursor:pointer;color:var(--g600);font-size:13px;font-weight:500;transition:var(--t);margin:1px 0;border:1.5px solid transparent}
57
- .nv:hover{background:var(--g50);color:var(--ink)}
58
- .nv.active{background:var(--acclt);color:var(--acc);border-color:#b8dfc6;font-weight:600}
59
- .nv-ic{font-size:14px;width:18px;text-align:center}
60
- .sb-foot{margin-top:auto;padding:12px 14px;border-top:1px solid var(--g100);font-size:11px;color:var(--g400)}
61
- .qtl-main{flex:1;overflow-y:auto;background:var(--off)}
62
- .pg{display:none;padding:26px 28px;animation:fu .22s ease}
63
- .pg.active{display:block}
64
- @keyframes fu{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
65
- .ph{margin-bottom:22px}
66
- .pt{font-size:24px;font-weight:700;color:var(--ink);line-height:1.2}
67
- .ps{font-size:12px;color:var(--g600);margin-top:3px}
68
- .phr{display:flex;align-items:flex-start;justify-content:space-between;gap:14px}
69
- .card{background:var(--white);border-radius:var(--rlg);border:1.5px solid var(--g100);box-shadow:var(--shsm);margin-bottom:18px;overflow:hidden}
70
- .ch{padding:14px 18px 12px;border-bottom:1px solid var(--g100);display:flex;align-items:center;justify-content:space-between;background:var(--white)}
71
- .ct{font-size:13px;font-weight:600;color:var(--ink)}
72
- .cst{font-size:11px;color:var(--g400);margin-top:2px}
73
- .cb{padding:18px}
74
- .g2{display:grid;grid-template-columns:1fr 1fr;gap:18px}
75
- .g3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:18px}
76
- .g4{display:grid;grid-template-columns:repeat(4,1fr);gap:14px}
77
- .st{background:var(--white);border-radius:var(--r);border:1.5px solid var(--g100);padding:14px 16px;transition:var(--t)}
78
- .st:hover{box-shadow:var(--sh);border-color:var(--g200)}
79
- .st-l{font-size:9px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--g400);margin-bottom:5px}
80
- .st-v{font-size:26px;font-weight:700;color:var(--ink);line-height:1}
81
- .st-s{font-size:11px;color:var(--g400);margin-top:3px}
82
- .st.acc{border-color:#b8dfc6;background:var(--acclt)}
83
- .st.acc .st-v{color:var(--acc)}
84
- .uzone{border:2px dashed var(--g200);border-radius:var(--rlg);padding:28px 20px;text-align:center;cursor:pointer;transition:var(--t);background:var(--g50)}
85
- .uzone:hover{border-color:var(--acc);background:var(--acclt)}
86
- .uzone-ic{font-size:28px;margin-bottom:8px}
87
- .uzone-t{font-size:13px;font-weight:600;color:var(--ink)}
88
- .uzone-s{font-size:11px;color:var(--g400);margin-top:4px}
89
- .uzone .shiny-input-container{margin:0}
90
- .fmt-box{background:var(--g50);border:1.5px solid var(--g100);border-radius:var(--r);padding:12px 14px;margin-top:12px}
91
- .fmt-title{font-size:11px;font-weight:700;color:var(--g600);letter-spacing:.5px;text-transform:uppercase;margin-bottom:8px}
92
- .fmt-table{width:100%;border-collapse:collapse;font-size:11px;font-family:var(--fm)}
93
- .fmt-table th{background:var(--g100);padding:4px 8px;text-align:left;color:var(--g600);font-weight:600}
94
- .fmt-table td{padding:3px 8px;color:var(--ink);border-bottom:1px solid var(--g100)}
95
- .fmt-table tr:last-child td{border-bottom:none}
96
- .fmt-table .hdr{color:var(--acc);font-weight:600}
97
- .fmt-table .pos-row{color:var(--amb);font-style:italic}
98
- .fl{display:block;font-size:12px;font-weight:600;color:var(--g600);margin-bottom:5px;letter-spacing:.2px}
99
- .fm-g{margin-bottom:14px}
100
- .selectize-input{border:1.5px solid var(--g100)!important;border-radius:var(--rsm)!important;font-size:13px!important;padding:7px 12px!important;box-shadow:none!important}
101
- .selectize-input.focus{border-color:var(--acc)!important;box-shadow:0 0 0 3px rgba(26,107,58,.1)!important}
102
- input[type=number],input[type=text]{width:100%;padding:8px 12px;border:1.5px solid var(--g100);border-radius:var(--rsm);font-size:13px;outline:none}
103
- input[type=number]:focus,input[type=text]:focus{border-color:var(--acc);box-shadow:0 0 0 3px rgba(26,107,58,.1)}
104
- .irs--shiny .irs-bar{background:var(--acc)!important}
105
- .irs--shiny .irs-handle{background:var(--acc)!important;border-color:var(--acc)!important}
106
- .btn-p{background:var(--acc);color:#fff;border:none;padding:9px 20px;border-radius:var(--rsm);font-size:13px;font-weight:600;cursor:pointer;transition:var(--t);display:inline-flex;align-items:center;gap:6px}
107
- .btn-p:hover{background:#155a30;box-shadow:var(--sh);transform:translateY(-1px)}
108
- .btn-s{background:#fff;color:var(--g600);border:1.5px solid var(--g100);padding:7px 16px;border-radius:var(--rsm);font-size:13px;font-weight:500;cursor:pointer;transition:var(--t)}
109
- .btn-s:hover{border-color:var(--g200);color:var(--ink);background:var(--g50)}
110
- .btn-dl{background:#fff;color:var(--acc);border:1.5px solid var(--acc);padding:6px 14px;border-radius:var(--rsm);font-size:12px;font-weight:600;cursor:pointer;transition:var(--t);display:inline-flex;align-items:center;gap:5px}
111
- .btn-dl:hover{background:var(--acc);color:#fff}
112
- .br{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:6px}
113
- .qtabs{display:flex;gap:2px;border-bottom:1.5px solid var(--g100);margin-bottom:18px}
114
- .qtab{padding:8px 16px;font-size:12px;font-weight:600;cursor:pointer;color:var(--g400);border-bottom:2px solid transparent;margin-bottom:-1.5px;transition:var(--t)}
115
- .qtab:hover{color:var(--ink)}
116
- .qtab.active{color:var(--acc);border-bottom-color:var(--acc)}
117
- .prog-out{height:5px;background:var(--g100);border-radius:20px;overflow:hidden;margin:7px 0}
118
- .prog-in{height:100%;background:linear-gradient(90deg,var(--acc),var(--accmd));border-radius:20px;transition:width .4s ease}
119
- .al{padding:11px 14px;border-radius:var(--rsm);font-size:13px;margin-bottom:12px;border-left:3px solid;display:flex;align-items:flex-start;gap:9px}
120
- .al-ok{background:var(--acclt);border-color:var(--accmd);color:#0f4a28}
121
- .al-warn{background:var(--amblt);border-color:var(--amb);color:#6b4000}
122
- .al-err{background:var(--redlt);border-color:var(--red);color:#6b0000}
123
- .al-info{background:var(--blult);border-color:var(--blu);color:#0a2a5a}
124
- .mchips{display:flex;flex-wrap:wrap;gap:7px}
125
- .mc{padding:5px 12px;border-radius:var(--rsm);font-size:12px;font-weight:500;cursor:pointer;border:1.5px solid var(--g100);background:#fff;color:var(--g600);transition:var(--t);user-select:none}
126
- .mc:hover{border-color:var(--acc);color:var(--acc);background:var(--acclt)}
127
- .mc.sel{background:var(--acc);color:#fff;border-color:var(--acc)}
128
- .sbadge{display:inline-flex;align-items:center;gap:5px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:600}
129
- .sbadge-ok{background:var(--acclt);color:var(--acc);border:1px solid #b8dfc6}
130
- .sbadge-pend{background:var(--amblt);color:var(--amb);border:1px solid #e8c070}
131
- .sbadge-err{background:var(--redlt);color:var(--red);border:1px solid #e8a0a0}
132
- .tip{font-size:11px;color:var(--g400);font-style:italic;margin-top:4px}
133
- .dataTables_wrapper{font-size:13px}
134
- .dataTables_wrapper .dataTables_filter input{border:1.5px solid var(--g100);border-radius:var(--rsm);padding:5px 10px;font-size:12px;outline:none}
135
- table.dataTable thead th{background:var(--g50);font-size:10px;font-weight:700;letter-spacing:.5px;text-transform:uppercase;color:var(--g600);padding:9px 11px!important;border-bottom:1.5px solid var(--g100)!important}
136
- table.dataTable tbody td{padding:8px 11px!important;font-size:12px}
137
- table.dataTable tbody tr:hover{background:var(--g50)!important}
138
- ::-webkit-scrollbar{width:5px;height:5px}
139
- ::-webkit-scrollbar-thumb{background:var(--g200);border-radius:20px}
140
- ::-webkit-scrollbar-thumb:hover{background:var(--g400)}
141
- .well{background:var(--g50);border:1.5px solid var(--g100);border-radius:var(--r);box-shadow:none;padding:14px}
142
- .shiny-input-checkboxgroup label,.shiny-input-radiogroup label{font-size:12px;color:var(--g600)}
143
- input[type=checkbox]{accent-color:var(--acc)}
144
- input[type=radio]{accent-color:var(--acc)}
145
- "
146
 
147
- # ── Model metadata ────────────────────────────────────────
148
- MODEL_LABELS <- c(
149
- em="EM Algorithm", hk="Haley-Knott", mr="Marker Regression",
150
- im="Interval Mapping", cim="CIM", ehk="Extended HK",
151
- imp="Imputation", hkperm="HK+Permutation", scanone_np="Non-parametric", mqm="MQM"
152
- )
153
- MODEL_COLORS <- c(
154
- em="#1a6b3a", hk="#2d9e58", mr="#c47c1a", im="#1a4a8a", cim="#b83232",
155
- ehk="#7b3fa0", imp="#1a8a8a", hkperm="#8a5a1a", scanone_np="#555555", mqm="#e05c00"
156
- )
157
-
158
- # ── HELPERS ───────────────────────────────────────────────
159
- chr_order_fn <- function(x) {
160
- nums <- suppressWarnings(as.numeric(x))
161
- if (any(!is.na(nums))) order(ifelse(is.na(nums), Inf, nums)) else order(x)
162
  }
163
 
164
- cum_positions <- function(df, chr_col="chr", pos_col="pos") {
165
- chrs <- unique(df[[chr_col]])[chr_order_fn(unique(df[[chr_col]]))]
166
- chr_lens <- sapply(chrs, function(c) max(df[[pos_col]][df[[chr_col]] == c]))
167
- offsets <- c(0, cumsum(chr_lens[-length(chr_lens)])); names(offsets) <- chrs
168
- df$cum_pos <- df[[pos_col]] + offsets[df[[chr_col]]]
169
- list(df=df, offsets=offsets, chrs=chrs)
170
- }
171
-
172
- build_cross_from_files <- function(geno_path, pheno_path, cross_type="bc") {
173
- geno_raw <- read.csv(geno_path, header=FALSE, stringsAsFactors=FALSE,
174
- check.names=FALSE, na.strings=c("NA","","N/A"))
175
- marker_names <- as.character(geno_raw[1, -1])
176
- chr_row <- as.character(geno_raw[2, -1])
177
- pos_row <- suppressWarnings(as.numeric(as.character(geno_raw[3, -1])))
178
- sample_ids <- as.character(geno_raw[-(1:3), 1])
179
- geno_matrix <- geno_raw[-(1:3), -1, drop=FALSE]
180
-
181
- chr_clean <- gsub("^chr0*", "", chr_row, ignore.case=TRUE)
182
- chr_clean <- gsub("^0+", "", chr_clean)
183
-
184
- geno_num <- apply(geno_matrix, 2, function(col) {
185
- v <- suppressWarnings(as.numeric(as.character(col)))
186
- ifelse(is.na(v) | v == -1, NA,
187
- ifelse(v == 0, 1L,
188
- ifelse(v == 1, 2L,
189
- ifelse(v == 2, 3L, NA))))
190
- })
191
- rownames(geno_num) <- sample_ids
192
- colnames(geno_num) <- marker_names
193
-
194
- pheno_raw <- read.csv(pheno_path, header=TRUE, stringsAsFactors=FALSE,
195
- check.names=FALSE, na.strings=c("NA","","N/A"))
196
- colnames(pheno_raw)[1] <- "id"
197
- rownames(pheno_raw) <- as.character(pheno_raw$id)
198
-
199
- common_ids <- intersect(sample_ids, as.character(pheno_raw$id))
200
- if (length(common_ids) == 0)
201
- stop("No matching sample IDs between genotype and phenotype files.")
202
-
203
- geno_aln <- geno_num[common_ids, , drop=FALSE]
204
- pheno_aln <- pheno_raw[common_ids, -1, drop=FALSE]
205
- n_ind <- length(common_ids)
206
-
207
- uniq_chrs <- unique(chr_clean)
208
- chr_nums <- suppressWarnings(as.numeric(uniq_chrs))
209
- uniq_chrs <- if (all(!is.na(chr_nums))) uniq_chrs[order(chr_nums)] else sort(uniq_chrs)
210
-
211
- map <- setNames(vector("list", length(uniq_chrs)), uniq_chrs)
212
- for (ch in uniq_chrs) {
213
- idx <- which(chr_clean == ch)
214
- mk_pos <- pos_row[idx]; names(mk_pos) <- marker_names[idx]
215
- map[[ch]] <- mk_pos
216
- }
217
-
218
- geno_list <- setNames(vector("list", length(uniq_chrs)), uniq_chrs)
219
- for (ch in uniq_chrs) {
220
- idx <- which(chr_clean == ch)
221
- mat <- geno_aln[, idx, drop=FALSE]
222
- storage.mode(mat) <- "integer"
223
- geno_list[[ch]] <- list(data=mat, map=map[[ch]])
224
- class(geno_list[[ch]]) <- "A"
225
- }
226
-
227
- cross <- list(geno=geno_list, pheno=as.data.frame(pheno_aln, stringsAsFactors=FALSE))
228
- for (j in seq_len(ncol(cross$pheno)))
229
- cross$pheno[, j] <- suppressWarnings(as.numeric(as.character(cross$pheno[, j])))
230
- rownames(cross$pheno) <- common_ids
231
- class(cross) <- c(cross_type, "cross")
232
- cross <- jittermap(cross)
233
-
234
- list(cross=cross, n_ind=n_ind, n_markers=length(marker_names),
235
- n_chr=length(uniq_chrs), n_pheno=ncol(pheno_aln),
236
- pheno_names=colnames(pheno_aln), sample_ids=common_ids,
237
- skipped_ids=setdiff(sample_ids, common_ids))
238
- }
239
-
240
- # ── Compatibility helper: detect ggplot2 version for stat() vs after_stat() ──
241
- # FIX: avoid stat(density) which errors in ggplot2 >= 3.4.0
242
- .gg_after_stat_density <- function() {
243
- vv <- tryCatch(packageVersion("ggplot2"), error=function(e) package_version("3.0.0"))
244
- vv >= "3.3.0"
245
- }
246
-
247
- # ── UI ────────────────────────────────────────────────────
248
- ui <- fluidPage(
249
- useShinyjs(),
250
- tags$head(
251
- tags$style(APP_CSS),
252
- tags$script(HTML("
253
- $(document).on('click','.nv',function(){
254
- var pg=$(this).data('page'); if(!pg)return;
255
- $('.nv').removeClass('active'); $(this).addClass('active');
256
- $('.pg').removeClass('active'); $('#pg-'+pg).addClass('active');
257
- Shiny.setInputValue('active_page',pg,{priority:'event'});
258
- });
259
- $(document).on('click','.qtab',function(){
260
- var g=$(this).data('group'),t=$(this).data('tab');
261
- $('.qtab[data-group='+g+']').removeClass('active'); $(this).addClass('active');
262
- Shiny.setInputValue('tab_'+g,t,{priority:'event'});
263
- });
264
- $(document).on('click','.mc',function(){
265
- $(this).toggleClass('sel');
266
- var sel=[];$('.mc.sel').each(function(){sel.push($(this).data('model'));});
267
- Shiny.setInputValue('sel_models',sel,{priority:'event'});
268
- });
269
- "))
270
- ),
271
-
272
- div(class="qtl-top",
273
- div(class="tlmark","Q"),
274
- span(class="tlname","QTL Mapping Suite"),
275
- span(class="tlver","v2.2"),
276
- div(class="tldiv"),
277
- div(class="stpill", div(class="dot"), span(id="stlbl","Ready")),
278
- div(class="tlright", downloadButton("dl_full","Export All",class="btn-tn"))
279
- ),
280
-
281
- div(class="qtl-lay",
282
- div(class="qtl-sb",
283
- div(class="sb-sec",
284
- div(class="sb-sec-t","Data"),
285
- tags$div(class="nv active",`data-page`="upload", span(class="nv-ic","U"), span("Upload Data")),
286
- tags$div(class="nv",`data-page`="explore", span(class="nv-ic","E"), span("Data Explorer"))
287
- ),
288
- div(class="sb-sec",
289
- div(class="sb-sec-t","Analysis"),
290
- tags$div(class="nv",`data-page`="config", span(class="nv-ic","C"), span("Configure")),
291
- tags$div(class="nv",`data-page`="run", span(class="nv-ic","R"), span("Run Scan"))
292
- ),
293
- div(class="sb-sec",
294
- div(class="sb-sec-t","Results"),
295
- tags$div(class="nv",`data-page`="genome", span(class="nv-ic","G"), span("Genome Scan")),
296
- tags$div(class="nv",`data-page`="qtlmap", span(class="nv-ic","M"), span("QTL Map")),
297
- tags$div(class="nv",`data-page`="effects", span(class="nv-ic","F"), span("Effects & PVE")),
298
- tags$div(class="nv",`data-page`="compare", span(class="nv-ic","V"), span("Model Compare")),
299
- tags$div(class="nv",`data-page`="circos", span(class="nv-ic","O"), span("Circos Plot")),
300
- tags$div(class="nv",`data-page`="table", span(class="nv-ic","T"), span("Results Table"))
301
- ),
302
- div(class="sb-foot","QTL Suite 2024")
303
- ),
304
-
305
- div(class="qtl-main",
306
-
307
- # ── UPLOAD ──
308
- div(id="pg-upload", class="pg active",
309
- div(class="ph",
310
- div(class="pt","Upload Data Files"),
311
- div(class="ps","Upload genotype and phenotype files separately or load the built-in demo")
312
- ),
313
- div(class="card",
314
- div(class="ch", div(div(class="ct","Expected File Formats"), div(class="cst","Your exact format is supported"))),
315
- div(class="cb",
316
- div(class="g2",
317
- div(
318
- div(class="fmt-title","GENOTYPE CSV"),
319
- tags$table(class="fmt-table",
320
- tags$thead(tags$tr(tags$th("Row"),tags$th("Col 1"),tags$th("Col 2+"))),
321
- tags$tbody(
322
- tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id"),tags$td(class="hdr","marker names")),
323
- tags$tr(tags$td(class="pos-row","Row 2 (Chr)"),tags$td(class="pos-row","1"),tags$td(class="pos-row","chromosome")),
324
- tags$tr(tags$td(class="pos-row","Row 3 (Pos)"),tags$td(class="pos-row","0"),tags$td(class="pos-row","position cM")),
325
- tags$tr(tags$td("Row 4+"),tags$td("Sample ID"),tags$td("0=AA, 1=AB, 2=BB, -1=missing"))
326
- )
327
- )
328
- ),
329
- div(
330
- div(class="fmt-title","PHENOTYPE CSV"),
331
- tags$table(class="fmt-table",
332
- tags$thead(tags$tr(tags$th("Row"),tags$th("Col 1"),tags$th("Col 2+"))),
333
- tags$tbody(
334
- tags$tr(tags$td(class="hdr","Row 1 (Header)"),tags$td(class="hdr","id"),tags$td(class="hdr","trait names")),
335
- tags$tr(tags$td("Row 2+"),tags$td("Sample ID"),tags$td("Numeric phenotype values"))
336
- )
337
- ),
338
- div(style="margin-top:10px;",
339
- div(class="al al-info","i",div("Sample IDs must match exactly between the two files."))
340
- )
341
- )
342
- )
343
- )
344
- ),
345
- div(class="g2",
346
- div(class="card",
347
- div(class="ch",
348
- div(div(class="ct","Genotype File"), div(class="cst","CSV with chr/pos rows")),
349
- uiOutput("geno_badge")
350
- ),
351
- div(class="cb",
352
- div(class="uzone",
353
- div(class="uzone-ic","[G]"),
354
- div(class="uzone-t","Drop Genotype CSV"),
355
- div(class="uzone-s","Row 2=chromosome, Row 3=cM position, Row 4+=samples"),
356
- fileInput("geno_file", NULL, accept=c(".csv",".CSV"), buttonLabel="Browse", placeholder="No file selected")
357
- ),
358
- div(class="tip","Genotype codes: 0=AA, 1=AB, 2=BB, -1=missing")
359
- )
360
- ),
361
- div(class="card",
362
- div(class="ch",
363
- div(div(class="ct","Phenotype File"), div(class="cst","CSV with trait columns")),
364
- uiOutput("pheno_badge")
365
- ),
366
- div(class="cb",
367
- div(class="uzone",
368
- div(class="uzone-ic","[P]"),
369
- div(class="uzone-t","Drop Phenotype CSV"),
370
- div(class="uzone-s","Multiple environments/traits supported as separate columns"),
371
- fileInput("pheno_file", NULL, accept=c(".csv",".CSV"), buttonLabel="Browse", placeholder="No file selected")
372
- ),
373
- div(class="tip","First column = sample ID, remaining columns = trait values")
374
- )
375
- )
376
- ),
377
- div(class="card",
378
- div(class="ch", div(div(class="ct","Cross Settings & Load"))),
379
- div(class="cb",
380
- div(class="g2",
381
- div(
382
- div(class="fm-g", label(class="fl","Cross Type"),
383
- selectInput("cross_type", NULL,
384
- choices=c("Backcross"="bc","F2 Intercross"="f2","RIL by selfing"="riself","RIL by sibling"="risib","Doubled Haploid"="dh"),
385
- selected="bc", width="100%"))
386
- ),
387
- div(
388
- div(class="fm-g", label(class="fl","Missing Genotype Value"),
389
- selectInput("miss_val", NULL, choices=c("-1 (default)"="-1","NA"="NA","0"="0"), selected="-1", width="100%"))
390
- )
391
- ),
392
- div(class="br",
393
- actionButton("load_data","Load Files", class="btn-p"),
394
- actionButton("load_demo","Load Listeria Demo", class="btn-s")
395
- ),
396
- br(),
397
- uiOutput("upload_status_msg")
398
- )
399
- ),
400
- uiOutput("upload_summary")
401
- ),
402
-
403
- # ── EXPLORE ──
404
- div(id="pg-explore", class="pg",
405
- div(class="ph", div(class="pt","Data Explorer"), div(class="ps","Inspect genotype, phenotype and map structure")),
406
- div(class="g4", uiOutput("stat_tiles")),
407
- br(),
408
- div(class="qtabs",
409
- div(class="qtab active",`data-group`="ex",`data-tab`="pheno","Phenotype"),
410
- div(class="qtab",`data-group`="ex",`data-tab`="map","Genetic Map"),
411
- div(class="qtab",`data-group`="ex",`data-tab`="miss","Missing Data"),
412
- div(class="qtab",`data-group`="ex",`data-tab`="gfreq","Genotype Freq")
413
- ),
414
- uiOutput("explore_content")
415
- ),
416
-
417
- # ── CONFIG ──
418
- div(id="pg-config", class="pg",
419
- div(class="ph", div(class="pt","Configure Analysis"), div(class="ps","Select phenotype, models, and scan parameters")),
420
- div(class="g2",
421
- div(class="card",
422
- div(class="ch", div(div(class="ct","Phenotype & Scan Settings"))),
423
- div(class="cb",
424
- div(class="fm-g", label(class="fl","Phenotype"), uiOutput("pheno_sel")),
425
- div(class="fm-g", label(class="fl","Chromosomes to Scan"), uiOutput("chr_sel")),
426
- div(class="fm-g", label(class="fl","Step Size (cM)"),
427
- sliderInput("step_sz",NULL,min=1,max=10,value=2,step=1,width="100%")),
428
- div(class="fm-g", label(class="fl","Error Probability"),
429
- sliderInput("err_prob",NULL,min=0.001,max=0.05,value=0.001,step=0.001,width="100%"))
430
- )
431
- ),
432
- div(class="card",
433
- div(class="ch", div(div(class="ct","QTL Models"), div(class="cst","Click chips to select/deselect"))),
434
- div(class="cb",
435
- div(class="fm-g", label(class="fl","Available Models"),
436
- div(class="mchips",
437
- div(class="mc sel",`data-model`="em","EM Algorithm"),
438
- div(class="mc sel",`data-model`="hk","Haley-Knott"),
439
- div(class="mc",`data-model`="mr","Marker Regression"),
440
- div(class="mc",`data-model`="im","Interval Mapping"),
441
- div(class="mc",`data-model`="cim","CIM"),
442
- div(class="mc",`data-model`="ehk","Extended HK"),
443
- div(class="mc",`data-model`="imp","Imputation"),
444
- div(class="mc",`data-model`="hkperm","HK+Permutation"),
445
- div(class="mc",`data-model`="scanone_np","Non-parametric"),
446
- div(class="mc",`data-model`="mqm","MQM")
447
- )
448
- ),
449
- div(class="fm-g", label(class="fl","LOD Threshold"),
450
- numericInput("lod_thr",NULL,value=3.0,min=1,max=10,step=0.1,width="100%")),
451
- div(class="fm-g", label(class="fl","Permutations (0=skip)"),
452
- numericInput("n_perm",NULL,value=0,min=0,max=1000,step=100,width="100%")),
453
- div(class="fm-g", label(class="fl","Imputations (for imp model)"),
454
- numericInput("n_imp",NULL,value=32,min=8,max=128,step=8,width="100%"))
455
- )
456
- )
457
- )
458
- ),
459
-
460
- # ── RUN ──
461
- div(id="pg-run", class="pg",
462
- div(class="ph", div(class="pt","Run QTL Scan"), div(class="ps","Execute selected models across the genome")),
463
- div(class="card",
464
- div(class="ch", div(div(class="ct","Analysis Pipeline"))),
465
- div(class="cb",
466
- uiOutput("run_summary"), br(),
467
- div(class="br",
468
- actionButton("run_scan","Run QTL Scan",class="btn-p"),
469
- actionButton("clr_res","Clear",class="btn-s")
470
- ),
471
- br(),
472
- uiOutput("prog_ui"),
473
- uiOutput("log_ui")
474
- )
475
- )
476
- ),
477
-
478
- # ── GENOME SCAN ──
479
- div(id="pg-genome", class="pg",
480
- div(class="ph", div(class="pt","Genome Scan"), div(class="ps","LOD score profiles")),
481
- div(class="card",
482
- div(class="ch",
483
- div(div(class="ct","LOD Profiles"), div(class="cst","All selected models")),
484
- div(class="br", uiOutput("gm_model_sel"), downloadButton("dl_genome","PNG",class="btn-dl"))
485
- ),
486
- div(class="cb", withSpinner(plotlyOutput("pl_genome",height="400px"),color="#1a6b3a"))
487
- ),
488
- div(class="g2",
489
- div(class="card",
490
- div(class="ch", div(div(class="ct","Per-Chromosome Max LOD"))),
491
- div(class="cb", withSpinner(plotlyOutput("pl_chr_bar",height="280px"),color="#1a6b3a"))
492
- ),
493
- div(class="card",
494
- div(class="ch", div(div(class="ct","QQ Plot"))),
495
- div(class="cb", withSpinner(plotlyOutput("pl_qq",height="280px"),color="#1a6b3a"))
496
- )
497
- )
498
- ),
499
-
500
- # ── QTL MAP ──
501
- div(id="pg-qtlmap", class="pg",
502
- div(class="ph", div(class="pt","QTL Map"), div(class="ps","Significant QTL locations")),
503
- div(class="card",
504
- div(class="ch",
505
- div(div(class="ct","Manhattan Plot"), div(class="cst","Red = significant")),
506
- downloadButton("dl_manh","PNG",class="btn-dl")
507
- ),
508
- div(class="cb", withSpinner(plotlyOutput("pl_manh",height="340px"),color="#1a6b3a"))
509
- ),
510
- div(class="g2",
511
- div(class="card",
512
- div(class="ch", div(div(class="ct","1.5-LOD Interval Plot"))),
513
- div(class="cb", withSpinner(plotlyOutput("pl_interval",height="300px"),color="#1a6b3a"))
514
- ),
515
- div(class="card",
516
- div(class="ch", div(div(class="ct","QTL Density"))),
517
- div(class="cb", withSpinner(plotlyOutput("pl_density",height="300px"),color="#1a6b3a"))
518
- )
519
- )
520
- ),
521
-
522
- # ── EFFECTS ──
523
- div(id="pg-effects", class="pg",
524
- div(class="ph", div(class="pt","Effects & PVE"), div(class="ps","QTL effect sizes and percent variance explained")),
525
- div(class="g2",
526
- div(class="card",
527
- div(class="ch", div(div(class="ct","Percent Variance Explained"))),
528
- div(class="cb", withSpinner(plotlyOutput("pl_pve",height="300px"),color="#1a6b3a"))
529
- ),
530
- div(class="card",
531
- div(class="ch", div(div(class="ct","Additive Effects"))),
532
- div(class="cb", uiOutput("eff_chr_ui"), withSpinner(plotlyOutput("pl_eff",height="280px"),color="#1a6b3a"))
533
- )
534
- ),
535
- div(class="card",
536
- div(class="ch", div(div(class="ct","Phenotype x Genotype Violin"))),
537
- div(class="cb",
538
- div(class="fm-g", label(class="fl","Select QTL Peak"), uiOutput("peak_sel")),
539
- withSpinner(plotlyOutput("pl_violin",height="300px"),color="#1a6b3a")
540
- )
541
- )
542
- ),
543
-
544
- # ── COMPARE ──
545
- div(id="pg-compare", class="pg",
546
- div(class="ph", div(class="pt","Model Comparison"), div(class="ps","LOD profiles across all models")),
547
- div(class="card",
548
- div(class="ch", div(div(class="ct","LOD Heatmap — Marker x Model"))),
549
- div(class="cb", withSpinner(plotlyOutput("pl_heatmap",height="380px"),color="#1a6b3a"))
550
- ),
551
- div(class="card",
552
- div(class="ch", div(div(class="ct","Common QTL"), div(class="cst","Amber = peaks in 2+ models"))),
553
- div(class="cb", withSpinner(plotlyOutput("pl_common",height="340px"),color="#1a6b3a"))
554
- ),
555
- div(class="card",
556
- div(class="ch", div(div(class="ct","Peak LOD Parallel Lines"))),
557
- div(class="cb", withSpinner(plotlyOutput("pl_pkcomp",height="300px"),color="#1a6b3a"))
558
- )
559
- ),
560
-
561
- # ── CIRCOS ──
562
- div(id="pg-circos", class="pg",
563
- div(class="ph", div(class="pt","Circos Plot"), div(class="ps","Circular genome view of QTL")),
564
- div(class="card",
565
- div(class="ch",
566
- div(div(class="ct","Circular QTL View"), div(class="cst","Each ring = one model")),
567
- downloadButton("dl_circos","PNG",class="btn-dl")
568
- ),
569
- div(class="cb",
570
- div(style="display:flex;justify-content:center;",
571
- withSpinner(plotOutput("pl_circos",width="680px",height="680px"),color="#1a6b3a")
572
- )
573
- )
574
- )
575
- ),
576
-
577
- # ── TABLE ──
578
- div(id="pg-table", class="pg",
579
- div(class="ph",
580
- div(class="phr",
581
- div(div(class="pt","Results Table"), div(class="ps","Significant QTL")),
582
- div(class="br",
583
- downloadButton("dl_csv","CSV",class="btn-dl"),
584
- downloadButton("dl_tsv","TSV",class="btn-dl"),
585
- downloadButton("dl_rds","RData",class="btn-dl")
586
- )
587
- )
588
- ),
589
- div(class="card",
590
- div(class="ch", div(div(class="ct","Significant QTL"), div(class="cst","LOD >= threshold"))),
591
- div(class="cb", withSpinner(DTOutput("tbl_qtl"),color="#1a6b3a"))
592
- ),
593
- div(class="card",
594
- div(class="ch", div(div(class="ct","Full Scan Output"))),
595
- div(class="cb", withSpinner(DTOutput("tbl_full"),color="#1a6b3a"))
596
- )
597
- )
598
- )
599
- )
600
- )
601
-
602
- # ── SERVER ────────────────────────────────────────────────
603
- server <- function(input, output, session) {
604
-
605
- rv <- reactiveValues(
606
- cross=NULL, scan_list=list(), sig_qtl=list(),
607
- log_msgs=character(0), running=FALSE,
608
- pheno_name="Phenotype", geno_ok=FALSE, pheno_ok=FALSE,
609
- load_msg=NULL, load_ok=FALSE
610
- )
611
-
612
- add_log <- function(msg) {
613
- rv$log_msgs <- c(rv$log_msgs, paste0("[",format(Sys.time(),"%H:%M:%S"),"] ",msg))
614
- }
615
-
616
- output$geno_badge <- renderUI({
617
- if (rv$geno_ok) div(class="sbadge sbadge-ok","Loaded")
618
- else if (!is.null(input$geno_file)) div(class="sbadge sbadge-pend","Pending")
619
- else div(class="sbadge sbadge-pend","Not loaded")
620
- })
621
-
622
- output$pheno_badge <- renderUI({
623
- if (rv$pheno_ok) div(class="sbadge sbadge-ok","Loaded")
624
- else if (!is.null(input$pheno_file)) div(class="sbadge sbadge-pend","Pending")
625
- else div(class="sbadge sbadge-pend","Not loaded")
626
- })
627
-
628
- observeEvent(input$load_demo, {
629
- withProgress(message="Loading Listeria demo...", {
630
- tryCatch({
631
- data(listeria, package="qtl")
632
- rv$cross <- listeria
633
- rv$geno_ok <- TRUE
634
- rv$pheno_ok <- TRUE
635
- rv$load_ok <- TRUE
636
- rv$load_msg <- "Listeria demo loaded (F2, 20 chr, 133 markers, 1 phenotype)"
637
- rv$log_msgs <- character(0)
638
- add_log("Loaded Listeria demo")
639
- showNotification("Listeria dataset loaded!", type="message", duration=3)
640
- shinyjs::runjs("$('.nv').removeClass('active');$('[data-page=explore]').addClass('active');$('.pg').removeClass('active');$('#pg-explore').addClass('active');")
641
- }, error=function(e) {
642
- rv$load_ok <- FALSE
643
- rv$load_msg <- paste("Error:", e$message)
644
- showNotification(paste("Error:", e$message), type="error")
645
- })
646
- })
647
- })
648
-
649
- observeEvent(input$load_data, {
650
- if (is.null(input$geno_file)) { showNotification("Please upload a genotype CSV file first.", type="warning"); return() }
651
- if (is.null(input$pheno_file)) { showNotification("Please upload a phenotype CSV file first.", type="warning"); return() }
652
- withProgress(message="Building cross object...", value=0, {
653
- tryCatch({
654
- incProgress(0.3, detail="Reading files...")
655
- result <- build_cross_from_files(input$geno_file$datapath, input$pheno_file$datapath, input$cross_type)
656
- incProgress(0.5, detail="Checking cross...")
657
- rv$cross <- result$cross
658
- rv$geno_ok <- TRUE
659
- rv$pheno_ok <- TRUE
660
- rv$load_ok <- TRUE
661
- rv$log_msgs <- character(0)
662
- msg <- paste0("Loaded: ",result$n_ind," individuals, ",result$n_markers," markers, ",
663
- result$n_chr," chromosomes, ",result$n_pheno," phenotype(s): ",
664
- paste(result$pheno_names,collapse=", "))
665
- if (length(result$skipped_ids) > 0)
666
- msg <- paste0(msg," | Skipped ",length(result$skipped_ids)," unmatched IDs")
667
- rv$load_msg <- msg
668
- add_log(msg)
669
- incProgress(0.2, detail="Done")
670
- showNotification("Data loaded successfully!", type="message", duration=4)
671
- shinyjs::runjs("$('.nv').removeClass('active');$('[data-page=explore]').addClass('active');$('.pg').removeClass('active');$('#pg-explore').addClass('active');")
672
- }, error=function(e) {
673
- rv$geno_ok <- FALSE
674
- rv$pheno_ok <- FALSE
675
- rv$load_ok <- FALSE
676
- rv$load_msg <- paste("Load error:", e$message)
677
- add_log(paste("ERROR:", e$message))
678
- showNotification(paste("Load error:", e$message), type="error", duration=8)
679
- })
680
- })
681
- })
682
-
683
- output$upload_status_msg <- renderUI({
684
- req(!is.null(rv$load_msg))
685
- if (rv$load_ok) div(class="al al-ok","OK",div(div(style="font-weight:600;","Success"),div(rv$load_msg)))
686
- else div(class="al al-err","!",div(div(style="font-weight:600;","Error"),div(rv$load_msg)))
687
- })
688
-
689
- output$upload_summary <- renderUI({
690
- req(rv$cross); cr <- rv$cross
691
- div(class="card",
692
- div(class="ch", div(div(class="ct","Dataset Summary"))),
693
- div(class="cb",
694
- div(class="g4",
695
- div(class="st acc", div(class="st-l","Individuals"), div(class="st-v", nind(cr))),
696
- div(class="st", div(class="st-l","Markers"), div(class="st-v", totmar(cr))),
697
- div(class="st", div(class="st-l","Chromosomes"), div(class="st-v", nchr(cr))),
698
- div(class="st", div(class="st-l","Phenotypes"), div(class="st-v", nphe(cr)))
699
- ),
700
- br(),
701
- div(class="tip", paste("Phenotypes:", paste(phenames(cr), collapse=", ")))
702
- )
703
- )
704
- })
705
-
706
- output$stat_tiles <- renderUI({
707
- req(rv$cross); cr <- rv$cross
708
- tagList(
709
- div(class="st acc", div(class="st-l","Individuals"), div(class="st-v", nind(cr))),
710
- div(class="st", div(class="st-l","Markers"), div(class="st-v", totmar(cr))),
711
- div(class="st", div(class="st-l","Chromosomes"), div(class="st-v", nchr(cr))),
712
- div(class="st", div(class="st-l","Phenotypes"), div(class="st-v", nphe(cr)))
713
- )
714
- })
715
-
716
- output$explore_content <- renderUI({
717
- tab <- if (is.null(input$tab_ex)) "pheno" else input$tab_ex
718
- req(rv$cross)
719
- if (tab == "pheno") {
720
- div(class="card",
721
- div(class="ch", div(class="ct","Phenotype Distribution"), uiOutput("ex_pheno_sel_ui")),
722
- div(class="cb", withSpinner(plotlyOutput("pl_ex_pheno",height="320px"),color="#1a6b3a"))
723
- )
724
- } else if (tab == "map") {
725
- div(class="card",div(class="ch",div(class="ct","Genetic Map")),div(class="cb",withSpinner(plotlyOutput("pl_ex_map",height="380px"),color="#1a6b3a")))
726
- } else if (tab == "miss") {
727
- div(class="card",div(class="ch",div(class="ct","Missing Genotypes")),div(class="cb",withSpinner(plotlyOutput("pl_ex_miss",height="350px"),color="#1a6b3a")))
728
- } else {
729
- div(class="card",div(class="ch",div(class="ct","Genotype Frequencies")),div(class="cb",withSpinner(plotlyOutput("pl_ex_gf",height="350px"),color="#1a6b3a")))
730
- }
731
- })
732
-
733
- output$ex_pheno_sel_ui <- renderUI({
734
- req(rv$cross); pn <- phenames(rv$cross)
735
- if (length(pn) > 1) selectInput("ex_pheno_col",NULL,choices=pn,selected=pn[1],width="200px")
736
- })
737
-
738
- output$pl_ex_pheno <- renderPlotly({
739
- req(rv$cross)
740
- pn <- phenames(rv$cross)
741
- sel <- if (!is.null(input$ex_pheno_col) && input$ex_pheno_col %in% pn) input$ex_pheno_col else pn[1]
742
- phe <- pull.pheno(rv$cross, which(pn == sel))
743
- df <- data.frame(y=phe[!is.na(phe)])
744
-
745
- # FIX: Use after_stat(density) instead of deprecated stat(density)
746
- # Both work in ggplot2 >= 3.3; after_stat is the correct modern form
747
- p <- ggplot(df, aes(x=y)) +
748
- geom_histogram(aes(y=after_stat(density)), bins=30,
749
- fill="#1a6b3a", color="white", alpha=.85) +
750
- geom_density(color="#c47c1a", linewidth=1) +
751
- labs(x=sel, y="Density", title=paste("Phenotype:",sel)) +
752
- theme_minimal() + theme(panel.grid.minor=element_blank())
753
- ggplotly(p) %>% layout(font=list(family="sans-serif"))
754
- })
755
-
756
- output$pl_ex_map <- renderPlotly({
757
- req(rv$cross); map <- pull.map(rv$cross)
758
- df <- do.call(rbind, lapply(names(map), function(c)
759
- data.frame(chr=c, pos=map[[c]], marker=names(map[[c]]), stringsAsFactors=FALSE)))
760
- df$cn <- as.numeric(factor(df$chr, levels=names(map)))
761
- p <- ggplot(df, aes(x=pos, y=cn, text=paste0("Marker:",marker,"<br>Chr:",chr,"<br>Pos:",round(pos,2),"cM"))) +
762
- geom_line(aes(group=chr), color="#d0d0cc", linewidth=.5) +
763
- geom_point(color="#1a6b3a", size=2.5, alpha=.8) +
764
- scale_y_continuous(breaks=unique(df$cn), labels=names(map)) +
765
- labs(x="Position (cM)", y="Chromosome", title="Genetic Map") +
766
- theme_minimal() + theme(panel.grid.minor=element_blank())
767
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
768
- })
769
-
770
- output$pl_ex_miss <- renderPlotly({
771
- req(rv$cross); gt <- pull.geno(rv$cross)
772
- mp <- colMeans(is.na(gt)) * 100
773
- df <- data.frame(marker=names(mp), pct=mp, idx=seq_along(mp))
774
- p <- ggplot(df, aes(x=idx, y=pct, text=paste0("Marker:",marker,"<br>Missing:",round(pct,1),"%"))) +
775
- geom_col(fill="#1a4a8a", alpha=.7) +
776
- labs(x="Marker Index", y="Missing (%)", title="Missing Genotype Data") +
777
- theme_minimal() + theme(panel.grid.minor=element_blank())
778
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
779
- })
780
-
781
- output$pl_ex_gf <- renderPlotly({
782
- req(rv$cross); gt <- pull.geno(rv$cross)
783
- max_g <- max(gt, na.rm=TRUE)
784
- lvls <- 1:max(max_g, 3)
785
- lbl <- c("1"="AA","2"="AB","3"="BB")
786
- cnts <- apply(gt, 2, function(x) table(factor(x, levels=lvls)))
787
- df <- as.data.frame(t(cnts)); df$marker <- rownames(df)
788
- cn <- intersect(c("1","2","3"), colnames(df))
789
- names(df)[names(df) %in% cn] <- lbl[cn]
790
- gn <- intersect(c("AA","AB","BB"), names(df))
791
-
792
- # FIX: Use base reshape instead of tidyr::pivot_longer to avoid all_of() issues
793
- dl <- do.call(rbind, lapply(gn, function(g) {
794
- data.frame(marker=df$marker, geno=g, count=df[[g]], stringsAsFactors=FALSE)
795
- }))
796
- dl$idx <- match(dl$marker, unique(dl$marker))
797
-
798
- p <- ggplot(dl, aes(x=idx, y=count, fill=geno,
799
- text=paste0("Marker:",marker,"<br>Geno:",geno,"<br>N:",count))) +
800
- geom_col(position="fill", width=1) +
801
- scale_fill_manual(values=c(AA="#1a6b3a",AB="#c47c1a",BB="#1a4a8a")) +
802
- labs(x="Marker Index", y="Proportion", fill="Genotype") +
803
- theme_minimal() + theme(panel.grid.minor=element_blank())
804
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
805
- })
806
-
807
- output$pheno_sel <- renderUI({
808
- req(rv$cross); pn <- phenames(rv$cross)
809
- selectInput("pheno_col", NULL, choices=pn, selected=pn[1], width="100%")
810
- })
811
-
812
- output$chr_sel <- renderUI({
813
- req(rv$cross); ch <- chrnames(rv$cross)
814
- checkboxGroupInput("scan_chrs", NULL, choices=ch, selected=ch, inline=TRUE)
815
- })
816
-
817
- output$run_summary <- renderUI({
818
- mods <- if (is.null(input$sel_models) || !length(input$sel_models)) c("em","hk") else input$sel_models
819
- pn <- if (is.null(input$pheno_col)) "?" else input$pheno_col
820
- thr <- if (is.null(input$lod_thr)) 3.0 else input$lod_thr
821
- div(
822
- div(class="al al-info","i",div(
823
- div(style="font-weight:600;","Configured"),
824
- div(paste("Phenotype:",pn,"| Models:",length(mods),"| Threshold:",thr,"| Permutations:",input$n_perm))
825
- )),
826
- div(class="mchips", lapply(mods, function(m) div(class="mc sel",`data-model`=m, MODEL_LABELS[m])))
827
- )
828
- })
829
-
830
- output$prog_ui <- renderUI({
831
- if (!rv$running && !length(rv$scan_list)) return(NULL)
832
- if (rv$running) {
833
- tagList(div(class="prog-out",div(class="prog-in",style="width:60%")), div(class="tip","Scanning..."))
834
- } else {
835
- div(class="al al-ok","OK",div(div(style="font-weight:600;","Complete"),div(paste(length(rv$scan_list),"models done"))))
836
- }
837
- })
838
-
839
- output$log_ui <- renderUI({
840
- if (!length(rv$log_msgs)) return(NULL)
841
- div(class="card", style="margin-top:10px;",
842
- div(class="ch", div(class="ct","Run Log")),
843
- div(class="cb",
844
- tags$pre(style="font-family:monospace;font-size:11px;color:#5c5c58;background:#f8f8f6;padding:10px;border-radius:6px;max-height:180px;overflow-y:auto;",
845
- paste(rv$log_msgs, collapse="\n"))
846
- )
847
- )
848
- })
849
-
850
- observeEvent(input$run_scan, {
851
- req(rv$cross)
852
- mods <- if (is.null(input$sel_models) || !length(input$sel_models)) c("em","hk") else input$sel_models
853
- phe_col <- if (is.null(input$pheno_col)) 1 else { v <- which(phenames(rv$cross)==input$pheno_col)[1]; if(is.na(v)) 1 else v }
854
- step <- if (is.null(input$step_sz)) 2 else input$step_sz
855
- ep <- if (is.null(input$err_prob)) 0.001 else input$err_prob
856
- thr <- if (is.null(input$lod_thr)) 3.0 else input$lod_thr
857
- n_perm <- if (is.null(input$n_perm)) 0 else input$n_perm
858
- n_imp <- if (is.null(input$n_imp)) 32 else input$n_imp
859
-
860
- rv$running <- TRUE
861
- rv$scan_list <- list()
862
- rv$sig_qtl <- list()
863
- rv$log_msgs <- character(0)
864
- rv$pheno_name <- phenames(rv$cross)[phe_col]
865
-
866
- withProgress(message="Running QTL scan...", value=0, {
867
- tryCatch({
868
- add_log("Computing conditional genotype probabilities...")
869
- rv$cross <- calc.genoprob(rv$cross, step=step, error.prob=ep)
870
- incProgress(0.1)
871
-
872
- if ("imp" %in% mods) {
873
- add_log("Simulating genotypes for imputation...")
874
- rv$cross <- sim.geno(rv$cross, n.draws=n_imp, step=step, error.prob=ep)
875
- }
876
-
877
- for (i in seq_along(mods)) {
878
- m <- mods[i]
879
- add_log(paste("Model:", MODEL_LABELS[m], "..."))
880
- incProgress(0.8/length(mods), detail=MODEL_LABELS[m])
881
-
882
- res <- tryCatch({
883
- switch(m,
884
- em = scanone(rv$cross, pheno.col=phe_col, method="em"),
885
- hk = scanone(rv$cross, pheno.col=phe_col, method="hk"),
886
- mr = scanone(rv$cross, pheno.col=phe_col, method="mr"),
887
- im = scanone(rv$cross, pheno.col=phe_col, method="em"),
888
- ehk = scanone(rv$cross, pheno.col=phe_col, method="ehk"),
889
- imp = scanone(rv$cross, pheno.col=phe_col, method="imp"),
890
- hkperm = scanone(rv$cross, pheno.col=phe_col, method="hk"),
891
- scanone_np = scanone(rv$cross, pheno.col=phe_col, method="np"),
892
- cim = cim(rv$cross, pheno.col=phe_col, method="hk"),
893
- mqm = tryCatch(mqmscan(rv$cross, pheno.col=phe_col),
894
- error=function(e) scanone(rv$cross, pheno.col=phe_col, method="hk")),
895
- scanone(rv$cross, pheno.col=phe_col, method="hk")
896
- )
897
- }, error=function(e) {
898
- add_log(paste(" ", m, "failed:", e$message, "-> fallback HK"))
899
- scanone(rv$cross, pheno.col=phe_col, method="hk")
900
- })
901
-
902
- rv$scan_list[[m]] <- res
903
- lc <- ncol(res)
904
- sig <- res[res[, lc] >= thr, ]
905
- if (nrow(sig) > 0) {
906
- sig$model <- MODEL_LABELS[m]
907
- sig$model_id <- m
908
- sig$marker <- rownames(sig)
909
- sig$pve <- round(100*(1-exp(-2*sig[,lc]/nind(rv$cross))), 2)
910
- }
911
- rv$sig_qtl[[m]] <- sig
912
- add_log(paste(" OK", MODEL_LABELS[m], "peaks:", nrow(sig)))
913
- }
914
-
915
- if ("hkperm" %in% mods && n_perm > 0) {
916
- add_log(paste("Running", n_perm, "permutations for HK..."))
917
- perm <- scanone(rv$cross, pheno.col=phe_col, method="hk", n.perm=n_perm, verbose=FALSE)
918
- thr_perm <- summary(perm, alpha=0.05)[1]
919
- add_log(paste(" Permutation threshold (5%):", round(thr_perm, 2)))
920
- }
921
-
922
- rv$running <- FALSE
923
- incProgress(0.1)
924
- add_log(paste("All", length(mods), "models completed."))
925
- showNotification("Scan complete!", type="message", duration=3)
926
-
927
- }, error=function(e) {
928
- rv$running <- FALSE
929
- add_log(paste("FATAL:", e$message))
930
- showNotification(paste("Error:", e$message), type="error")
931
- })
932
- })
933
- })
934
-
935
- observeEvent(input$clr_res, {
936
- rv$scan_list <- list(); rv$sig_qtl <- list(); rv$log_msgs <- character(0)
937
- })
938
-
939
- comb_df <- reactive({
940
- req(length(rv$scan_list) > 0)
941
- do.call(rbind, lapply(names(rv$scan_list), function(m) {
942
- sc <- rv$scan_list[[m]]; lc <- ncol(sc)
943
- data.frame(chr=as.character(sc$chr), pos=sc$pos, lod=sc[,lc],
944
- model=MODEL_LABELS[m], model_id=m, marker=rownames(sc),
945
- stringsAsFactors=FALSE)
946
- }))
947
- })
948
-
949
- sig_df <- reactive({
950
- req(length(rv$sig_qtl) > 0)
951
- dfs <- Filter(function(d) nrow(d) > 0, rv$sig_qtl)
952
- if (!length(dfs)) return(NULL)
953
- do.call(rbind, dfs)
954
- })
955
-
956
- thresh_val <- reactive({ if (is.null(input$lod_thr)) 3.0 else input$lod_thr })
957
-
958
- output$gm_model_sel <- renderUI({
959
- req(length(rv$scan_list) > 0)
960
- selectInput("gm_msel", NULL,
961
- choices=setNames(names(rv$scan_list), MODEL_LABELS[names(rv$scan_list)]),
962
- multiple=TRUE, selected=names(rv$scan_list), width="260px")
963
- })
964
-
965
- output$pl_genome <- renderPlotly({
966
- req(length(rv$scan_list) > 0); df <- comb_df()
967
- sel <- if (!is.null(input$gm_msel)) input$gm_msel else unique(df$model_id)
968
- df <- df[df$model_id %in% sel, ]; thr <- thresh_val()
969
- res <- cum_positions(df); df <- res$df; offsets <- res$offsets; chrs <- res$chrs
970
- p <- ggplot(df, aes(x=cum_pos, y=lod, color=model,
971
- text=paste0("Chr:",chr,"<br>Pos:",round(pos,1),"cM<br>LOD:",round(lod,2),"<br>Model:",model))) +
972
- geom_line(linewidth=.7, alpha=.88) +
973
- geom_hline(yintercept=thr, linetype="dashed", color="#b83232", linewidth=.6) +
974
- scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) +
975
- labs(x="Genomic Position (cM)", y="LOD Score", color="Model") +
976
- theme_minimal() + theme(panel.grid.minor=element_blank(), panel.grid.major.x=element_blank(), legend.position="bottom")
977
- for (nm in names(offsets)[-1]) p <- p + geom_vline(xintercept=offsets[nm], color="#e0e0dc", linewidth=.35)
978
- mids <- tapply(df$cum_pos, df$chr, mean)
979
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"),
980
- annotations=lapply(chrs, function(c) list(x=mids[c],y=-0.4,text=c,showarrow=FALSE,font=list(size=8,color="#9a9a94"),xanchor="center")))
981
- })
982
-
983
- output$pl_chr_bar <- renderPlotly({
984
- req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val()
985
- pk <- df %>% group_by(chr, model) %>% summarise(mx=max(lod), .groups="drop")
986
- p <- ggplot(pk, aes(x=chr, y=mx, fill=model, text=paste0("Chr:",chr,"<br>",model,"<br>Max LOD:",round(mx,2)))) +
987
- geom_col(position="dodge", alpha=.85) +
988
- geom_hline(yintercept=thr, linetype="dashed", color="#b83232") +
989
- scale_fill_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) +
990
- labs(x="Chromosome", y="Max LOD", fill="Model") +
991
- theme_minimal() + theme(panel.grid.minor=element_blank(), legend.position="none")
992
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
993
- })
994
-
995
- output$pl_qq <- renderPlotly({
996
- req(length(rv$scan_list) > 0); df <- comb_df()
997
- df1 <- df[df$model_id == names(rv$scan_list)[1], ]
998
- lods <- sort(df1$lod); n <- length(lods)
999
- qq <- data.frame(ex=-log10(seq(n,1)/n), ob=lods)
1000
- p <- ggplot(qq, aes(x=ex, y=ob)) +
1001
- geom_point(color="#1a6b3a", alpha=.6, size=1.5) +
1002
- geom_abline(slope=1, intercept=0, color="#b83232", linetype="dashed") +
1003
- labs(x="Expected LOD", y="Observed LOD", title="QQ Plot") +
1004
- theme_minimal() + theme(panel.grid.minor=element_blank())
1005
- ggplotly(p) %>% layout(font=list(family="sans-serif"))
1006
- })
1007
-
1008
- output$pl_manh <- renderPlotly({
1009
- req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val()
1010
- df1 <- df[df$model_id == names(rv$scan_list)[1], ]
1011
- res <- cum_positions(df1); df1 <- res$df; chrs <- res$chrs; offsets <- res$offsets
1012
- df1$sig <- df1$lod >= thr
1013
- df1$cn <- match(df1$chr, chrs)
1014
- pal <- rep(c("#1a6b3a","#6aab87"), ceiling(length(chrs)/2))[seq_along(chrs)]
1015
- df1$ptcol <- ifelse(df1$sig, "#b83232", pal[df1$cn])
1016
- p <- ggplot(df1, aes(x=cum_pos, y=lod, color=ptcol,
1017
- text=paste0("Chr:",chr,"<br>Pos:",round(pos,1),"cM<br>",marker,"<br>LOD:",round(lod,2)))) +
1018
- geom_point(size=ifelse(df1$sig,2.5,1.2), alpha=ifelse(df1$sig,1,.7)) +
1019
- geom_hline(yintercept=thr, linetype="dashed", color="#b83232") +
1020
- scale_color_identity() +
1021
- labs(x="Position (cM)", y="LOD") +
1022
- theme_minimal() + theme(panel.grid.minor=element_blank(), panel.grid.major.x=element_blank())
1023
- mids <- tapply(df1$cum_pos, df1$chr, mean)
1024
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"),
1025
- annotations=lapply(chrs, function(c) list(x=mids[c],y=-0.3,text=c,showarrow=FALSE,font=list(size=8,color="#9a9a94"),xanchor="center")))
1026
- })
1027
-
1028
- output$pl_interval <- renderPlotly({
1029
- req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val()
1030
- sig_sub <- df[df$lod >= thr, ]
1031
- if (!nrow(sig_sub)) return(plotly_empty() %>% layout(title="No significant QTL"))
1032
-
1033
- # FIX: base R peak-per-chr-model aggregation (replaces slice_max)
1034
- pk_list <- lapply(
1035
- split(sig_sub, paste0(sig_sub$model, "__", sig_sub$chr)),
1036
- function(sub) { if (!nrow(sub)) return(NULL); sub[which.max(sub$lod), ] }
1037
- )
1038
- pk <- do.call(rbind, Filter(Negate(is.null), pk_list))
1039
- if (is.null(pk) || nrow(pk) == 0) return(plotly_empty() %>% layout(title="No significant QTL"))
1040
-
1041
- int_df <- do.call(rbind, lapply(seq_len(nrow(pk)), function(i) {
1042
- r <- pk[i, ]; sub <- df[df$model == r$model & df$chr == r$chr, ]; sub <- sub[order(sub$pos), ]
1043
- hl <- r$lod - 1.5
1044
- lft <- min(sub$pos[sub$lod >= hl], na.rm=TRUE)
1045
- rgt <- max(sub$pos[sub$lod >= hl], na.rm=TRUE)
1046
- data.frame(model=r$model, chr=r$chr, peak=r$pos, lod=r$lod, left=lft, right=rgt,
1047
- label=paste0(r$chr,"@",round(r$pos,1)), stringsAsFactors=FALSE)
1048
- }))
1049
- p <- ggplot(int_df, aes(y=label, color=model,
1050
- text=paste0(chr," @ ",round(peak,1),"cM<br>LOD:",round(lod,2),"<br>[",round(left,1),"-",round(right,1),"] cM"))) +
1051
- geom_segment(aes(x=left, xend=right, yend=label), linewidth=3, alpha=.5) +
1052
- geom_point(aes(x=peak), size=4) +
1053
- scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) +
1054
- labs(x="Position (cM)", y="QTL") +
1055
- theme_minimal() + theme(panel.grid.minor=element_blank())
1056
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
1057
- })
1058
-
1059
- output$pl_density <- renderPlotly({
1060
- req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val()
1061
- sig <- df[df$lod >= thr, ]
1062
- if (!nrow(sig)) return(plotly_empty() %>% layout(title="No significant QTL"))
1063
- p <- ggplot(sig, aes(x=pos, fill=chr)) +
1064
- geom_density(alpha=.6) + facet_wrap(~chr, scales="free") +
1065
- scale_fill_viridis_d() + labs(x="Position (cM)", y="Density") +
1066
- theme_minimal() + theme(legend.position="none", panel.grid.minor=element_blank())
1067
- ggplotly(p) %>% layout(font=list(family="sans-serif"))
1068
- })
1069
-
1070
- output$eff_chr_ui <- renderUI({
1071
- req(rv$cross, length(rv$scan_list) > 0)
1072
- selectInput("eff_chr", "Select Chromosome:", choices=chrnames(rv$cross), width="180px")
1073
- })
1074
-
1075
- output$pl_pve <- renderPlotly({
1076
- req(length(rv$sig_qtl) > 0); sd <- sig_df(); req(!is.null(sd), nrow(sd) > 0)
1077
- pv <- sd %>% group_by(chr, model) %>% summarise(mp=max(pve, na.rm=TRUE), .groups="drop")
1078
- p <- ggplot(pv, aes(x=chr, y=mp, fill=model, text=paste0("Chr:",chr,"<br>",model,"<br>Max PVE:",round(mp,1),"%"))) +
1079
- geom_col(position="dodge", alpha=.85) +
1080
- scale_fill_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) +
1081
- labs(x="Chromosome", y="Max PVE (%)", fill="Model") +
1082
- theme_minimal() + theme(panel.grid.minor=element_blank())
1083
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
1084
- })
1085
-
1086
- output$pl_eff <- renderPlotly({
1087
- req(rv$cross, length(rv$scan_list) > 0)
1088
- ch <- if (is.null(input$eff_chr)) chrnames(rv$cross)[1] else input$eff_chr
1089
- sc <- rv$scan_list[[names(rv$scan_list)[1]]]; lc <- ncol(sc)
1090
- scc <- sc[sc$chr == ch, ]; if (!nrow(scc)) return(plotly_empty())
1091
- pm <- find.marker(rv$cross, ch, scc$pos[which.max(scc[, lc])])
1092
- eff <- effectplot(rv$cross, mname1=pm, pheno.col=1, draw=FALSE)
1093
- df <- data.frame(geno=names(eff$Means), mean=as.numeric(eff$Means),
1094
- sd=as.numeric(eff$SDs), n=as.numeric(eff$n))
1095
- df$se <- df$sd / sqrt(df$n)
1096
- p <- ggplot(df, aes(x=geno, y=mean, fill=geno, text=paste0("Geno:",geno,"<br>Mean:",round(mean,3),"<br>SE:",round(se,3)))) +
1097
- geom_col(alpha=.85) +
1098
- geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.25) +
1099
- scale_fill_manual(values=c("#1a6b3a","#c47c1a","#1a4a8a","#b83232")) +
1100
- labs(x="Genotype", y=rv$pheno_name, title=paste("Effects at",pm)) +
1101
- theme_minimal() + theme(legend.position="none", panel.grid.minor=element_blank())
1102
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
1103
- })
1104
-
1105
- output$peak_sel <- renderUI({
1106
- req(length(rv$sig_qtl) > 0); sd <- sig_df(); req(!is.null(sd))
1107
- ch <- paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")")
1108
- selectInput("pk_sel", NULL, choices=ch, width="100%")
1109
- })
1110
-
1111
- output$pl_violin <- renderPlotly({
1112
- req(rv$cross, length(rv$sig_qtl) > 0, !is.null(input$pk_sel))
1113
- sd <- sig_df(); req(!is.null(sd))
1114
- idx <- which(paste0(sd$chr," @ ",round(sd$pos,1),"cM (",sd$model_id,")")==input$pk_sel)[1]
1115
- req(!is.na(idx))
1116
- row <- sd[idx, ]
1117
- mar <- tryCatch(find.marker(rv$cross, row$chr, row$pos), error=function(e) row$marker)
1118
- gt <- pull.geno(rv$cross)[, mar]; phe <- pull.pheno(rv$cross, 1)
1119
- max_g <- max(gt, na.rm=TRUE)
1120
- gl <- if (max_g <= 2) c("1"="AA","2"="AB") else c("1"="AA","2"="AB","3"="BB")
1121
- bdf <- data.frame(geno=factor(gl[as.character(gt)], levels=gl), pheno=phe)
1122
- bdf <- bdf[!is.na(bdf$geno) & !is.na(bdf$pheno), ]
1123
- cols <- c(AA="#1a6b3a", AB="#c47c1a", BB="#1a4a8a")
1124
- p <- ggplot(bdf, aes(x=geno, y=pheno, fill=geno)) +
1125
- geom_violin(alpha=.4, draw_quantiles=c(.25,.5,.75)) +
1126
- geom_jitter(aes(color=geno), width=.15, size=1.5, alpha=.6) +
1127
- scale_fill_manual(values=cols) + scale_color_manual(values=cols) +
1128
- labs(x="Genotype", y=rv$pheno_name, title=paste("Phenotype at",mar)) +
1129
- theme_minimal() + theme(legend.position="none")
1130
- ggplotly(p) %>% layout(font=list(family="sans-serif"))
1131
- })
1132
-
1133
- output$pl_heatmap <- renderPlotly({
1134
- req(length(rv$scan_list) > 1); df <- comb_df()
1135
-
1136
- # FIX: base R top-marker selection (replaces slice_max)
1137
- mk_max <- tapply(df$lod, df$marker, max)
1138
- top_mk <- names(sort(mk_max, decreasing=TRUE)[seq_len(min(60, length(mk_max)))])
1139
-
1140
- hm <- df[df$marker %in% top_mk, c("marker","model","lod")]
1141
- # FIX: base R pivot_wider equivalent
1142
- hm_wide <- reshape(hm, idvar="marker", timevar="model", direction="wide")
1143
- colnames(hm_wide) <- gsub("^lod\\.", "", colnames(hm_wide))
1144
- rn <- hm_wide$marker; hm_wide$marker <- NULL
1145
- hm_wide[is.na(hm_wide)] <- 0
1146
- mat <- as.matrix(hm_wide)
1147
- plot_ly(z=mat, x=colnames(mat), y=rn, type="heatmap", colorscale="Viridis",
1148
- hovertemplate="Model: %{x}<br>Marker: %{y}<br>LOD: %{z:.2f}<extra></extra>") %>%
1149
- layout(font=list(family="sans-serif"), xaxis=list(title="Model"), yaxis=list(title="Marker",tickfont=list(size=8)))
1150
- })
1151
-
1152
- output$pl_common <- renderPlotly({
1153
- req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val()
1154
- sig <- df[df$lod >= thr, ]
1155
- sig_agg <- if (nrow(sig) > 0) {
1156
- do.call(rbind, lapply(split(sig, paste(sig$chr, round(sig$pos))), function(s)
1157
- data.frame(chr=s$chr[1], pos=s$pos[1], nm=length(unique(s$model)), mx=max(s$lod))))
1158
- } else data.frame(chr=character(0), pos=numeric(0), nm=integer(0), mx=numeric(0))
1159
-
1160
- df1 <- df[df$model_id == names(rv$scan_list)[1], ]
1161
- df1$common <- FALSE
1162
- if (nrow(sig_agg) > 0) {
1163
- for (i in seq_len(nrow(df1))) {
1164
- ms <- sig_agg[sig_agg$chr == df1$chr[i] & abs(sig_agg$pos - df1$pos[i]) < 5 & sig_agg$nm >= 2, ]
1165
- if (nrow(ms) > 0) df1$common[i] <- TRUE
1166
- }
1167
- }
1168
- res <- cum_positions(df1); df1 <- res$df; offsets <- res$offsets; chrs <- res$chrs
1169
- p <- ggplot(df1, aes(x=cum_pos, y=lod, color=common, size=common,
1170
- text=paste0("Chr:",chr,"<br>Pos:",round(pos,1),"cM<br>LOD:",round(lod,2),ifelse(common,"<br>COMMON QTL","")))) +
1171
- geom_line(aes(group=chr), color="#d0d0cc", linewidth=.5) +
1172
- geom_point(alpha=.8) +
1173
- geom_hline(yintercept=thr, linetype="dashed", color="#888", linewidth=.5) +
1174
- scale_color_manual(values=c("FALSE"="#1a6b3a","TRUE"="#c47c1a"), labels=c("FALSE"="Single model","TRUE"="Common (>=2)")) +
1175
- scale_size_manual(values=c("FALSE"=1,"TRUE"=3)) +
1176
- labs(x="Genomic Position (cM)", y="LOD", color="QTL") +
1177
- theme_minimal() + theme(panel.grid.minor=element_blank(), panel.grid.major.x=element_blank())
1178
- for (nm in names(offsets)[-1]) p <- p + geom_vline(xintercept=offsets[nm], color="#e0e0dc", linewidth=.3)
1179
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
1180
- })
1181
-
1182
- output$pl_pkcomp <- renderPlotly({
1183
- req(length(rv$scan_list) > 0); df <- comb_df(); thr <- thresh_val()
1184
- pk <- df %>% group_by(chr, model) %>% summarise(mx=max(lod), .groups="drop")
1185
- p <- ggplot(pk, aes(x=chr, y=mx, color=model, group=model, text=paste0("Chr:",chr,"<br>",model,"<br>LOD:",round(mx,2)))) +
1186
- geom_line(linewidth=.8, alpha=.8) + geom_point(size=3) +
1187
- geom_hline(yintercept=thr, linetype="dashed", color="#b83232") +
1188
- scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]), MODEL_LABELS)) +
1189
- labs(x="Chromosome", y="Peak LOD", color="Model") +
1190
- theme_minimal() + theme(panel.grid.minor=element_blank())
1191
- ggplotly(p, tooltip="text") %>% layout(font=list(family="sans-serif"))
1192
- })
1193
-
1194
- # ── CIRCOS ────────────────────────────────────────────────
1195
- circos_render <- function() {
1196
- req(rv$cross, length(rv$scan_list) > 0)
1197
- df <- comb_df(); thr <- thresh_val(); mods <- names(rv$scan_list)
1198
- map <- pull.map(rv$cross); cnms <- names(map)
1199
- clens <- sapply(map, max)
1200
- par(bg="white", mar=c(1,1,3,1))
1201
- circos.clear()
1202
- # FIX: removed canvas.xlim/canvas.ylim and other unsupported params;
1203
- # use only universally supported circos.par settings
1204
- circos.par(
1205
- "track.height" = 0.08,
1206
- "cell.padding" = c(0, 0, 0, 0),
1207
- "gap.after" = rep(2, length(cnms)),
1208
- "start.degree" = 90,
1209
- "clock.wise" = TRUE
1210
- )
1211
- circos.initialize(factors=cnms, xlim=cbind(rep(0, length(cnms)), clens))
1212
- circos.trackPlotRegion(
1213
- ylim=c(0, 1), track.height=0.05, bg.border=NA, bg.col="#f4f4f2",
1214
- panel.fun=function(x, y) {
1215
- chr <- get.cell.meta.data("sector.index")
1216
- circos.text(mean(get.cell.meta.data("xlim")), 0.5, chr,
1217
- facing="clockwise", niceFacing=TRUE, cex=.6, col="#2a2a27", font=2)
1218
- }
1219
- )
1220
- mpal <- c("#1a6b3a","#2d9e58","#c47c1a","#1a4a8a","#b83232",
1221
- "#7b3fa0","#1a8a8a","#8a5a1a","#555555","#e05c00")
1222
- for (mi in seq_along(mods)) {
1223
- m <- mods[mi]
1224
- mc <- mpal[((mi - 1) %% length(mpal)) + 1]
1225
- mclt <- paste0(mc, "44")
1226
- sc <- rv$scan_list[[m]]; lc <- ncol(sc)
1227
- dfm <- data.frame(chr=as.character(sc$chr), pos=sc$pos, lod=sc[, lc], stringsAsFactors=FALSE)
1228
- dfm <- dfm[dfm$chr %in% cnms, ]
1229
- mxl <- max(dfm$lod, na.rm=TRUE); if (mxl < .01) mxl <- 1
1230
- circos.trackPlotRegion(
1231
- ylim=c(0, mxl), track.height=0.07, bg.border="#e8e8e5", bg.col="#fafafa",
1232
- panel.fun=function(x, y) {
1233
- cs <- get.cell.meta.data("sector.index")
1234
- sub <- dfm[dfm$chr == cs, , drop=FALSE]
1235
- if (!nrow(sub)) return()
1236
- sub <- sub[order(sub$pos), ]
1237
- xs <- c(sub$pos[1], sub$pos, sub$pos[nrow(sub)])
1238
- ys <- c(0, sub$lod, 0)
1239
- circos.polygon(xs, ys, col=mclt, border=NA)
1240
- circos.lines(sub$pos, sub$lod, col=mc, lwd=1.2)
1241
- circos.lines(range(sub$pos), c(thr, thr), col="#b83232", lwd=.7, lty=2)
1242
- ss <- sub[sub$lod >= thr, ]
1243
- if (nrow(ss) > 0) {
1244
- pk <- ss[which.max(ss$lod), ]
1245
- circos.points(pk$pos, pk$lod, col="#b83232", pch=19, cex=.9)
1246
- }
1247
- }
1248
- )
1249
- }
1250
- legend("bottomright", legend=MODEL_LABELS[mods], col=mpal[seq_along(mods)],
1251
- lwd=2.5, bty="n", cex=.65, text.col="#2a2a27", title="Models", title.col="#2a2a27")
1252
- title(main=paste("Circos QTL -", rv$pheno_name), cex.main=.95, col.main="#0f0f0d", font.main=2)
1253
- circos.clear()
1254
- }
1255
-
1256
- output$pl_circos <- renderPlot({ circos_render() }, bg="white")
1257
-
1258
- build_qtl_table <- reactive({
1259
- req(length(rv$sig_qtl) > 0); sd <- sig_df(); req(!is.null(sd), nrow(sd) > 0)
1260
- rows <- lapply(seq_len(nrow(sd)), function(i) {
1261
- r <- sd[i, ]; sc <- rv$scan_list[[r$model_id]]; if (is.null(sc)) return(NULL)
1262
- lc <- ncol(sc); sch <- sc[sc$chr == r$chr, ]; hl <- r[, lc] - 1.5
1263
- left <- suppressWarnings(min(sch$pos[sch[, lc] >= hl], na.rm=TRUE))
1264
- right <- suppressWarnings(max(sch$pos[sch[, lc] >= hl], na.rm=TRUE))
1265
- lm <- tryCatch(find.marker(rv$cross, r$chr, left), error=function(e) "?")
1266
- rm <- tryCatch(find.marker(rv$cross, r$chr, right), error=function(e) "?")
1267
- pm <- tryCatch(find.marker(rv$cross, r$chr, r$pos), error=function(e) r$marker)
1268
- data.frame(
1269
- Phenotype=rv$pheno_name, Model=r$model, Chr=r$chr,
1270
- Peak_pos_cM=round(r$pos,2), Peak_Marker=pm, LOD=round(r[,lc],3),
1271
- PVE_pct=paste0(round(r$pve,1),"%"),
1272
- Left_cM=round(left,2), Right_cM=round(right,2),
1273
- Left_Marker=lm, Right_Marker=rm,
1274
- check.names=FALSE, stringsAsFactors=FALSE
1275
- )
1276
- })
1277
- do.call(rbind, Filter(Negate(is.null), rows))
1278
- })
1279
-
1280
- output$tbl_qtl <- renderDT({
1281
- tryCatch({
1282
- df <- build_qtl_table()
1283
- datatable(df, rownames=FALSE, extensions="Buttons",
1284
- options=list(dom="Bfrtip", buttons=c("copy","csv","excel"), pageLength=20, scrollX=TRUE,
1285
- columnDefs=list(list(className="dt-center", targets="_all")))) %>%
1286
- formatStyle("LOD", background=styleColorBar(range(df$LOD, na.rm=TRUE),"#e8f4ed"))
1287
- }, error=function(e) datatable(data.frame(Status="No significant QTL found"), options=list(dom="t")))
1288
- })
1289
-
1290
- output$tbl_full <- renderDT({
1291
- req(length(rv$scan_list) > 0); df <- comb_df()
1292
- df$lod <- round(df$lod,4); df$pos <- round(df$pos,2); df$sig <- df$lod >= thresh_val()
1293
- datatable(df[, c("chr","pos","marker","model","lod","sig")], rownames=FALSE,
1294
- options=list(pageLength=15, scrollX=TRUE,
1295
- columnDefs=list(list(className="dt-center", targets="_all")))) %>%
1296
- formatStyle("sig", target="row",
1297
- backgroundColor=styleEqual(c(TRUE,FALSE), c("#e8f4ed","white"))) %>%
1298
- formatStyle("lod", fontFamily="monospace")
1299
- })
1300
-
1301
- output$dl_csv <- downloadHandler(
1302
- filename=function() paste0("qtl_results_",Sys.Date(),".csv"),
1303
- content=function(f) tryCatch(write.csv(build_qtl_table(),f,row.names=FALSE), error=function(e) write.csv(data.frame(note="No results"),f))
1304
- )
1305
- output$dl_tsv <- downloadHandler(
1306
- filename=function() paste0("qtl_results_",Sys.Date(),".tsv"),
1307
- content=function(f) tryCatch(write.table(build_qtl_table(),f,sep="\t",row.names=FALSE), error=function(e) write.table(data.frame(note="No results"),f,sep="\t"))
1308
- )
1309
- output$dl_rds <- downloadHandler(
1310
- filename=function() paste0("qtl_results_",Sys.Date(),".RData"),
1311
- content=function(f) { scan_list<-rv$scan_list; sig_qtl<-rv$sig_qtl; cross<-rv$cross; save(scan_list,sig_qtl,cross,file=f) }
1312
- )
1313
- output$dl_full <- downloadHandler(
1314
- filename=function() paste0("qtl_full_scan_",Sys.Date(),".csv"),
1315
- content=function(f) if (length(rv$scan_list)>0) write.csv(comb_df(),f,row.names=FALSE) else write.csv(data.frame(note="No scan"),f)
1316
- )
1317
- output$dl_genome <- downloadHandler(
1318
- filename=function() paste0("genome_scan_",Sys.Date(),".png"),
1319
- content=function(f) {
1320
- req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val()
1321
- res <- cum_positions(df); df <- res$df
1322
- p <- ggplot(df,aes(x=cum_pos,y=lod,color=model))+geom_line(linewidth=.7)+
1323
- geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+
1324
- scale_color_manual(values=setNames(unname(MODEL_COLORS[names(MODEL_LABELS)]),MODEL_LABELS))+
1325
- labs(x="Position (cM)",y="LOD",title=paste("Genome Scan -",rv$pheno_name))+theme_minimal(base_size=12)
1326
- png(f,width=1400,height=500,res=120); print(p); dev.off()
1327
- }
1328
- )
1329
- output$dl_manh <- downloadHandler(
1330
- filename=function() paste0("manhattan_",Sys.Date(),".png"),
1331
- content=function(f) {
1332
- req(length(rv$scan_list)>0); df <- comb_df(); thr <- thresh_val()
1333
- df1 <- df[df$model_id==names(rv$scan_list)[1],]; res <- cum_positions(df1); df1 <- res$df
1334
- df1$sig <- df1$lod>=thr
1335
- p <- ggplot(df1,aes(x=cum_pos,y=lod,color=sig))+geom_point(size=1.5,alpha=.8)+
1336
- geom_hline(yintercept=thr,linetype="dashed",color="#b83232")+
1337
- scale_color_manual(values=c("FALSE"="#1a6b3a","TRUE"="#b83232"))+
1338
- labs(x="Position (cM)",y="LOD",title="Manhattan Plot")+theme_minimal(base_size=12)+theme(legend.position="none")
1339
- png(f,width=1400,height=500,res=120); print(p); dev.off()
1340
- }
1341
- )
1342
- output$dl_circos <- downloadHandler(
1343
- filename=function() paste0("circos_",Sys.Date(),".png"),
1344
- content=function(f) { png(f,width=900,height=900,res=120,bg="white"); circos_render(); dev.off() }
1345
- )
1346
  }
1347
 
1348
- shinyApp(ui=ui, server=server)
 
 
 
 
1
+ # prepare_data.R
2
+ # Helper script to prepare CSV files for QTL analysis
3
+
4
+ # Example: Prepare genotype data
5
+ prepare_genotype_file <- function() {
6
+ # Genotype file should have:
7
+ # - First column: Marker names
8
+ # - Subsequent columns: Individual genotypes
9
+ # - Values: A, H, B (for riself cross type)
10
+
11
+ # Example structure:
12
+ # marker, ind1, ind2, ind3, ...
13
+ # marker1, A, B, A, ...
14
+ # marker2, A, A, B, ...
15
+
16
+ # Save as CSV
17
+ # write.csv(genotype_data, "genotypes.csv", row.names = FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Example: Prepare phenotype file
21
+ prepare_phenotype_file <- function() {
22
+ # Phenotype file should have:
23
+ # - First column: Individual IDs (matching genotype file columns)
24
+ # - Subsequent columns: Phenotype measurements
25
+
26
+ # Example structure:
27
+ # id, height, weight
28
+ # ind1, 10.5, 20.3
29
+ # ind2, 11.2, 21.1
30
+
31
+ # Save as CSV
32
+ # write.csv(phenotype_data, "phenotypes.csv", row.names = FALSE)
 
 
33
  }
34
 
35
+ # Example data generation for testing
36
+ create_example_data <- function(n_individuals = 100, n_markers = 50) {
37
+ # Create example genotype data
38
+ markers <- paste0("M", 1:n_markers)
39
+ genotypes <- matrix(sample(c("A", "B"), n_markers * n_individuals,
40
+ replace = TRUE), nrow = n_markers)
41
+ colnames(genotypes) <- paste0("ind", 1:n_individuals)
42
+ genotype_df <- cbind(marker = markers, genotypes)
43
+
44
+ # Create example phenotype data
45
+ phenotype_df <- data.frame(
46
+ id = paste0("ind", 1:n_individuals),
47
+ trait1 = rnorm(n_individuals, mean = 10, sd = 2),
48
+ trait2 = rnorm(n_individuals, mean = 20, sd = 3)
49
+ )
50
+
51
+ # Save to files
52
+ write.csv(genotype_df, "example_genotypes.csv", row.names = FALSE)
53
+ write.csv(phenotype_df, "example_phenotypes.csv", row.names = FALSE)
54
+
55
+ message("Example files created:")
56
+ message("- example_genotypes.csv")
57
+ message("- example_phenotypes.csv")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  }
59
 
60
+ # Run this to create example data
61
+ create_example_data()
62
+ # Run the Shiny app
63
+ shiny::runApp("app.R")