softwareDevelopment commited on
Commit
2c50c36
Β·
verified Β·
1 Parent(s): 0f596b8

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +610 -46
app.R CHANGED
@@ -1,58 +1,622 @@
1
  library(shiny)
2
- library(bslib)
3
- library(dplyr)
4
  library(ggplot2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- df <- readr::read_csv("penguins.csv")
7
- # Find subset of columns that are suitable for scatter plot
8
- df_num <- df |> select(where(is.numeric), -Year)
9
-
10
- ui <- page_sidebar(
11
- theme = bs_theme(bootswatch = "minty"),
12
- title = "Penguins explorer",
13
- sidebar = sidebar(
14
- varSelectInput("xvar", "X variable", df_num, selected = "Bill Length (mm)"),
15
- varSelectInput("yvar", "Y variable", df_num, selected = "Bill Depth (mm)"),
16
- checkboxGroupInput("species", "Filter by species",
17
- choices = unique(df$Species), selected = unique(df$Species)
18
- ),
19
- hr(), # Add a horizontal rule
20
- checkboxInput("by_species", "Show species", TRUE),
21
- checkboxInput("show_margins", "Show marginal plots", TRUE),
22
- checkboxInput("smooth", "Add smoother"),
23
  ),
24
- plotOutput("scatter")
25
- )
26
 
27
- server <- function(input, output, session) {
28
- subsetted <- reactive({
29
- req(input$species)
30
- df |> filter(Species %in% input$species)
31
- })
32
-
33
- output$scatter <- renderPlot(
34
- {
35
- p <- ggplot(subsetted(), aes(!!input$xvar, !!input$yvar)) +
36
- theme_light() +
37
- list(
38
- theme(legend.position = "bottom"),
39
- if (input$by_species) aes(color = Species),
40
- geom_point(),
41
- if (input$smooth) geom_smooth()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  )
 
43
 
44
- if (input$show_margins) {
45
- margin_type <- if (input$by_species) "density" else "histogram"
46
- p <- p |> ggExtra::ggMarginal(
47
- type = margin_type, margins = "both",
48
- size = 8, groupColour = input$by_species, groupFill = input$by_species
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  )
50
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
- p
53
- },
54
- res = 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  )
56
  }
57
 
58
- shinyApp(ui, server)
 
1
  library(shiny)
2
+ library(shinydashboard)
3
+ library(DT)
4
  library(ggplot2)
5
+ library(dplyr)
6
+ library(reshape2)
7
+ library(bslib)
8
+
9
+ # ── Helper functions ──────────────────────────────────────────────────────────
10
+
11
+ load_data <- function(file_path, expected_cols = NULL) {
12
+ data <- read.csv(file_path, stringsAsFactors = FALSE)
13
+ if (!is.null(expected_cols) && !all(expected_cols %in% colnames(data))) {
14
+ stop(paste("Missing required columns. Expected:", paste(expected_cols, collapse = ", ")))
15
+ }
16
+ return(data)
17
+ }
18
+
19
+ process_kmat <- function(kmat_raw) {
20
+ Kmat <- as.matrix(kmat_raw[, -1])
21
+ rownames(Kmat) <- trimws(kmat_raw[, 1])
22
+ colnames(Kmat) <- rownames(Kmat)
23
+ Kmat[Kmat < 0] <- 1e-6
24
+ Kmat <- (Kmat + t(Kmat)) / 2
25
+ diag(Kmat) <- 0
26
+ return(Kmat)
27
+ }
28
+
29
+ relate_thinning <- function(K, criterion, threshold = 0.15, max_per_cluster = 5) {
30
+ K[K < 0] <- 1e-6
31
+ diag(K) <- 0
32
+ K_binary <- K
33
+ K_binary[K_binary > threshold] <- 1
34
+ K_binary[K_binary <= threshold] <- 0
35
+ size_init <- nrow(K_binary)
36
+
37
+ for (i in 1:nrow(K_binary)) {
38
+ index <- colSums(K_binary)
39
+ index <- sort(index, decreasing = TRUE)
40
+ index <- index[which(index > max_per_cluster)]
41
+ if (length(index) == 0) break
42
+ cluster_members <- names(which(K_binary[names(index)[1], ] == 1))
43
+ tmp <- criterion[match(cluster_members, criterion[, 1]), ]
44
+ tmp <- tmp[order(tmp$Criterion, decreasing = TRUE), ]
45
+ if (nrow(tmp) > max_per_cluster) {
46
+ tmp_rm <- match(tmp[-c(1:max_per_cluster), 1], rownames(K_binary))
47
+ tmp_rm <- tmp_rm[!is.na(tmp_rm)]
48
+ if (length(tmp_rm) > 0) K_binary <- K_binary[-tmp_rm, -tmp_rm]
49
+ }
50
+ }
51
+ return(rownames(K_binary))
52
+ }
53
+
54
+ generate_half_diallel <- function(parents, criterion, K) {
55
+ n <- length(parents)
56
+ if (n < 2) stop("Need at least 2 parents")
57
+ total_crosses <- n * (n - 1) / 2
58
+
59
+ P1 <- character(total_crosses)
60
+ P2 <- character(total_crosses)
61
+ P1_Value <- numeric(total_crosses)
62
+ P2_Value <- numeric(total_crosses)
63
+ Mid_Parent_Value <- numeric(total_crosses)
64
+ Kinship <- numeric(total_crosses)
65
+
66
+ idx <- 1
67
+ for (i in 1:(n - 1)) {
68
+ for (j in (i + 1):n) {
69
+ P1[idx] <- parents[i]
70
+ P2[idx] <- parents[j]
71
+ P1_Value[idx] <- criterion$Criterion[criterion$Genotype == parents[i]]
72
+ P2_Value[idx] <- criterion$Criterion[criterion$Genotype == parents[j]]
73
+ Mid_Parent_Value[idx] <- (P1_Value[idx] + P2_Value[idx]) / 2
74
+ Kinship[idx] <- K[parents[i], parents[j]]
75
+ idx <- idx + 1
76
+ }
77
+ }
78
+
79
+ crosses <- data.frame(
80
+ Cross_ID = 1:total_crosses,
81
+ Parent1 = P1,
82
+ Parent2 = P2,
83
+ P1_Criterion_Value = round(P1_Value, 4),
84
+ P2_Criterion_Value = round(P2_Value, 4),
85
+ Predicted_Offspring_Value = round(Mid_Parent_Value, 4),
86
+ Kinship_Coefficient = round(Kinship, 6),
87
+ stringsAsFactors = FALSE
88
+ )
89
+
90
+ crosses$Relatedness_Category <- cut(crosses$Kinship_Coefficient,
91
+ breaks = c(-Inf, 0.05, 0.125, 0.25, Inf),
92
+ labels = c("Unrelated", "Distantly_Related", "Moderately_Related", "Closely_Related")
93
+ )
94
+
95
+ q_breaks <- quantile(crosses$Predicted_Offspring_Value, probs = c(0, 0.25, 0.5, 0.75, 1))
96
+ if (length(unique(q_breaks)) < 5) {
97
+ crosses$Performance_Category <- "Medium"
98
+ } else {
99
+ crosses$Performance_Category <- cut(crosses$Predicted_Offspring_Value,
100
+ breaks = q_breaks,
101
+ labels = c("Low", "Medium", "High", "Very_High"),
102
+ include.lowest = TRUE
103
+ )
104
+ }
105
+
106
+ crosses <- crosses[order(crosses$Predicted_Offspring_Value, decreasing = TRUE), ]
107
+ rownames(crosses) <- NULL
108
+ crosses
109
+ }
110
 
111
+ # ── UI ───────────────────────────────────────────────────────────────────────
112
+
113
+ ui <- fluidPage(
114
+ theme = bs_theme(
115
+ bg = "#0d1117", fg = "#e6edf3",
116
+ primary = "#58a6ff", secondary = "#8b949e",
117
+ base_font = font_google("IBM Plex Sans"),
118
+ heading_font = font_google("IBM Plex Mono"),
119
+ bootswatch = NULL
 
 
 
 
 
 
 
 
120
  ),
 
 
121
 
122
+ tags$head(tags$style(HTML("
123
+ :root {
124
+ --accent: #58a6ff;
125
+ --accent2: #3fb950;
126
+ --accent3: #f78166;
127
+ --surface: #161b22;
128
+ --border: #30363d;
129
+ --muted: #8b949e;
130
+ }
131
+ body { background: #0d1117; color: #e6edf3; font-family: 'IBM Plex Sans', monospace; }
132
+ .app-header {
133
+ background: linear-gradient(135deg, #161b22 0%, #0d1117 100%);
134
+ border-bottom: 1px solid var(--border);
135
+ padding: 24px 32px 20px;
136
+ margin-bottom: 28px;
137
+ }
138
+ .app-title { font-family: 'IBM Plex Mono', monospace; font-size: 1.6rem; font-weight: 700; color: var(--accent); letter-spacing: -0.5px; margin: 0; }
139
+ .app-subtitle { color: var(--muted); font-size: 0.82rem; margin-top: 4px; letter-spacing: 0.5px; }
140
+ .card-panel {
141
+ background: var(--surface);
142
+ border: 1px solid var(--border);
143
+ border-radius: 8px;
144
+ padding: 20px 24px;
145
+ margin-bottom: 20px;
146
+ }
147
+ .card-title { font-family: 'IBM Plex Mono', monospace; font-size: 0.78rem; font-weight: 600; color: var(--muted); letter-spacing: 1.5px; text-transform: uppercase; margin-bottom: 14px; border-bottom: 1px solid var(--border); padding-bottom: 10px; }
148
+ .stat-box { background: #0d1117; border: 1px solid var(--border); border-radius: 6px; padding: 14px 18px; text-align: center; }
149
+ .stat-num { font-family: 'IBM Plex Mono', monospace; font-size: 2rem; font-weight: 700; color: var(--accent); }
150
+ .stat-lab { font-size: 0.72rem; color: var(--muted); text-transform: uppercase; letter-spacing: 1px; margin-top: 2px; }
151
+ .nav-tabs { border-bottom: 1px solid var(--border); }
152
+ .nav-tabs .nav-link { color: var(--muted); border: none; padding: 10px 18px; font-size: 0.84rem; font-family: 'IBM Plex Mono', monospace; }
153
+ .nav-tabs .nav-link.active { background: var(--surface); color: var(--accent); border-bottom: 2px solid var(--accent); border-radius: 0; }
154
+ .nav-tabs .nav-link:hover { color: #e6edf3; }
155
+ .form-control, .selectize-input, .shiny-input-container input {
156
+ background: #0d1117 !important; color: #e6edf3 !important;
157
+ border: 1px solid var(--border) !important; border-radius: 6px !important;
158
+ font-family: 'IBM Plex Mono', monospace !important; font-size: 0.84rem !important;
159
+ }
160
+ .form-label, label { color: var(--muted); font-size: 0.78rem; letter-spacing: 0.5px; text-transform: uppercase; }
161
+ .btn-primary { background: var(--accent); border-color: var(--accent); font-family: 'IBM Plex Mono', monospace; font-size: 0.82rem; letter-spacing: 0.5px; }
162
+ .btn-primary:hover { background: #79c0ff; border-color: #79c0ff; }
163
+ .btn-success { background: var(--accent2); border-color: var(--accent2); font-family: 'IBM Plex Mono', monospace; font-size: 0.82rem; }
164
+ .badge-unrelated { background: #238636; }
165
+ .badge-distant { background: #9e6a03; }
166
+ .badge-moderate { background: #da3633; }
167
+ table.dataTable { background: #0d1117; color: #e6edf3; border-color: var(--border); font-size: 0.82rem; }
168
+ table.dataTable thead { background: var(--surface); color: var(--muted); }
169
+ table.dataTable tbody tr:hover { background: var(--surface); }
170
+ .dataTables_wrapper { color: var(--muted); }
171
+ .dataTables_wrapper .dataTables_filter input,
172
+ .dataTables_wrapper .dataTables_length select { background: #0d1117; color: #e6edf3; border: 1px solid var(--border); border-radius: 4px; }
173
+ .dataTables_wrapper .dataTables_paginate .paginate_button.current,
174
+ .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover { background: var(--accent); border-color: var(--accent); color: white !important; border-radius: 4px; }
175
+ .dataTables_wrapper .dataTables_paginate .paginate_button:hover { background: var(--surface); color: #e6edf3 !important; border-color: var(--border); border-radius: 4px; }
176
+ .step-badge { display: inline-block; background: var(--accent); color: #0d1117; border-radius: 50%; width: 22px; height: 22px; text-align: center; line-height: 22px; font-size: 0.72rem; font-weight: 700; margin-right: 8px; }
177
+ .alert-info-custom { background: rgba(88,166,255,0.08); border: 1px solid rgba(88,166,255,0.3); border-radius: 6px; padding: 12px 16px; color: #79c0ff; font-size: 0.82rem; }
178
+ .alert-success-custom { background: rgba(63,185,80,0.08); border: 1px solid rgba(63,185,80,0.3); border-radius: 6px; padding: 12px 16px; color: var(--accent2); font-size: 0.82rem; }
179
+ .alert-warn-custom { background: rgba(210,153,34,0.1); border: 1px solid rgba(210,153,34,0.3); border-radius: 6px; padding: 12px 16px; color: #d29922; font-size: 0.82rem; }
180
+ .shiny-plot-output { border-radius: 6px; overflow: hidden; }
181
+ hr { border-color: var(--border); }
182
+ .progress { background: var(--border); }
183
+ .progress-bar { background: var(--accent); }
184
+ "))),
185
+
186
+ # Header
187
+ div(class = "app-header",
188
+ div(class = "app-title", "β—ˆ Half-Diallel Cross Optimizer"),
189
+ div(class = "app-subtitle", "GENOMIC SELECTION Β· KINSHIP-AWARE CROSSING Β· BREEDING VALUE PREDICTION")
190
+ ),
191
+
192
+ div(style = "padding: 0 24px;",
193
+ navset_tab(
194
+ # ── TAB 1: Upload & Configure ──
195
+ nav_panel("β‘  Upload & Configure",
196
+ br(),
197
+ fluidRow(
198
+ column(4,
199
+ div(class = "card-panel",
200
+ div(class = "card-title", "Step 1 β€” Load Data"),
201
+ div(class = "alert-info-custom", style = "margin-bottom: 14px;",
202
+ "Upload your criterion CSV (columns: Genotype, Criterion) and kinship matrix CSV."
203
+ ),
204
+ fileInput("criterion_file", "Criterion File (.csv)", accept = ".csv",
205
+ buttonLabel = "Browse", placeholder = "criterion.csv"),
206
+ fileInput("kmat_file", "Kinship Matrix File (.csv)", accept = ".csv",
207
+ buttonLabel = "Browse", placeholder = "kmat.csv"),
208
+ hr(),
209
+ div(class = "card-title", "Step 2 β€” Thinning Parameters"),
210
+ sliderInput("threshold", "Kinship Threshold", min = 0.05, max = 0.5, value = 0.15, step = 0.01),
211
+ sliderInput("max_per_cluster", "Max per Cluster", min = 1, max = 20, value = 5, step = 1),
212
+ hr(),
213
+ actionButton("run_btn", "β–Ά Run Analysis", class = "btn-primary btn-block", width = "100%"),
214
+ br(),
215
+ uiOutput("run_status")
216
+ )
217
+ ),
218
+ column(8,
219
+ div(class = "card-panel",
220
+ div(class = "card-title", "Data Preview & Validation"),
221
+ uiOutput("data_validation"),
222
+ fluidRow(
223
+ column(6, tableOutput("criterion_preview")),
224
+ column(6, uiOutput("kmat_preview"))
225
+ )
226
+ )
227
+ )
228
  )
229
+ ),
230
 
231
+ # ── TAB 2: Summary Dashboard ──
232
+ nav_panel("β‘‘ Summary Dashboard",
233
+ br(),
234
+ uiOutput("summary_stats_ui"),
235
+ br(),
236
+ fluidRow(
237
+ column(6,
238
+ div(class = "card-panel",
239
+ div(class = "card-title", "Predicted Offspring Value Distribution"),
240
+ plotOutput("hist_pov", height = "260px")
241
+ )
242
+ ),
243
+ column(6,
244
+ div(class = "card-panel",
245
+ div(class = "card-title", "Kinship Coefficient Distribution"),
246
+ plotOutput("hist_kinship", height = "260px")
247
+ )
248
+ )
249
+ ),
250
+ fluidRow(
251
+ column(6,
252
+ div(class = "card-panel",
253
+ div(class = "card-title", "Crosses by Relatedness Category"),
254
+ plotOutput("bar_relatedness", height = "260px")
255
+ )
256
+ ),
257
+ column(6,
258
+ div(class = "card-panel",
259
+ div(class = "card-title", "Value vs Kinship Scatter"),
260
+ plotOutput("scatter_vk", height = "260px")
261
+ )
262
+ )
263
  )
264
+ ),
265
+
266
+ # ── TAB 3: All Crosses ──
267
+ nav_panel("β‘’ All Crosses",
268
+ br(),
269
+ div(class = "card-panel",
270
+ div(class = "card-title", "Half-Diallel Cross Table"),
271
+ fluidRow(
272
+ column(3,
273
+ selectInput("filter_relatedness", "Filter Relatedness",
274
+ choices = c("All", "Unrelated", "Distantly_Related", "Moderately_Related", "Closely_Related"),
275
+ selected = "All")
276
+ ),
277
+ column(3,
278
+ selectInput("filter_performance", "Filter Performance",
279
+ choices = c("All", "Low", "Medium", "High", "Very_High"),
280
+ selected = "All")
281
+ ),
282
+ column(3,
283
+ numericInput("filter_kinship_max", "Max Kinship", value = 1, min = 0, max = 1, step = 0.01)
284
+ ),
285
+ column(3, style = "margin-top: 24px;",
286
+ downloadButton("download_all", "⬇ Download CSV", class = "btn-success")
287
+ )
288
+ ),
289
+ DTOutput("crosses_table")
290
+ )
291
+ ),
292
+
293
+ # ── TAB 4: Top Crosses ──
294
+ nav_panel("β‘£ Top Crosses",
295
+ br(),
296
+ fluidRow(
297
+ column(6,
298
+ div(class = "card-panel",
299
+ div(class = "card-title", "Top 50 β€” Low Kinship (K < 0.125)"),
300
+ DTOutput("top_low_kinship"),
301
+ br(),
302
+ downloadButton("dl_low_k", "⬇ Download", class = "btn-success btn-sm")
303
+ )
304
+ ),
305
+ column(6,
306
+ div(class = "card-panel",
307
+ div(class = "card-title", "Top 50 β€” Medium Kinship (0.125 ≀ K < 0.25)"),
308
+ DTOutput("top_med_kinship"),
309
+ br(),
310
+ downloadButton("dl_med_k", "⬇ Download", class = "btn-success btn-sm")
311
+ )
312
+ )
313
+ )
314
+ ),
315
+
316
+ # ── TAB 5: Parent Summary ──
317
+ nav_panel("β‘€ Parent Summary",
318
+ br(),
319
+ fluidRow(
320
+ column(5,
321
+ div(class = "card-panel",
322
+ div(class = "card-title", "Parent Usage & Criterion Values"),
323
+ DTOutput("parent_table"),
324
+ br(),
325
+ downloadButton("dl_parents", "⬇ Download", class = "btn-success btn-sm")
326
+ )
327
+ ),
328
+ column(7,
329
+ div(class = "card-panel",
330
+ div(class = "card-title", "Parent Criterion Values (Ranked)"),
331
+ plotOutput("parent_bar", height = "400px")
332
+ )
333
+ )
334
+ )
335
+ )
336
+ )
337
+ )
338
+ )
339
+
340
+ # ── Server ────────────────────────────────────────────────────────────────────
341
+
342
+ server <- function(input, output, session) {
343
+
344
+ dark_theme <- function() {
345
+ theme(
346
+ plot.background = element_rect(fill = "#161b22", color = NA),
347
+ panel.background = element_rect(fill = "#0d1117", color = NA),
348
+ panel.grid.major = element_line(color = "#21262d", size = 0.4),
349
+ panel.grid.minor = element_blank(),
350
+ axis.text = element_text(color = "#8b949e", size = 9, family = "mono"),
351
+ axis.title = element_text(color = "#8b949e", size = 9, family = "mono"),
352
+ plot.title = element_text(color = "#e6edf3", size = 11, family = "mono", face = "bold"),
353
+ legend.background = element_rect(fill = "#161b22"),
354
+ legend.text = element_text(color = "#8b949e", size = 8),
355
+ legend.title = element_text(color = "#8b949e", size = 8),
356
+ strip.background = element_rect(fill = "#161b22"),
357
+ strip.text = element_text(color = "#8b949e")
358
+ )
359
+ }
360
+
361
+ COLS <- c("Unrelated" = "#3fb950", "Distantly_Related" = "#d29922",
362
+ "Moderately_Related" = "#f78166", "Closely_Related" = "#da3633")
363
+
364
+ # ── Reactive data ──
365
+ criterion_data <- reactive({
366
+ req(input$criterion_file)
367
+ tryCatch(load_data(input$criterion_file$datapath, c("Genotype", "Criterion")),
368
+ error = function(e) { showNotification(e$message, type = "error"); NULL })
369
+ })
370
 
371
+ kmat_data <- reactive({
372
+ req(input$kmat_file)
373
+ tryCatch({
374
+ raw <- load_data(input$kmat_file$datapath)
375
+ process_kmat(raw)
376
+ }, error = function(e) { showNotification(e$message, type = "error"); NULL })
377
+ })
378
+
379
+ # ── Validation UI ──
380
+ output$data_validation <- renderUI({
381
+ crit <- criterion_data()
382
+ kmat <- kmat_data()
383
+ if (is.null(crit) && is.null(kmat)) return(div(class = "alert-info-custom", "Upload files to begin validation."))
384
+
385
+ msgs <- list()
386
+ if (!is.null(crit)) {
387
+ crit$Genotype <- trimws(as.character(crit$Genotype))
388
+ msgs <- c(msgs, list(div(class = "alert-success-custom", paste("βœ“ Criterion loaded:", nrow(crit), "rows,", length(unique(crit$Genotype)), "unique genotypes"))))
389
+ }
390
+ if (!is.null(kmat)) {
391
+ msgs <- c(msgs, list(div(class = "alert-success-custom", paste("βœ“ Kinship matrix loaded:", nrow(kmat), "Γ—", ncol(kmat)))))
392
+ }
393
+ if (!is.null(crit) && !is.null(kmat)) {
394
+ crit$Genotype <- trimws(as.character(crit$Genotype))
395
+ overlap <- sum(crit$Genotype %in% rownames(kmat))
396
+ cls <- if (overlap == 0) "alert-warn-custom" else "alert-success-custom"
397
+ msgs <- c(msgs, list(div(class = cls, paste("Overlap:", overlap, "genotypes match between files"))))
398
+ }
399
+ do.call(tagList, msgs)
400
+ })
401
+
402
+ output$criterion_preview <- renderTable({
403
+ req(criterion_data())
404
+ head(criterion_data(), 8)
405
+ }, striped = TRUE, bordered = TRUE, hover = TRUE)
406
+
407
+ output$kmat_preview <- renderUI({
408
+ req(kmat_data())
409
+ k <- kmat_data()
410
+ div(p(style = "color: #8b949e; font-size: 0.8rem;",
411
+ paste0("Matrix: ", nrow(k), " Γ— ", ncol(k), " | Range: [",
412
+ round(min(k), 4), ", ", round(max(k), 4), "]")))
413
+ })
414
+
415
+ # ── Analysis reactive ──
416
+ analysis_results <- eventReactive(input$run_btn, {
417
+ req(criterion_data(), kmat_data())
418
+ withProgress(message = "Running analysis...", value = 0, {
419
+ crit <- criterion_data()
420
+ crit$Genotype <- trimws(as.character(crit$Genotype))
421
+ kmat <- kmat_data()
422
+
423
+ incProgress(0.1, detail = "Filtering genotypes...")
424
+ crit_filtered <- crit[crit$Genotype %in% rownames(kmat), ]
425
+ validate(need(nrow(crit_filtered) > 0, "No matching genotypes. Check genotype name formats."))
426
+
427
+ incProgress(0.3, detail = "Relatedness thinning...")
428
+ keep <- tryCatch(
429
+ relate_thinning(kmat, crit_filtered, input$threshold, input$max_per_cluster),
430
+ error = function(e) { showNotification(paste("Thinning error:", e$message), type = "error"); NULL }
431
+ )
432
+ req(keep)
433
+
434
+ all_parents <- intersect(keep, rownames(kmat))
435
+ validate(need(length(all_parents) >= 2, "Need at least 2 parents after thinning."))
436
+
437
+ incProgress(0.5, detail = "Generating crosses...")
438
+ crosses <- tryCatch(
439
+ generate_half_diallel(all_parents, crit_filtered, kmat),
440
+ error = function(e) { showNotification(paste("Cross error:", e$message), type = "error"); NULL }
441
+ )
442
+ req(crosses)
443
+
444
+ incProgress(0.85, detail = "Building summaries...")
445
+
446
+ parent_usage <- data.frame(
447
+ Genotype = all_parents,
448
+ Times_Used = sapply(all_parents, function(x) sum(crosses$Parent1 == x | crosses$Parent2 == x)),
449
+ Criterion_Value = sapply(all_parents, function(x) crit_filtered$Criterion[crit_filtered$Genotype == x]),
450
+ stringsAsFactors = FALSE
451
+ )
452
+ parent_usage <- parent_usage[order(parent_usage$Criterion_Value, decreasing = TRUE), ]
453
+
454
+ incProgress(1)
455
+ list(crosses = crosses, parents = all_parents, parent_usage = parent_usage,
456
+ crit_filtered = crit_filtered, n_original = nrow(crit))
457
+ })
458
+ })
459
+
460
+ output$run_status <- renderUI({
461
+ res <- analysis_results()
462
+ if (is.null(res)) return(NULL)
463
+ div(class = "alert-success-custom", style = "margin-top: 10px;",
464
+ paste0("βœ“ Complete: ", nrow(res$crosses), " crosses from ", length(res$parents), " parents"))
465
+ })
466
+
467
+ # ── Summary stats ──
468
+ output$summary_stats_ui <- renderUI({
469
+ req(analysis_results())
470
+ res <- analysis_results()
471
+ cr <- res$crosses
472
+
473
+ make_stat <- function(num, lab) {
474
+ div(class = "stat-box",
475
+ div(class = "stat-num", num),
476
+ div(class = "stat-lab", lab)
477
+ )
478
+ }
479
+
480
+ div(class = "card-panel",
481
+ div(class = "card-title", "Analysis Summary"),
482
+ fluidRow(
483
+ column(2, make_stat(nrow(cr), "Total Crosses")),
484
+ column(2, make_stat(length(res$parents), "Parents")),
485
+ column(2, make_stat(round(mean(cr$Predicted_Offspring_Value), 3), "Mean POV")),
486
+ column(2, make_stat(round(max(cr$Predicted_Offspring_Value), 3), "Max POV")),
487
+ column(2, make_stat(sum(cr$Kinship_Coefficient < 0.125), "K < 0.125")),
488
+ column(2, make_stat(round(mean(cr$Kinship_Coefficient), 4), "Mean Kinship"))
489
+ )
490
+ )
491
+ })
492
+
493
+ # ── Plots ──
494
+ output$hist_pov <- renderPlot({
495
+ req(analysis_results())
496
+ cr <- analysis_results()$crosses
497
+ ggplot(cr, aes(x = Predicted_Offspring_Value)) +
498
+ geom_histogram(bins = 40, fill = "#58a6ff", alpha = 0.85, color = "#0d1117") +
499
+ geom_vline(xintercept = mean(cr$Predicted_Offspring_Value), color = "#3fb950", linetype = "dashed", size = 0.8) +
500
+ labs(x = "Predicted Offspring Value", y = "Count") +
501
+ dark_theme()
502
+ }, bg = "#161b22")
503
+
504
+ output$hist_kinship <- renderPlot({
505
+ req(analysis_results())
506
+ cr <- analysis_results()$crosses
507
+ ggplot(cr, aes(x = Kinship_Coefficient)) +
508
+ geom_histogram(bins = 40, fill = "#f78166", alpha = 0.85, color = "#0d1117") +
509
+ geom_vline(xintercept = 0.125, color = "#d29922", linetype = "dashed", size = 0.8) +
510
+ geom_vline(xintercept = 0.25, color = "#da3633", linetype = "dashed", size = 0.8) +
511
+ labs(x = "Kinship Coefficient (K)", y = "Count") +
512
+ dark_theme()
513
+ }, bg = "#161b22")
514
+
515
+ output$bar_relatedness <- renderPlot({
516
+ req(analysis_results())
517
+ cr <- analysis_results()$crosses
518
+ cnt <- as.data.frame(table(cr$Relatedness_Category))
519
+ colnames(cnt) <- c("Category", "Count")
520
+ ggplot(cnt, aes(x = reorder(Category, -Count), y = Count, fill = Category)) +
521
+ geom_col(alpha = 0.9, width = 0.6) +
522
+ scale_fill_manual(values = COLS, guide = "none") +
523
+ labs(x = "", y = "Number of Crosses") +
524
+ dark_theme() +
525
+ theme(axis.text.x = element_text(angle = 20, hjust = 1))
526
+ }, bg = "#161b22")
527
+
528
+ output$scatter_vk <- renderPlot({
529
+ req(analysis_results())
530
+ cr <- analysis_results()$crosses
531
+ ggplot(cr, aes(x = Kinship_Coefficient, y = Predicted_Offspring_Value, color = Relatedness_Category)) +
532
+ geom_point(alpha = 0.35, size = 0.8) +
533
+ geom_vline(xintercept = 0.125, color = "#d29922", linetype = "dashed", size = 0.6, alpha = 0.7) +
534
+ scale_color_manual(values = COLS, name = "Relatedness") +
535
+ labs(x = "Kinship (K)", y = "Predicted Offspring Value") +
536
+ dark_theme() +
537
+ theme(legend.position = "bottom")
538
+ }, bg = "#161b22")
539
+
540
+ output$parent_bar <- renderPlot({
541
+ req(analysis_results())
542
+ pu <- analysis_results()$parent_usage
543
+ pu$Genotype <- factor(pu$Genotype, levels = pu$Genotype[order(pu$Criterion_Value)])
544
+ ggplot(pu, aes(x = Criterion_Value, y = Genotype)) +
545
+ geom_col(fill = "#58a6ff", alpha = 0.8, width = 0.7) +
546
+ labs(x = "Criterion Value", y = "") +
547
+ dark_theme() +
548
+ theme(axis.text.y = element_text(size = 7))
549
+ }, bg = "#161b22")
550
+
551
+ # ── Tables ──
552
+ dt_opts <- function(dom = "lfrtip") {
553
+ list(pageLength = 15, dom = dom,
554
+ initComplete = JS("function(settings, json) {
555
+ $(this.api().table().header()).css({'background-color': '#161b22', 'color': '#8b949e'});
556
+ }"))
557
+ }
558
+
559
+ filtered_crosses <- reactive({
560
+ req(analysis_results())
561
+ cr <- analysis_results()$crosses
562
+ if (input$filter_relatedness != "All") cr <- cr[cr$Relatedness_Category == input$filter_relatedness, ]
563
+ if (input$filter_performance != "All") cr <- cr[cr$Performance_Category == input$filter_performance, ]
564
+ cr <- cr[cr$Kinship_Coefficient <= input$filter_kinship_max, ]
565
+ cr
566
+ })
567
+
568
+ output$crosses_table <- renderDT({
569
+ req(filtered_crosses())
570
+ datatable(filtered_crosses(), options = dt_opts(), rownames = FALSE,
571
+ selection = "none") %>%
572
+ formatRound(c("P1_Criterion_Value", "P2_Criterion_Value", "Predicted_Offspring_Value"), 4) %>%
573
+ formatRound("Kinship_Coefficient", 6)
574
+ })
575
+
576
+ output$top_low_kinship <- renderDT({
577
+ req(analysis_results())
578
+ d <- analysis_results()$crosses %>% filter(Kinship_Coefficient < 0.125) %>% head(50) %>%
579
+ select(Parent1, Parent2, Predicted_Offspring_Value, Kinship_Coefficient, Relatedness_Category)
580
+ datatable(d, options = dt_opts("tp"), rownames = FALSE) %>%
581
+ formatRound(c("Predicted_Offspring_Value", "Kinship_Coefficient"), 4)
582
+ })
583
+
584
+ output$top_med_kinship <- renderDT({
585
+ req(analysis_results())
586
+ d <- analysis_results()$crosses %>%
587
+ filter(Kinship_Coefficient >= 0.125, Kinship_Coefficient < 0.25) %>% head(50) %>%
588
+ select(Parent1, Parent2, Predicted_Offspring_Value, Kinship_Coefficient, Relatedness_Category)
589
+ datatable(d, options = dt_opts("tp"), rownames = FALSE) %>%
590
+ formatRound(c("Predicted_Offspring_Value", "Kinship_Coefficient"), 4)
591
+ })
592
+
593
+ output$parent_table <- renderDT({
594
+ req(analysis_results())
595
+ datatable(analysis_results()$parent_usage, options = dt_opts("tp"), rownames = FALSE) %>%
596
+ formatRound("Criterion_Value", 4)
597
+ })
598
+
599
+ # ── Downloads ──
600
+ output$download_all <- downloadHandler(
601
+ filename = function() paste0("Half_Diallel_Crosses_", Sys.Date(), ".csv"),
602
+ content = function(file) write.csv(filtered_crosses(), file, row.names = FALSE)
603
+ )
604
+ output$dl_low_k <- downloadHandler(
605
+ filename = function() paste0("Top50_Low_Kinship_", Sys.Date(), ".csv"),
606
+ content = function(file) write.csv(
607
+ analysis_results()$crosses %>% filter(Kinship_Coefficient < 0.125) %>% head(50),
608
+ file, row.names = FALSE)
609
+ )
610
+ output$dl_med_k <- downloadHandler(
611
+ filename = function() paste0("Top50_Med_Kinship_", Sys.Date(), ".csv"),
612
+ content = function(file) write.csv(
613
+ analysis_results()$crosses %>% filter(Kinship_Coefficient >= 0.125, Kinship_Coefficient < 0.25) %>% head(50),
614
+ file, row.names = FALSE)
615
+ )
616
+ output$dl_parents <- downloadHandler(
617
+ filename = function() paste0("Parent_Usage_", Sys.Date(), ".csv"),
618
+ content = function(file) write.csv(analysis_results()$parent_usage, file, row.names = FALSE)
619
  )
620
  }
621
 
622
+ shinyApp(ui, server)