softwareDevelopment commited on
Commit
05218a7
Β·
verified Β·
1 Parent(s): 3b8cb6e

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +874 -638
app.R CHANGED
@@ -7,722 +7,958 @@ library(dplyr)
7
  library(RColorBrewer)
8
  library(ggrepel)
9
 
10
- # UI definition
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  ui <- fluidPage(
12
- tags$head(
13
- tags$style(HTML("
14
- body { background-color: #ffffff; color: #333333; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
15
- .navbar { background-color: #1E3A8A !important; border-bottom: 2px solid #1E40AF; }
16
- .navbar-brand { color: #ffffff !important; font-weight: bold; }
17
- .nav-tabs { background-color: #1E3A8A; border-bottom: 2px solid #1E40AF; }
18
- .nav-tabs > li > a { color: #cccccc !important; background-color: #1E3A8A; border: 1px solid #1E40AF; margin-right: 5px; }
19
- .nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus { color: #ffffff !important; background-color: #1E40AF; border: 1px solid #1E40AF; font-weight: bold; }
20
- .nav-tabs > li > a:hover { background-color: #2563EB; color: #ffffff !important; }
21
- .well { background-color: #EFF6FF; border: 1px solid #BFDBFE; color: #333333; }
22
- .form-control { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
23
- .form-control:focus { background-color: #FFFFFF; color: #333333; border-color: #3B82F6; box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25); }
24
- .btn { border: 1px solid; }
25
- .btn-default { background-color: #3B82F6; color: #ffffff; border-color: #2563EB; }
26
- .btn-default:hover { background-color: #2563EB; color: #ffffff; border-color: #1D4ED8; }
27
- .btn-primary { background-color: #1D4ED8; color: #ffffff; border-color: #1E40AF; }
28
- .btn-primary:hover { background-color: #1E40AF; color: #ffffff; border-color: #1E3A8A; }
29
- .btn-success { background-color: #059669; color: #ffffff; border-color: #047857; }
30
- .btn-success:hover { background-color: #047857; color: #ffffff; border-color: #065F46; }
31
- .btn-info { background-color: #0891B2; color: #ffffff; border-color: #0E7490; }
32
- .btn-info:hover { background-color: #0E7490; color: #ffffff; border-color: #155E75; }
33
- .irs-bar, .irs-bar-edge { background: #3B82F6; border: 1px solid #2563EB; }
34
- .irs-single, .irs-from, .irs-to { background: #2563EB; color: #ffffff; }
35
- .shiny-input-container { color: #333333; }
36
- .help-block { color: #666666; }
37
- .dataTables_wrapper { color: #333333; }
38
- table.dataTable { border: 1px solid #BFDBFE; }
39
- .dataTables_filter input { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
40
- .selectize-input { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
41
- .selectize-dropdown { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
42
- .selectize-dropdown .active { background-color: #DBEAFE; color: #333333; }
43
- .footer { position: fixed; bottom: 0; width: 100%; background-color: #1E3A8A; color: #cccccc; text-align: center; padding: 10px; border-top: 1px solid #1E40AF; }
44
- .tab-content { color: #666666; }
45
- .tab-content h3, .tab-content h4 { color: #1E3A8A; }
46
- .tab-content ul, .tab-content li, .tab-content p { color: #666666; }
47
- "))
48
- ),
49
-
50
- navbarPage(
51
- "Linkage Map Creator",
52
- id = "nav",
53
- tabPanel("Data Upload", icon = icon("upload"), sidebarLayout(
54
- sidebarPanel(width = 4, wellPanel(
55
- h3("Upload Data", icon("file-import")),
56
- fileInput("file", "Choose Excel File", accept = c(".xlsx", ".xls"), buttonLabel = "Browse...", placeholder = "No file selected"),
57
- selectInput("population_type", "Population Type:", choices = c("RIL" = "RIL", "F2" = "F2"), selected = "RIL"),
58
- helpText("Note: File must contain 'Marker' and 'Chromosome' columns with genotype data in subsequent columns.")
59
- )),
60
- mainPanel(width = 8, wellPanel(
61
- h3("Data Preview"),
62
- div(style = "overflow-x: auto;", dataTableOutput("preview_table"))
63
- ))
64
- )),
65
- tabPanel("Parameters", icon = icon("sliders-h"), sidebarLayout(
66
- sidebarPanel(width = 4, wellPanel(
67
- h3("Analysis Parameters", icon("cog")),
68
- sliderInput("missing_threshold", "Missing Data Threshold:", min = 0, max = 1, value = 0.1, step = 0.01),
69
- sliderInput("recombination_threshold", "Recombination Threshold:", min = 0, max = 1, value = 0.5, step = 0.01),
70
- sliderInput("chi_square_threshold", "Chi-Square Threshold:", min = 0, max = 0.2, value = 0.05, step = 0.01),
71
- sliderInput("cluster_threshold", "Cluster Threshold:", min = 10, max = 100, value = 40, step = 5),
72
- h4("Map Scaling Options", icon("expand")),
73
- numericInput("max_total_cm", "Maximum Total Map Length (cM):", min = 100, max = 5000, value = 1500, step = 100),
74
- selectInput("scaling_method", "Scaling Method:", choices = c("Proportional" = "proportional", "Uniform" = "uniform"), selected = "proportional"),
75
- helpText("Note: First marker of each chromosome will remain at 0 cM."),
76
- actionButton("run_analysis", "Run Analysis", class = "btn-primary btn-block", icon = icon("play"))
77
- )),
78
- mainPanel(width = 8, wellPanel(
79
- h3("Parameter Descriptions"),
80
- tags$ul(
81
- tags$li(tags$b("Missing Data Threshold:"), "Maximum allowed fraction of missing data per marker"),
82
- tags$li(tags$b("Recombination Threshold:"), "Maximum recombination fraction for linkage"),
83
- tags$li(tags$b("Chi-Square Threshold:"), "P-value threshold for segregation distortion"),
84
- tags$li(tags$b("Cluster Threshold:"), "Distance threshold for marker grouping"),
85
- tags$li(tags$b("Maximum Total Map Length:"), "Sets the upper limit for the sum of all chromosome lengths"),
86
- tags$li(tags$b("Proportional Scaling:"), "Each chromosome is scaled proportionally to its original length"),
87
- tags$li(tags$b("Uniform Scaling:"), "All chromosomes are scaled by the same factor")
88
- ),
89
- br(),
90
- h4("Scaling Summary"),
91
- verbatimTextOutput("scaling_summary"),
92
- br(),
93
- h4("Before Scaling"),
94
- verbatimTextOutput("before_scaling_stats"),
95
- br(),
96
- h4("After Scaling"),
97
- verbatimTextOutput("after_scaling_stats")
98
- ))
99
- )),
100
- tabPanel("Results", icon = icon("table"), fluidRow(
101
- column(12, wellPanel(
102
- h3("Analysis Results", icon("chart-bar")),
103
- conditionalPanel(
104
- condition = "output.analysis_run",
105
- downloadButton("download_results", "Download Excel Results", class = "btn-success"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  br(), br(),
107
  h4("Linkage Map Data"),
108
- div(style = "overflow-x: auto;", dataTableOutput("result_table")),
109
  h4("Summary Statistics"),
110
  verbatimTextOutput("summary_stats")
111
  ),
112
- conditionalPanel(
113
- condition = "!output.analysis_run",
114
- p("Please upload data and run analysis to see results.", style = "color: #888; font-style: italic; text-align: center; padding: 40px;")
115
  )
116
- ))
117
- )),
118
- tabPanel("Plot Customization", icon = icon("palette"), sidebarLayout(
119
- sidebarPanel(width = 4, wellPanel(
120
- h3("Plot Customization", icon("paint-brush")),
121
- selectInput("color_palette", "Color Palette:",
122
- choices = c("Set1", "Set2", "Set3", "Paired", "Dark2", "Accent",
123
- "Blues", "Reds", "Greens", "Purples", "Oranges",
124
- "Greys", "Spectral", "RdBu"),
125
- selected = "Set2"),
126
- checkboxInput("show_labels", "Show Marker Labels", value = TRUE),
127
- sliderInput("marker_label_size", "Marker Label Size:", min = 2, max = 10, value = 3, step = 0.5),
128
- sliderInput("plot_width", "Plot Width (px):", min = 600, max = 1600, value = 1200, step = 50),
129
- sliderInput("plot_height", "Plot Height (px):", min = 400, max = 1200, value = 600, step = 50),
130
- helpText("Select a color palette and adjust plot settings. Preview updates in the Visualization tab.")
131
- )),
132
- mainPanel(width = 8, wellPanel(
133
- h3("Color Palette Preview"),
134
- p("The selected palette will be applied to chromosomes in the visualization. Below is a preview of the colors:"),
135
- plotOutput("palette_preview", height = "200px"),
136
- h4("Available Palettes"),
137
- tags$ul(
138
- tags$li(tags$b("Set1, Set2, Set3, Paired, Dark2, Accent:"), "Qualitative palettes for distinct categories"),
139
- tags$li(tags$b("Blues, Reds, Greens, Purples, Oranges, Greys:"), "Sequential palettes for gradients"),
140
- tags$li(tags$b("Spectral, RdBu:"), "Diverging palettes for contrasting values"),
141
- tags$li(tags$b("Viridis, Magma, Inferno, Plasma:"), "Perceptually uniform sequential palettes")
142
- )
143
- ))
144
- )),
145
- tabPanel("Visualization", icon = icon("chart-bar"), fluidRow(
146
- column(12, wellPanel(
147
- h3("Chromosome Map Visualization", icon("image")),
148
- conditionalPanel(
149
- condition = "output.analysis_run",
150
- selectInput("chromosome_select", "Select Chromosomes:", choices = NULL, multiple = TRUE),
151
- downloadButton("download_plot", "Download Plot as PNG", class = "btn-success"),
 
152
  br(), br(),
153
  plotOutput("chromosome_plot", height = "auto")
154
  ),
155
- conditionalPanel(
156
- condition = "!output.analysis_run",
157
- p("Please upload data and run analysis to see visualizations.", style = "color: #888; font-style: italic; text-align: center; padding: 40px;")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  )
159
- ))
160
- )),
161
- tabPanel("Help", icon = icon("question-circle"), wellPanel(
162
- h3("Application Guide", icon("info-circle")),
163
- h4("Input File Format:"),
164
- p("Excel file with the following structure:"),
165
- tags$ul(
166
- tags$li("'Marker' column: Marker names"),
167
- tags$li("'Chromosome' column: Chromosome assignments"),
168
- tags$li("Subsequent columns: Genotype data for each individual (use 'a', 'b', 'ab', or '-' for missing)")
169
- ),
170
- h4("Parameters Explanation:"),
171
- tags$ul(
172
- tags$li(tags$b("Missing Data Threshold:"), "Maximum allowed fraction of missing data per marker"),
173
- tags$li(tags$b("Recombination Threshold:"), "Maximum recombination fraction for linkage"),
174
- tags$li(tags$b("Chi-Square Threshold:"), "P-value threshold for segregation distortion test"),
175
- tags$li(tags$b("Cluster Threshold:"), "Distance threshold for marker grouping"),
176
- tags$li(tags$b("Maximum Total Map Length:"), "Sets the upper limit for the sum of all chromosome lengths"),
177
- tags$li(tags$b("Proportional Scaling:"), "Each chromosome is scaled proportionally to its original length"),
178
- tags$li(tags$b("Uniform Scaling:"), "All chromosomes are scaled by the same factor")
179
- ),
180
- h4("Population Types:"),
181
- tags$ul(
182
- tags$li(tags$b("RIL:"), "Recombinant Inbred Lines"),
183
- tags$li(tags$b("F2:"), "Second filial generation")
184
- ),
185
- h4("Output:"),
186
- p("The application generates:"),
187
- tags$ul(
188
- tags$li("Excel file with three sheets: Original Data, Recombination Fractions, and Linkage Map"),
189
- tags$li("Interactive chromosome visualization with customizable appearance"),
190
- tags$li("High-resolution PNG export for publications and presentations")
191
  )
192
- ))
193
  ),
194
- div(class = "footer", "Linkage Map Creator v2.0 | Created with Shiny | Β© 2023 Bioinformatics Tool")
 
 
195
  )
196
 
197
- # Server logic
 
 
 
198
  server <- function(input, output, session) {
199
- uploaded_data <- reactiveVal(NULL)
200
- analysis_results <- reactiveVal(NULL)
 
201
  pre_scaling_stats <- reactiveVal(NULL)
202
-
 
203
  observeEvent(input$file, {
204
  req(input$file)
205
  tryCatch({
206
  df <- read.xlsx(input$file$datapath, sheet = 1)
207
- required_columns <- c('Marker', 'Chromosome')
208
- if (!all(required_columns %in% colnames(df))) {
209
- stop("Required columns ('Marker' and 'Chromosome') not found in the uploaded file.")
210
- }
211
- if (ncol(df) < 3 || nrow(df) == 0) {
212
- stop("Uploaded file contains no valid genotype data.")
213
- }
214
- genotype_data <- df[, 3:ncol(df)]
215
- if (all(genotype_data == '-', na.rm = TRUE)) {
216
- stop("Uploaded file contains no valid genotype data (all missing).")
217
- }
218
  uploaded_data(df)
219
  showNotification("File uploaded successfully!", type = "message")
220
  }, error = function(e) {
221
- showNotification(paste("Error:", e$message), type = "error")
222
  })
223
  })
224
-
225
  output$preview_table <- renderDataTable({
226
  req(uploaded_data())
227
- datatable(head(uploaded_data(), 10), options = list(scrollX = TRUE, dom = 't', pageLength = 10), rownames = FALSE)
 
 
228
  })
229
-
230
- calculate_recombination <- function(population_type, genotype1, genotype2) {
231
- valid_pairs <- data.frame(g1 = genotype1, g2 = genotype2)
232
- valid_pairs <- valid_pairs[!(genotype1 == '-' | genotype2 == '-'), ]
233
- if (nrow(valid_pairs) == 0) {
234
- return(NA)
235
- }
236
- recombination_events <- sum(valid_pairs$g1 != valid_pairs$g2)
237
- if (population_type == 'RIL') {
238
- recombination_fraction <- recombination_events / nrow(valid_pairs)
239
- rf_ril <- 1 / (2 * (1 + 2 * recombination_fraction))
240
- return(rf_ril)
241
- } else if (population_type == 'F2') {
242
- recombination_fraction_F2 <- recombination_events / nrow(valid_pairs)
243
- return(recombination_fraction_F2)
244
- } else {
245
- stop("Invalid population type. Use 'RIL' or 'F2'.")
246
- }
247
- }
248
-
249
- calculate_cM_kosambi <- function(recombination_fraction) {
250
- if (is.na(recombination_fraction)) return(NA)
251
- if (recombination_fraction >= 0.5) return(50)
252
- if (recombination_fraction <= 0) return(0)
253
- return(25 * log((1 + 2 * recombination_fraction) / (1 - 2 * recombination_fraction)))
254
- }
255
-
256
- correct_errors_and_impute_missing <- function(df) {
257
- df[df == '-'] <- NA
258
- if (ncol(df) > 2) {
259
- na_fractions <- colMeans(is.na(df[, 3:ncol(df)]))
260
- valid_individuals <- na_fractions < 1
261
- df <- df[, c(TRUE, TRUE, valid_individuals)]
262
- }
263
- if (ncol(df) > 2) {
264
- df[, 3:ncol(df)] <- lapply(df[, 3:ncol(df)], function(x) {
265
- if (all(is.na(x))) {
266
- return(x)
267
- }
268
- mode_val <- names(which.max(table(x[!is.na(x)])))
269
- if (length(mode_val) == 0 || is.null(mode_val)) {
270
- mode_val <- 'a'
271
- }
272
- x[is.na(x)] <- mode_val
273
- return(x)
274
- })
275
- }
276
- return(df)
277
- }
278
-
279
- quality_control <- function(df, missing_threshold = 0.1) {
280
- if (ncol(df) < 3 || nrow(df) == 0) {
281
- return(df[0, ])
282
- }
283
- missing_data_fraction <- rowMeans(is.na(df[, 3:ncol(df)]))
284
- missing_data_fraction[is.na(missing_data_fraction)] <- 1
285
- return(df[missing_data_fraction <= missing_threshold, ])
286
- }
287
-
288
- perform_chi_square_test <- function(genotype_data, population_type, chi_square_threshold = 0.05) {
289
- if (nrow(genotype_data) == 0 || ncol(genotype_data) == 0) {
290
- return(logical(0))
291
- }
292
- if (population_type == 'RIL') expected_ratio <- c(0.5, 0.5)
293
- else if (population_type == 'F2') expected_ratio <- c(0.25, 0.5, 0.25)
294
- else stop("Invalid population type. Use 'RIL' or 'F2'.")
295
- chi_square_results <- apply(genotype_data, 1, function(marker) {
296
- observed <- table(factor(marker, levels = c('a', 'b', 'ab')))
297
- if (length(observed) != length(expected_ratio)) return(1)
298
- expected <- expected_ratio * sum(observed)
299
- chi_square_stat <- sum((observed - expected)^2 / expected)
300
- p_value <- pchisq(chi_square_stat, df = length(observed) - 1, lower.tail = FALSE)
301
- return(p_value)
302
- })
303
- non_distorted_markers <- chi_square_results > chi_square_threshold
304
- return(non_distorted_markers)
305
- }
306
-
307
- group_and_order_markers <- function(map_distance_df, threshold = 40) {
308
- markers <- unique(c(map_distance_df$Marker1, map_distance_df$Marker2))
309
- if (nrow(map_distance_df) == 0 || length(markers) == 0) {
310
- return(data.frame(Marker = character(0), Group = integer(0), Order = integer(0)))
311
- }
312
- if (length(markers) <= 1) return(data.frame(Marker = markers, Group = 1, Order = seq_along(markers)))
313
- distance_matrix <- matrix(Inf, nrow = length(markers), ncol = length(markers))
314
- rownames(distance_matrix) <- markers
315
- colnames(distance_matrix) <- markers
316
- for (i in 1:nrow(map_distance_df)) {
317
- marker1 <- as.character(map_distance_df[i, 'Marker1'])
318
- marker2 <- as.character(map_distance_df[i, 'Marker2'])
319
- distance <- map_distance_df[i, 'MapDistance_cM']
320
- idx1 <- which(markers == marker1)
321
- idx2 <- which(markers == marker2)
322
- if (length(idx1) > 0 && length(idx2) > 0) {
323
- distance_matrix[idx1, idx2] <- distance
324
- distance_matrix[idx2, idx1] <- distance
325
- }
326
- }
327
- diag(distance_matrix) <- 0
328
- max_finite <- max(distance_matrix[is.finite(distance_matrix)])
329
- if (!is.finite(max_finite)) max_finite <- 100
330
- distance_matrix[is.infinite(distance_matrix)] <- max_finite * 1.5
331
- dist_obj <- as.dist(distance_matrix)
332
- tryCatch({
333
- clustering <- hclust(dist_obj, method = 'average')
334
- if (any(diff(clustering$height) < 0)) clustering$height <- sort(clustering$height)
335
- labels <- cutree(clustering, h = threshold)
336
- grouped_markers <- data.frame(Marker = markers, Group = labels)
337
- ordered_markers <- markers[clustering$order]
338
- grouped_markers$Order <- match(grouped_markers$Marker, ordered_markers)
339
- return(grouped_markers)
340
- }, error = function(e) {
341
- warning("Hierarchical clustering failed: ", e$message)
342
- return(data.frame(Marker = markers, Group = seq_along(markers), Order = seq_along(markers)))
343
- })
344
- }
345
-
346
- scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
347
- positioned_markers <- linkage_map[!is.na(linkage_map$Position), ]
348
- if (nrow(positioned_markers) == 0) {
349
- return(list(scaled_map = linkage_map, chrom_lengths_before = data.frame(), chrom_lengths_after = data.frame()))
350
- }
351
- chrom_lengths_before <- positioned_markers %>% group_by(Chromosome) %>% summarise(Original_Length = max(Position, na.rm = TRUE), .groups = 'drop')
352
- total_current_length <- sum(chrom_lengths_before$Original_Length, na.rm = TRUE)
353
- scaled_map <- linkage_map
354
- if (total_current_length <= max_total_cm || total_current_length == 0) {
355
- return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_before))
356
- }
357
- if (method == "proportional") {
358
- scaling_factor <- max_total_cm / total_current_length
359
- chrom_lengths_before$Scaling_Factor <- scaling_factor
360
- } else if (method == "uniform") {
361
- n_chromosomes <- nrow(chrom_lengths_before)
362
- if (n_chromosomes == 0) {
363
- return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_before))
364
- }
365
- target_per_chromosome <- max_total_cm / n_chromosomes
366
- chrom_lengths_before$Scaling_Factor <- ifelse(chrom_lengths_before$Original_Length > 0, target_per_chromosome / chrom_lengths_before$Original_Length, 1)
367
- }
368
- for (chrom in chrom_lengths_before$Chromosome) {
369
- scaling_factor <- chrom_lengths_before$Scaling_Factor[chrom_lengths_before$Chromosome == chrom]
370
- if (is.na(scaling_factor) || !is.finite(scaling_factor)) next
371
- chrom_indices <- which(scaled_map$Chromosome == chrom & !is.na(scaled_map$Position))
372
- if (length(chrom_indices) > 0) {
373
- min_pos <- min(scaled_map$Position[chrom_indices], na.rm = TRUE)
374
- scaled_map$Position[chrom_indices] <- (scaled_map$Position[chrom_indices] - min_pos) * scaling_factor
375
- }
376
- }
377
- chrom_lengths_after <- scaled_map %>% filter(!is.na(Position)) %>% group_by(Chromosome) %>% summarise(Original_Length = max(Position, na.rm = TRUE), .groups = 'drop')
378
- return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_after))
379
- }
380
-
381
- create_linkage_map <- function(df, population_type, missing_threshold = 0.1, recombination_threshold = 0.5, chi_square_threshold = 0.05, threshold = 40, max_total_cm = 1500, scaling_method = "proportional") {
382
- df <- correct_errors_and_impute_missing(df)
383
- df <- quality_control(df, missing_threshold)
384
- if (nrow(df) == 0 || ncol(df) < 3) {
385
- return(list(original_data = df, recombination_data = data.frame(), linkage_map = data.frame(Marker = character(0), Chromosome = character(0), Position = numeric(0)), chrom_lengths_before = data.frame(), chrom_lengths_after = data.frame()))
386
- }
387
- genotype_data <- df[, 3:ncol(df)]
388
- non_distorted_markers <- perform_chi_square_test(genotype_data, population_type, chi_square_threshold)
389
- df <- df[non_distorted_markers, ]
390
- markers <- unique(df$Marker)
391
- if (length(markers) == 0) return(list(original_data = df, recombination_data = data.frame(), linkage_map = data.frame(Marker = df$Marker, Chromosome = df$Chromosome, Position = NA), chrom_lengths_before = data.frame(), chrom_lengths_after = data.frame()))
392
- G <- graph(edges = NULL, n = length(markers), directed = FALSE)
393
- V(G)$name <- markers
394
- map_distance_df <- data.frame()
395
- chromosomes <- unique(df$Chromosome)
396
- for (chromosome in chromosomes) {
397
- markers_on_chromosome <- subset(df, Chromosome == chromosome)
398
- if (nrow(markers_on_chromosome) < 2) next
399
- marker_combinations <- combn(markers_on_chromosome$Marker, 2, simplify = TRUE)
400
- for (i in 1:ncol(marker_combinations)) {
401
- marker1 <- as.character(marker_combinations[1, i])
402
- marker2 <- as.character(marker_combinations[2, i])
403
- genotype1 <- as.character(markers_on_chromosome[markers_on_chromosome$Marker == marker1, 3:ncol(df)])
404
- genotype2 <- as.character(markers_on_chromosome[markers_on_chromosome$Marker == marker2, 3:ncol(df)])
405
- recombination_fraction <- calculate_recombination(population_type, genotype1, genotype2)
406
- if (!is.na(recombination_fraction) && recombination_fraction < recombination_threshold) {
407
- map_distance_cM <- calculate_cM_kosambi(recombination_fraction)
408
- G <- add_edges(G, edges = c(marker1, marker2), weight = map_distance_cM)
409
- new_row <- data.frame(Marker1 = marker1, Marker2 = marker2, RecombinationFraction = recombination_fraction, MapDistance_cM = map_distance_cM)
410
- map_distance_df <- rbind(map_distance_df, new_row)
411
- }
412
- }
413
- }
414
- if (nrow(map_distance_df) == 0) return(list(original_data = df, recombination_data = map_distance_df, linkage_map = data.frame(Marker = df$Marker, Chromosome = df$Chromosome, Position = NA), chrom_lengths_before = data.frame(), chrom_lengths_after = data.frame()))
415
- grouped_markers <- group_and_order_markers(map_distance_df, threshold)
416
- positions <- list()
417
- for (chromosome in chromosomes) {
418
- markers_on_chromosome <- subset(df, Chromosome == chromosome)$Marker
419
- if (length(markers_on_chromosome) == 0) next
420
- chrom_grouped <- grouped_markers[grouped_markers$Marker %in% markers_on_chromosome, ]
421
- if (nrow(chrom_grouped) == 0) {
422
- ordered_markers <- markers_on_chromosome
423
- } else {
424
- chrom_grouped <- chrom_grouped[order(chrom_grouped$Order), ]
425
- ordered_markers <- chrom_grouped$Marker
426
- }
427
- if (length(ordered_markers) > 0) {
428
- positions[[ordered_markers[1]]] <- 0
429
- if (length(ordered_markers) > 1) {
430
- for (i in 2:length(ordered_markers)) {
431
- marker <- ordered_markers[i]
432
- prev_marker <- ordered_markers[i-1]
433
- edge_id <- get.edge.ids(G, c(marker, prev_marker))
434
- if (edge_id != 0 && length(edge_id) > 0) {
435
- distance <- edge_attr(G, 'weight', edge_id)
436
- } else {
437
- distance <- 1
438
- }
439
- positions[[marker]] <- positions[[prev_marker]] + distance
440
- }
441
- }
442
- }
443
- }
444
- if (length(positions) == 0) {
445
- return(list(original_data = df, recombination_data = map_distance_df, linkage_map = data.frame(Marker = df$Marker, Chromosome = df$Chromosome, Position = NA), chrom_lengths_before = data.frame(), chrom_lengths_after = data.frame()))
446
- }
447
- positions_df <- data.frame(Marker = names(positions), Position = unlist(positions))
448
- linkage_map <- merge(df[, c('Marker', 'Chromosome')], positions_df, by = "Marker", all.x = TRUE)
449
- linkage_map <- linkage_map[order(linkage_map$Chromosome, linkage_map$Position), ]
450
- scaled_results <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
451
- return(list(original_data = df, recombination_data = map_distance_df, linkage_map = scaled_results$scaled_map, chrom_lengths_before = scaled_results$chrom_lengths_before, chrom_lengths_after = scaled_results$chrom_lengths_after))
452
- }
453
-
454
- create_multi_chromosome_plot <- function(linkage_data, selected_chromosomes, label_size = 3, show_labels = TRUE, color_palette = "Set2", plot_width = 1200, plot_height = 800, chrom_width = 0.5, point_size = 2, chrom_spacing = 5.0) {
455
- library(ggplot2)
456
- library(dplyr)
457
- library(RColorBrewer)
458
-
459
- plot_data <- linkage_data %>%
460
- filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
461
- arrange(Chromosome, Position)
462
-
463
- if (nrow(plot_data) == 0) {
464
- return(ggplot() +
465
- annotate("text", x = 0.5, y = 0.5,
466
- label = "No valid marker positions available",
467
- size = 6, color = "red") +
468
- theme_void())
469
- }
470
-
471
- chrom_stats <- plot_data %>%
472
- group_by(Chromosome) %>%
473
- summarise(
474
- max_pos = max(Position),
475
- min_pos = min(Position),
476
- num_markers = n(),
477
- .groups = "drop"
478
- ) %>%
479
- arrange(Chromosome) %>%
480
- mutate(
481
- chrom_x = seq(1, by = chrom_spacing, length.out = n()),
482
- chrom_center = chrom_x
483
- )
484
-
485
- plot_data <- plot_data %>%
486
- left_join(chrom_stats %>% select(Chromosome, chrom_x, chrom_center), by = "Chromosome")
487
-
488
- n_chrom <- nrow(chrom_stats)
489
- chrom_colors <- if (n_chrom <= 8) {
490
- brewer.pal(max(3, n_chrom), color_palette)
491
- } else {
492
- colorRampPalette(brewer.pal(8, color_palette))(n_chrom)
493
- }
494
-
495
- p <- ggplot() +
496
- geom_segment(
497
- data = chrom_stats,
498
- aes(x = chrom_center, xend = chrom_center,
499
- y = min_pos, yend = max_pos,
500
- color = as.factor(Chromosome)),
501
- size = chrom_width * 20,
502
- alpha = 0.7,
503
- lineend = "round"
504
- ) +
505
- geom_point(
506
- data = plot_data,
507
- aes(x = chrom_center, y = Position,
508
- color = as.factor(Chromosome)),
509
- size = point_size,
510
- alpha = 0.8
511
- ) +
512
- {if (show_labels && "Marker" %in% names(plot_data))
513
- geom_text(
514
- data = plot_data,
515
- aes(x = chrom_center + chrom_width * 0.6,
516
- y = Position,
517
- label = Marker,
518
- color = as.factor(Chromosome)),
519
- size = label_size,
520
- hjust = 0,
521
- vjust = 0.5,
522
- check_overlap = TRUE,
523
- alpha = 0.7
524
- )
525
- } +
526
- geom_text(
527
- data = chrom_stats,
528
- aes(x = chrom_center, y = max_pos * 1.05,
529
- label = paste0("Chr", Chromosome),
530
- color = as.factor(Chromosome)),
531
- size = label_size + 1,
532
- fontface = "bold",
533
- vjust = 0
534
- ) +
535
- scale_color_manual(values = chrom_colors) +
536
- scale_fill_manual(values = chrom_colors) +
537
- scale_y_reverse(
538
- name = "Genetic Position (cM)",
539
- expand = expansion(mult = c(0.05, 0.1))
540
- ) +
541
- scale_x_continuous(
542
- breaks = chrom_stats$chrom_center,
543
- labels = chrom_stats$Chromosome,
544
- name = "Chromosome",
545
- expand = expansion(mult = 0.1)
546
- ) +
547
- theme_minimal() +
548
- theme(
549
- legend.position = "none",
550
- axis.text.y = element_text(size = 10, color = "black"),
551
- axis.text.x = element_text(size = 12, angle = 0, hjust = 0.5, face = "bold"),
552
- axis.title.y = element_text(size = 12, face = "bold", margin = margin(r = 10)),
553
- axis.title.x = element_text(size = 12, face = "bold", margin = margin(t = 10)),
554
- panel.grid.major.x = element_blank(),
555
- panel.grid.minor.x = element_blank(),
556
- panel.grid.major.y = element_line(color = "grey90", size = 0.2),
557
- panel.grid.minor.y = element_line(color = "grey95", size = 0.1),
558
- plot.margin = margin(20, 20, 20, 20)
559
- )
560
-
561
- return(p)
562
- }
563
-
564
- create_single_chromosome_plot <- function(linkage_data, selected_chromosome, label_size = 3, show_labels = TRUE, color_palette = "Set2") {
565
- plot_data <- linkage_data %>% filter(Chromosome == selected_chromosome, !is.na(Position)) %>% arrange(Position)
566
- if (nrow(plot_data) == 0) return(ggplot() + annotate("text", x = 0.5, y = 0.5, label = paste("No valid marker positions available for Chromosome", selected_chromosome), size = 6, color = "red") + theme_void())
567
- chrom_color <- brewer.pal(3, color_palette)[1]
568
- p <- ggplot(plot_data, aes(x = Position, y = 1)) +
569
- geom_segment(aes(x = 0, xend = max(Position, na.rm = TRUE), y = 1, yend = 1), color = chrom_color, size = 2) +
570
- geom_point(aes(x = Position, y = 1), color = "red", size = 3) +
571
- {if (show_labels) geom_text_repel(aes(label = Marker), size = label_size, box.padding = 0.5, segment.color = "gray")} +
572
- labs(title = paste("Chromosome", selected_chromosome, "Linkage Map"), x = "Position (cM)", y = "") +
573
- theme_minimal() +
574
- theme(
575
- axis.text.y = element_blank(),
576
- axis.ticks.y = element_blank(),
577
- panel.grid.major.y = element_blank(),
578
- panel.grid.minor.y = element_blank(),
579
- plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
580
- axis.title.x = element_text(size = 12),
581
- axis.text.x = element_text(size = 10)
582
- )
583
- return(p)
584
- }
585
-
586
- output$palette_preview <- renderPlot({
587
- req(input$color_palette)
588
- colors <- brewer.pal(8, input$color_palette)
589
- n <- length(colors)
590
- df <- data.frame(x = 1:n, y = rep(1, n), color = colors)
591
- ggplot(df, aes(x = x, y = y, fill = I(color))) +
592
- geom_tile(width = 0.9, height = 0.9) +
593
- scale_x_continuous(breaks = 1:n, labels = 1:n) +
594
- labs(title = paste("Preview of", input$color_palette, "Palette")) +
595
- theme_minimal() +
596
- theme(
597
- axis.text.y = element_blank(),
598
- axis.ticks.y = element_blank(),
599
- axis.title = element_blank(),
600
- panel.grid = element_blank(),
601
- plot.title = element_text(hjust = 0.5, size = 14, face = "bold")
602
- )
603
- }, height = 200)
604
-
605
  observeEvent(input$run_analysis, {
606
  req(uploaded_data())
607
- showModal(modalDialog(title = "Processing", "Creating and scaling linkage map... This may take a few moments.", footer = NULL))
 
 
 
 
 
608
  tryCatch({
609
  result <- create_linkage_map(
610
- df = uploaded_data(),
611
- population_type = input$population_type,
612
- missing_threshold = input$missing_threshold,
613
  recombination_threshold = input$recombination_threshold,
614
- chi_square_threshold = input$chi_square_threshold,
615
- threshold = input$cluster_threshold,
616
- max_total_cm = input$max_total_cm,
617
- scaling_method = input$scaling_method
618
  )
619
  analysis_results(result)
620
  pre_scaling_stats(result$chrom_lengths_before)
621
- chromosomes <- unique(result$linkage_map$Chromosome)
622
- updateSelectInput(session, "chromosome_select", choices = chromosomes, selected = if(length(chromosomes) > 0) chromosomes[1:2] else NULL)
 
 
 
623
  removeModal()
624
- showNotification("Analysis and scaling completed successfully!", type = "message")
625
  }, error = function(e) {
626
  removeModal()
627
- showNotification(paste("Error in analysis:", e$message), type = "error")
628
  })
629
  })
630
-
631
  output$analysis_run <- reactive({ !is.null(analysis_results()) })
632
- outputOptions(output, 'analysis_run', suspendWhenHidden = FALSE)
633
-
 
634
  output$scaling_summary <- renderText({
635
  req(analysis_results())
636
- paste0("SCALING SUMMARY\n==================\nScaling Method: ", input$scaling_method, "\nMaximum Total Map Length: ", input$max_total_cm, " cM\n")
 
637
  })
638
-
 
 
 
 
 
 
 
 
639
  output$before_scaling_stats <- renderText({
640
- req(analysis_results(), pre_scaling_stats())
641
- chrom_lengths_before <- pre_scaling_stats()
642
- if (nrow(chrom_lengths_before) > 0) {
643
- total_length <- sum(chrom_lengths_before$Original_Length, na.rm = TRUE)
644
- paste0("BEFORE SCALING\n==================\nTotal Map Length: ", round(total_length, 2), " cM\nChromosome Lengths:\n", paste(apply(chrom_lengths_before, 1, function(x) paste0("Chromosome ", x[1], ": ", round(as.numeric(x[2]), 2), " cM")), collapse = "\n"))
645
- } else "No chromosome length data available before scaling."
646
  })
647
-
648
  output$after_scaling_stats <- renderText({
649
- req(analysis_results())
650
- chrom_lengths_after <- analysis_results()$chrom_lengths_after
651
- if (nrow(chrom_lengths_after) > 0) {
652
- total_length <- sum(chrom_lengths_after$Original_Length, na.rm = TRUE)
653
- paste0("AFTER SCALING\n==================\nTotal Map Length: ", round(total_length, 2), " cM\nChromosome Lengths:\n", paste(apply(chrom_lengths_after, 1, function(x) paste0("Chromosome ", x[1], ": ", round(as.numeric(x[2]), 2), " cM")), collapse = "\n"))
654
- } else "No chromosome length data available after scaling."
655
  })
656
-
 
657
  output$result_table <- renderDataTable({
658
  req(analysis_results())
659
- linkage_map <- analysis_results()$linkage_map
660
- if (nrow(linkage_map) > 0) {
661
- datatable(linkage_map, options = list(scrollX = TRUE, pageLength = 25, order = list(list(1, 'asc'), list(2, 'asc'))), rownames = FALSE, caption = "Linkage Map Results - Marker positions in centiMorgans (cM)") %>% formatRound('Position', 2)
662
- } else datatable(data.frame(Message = "No linkage map data available"), options = list(dom = 't'), rownames = FALSE)
 
 
 
 
 
 
 
 
663
  })
664
-
 
665
  output$summary_stats <- renderText({
666
  req(analysis_results())
667
- linkage_map <- analysis_results()$linkage_map
668
- recomb_data <- analysis_results()$recombination_data
669
- if (nrow(linkage_map) > 0) {
670
- n_markers <- nrow(linkage_map)
671
- n_chromosomes <- length(unique(linkage_map$Chromosome))
672
- n_positioned <- sum(!is.na(linkage_map$Position))
673
- chrom_lengths <- linkage_map %>% filter(!is.na(Position)) %>% group_by(Chromosome) %>% summarise(Length = max(Position, na.rm = TRUE), .groups = 'drop')
674
- total_length <- sum(chrom_lengths$Length, na.rm = TRUE)
675
- avg_length <- mean(chrom_lengths$Length, na.rm = TRUE)
676
- paste0("LINKAGE MAP SUMMARY\n==================\nTotal Markers: ", n_markers, "\nPositioned Markers: ", n_positioned, "\nNumber of Chromosomes: ", n_chromosomes, "\nTotal Map Length: ", round(total_length, 2), " cM\nAverage Chromosome Length: ", round(avg_length, 2), " cM\nNumber of Marker Pairs Analyzed: ", nrow(recomb_data), "\n\nCHROMOSOME DETAILS:\n", paste(apply(chrom_lengths, 1, function(x) paste0("Chromosome ", x[1], ": ", round(as.numeric(x[2]), 2), " cM")), collapse = "\n"))
677
- } else "No summary statistics available - no positioned markers found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678
  })
679
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
  output$chromosome_plot <- renderPlot({
681
  req(analysis_results(), input$chromosome_select)
682
- linkage_map <- analysis_results()$linkage_map
683
  create_multi_chromosome_plot(
684
- linkage_map,
685
  input$chromosome_select,
686
- label_size = input$marker_label_size,
687
- show_labels = input$show_labels,
688
  color_palette = input$color_palette,
689
- plot_width = input$plot_width,
690
- plot_height = input$plot_height
691
  )
692
  }, height = function() input$plot_height)
693
-
 
694
  output$download_results <- downloadHandler(
695
- filename = function() paste0("linkage_map_results_", Sys.Date(), ".xlsx"),
696
- content = function(file) {
697
  req(analysis_results())
698
  wb <- createWorkbook()
699
  addWorksheet(wb, "Original_Data")
700
  addWorksheet(wb, "Recombination_Fractions")
701
  addWorksheet(wb, "Linkage_Map")
702
- writeData(wb, "Original_Data", analysis_results()$original_data)
703
- writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
704
- writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
705
  saveWorkbook(wb, file, overwrite = TRUE)
706
  }
707
  )
708
-
709
  output$download_plot <- downloadHandler(
710
  filename = function() paste0("chromosome_map_", Sys.Date(), ".png"),
711
- content = function(file) {
712
  req(analysis_results(), input$chromosome_select)
713
- linkage_map <- analysis_results()$linkage_map
714
- plot <- create_multi_chromosome_plot(
715
- linkage_map,
716
  input$chromosome_select,
717
- label_size = input$marker_label_size,
718
- show_labels = input$show_labels,
719
  color_palette = input$color_palette,
720
- plot_width = input$plot_width,
721
- plot_height = input$plot_height
722
  )
723
- width_inches <- input$plot_width / 300
724
- height_inches <- input$plot_height / 300
725
- ggsave(file, plot, width = width_inches, height = height_inches, dpi = 300, bg = "white")
 
726
  }
727
  )
728
  }
 
7
  library(RColorBrewer)
8
  library(ggrepel)
9
 
10
+ # ─────────────────────────────────────────────
11
+ # CORE GENETIC FUNCTIONS (Fixed for F2/RIL)
12
+ # ─────────────────────────────────────────────
13
+
14
+ ## 1. Recombination fraction --------------------------------------------------
15
+ # F2: uses all three genotype classes (a, ab, b)
16
+ # RIL: only homozygous classes used; RIL correction applied
17
+ calculate_recombination <- function(population_type, genotype1, genotype2) {
18
+ g1 <- as.character(genotype1)
19
+ g2 <- as.character(genotype2)
20
+
21
+ # remove pairs where either marker is missing
22
+ keep <- !(g1 %in% c('-', 'NA', NA) | g2 %in% c('-', 'NA', NA))
23
+ g1 <- g1[keep]; g2 <- g2[keep]
24
+ n <- length(g1)
25
+ if (n == 0) return(NA_real_)
26
+
27
+ if (population_type == "RIL") {
28
+ # RIL: only homozygous calls informative
29
+ hom <- !(g1 == "ab" | g2 == "ab")
30
+ g1h <- g1[hom]; g2h <- g2[hom]
31
+ if (length(g1h) == 0) return(NA_real_)
32
+ r_obs <- mean(g1h != g2h) # observed recombination
33
+ # Haldane correction for RIL (Rezvoy et al.)
34
+ rf <- r_obs / (2 * (1 - r_obs)) # r_RIL -> r_meiosis
35
+ rf <- min(rf, 0.4999)
36
+ return(rf)
37
+
38
+ } else if (population_type == "F2") {
39
+ # Maximum-likelihood estimate of r from F2 data
40
+ # Genotype coding: a=AA, ab=Aa, b=BB
41
+ # Expected frequencies as function of r (Mather 1936):
42
+ # AA: (1-r)^2 / D
43
+ # Aa: 2r(1-r) / D (repulsion) or different formula for coupling
44
+ # Simple approach: count recombinant gametes
45
+ # For each individual: infer number of recombinant gametes
46
+ # Treat hetΓ—het as uninformative for phase-unknown F2
47
+
48
+ # Phase-unknown EM for F2 (simplified Kosambi/Haldane MLE)
49
+ # Observed counts
50
+ AA_AA <- sum(g1 == "a" & g2 == "a")
51
+ AA_Aa <- sum(g1 == "a" & g2 == "ab")
52
+ AA_BB <- sum(g1 == "a" & g2 == "b")
53
+ Aa_AA <- sum(g1 == "ab" & g2 == "a")
54
+ Aa_Aa <- sum(g1 == "ab" & g2 == "ab")
55
+ Aa_BB <- sum(g1 == "ab" & g2 == "b")
56
+ BB_AA <- sum(g1 == "b" & g2 == "a")
57
+ BB_Aa <- sum(g1 == "b" & g2 == "ab")
58
+ BB_BB <- sum(g1 == "b" & g2 == "b")
59
+
60
+ # EM algorithm for F2 recombination fraction
61
+ # Starting value
62
+ r <- 0.25
63
+ for (iter in 1:200) {
64
+ r_old <- r
65
+ q <- 1 - r
66
+
67
+ # E-step for AaΓ—Aa class: partition into parental and recombinant
68
+ denom_AaAa <- 2 * r^2 + 4 * r * q + 2 * q^2 # = 2*(r+q)^2 = 2 but keep explicit
69
+ # Expected proportion of each gamete combination within AaΓ—Aa
70
+ # Coupling: (AA+BB from parental) vs (AB+BA from recombinant)
71
+ p_parental <- (q^2 + r^2) # AA/BB gamete combos
72
+ p_recomb <- 2 * r * q # AB/BA gamete combos
73
+ norm <- p_parental + p_recomb # = (r+q)^2 = 1
74
+
75
+ n_parental_AaAa <- if (norm > 0) Aa_Aa * p_parental / norm else 0
76
+ n_recomb_AaAa <- if (norm > 0) Aa_Aa * p_recomb / norm else 0
77
+
78
+ # M-step: recombinant gametes
79
+ # Each AAΓ—BB or BBΓ—AA individual contributes 2 recombinant gametes
80
+ # Each AAΓ—Aa or similar contributes 1 recombinant gamete (one het parent)
81
+ recomb_count <- 2 * (AA_BB + BB_AA) +
82
+ (AA_Aa + Aa_AA + Aa_BB + BB_Aa) +
83
+ 2 * n_recomb_AaAa
84
+
85
+ total_gametes <- 2 * n
86
+
87
+ r_new <- recomb_count / total_gametes
88
+ r_new <- max(1e-6, min(r_new, 0.4999))
89
+ r <- r_new
90
+ if (abs(r - r_old) < 1e-8) break
91
+ }
92
+ return(r)
93
+
94
+ } else {
95
+ stop("population_type must be 'RIL' or 'F2'")
96
+ }
97
+ }
98
+
99
+ ## 2. Kosambi map function ----------------------------------------------------
100
+ calculate_cM_kosambi <- function(r) {
101
+ if (is.na(r)) return(NA_real_)
102
+ r <- max(0, min(r, 0.4999))
103
+ if (r == 0) return(0)
104
+ 25 * log((1 + 2*r) / (1 - 2*r)) # Kosambi: cM = 25*ln((1+2r)/(1-2r))
105
+ }
106
+
107
+ ## 3. Impute missing / correct errors ----------------------------------------
108
+ correct_errors_and_impute_missing <- function(df) {
109
+ valid_geno <- c("a", "b", "ab")
110
+
111
+ # Replace '-', NA, blanks with NA
112
+ for (j in seq(3, ncol(df))) {
113
+ x <- as.character(df[[j]])
114
+ x[x %in% c("-", "NA", "", " ")] <- NA
115
+ x[!is.na(x) & !(x %in% valid_geno)] <- NA
116
+ df[[j]] <- x
117
+ }
118
+
119
+ # Drop individuals (columns) that are entirely missing
120
+ if (ncol(df) > 2) {
121
+ na_col <- colMeans(is.na(df[, 3:ncol(df), drop = FALSE]))
122
+ keep_cols <- c(TRUE, TRUE, na_col < 1)
123
+ df <- df[, keep_cols, drop = FALSE]
124
+ }
125
+
126
+ # Impute remaining NAs per marker (row) with mode of observed values
127
+ if (ncol(df) > 2) {
128
+ df[, 3:ncol(df)] <- t(apply(df[, 3:ncol(df), drop = FALSE], 1, function(row) {
129
+ nas <- is.na(row)
130
+ if (all(nas)) return(row)
131
+ tbl <- table(row[!nas])
132
+ mode_val <- names(which.max(tbl))
133
+ row[nas] <- mode_val
134
+ row
135
+ }))
136
+ }
137
+ df
138
+ }
139
+
140
+ ## 4. Quality control ---------------------------------------------------------
141
+ quality_control <- function(df, missing_threshold = 0.1) {
142
+ if (ncol(df) < 3 || nrow(df) == 0) return(df[0, ])
143
+ geno <- df[, 3:ncol(df), drop = FALSE]
144
+ miss_frac <- rowMeans(is.na(geno))
145
+ miss_frac[is.na(miss_frac)] <- 1
146
+ df[miss_frac <= missing_threshold, ]
147
+ }
148
+
149
+ ## 5. Chi-square segregation distortion test ----------------------------------
150
+ perform_chi_square_test <- function(df, population_type, chi_square_threshold = 0.05) {
151
+ if (nrow(df) == 0) return(logical(0))
152
+ geno_mat <- as.matrix(df[, 3:ncol(df), drop = FALSE])
153
+
154
+ keep <- apply(geno_mat, 1, function(row) {
155
+ obs <- table(factor(row, levels = c("a", "ab", "b")))
156
+
157
+ if (population_type == "RIL") {
158
+ # Expected 1:1 (a : b), ignore ab
159
+ obs2 <- c(obs["a"], obs["b"])
160
+ if (sum(obs2) == 0) return(TRUE) # can't test β†’ keep
161
+ exp2 <- rep(sum(obs2) / 2, 2)
162
+ stat <- sum((obs2 - exp2)^2 / exp2)
163
+ pval <- pchisq(stat, df = 1, lower.tail = FALSE)
164
+ } else {
165
+ # F2: Expected 1:2:1 (a : ab : b)
166
+ total <- sum(obs)
167
+ if (total == 0) return(TRUE)
168
+ exp3 <- c(total * 0.25, total * 0.50, total * 0.25)
169
+ # avoid division by zero
170
+ valid <- exp3 > 0
171
+ stat <- sum(((obs[valid] - exp3[valid])^2) / exp3[valid])
172
+ pval <- pchisq(stat, df = sum(valid) - 1, lower.tail = FALSE)
173
+ }
174
+
175
+ return(pval > chi_square_threshold)
176
+ })
177
+ keep
178
+ }
179
+
180
+ ## 6. Marker ordering using MDS on pairwise distances ------------------------
181
+ order_markers_mds <- function(map_distance_df, markers) {
182
+ n <- length(markers)
183
+ if (n <= 1) return(markers)
184
+
185
+ # Build distance matrix
186
+ D <- matrix(Inf, n, n, dimnames = list(markers, markers))
187
+ diag(D) <- 0
188
+
189
+ for (i in seq_len(nrow(map_distance_df))) {
190
+ m1 <- as.character(map_distance_df$Marker1[i])
191
+ m2 <- as.character(map_distance_df$Marker2[i])
192
+ d <- map_distance_df$MapDistance_cM[i]
193
+ if (m1 %in% markers && m2 %in% markers && is.finite(d)) {
194
+ D[m1, m2] <- min(D[m1, m2], d)
195
+ D[m2, m1] <- min(D[m2, m1], d)
196
+ }
197
+ }
198
+
199
+ # Replace Inf with large value
200
+ max_d <- max(D[is.finite(D)], na.rm = TRUE)
201
+ if (!is.finite(max_d) || max_d == 0) max_d <- 100
202
+ D[!is.finite(D)] <- max_d * 2
203
+
204
+ # Classical MDS β†’ project onto 1D β†’ sort
205
+ tryCatch({
206
+ mds <- cmdscale(as.dist(D), k = 1)
207
+ markers[order(mds[, 1])]
208
+ }, error = function(e) {
209
+ # Fallback: greedy nearest-neighbour starting from first marker
210
+ remaining <- markers
211
+ ordered <- remaining[1]
212
+ remaining <- remaining[-1]
213
+ while (length(remaining) > 0) {
214
+ last <- ordered[length(ordered)]
215
+ dists_to_last <- D[last, remaining]
216
+ next_m <- remaining[which.min(dists_to_last)]
217
+ ordered <- c(ordered, next_m)
218
+ remaining <- remaining[remaining != next_m]
219
+ }
220
+ ordered
221
+ })
222
+ }
223
+
224
+ ## 7. Cluster markers into linkage groups (hclust) ---------------------------
225
+ group_markers <- function(map_distance_df, markers, threshold = 40) {
226
+ n <- length(markers)
227
+ if (n <= 1) return(setNames(seq_len(n), markers))
228
+
229
+ D <- matrix(Inf, n, n, dimnames = list(markers, markers))
230
+ diag(D) <- 0
231
+
232
+ for (i in seq_len(nrow(map_distance_df))) {
233
+ m1 <- as.character(map_distance_df$Marker1[i])
234
+ m2 <- as.character(map_distance_df$Marker2[i])
235
+ d <- map_distance_df$MapDistance_cM[i]
236
+ if (m1 %in% markers && m2 %in% markers && is.finite(d)) {
237
+ D[m1, m2] <- min(D[m1, m2], d)
238
+ D[m2, m1] <- min(D[m2, m1], d)
239
+ }
240
+ }
241
+
242
+ max_d <- max(D[is.finite(D)], na.rm = TRUE)
243
+ if (!is.finite(max_d) || max_d == 0) max_d <- 100
244
+ D[!is.finite(D)] <- max_d * 2
245
+
246
+ tryCatch({
247
+ hc <- hclust(as.dist(D), method = "average")
248
+ hc$height <- pmax(hc$height, 0) # ensure non-negative
249
+ cutree(hc, h = threshold)
250
+ }, error = function(e) {
251
+ setNames(seq_len(n), markers)
252
+ })
253
+ }
254
+
255
+ ## 8. Map scaling -------------------------------------------------------------
256
+ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
257
+ pos_map <- linkage_map[!is.na(linkage_map$Position), ]
258
+ if (nrow(pos_map) == 0)
259
+ return(list(scaled_map = linkage_map,
260
+ chrom_lengths_before = data.frame(),
261
+ chrom_lengths_after = data.frame()))
262
+
263
+ before <- pos_map %>%
264
+ group_by(Chromosome) %>%
265
+ summarise(Original_Length = max(Position, na.rm = TRUE), .groups = "drop")
266
+
267
+ total <- sum(before$Original_Length, na.rm = TRUE)
268
+
269
+ if (total <= max_total_cm || total == 0)
270
+ return(list(scaled_map = linkage_map,
271
+ chrom_lengths_before = before,
272
+ chrom_lengths_after = before))
273
+
274
+ scaled <- linkage_map
275
+
276
+ if (method == "proportional") {
277
+ sf <- max_total_cm / total
278
+ before$sf <- sf
279
+ } else {
280
+ n_chr <- nrow(before)
281
+ before$sf <- ifelse(before$Original_Length > 0,
282
+ (max_total_cm / n_chr) / before$Original_Length, 1)
283
+ }
284
+
285
+ for (chr in before$Chromosome) {
286
+ sf <- before$sf[before$Chromosome == chr]
287
+ idx <- which(scaled$Chromosome == chr & !is.na(scaled$Position))
288
+ if (length(idx) > 0) {
289
+ mn <- min(scaled$Position[idx])
290
+ scaled$Position[idx] <- (scaled$Position[idx] - mn) * sf
291
+ }
292
+ }
293
+
294
+ after <- scaled %>%
295
+ filter(!is.na(Position)) %>%
296
+ group_by(Chromosome) %>%
297
+ summarise(Original_Length = max(Position, na.rm = TRUE), .groups = "drop")
298
+
299
+ list(scaled_map = scaled, chrom_lengths_before = before, chrom_lengths_after = after)
300
+ }
301
+
302
+ ## 9. Master analysis function ------------------------------------------------
303
+ create_linkage_map <- function(df,
304
+ population_type = "F2",
305
+ missing_threshold = 0.1,
306
+ recombination_threshold = 0.5,
307
+ chi_square_threshold = 0.05,
308
+ cluster_threshold = 40,
309
+ max_total_cm = 1500,
310
+ scaling_method = "proportional") {
311
+
312
+ empty_result <- function(df_in = df) {
313
+ list(original_data = df_in,
314
+ recombination_data = data.frame(),
315
+ linkage_map = data.frame(Marker = character(0),
316
+ Chromosome = character(0),
317
+ Position = numeric(0)),
318
+ chrom_lengths_before = data.frame(),
319
+ chrom_lengths_after = data.frame())
320
+ }
321
+
322
+ # ── pre-processing ──────────────────────────────────────────────────────────
323
+ df <- correct_errors_and_impute_missing(df)
324
+ df <- quality_control(df, missing_threshold)
325
+
326
+ if (nrow(df) == 0 || ncol(df) < 3) return(empty_result())
327
+
328
+ # ── segregation distortion filter ───────────────────────────────────────────
329
+ keep <- perform_chi_square_test(df, population_type, chi_square_threshold)
330
+ if (length(keep) == nrow(df)) df <- df[keep, ]
331
+
332
+ if (nrow(df) == 0) return(empty_result())
333
+
334
+ chromosomes <- unique(df$Chromosome)
335
+
336
+ # ── pairwise recombination fractions ────────────────────────────────────────
337
+ rec_rows <- list()
338
+ for (chr in chromosomes) {
339
+ sub <- df[df$Chromosome == chr, ]
340
+ mks <- sub$Marker
341
+ if (length(mks) < 2) next
342
+
343
+ pairs <- combn(mks, 2, simplify = FALSE)
344
+ for (pr in pairs) {
345
+ m1 <- pr[1]; m2 <- pr[2]
346
+ g1 <- unlist(sub[sub$Marker == m1, 3:ncol(df)])
347
+ g2 <- unlist(sub[sub$Marker == m2, 3:ncol(df)])
348
+ rf <- calculate_recombination(population_type, g1, g2)
349
+ if (!is.na(rf) && rf < recombination_threshold) {
350
+ cM <- calculate_cM_kosambi(rf)
351
+ rec_rows[[length(rec_rows) + 1]] <-
352
+ data.frame(Marker1 = m1, Marker2 = m2,
353
+ RecombinationFraction = rf,
354
+ MapDistance_cM = cM,
355
+ Chromosome = chr,
356
+ stringsAsFactors = FALSE)
357
+ }
358
+ }
359
+ }
360
+
361
+ if (length(rec_rows) == 0) {
362
+ lm_empty <- data.frame(Marker = df$Marker, Chromosome = df$Chromosome,
363
+ Position = NA_real_)
364
+ return(list(original_data = df, recombination_data = data.frame(),
365
+ linkage_map = lm_empty,
366
+ chrom_lengths_before = data.frame(),
367
+ chrom_lengths_after = data.frame()))
368
+ }
369
+
370
+ rec_df <- do.call(rbind, rec_rows)
371
+
372
+ # ── build linkage map per chromosome ────────────────────────────────────────
373
+ positions_list <- list()
374
+
375
+ for (chr in chromosomes) {
376
+ sub <- df[df$Chromosome == chr, ]
377
+ mks <- sub$Marker
378
+ if (length(mks) == 0) next
379
+
380
+ chr_rec <- rec_df[rec_df$Chromosome == chr, ]
381
+
382
+ # Order markers using MDS
383
+ ordered_mks <- order_markers_mds(chr_rec, mks)
384
+
385
+ # Assign cumulative positions using consecutive pairwise distances
386
+ pos <- numeric(length(ordered_mks))
387
+ names(pos) <- ordered_mks
388
+ pos[1] <- 0
389
+
390
+ if (length(ordered_mks) > 1) {
391
+ for (i in 2:length(ordered_mks)) {
392
+ m_prev <- ordered_mks[i - 1]
393
+ m_curr <- ordered_mks[i]
394
+
395
+ # Find distance in rec_df (either direction)
396
+ d_row <- chr_rec[(chr_rec$Marker1 == m_prev & chr_rec$Marker2 == m_curr) |
397
+ (chr_rec$Marker1 == m_curr & chr_rec$Marker2 == m_prev), ]
398
+ if (nrow(d_row) > 0) {
399
+ d <- d_row$MapDistance_cM[1]
400
+ } else {
401
+ # Use nearest available distance or default
402
+ d <- 1
403
+ }
404
+ pos[i] <- pos[i - 1] + abs(d)
405
+ }
406
+ }
407
+
408
+ for (mk in names(pos)) {
409
+ positions_list[[mk]] <- pos[mk]
410
+ }
411
+ }
412
+
413
+ if (length(positions_list) == 0) {
414
+ lm_empty <- data.frame(Marker = df$Marker, Chromosome = df$Chromosome,
415
+ Position = NA_real_)
416
+ return(list(original_data = df, recombination_data = rec_df,
417
+ linkage_map = lm_empty,
418
+ chrom_lengths_before = data.frame(),
419
+ chrom_lengths_after = data.frame()))
420
+ }
421
+
422
+ pos_df <- data.frame(Marker = names(positions_list),
423
+ Position = unlist(positions_list),
424
+ stringsAsFactors = FALSE)
425
+
426
+ linkage_map <- merge(df[, c("Marker", "Chromosome")], pos_df,
427
+ by = "Marker", all.x = TRUE)
428
+ linkage_map <- linkage_map[order(linkage_map$Chromosome, linkage_map$Position), ]
429
+
430
+ # ── scaling ─────────────────────────────────────────────────────────────────
431
+ scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
432
+
433
+ list(original_data = df,
434
+ recombination_data = rec_df,
435
+ linkage_map = scaled$scaled_map,
436
+ chrom_lengths_before = scaled$chrom_lengths_before,
437
+ chrom_lengths_after = scaled$chrom_lengths_after)
438
+ }
439
+
440
+ # ─────────────────────────────────────────────
441
+ # PLOTTING FUNCTIONS
442
+ # ─────────────────────────────────────────────
443
+
444
+ create_multi_chromosome_plot <- function(linkage_data,
445
+ selected_chromosomes,
446
+ label_size = 3,
447
+ show_labels = TRUE,
448
+ color_palette = "Set2",
449
+ plot_width = 1200,
450
+ plot_height = 800,
451
+ chrom_width = 0.5,
452
+ point_size = 2,
453
+ chrom_spacing = 5.0) {
454
+
455
+ plot_data <- linkage_data %>%
456
+ filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
457
+ arrange(Chromosome, Position)
458
+
459
+ if (nrow(plot_data) == 0) {
460
+ return(ggplot() +
461
+ annotate("text", x = 0.5, y = 0.5,
462
+ label = "No valid marker positions available",
463
+ size = 6, color = "red") +
464
+ theme_void())
465
+ }
466
+
467
+ chrom_stats <- plot_data %>%
468
+ group_by(Chromosome) %>%
469
+ summarise(max_pos = max(Position), min_pos = min(Position),
470
+ num_markers = n(), .groups = "drop") %>%
471
+ arrange(Chromosome) %>%
472
+ mutate(chrom_x = seq(1, by = chrom_spacing, length.out = n()),
473
+ chrom_center = chrom_x)
474
+
475
+ plot_data <- plot_data %>%
476
+ left_join(chrom_stats %>% select(Chromosome, chrom_x, chrom_center),
477
+ by = "Chromosome")
478
+
479
+ n_chrom <- nrow(chrom_stats)
480
+ # Robust palette selection
481
+ palette_ok <- tryCatch({
482
+ brewer.pal(max(3, n_chrom), color_palette); TRUE
483
+ }, error = function(e) FALSE)
484
+
485
+ chrom_colors <- if (palette_ok && n_chrom <= 8) {
486
+ brewer.pal(max(3, n_chrom), color_palette)[1:n_chrom]
487
+ } else if (palette_ok) {
488
+ colorRampPalette(brewer.pal(8, color_palette))(n_chrom)
489
+ } else {
490
+ colorRampPalette(brewer.pal(8, "Set2"))(n_chrom)
491
+ }
492
+
493
+ p <- ggplot() +
494
+ geom_segment(data = chrom_stats,
495
+ aes(x = chrom_center, xend = chrom_center,
496
+ y = min_pos, yend = max_pos,
497
+ color = as.factor(Chromosome)),
498
+ linewidth = chrom_width * 10, alpha = 0.6, lineend = "round") +
499
+ geom_point(data = plot_data,
500
+ aes(x = chrom_center, y = Position,
501
+ color = as.factor(Chromosome)),
502
+ size = point_size, alpha = 0.9) +
503
+ geom_text(data = chrom_stats,
504
+ aes(x = chrom_center, y = -(max(chrom_stats$max_pos) * 0.03),
505
+ label = paste0("Chr\n", Chromosome),
506
+ color = as.factor(Chromosome)),
507
+ size = label_size + 1, fontface = "bold", vjust = 1) +
508
+ scale_color_manual(values = chrom_colors) +
509
+ scale_y_reverse(name = "Genetic Position (cM)",
510
+ expand = expansion(mult = c(0.02, 0.12))) +
511
+ scale_x_continuous(breaks = chrom_stats$chrom_center,
512
+ labels = chrom_stats$Chromosome,
513
+ name = "Chromosome",
514
+ expand = expansion(mult = 0.1)) +
515
+ theme_minimal(base_size = 12) +
516
+ theme(
517
+ legend.position = "none",
518
+ axis.text.x = element_blank(),
519
+ axis.ticks.x = element_blank(),
520
+ axis.title.y = element_text(size = 12, face = "bold",
521
+ margin = margin(r = 10)),
522
+ axis.title.x = element_text(size = 12, face = "bold",
523
+ margin = margin(t = 10)),
524
+ panel.grid.major.x = element_blank(),
525
+ panel.grid.minor.x = element_blank(),
526
+ panel.grid.major.y = element_line(color = "grey88", linewidth = 0.3),
527
+ panel.grid.minor.y = element_line(color = "grey94", linewidth = 0.15),
528
+ plot.margin = margin(20, 20, 20, 20)
529
+ )
530
+
531
+ # Optionally add marker labels with ggrepel
532
+ if (show_labels && "Marker" %in% names(plot_data)) {
533
+ p <- p + geom_text_repel(
534
+ data = plot_data,
535
+ aes(x = chrom_center, y = Position, label = Marker,
536
+ color = as.factor(Chromosome)),
537
+ size = label_size,
538
+ direction = "y",
539
+ nudge_x = 0.3,
540
+ segment.size = 0.3,
541
+ segment.alpha = 0.5,
542
+ max.overlaps = 20,
543
+ show.legend = FALSE
544
+ )
545
+ }
546
+ p
547
+ }
548
+
549
+ # ─────────────────────────────────────────────
550
+ # UI
551
+ # ─────────────────────────────────────────────
552
+
553
  ui <- fluidPage(
554
+ tags$head(tags$style(HTML("
555
+ body { background-color:#ffffff; color:#333333;
556
+ font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif; }
557
+ .navbar { background-color:#1E3A8A !important;
558
+ border-bottom:2px solid #1E40AF; }
559
+ .navbar-brand { color:#ffffff !important; font-weight:bold; }
560
+ .nav-tabs { background-color:#1E3A8A; border-bottom:2px solid #1E40AF; }
561
+ .nav-tabs > li > a { color:#cccccc !important;
562
+ background-color:#1E3A8A;
563
+ border:1px solid #1E40AF; margin-right:5px; }
564
+ .nav-tabs > li.active > a,
565
+ .nav-tabs > li.active > a:hover,
566
+ .nav-tabs > li.active > a:focus { color:#ffffff !important;
567
+ background-color:#1E40AF;
568
+ font-weight:bold; }
569
+ .nav-tabs > li > a:hover { background-color:#2563EB; color:#ffffff !important; }
570
+ .well { background-color:#EFF6FF; border:1px solid #BFDBFE; color:#333333; }
571
+ .form-control { background-color:#FFFFFF; color:#333333;
572
+ border:1px solid #93C5FD; }
573
+ .form-control:focus { border-color:#3B82F6;
574
+ box-shadow:0 0 0 .2rem rgba(59,130,246,.25); }
575
+ .btn { border:1px solid; }
576
+ .btn-primary { background-color:#1D4ED8; color:#ffffff;
577
+ border-color:#1E40AF; }
578
+ .btn-primary:hover { background-color:#1E40AF; border-color:#1E3A8A; }
579
+ .btn-success { background-color:#059669; color:#ffffff;
580
+ border-color:#047857; }
581
+ .btn-success:hover { background-color:#047857; border-color:#065F46; }
582
+ .dataTables_wrapper { color:#333333; }
583
+ table.dataTable { border:1px solid #BFDBFE; }
584
+ .footer { position:fixed; bottom:0; width:100%;
585
+ background-color:#1E3A8A; color:#cccccc;
586
+ text-align:center; padding:10px;
587
+ border-top:1px solid #1E40AF; }
588
+ .tab-content h3, .tab-content h4 { color:#1E3A8A; }
589
+ "))),
590
+
591
+ navbarPage("Linkage Map Creator", id = "nav",
592
+
593
+ # ── Tab 1: Upload ──────────────────────────────────────────────────────────
594
+ tabPanel("Data Upload", icon = icon("upload"),
595
+ sidebarLayout(
596
+ sidebarPanel(width = 4, wellPanel(
597
+ h3("Upload Data"),
598
+ fileInput("file", "Choose Excel File",
599
+ accept = c(".xlsx", ".xls"),
600
+ buttonLabel = "Browse…",
601
+ placeholder = "No file selected"),
602
+ selectInput("population_type", "Population Type:",
603
+ choices = c("RIL" = "RIL", "F2" = "F2"),
604
+ selected = "F2"),
605
+ helpText("Required columns: 'Marker', 'Chromosome'. ",
606
+ "Genotype columns after that: use 'a', 'b', 'ab', or '-'.")
607
+ )),
608
+ mainPanel(width = 8, wellPanel(
609
+ h3("Data Preview"),
610
+ div(style = "overflow-x:auto;", dataTableOutput("preview_table"))
611
+ ))
612
+ )
613
+ ),
614
+
615
+ # ── Tab 2: Parameters ─────────────────────────────────────────────────────
616
+ tabPanel("Parameters", icon = icon("sliders-h"),
617
+ sidebarLayout(
618
+ sidebarPanel(width = 4, wellPanel(
619
+ h3("Analysis Parameters"),
620
+ sliderInput("missing_threshold", "Missing Data Threshold:",
621
+ min = 0, max = 1, value = 0.1, step = 0.01),
622
+ sliderInput("recombination_threshold", "Recombination Threshold:",
623
+ min = 0, max = 0.5, value = 0.45, step = 0.01),
624
+ sliderInput("chi_square_threshold", "Chi-Square P Threshold:",
625
+ min = 0, max = 0.2, value = 0.05, step = 0.01),
626
+ sliderInput("cluster_threshold", "Cluster Threshold (cM):",
627
+ min = 10, max = 100, value = 40, step = 5),
628
+ h4("Map Scaling"),
629
+ numericInput("max_total_cm", "Max Total Map Length (cM):",
630
+ min = 100, max = 5000, value = 1500, step = 100),
631
+ selectInput("scaling_method", "Scaling Method:",
632
+ choices = c("Proportional" = "proportional",
633
+ "Uniform" = "uniform"),
634
+ selected = "proportional"),
635
+ helpText("First marker of each chromosome stays at 0 cM."),
636
+ actionButton("run_analysis", "Run Analysis",
637
+ class = "btn-primary btn-block", icon = icon("play"))
638
+ )),
639
+ mainPanel(width = 8, wellPanel(
640
+ h3("Parameter Descriptions"),
641
+ tags$ul(
642
+ tags$li(tags$b("Missing Data Threshold:"),
643
+ "Max fraction of missing genotypes per marker."),
644
+ tags$li(tags$b("Recombination Threshold:"),
645
+ "Only marker pairs with r < this value are linked. ",
646
+ "Recommended ≀ 0.45 for F2."),
647
+ tags$li(tags$b("Chi-Square P Threshold:"),
648
+ "Markers with segregation distortion p < threshold are removed."),
649
+ tags$li(tags$b("Cluster Threshold:"),
650
+ "cM cut-off for merging markers into the same linkage group."),
651
+ tags$li(tags$b("Max Total Map Length:"),
652
+ "Upper limit for sum of all chromosome lengths after scaling.")
653
+ ),
654
+ br(), h4("Scaling Summary"), verbatimTextOutput("scaling_summary"),
655
+ br(), h4("Before Scaling"), verbatimTextOutput("before_scaling_stats"),
656
+ br(), h4("After Scaling"), verbatimTextOutput("after_scaling_stats")
657
+ ))
658
+ )
659
+ ),
660
+
661
+ # ── Tab 3: Results ────────────────────────────────────────────────────────
662
+ tabPanel("Results", icon = icon("table"),
663
+ fluidRow(column(12, wellPanel(
664
+ h3("Analysis Results"),
665
+ conditionalPanel("output.analysis_run",
666
+ downloadButton("download_results", "Download Excel Results",
667
+ class = "btn-success"),
668
  br(), br(),
669
  h4("Linkage Map Data"),
670
+ div(style = "overflow-x:auto;", dataTableOutput("result_table")),
671
  h4("Summary Statistics"),
672
  verbatimTextOutput("summary_stats")
673
  ),
674
+ conditionalPanel("!output.analysis_run",
675
+ p("Please upload data and run analysis to see results.",
676
+ style = "color:#888;font-style:italic;text-align:center;padding:40px;")
677
  )
678
+ )))
679
+ ),
680
+
681
+ # ── Tab 4: Plot Customization ──────────────────────────────────────────────
682
+ tabPanel("Plot Customization", icon = icon("palette"),
683
+ sidebarLayout(
684
+ sidebarPanel(width = 4, wellPanel(
685
+ h3("Plot Options"),
686
+ selectInput("color_palette", "Color Palette:",
687
+ choices = c("Set1","Set2","Set3","Paired","Dark2","Accent",
688
+ "Blues","Reds","Greens","Purples","Oranges",
689
+ "Greys","Spectral","RdBu"),
690
+ selected = "Set2"),
691
+ checkboxInput("show_labels", "Show Marker Labels", value = TRUE),
692
+ sliderInput("marker_label_size", "Marker Label Size:",
693
+ min = 2, max = 10, value = 3, step = 0.5),
694
+ sliderInput("plot_width", "Plot Width (px):",
695
+ min = 600, max = 1600, value = 1200, step = 50),
696
+ sliderInput("plot_height", "Plot Height (px):",
697
+ min = 400, max = 1200, value = 700, step = 50)
698
+ )),
699
+ mainPanel(width = 8, wellPanel(
700
+ h3("Color Palette Preview"),
701
+ plotOutput("palette_preview", height = "200px")
702
+ ))
703
+ )
704
+ ),
705
+
706
+ # ── Tab 5: Visualization ──────────────────────────────────────────────────
707
+ tabPanel("Visualization", icon = icon("chart-bar"),
708
+ fluidRow(column(12, wellPanel(
709
+ h3("Chromosome Map Visualization"),
710
+ conditionalPanel("output.analysis_run",
711
+ selectInput("chromosome_select", "Select Chromosomes:",
712
+ choices = NULL, multiple = TRUE),
713
+ downloadButton("download_plot", "Download PNG",
714
+ class = "btn-success"),
715
  br(), br(),
716
  plotOutput("chromosome_plot", height = "auto")
717
  ),
718
+ conditionalPanel("!output.analysis_run",
719
+ p("Please upload data and run analysis to see the map.",
720
+ style = "color:#888;font-style:italic;text-align:center;padding:40px;")
721
+ )
722
+ )))
723
+ ),
724
+
725
+ # ── Tab 6: Help ───────────────────────────────────────────────────────────
726
+ tabPanel("Help", icon = icon("question-circle"),
727
+ wellPanel(
728
+ h3("Application Guide"),
729
+ h4("Input File Format"),
730
+ p("Excel (.xlsx) with:"),
731
+ tags$ul(
732
+ tags$li("Column 1 β€” 'Marker': marker names"),
733
+ tags$li("Column 2 β€” 'Chromosome': chromosome/linkage-group assignment"),
734
+ tags$li("Columns 3+ β€” individual genotype calls: 'a' (AA), 'b' (BB), 'ab' (Aa), '-' (missing)")
735
+ ),
736
+ h4("F2 vs RIL"),
737
+ tags$ul(
738
+ tags$li(tags$b("F2:"), "heterozygotes (ab) are expected and informative; MLE used for r."),
739
+ tags$li(tags$b("RIL:"), "homozygous lines; heterozygotes ignored; Haldane RIL correction applied.")
740
+ ),
741
+ h4("Output"),
742
+ tags$ul(
743
+ tags$li("Excel: Original Data | Recombination Fractions | Linkage Map"),
744
+ tags$li("PNG: high-resolution chromosome map for publication")
745
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
746
  )
747
+ )
748
  ),
749
+
750
+ div(class = "footer",
751
+ "Linkage Map Creator v3.0 | F2 / RIL | Β© 2024 Bioinformatics Tool")
752
  )
753
 
754
+ # ─────────────────────────────────────────────
755
+ # SERVER
756
+ # ─────────────────────────────────────────────
757
+
758
  server <- function(input, output, session) {
759
+
760
+ uploaded_data <- reactiveVal(NULL)
761
+ analysis_results <- reactiveVal(NULL)
762
  pre_scaling_stats <- reactiveVal(NULL)
763
+
764
+ # ── File upload ─────────────────────────────────────────────────────────────
765
  observeEvent(input$file, {
766
  req(input$file)
767
  tryCatch({
768
  df <- read.xlsx(input$file$datapath, sheet = 1)
769
+ if (!all(c("Marker", "Chromosome") %in% colnames(df)))
770
+ stop("Required columns 'Marker' and 'Chromosome' not found.")
771
+ if (ncol(df) < 3 || nrow(df) == 0)
772
+ stop("File contains no genotype columns.")
 
 
 
 
 
 
 
773
  uploaded_data(df)
774
  showNotification("File uploaded successfully!", type = "message")
775
  }, error = function(e) {
776
+ showNotification(paste("Upload error:", e$message), type = "error")
777
  })
778
  })
779
+
780
  output$preview_table <- renderDataTable({
781
  req(uploaded_data())
782
+ datatable(head(uploaded_data(), 10),
783
+ options = list(scrollX = TRUE, dom = "t", pageLength = 10),
784
+ rownames = FALSE)
785
  })
786
+
787
+ # ── Run analysis ────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
788
  observeEvent(input$run_analysis, {
789
  req(uploaded_data())
790
+ showModal(modalDialog(
791
+ title = "Processing",
792
+ paste0("Building linkage map for ", input$population_type,
793
+ " population β€” this may take a few moments…"),
794
+ footer = NULL
795
+ ))
796
  tryCatch({
797
  result <- create_linkage_map(
798
+ df = uploaded_data(),
799
+ population_type = input$population_type,
800
+ missing_threshold = input$missing_threshold,
801
  recombination_threshold = input$recombination_threshold,
802
+ chi_square_threshold = input$chi_square_threshold,
803
+ cluster_threshold = input$cluster_threshold,
804
+ max_total_cm = input$max_total_cm,
805
+ scaling_method = input$scaling_method
806
  )
807
  analysis_results(result)
808
  pre_scaling_stats(result$chrom_lengths_before)
809
+
810
+ chromosomes <- sort(unique(result$linkage_map$Chromosome))
811
+ updateSelectInput(session, "chromosome_select",
812
+ choices = chromosomes,
813
+ selected = chromosomes)
814
  removeModal()
815
+ showNotification("Analysis complete!", type = "message")
816
  }, error = function(e) {
817
  removeModal()
818
+ showNotification(paste("Analysis error:", e$message), type = "error")
819
  })
820
  })
821
+
822
  output$analysis_run <- reactive({ !is.null(analysis_results()) })
823
+ outputOptions(output, "analysis_run", suspendWhenHidden = FALSE)
824
+
825
+ # ── Scaling text outputs ────────────────────────────────────────────────────
826
  output$scaling_summary <- renderText({
827
  req(analysis_results())
828
+ paste0("Scaling Method : ", input$scaling_method,
829
+ "\nMax Total cM : ", input$max_total_cm, " cM")
830
  })
831
+
832
+ fmt_chrom_lengths <- function(df) {
833
+ if (is.null(df) || nrow(df) == 0) return("No data.")
834
+ total <- sum(df$Original_Length, na.rm = TRUE)
835
+ rows <- apply(df, 1, function(x)
836
+ paste0(" Chr ", x[1], ": ", round(as.numeric(x[2]), 2), " cM"))
837
+ paste0("Total : ", round(total, 2), " cM\n", paste(rows, collapse = "\n"))
838
+ }
839
+
840
  output$before_scaling_stats <- renderText({
841
+ req(pre_scaling_stats()); fmt_chrom_lengths(pre_scaling_stats())
 
 
 
 
 
842
  })
 
843
  output$after_scaling_stats <- renderText({
844
+ req(analysis_results()); fmt_chrom_lengths(analysis_results()$chrom_lengths_after)
 
 
 
 
 
845
  })
846
+
847
+ # ── Result table ────────────────────────────────────────────────────────────
848
  output$result_table <- renderDataTable({
849
  req(analysis_results())
850
+ lm <- analysis_results()$linkage_map
851
+ if (nrow(lm) > 0) {
852
+ datatable(lm,
853
+ options = list(scrollX = TRUE, pageLength = 25,
854
+ order = list(list(1, "asc"), list(2, "asc"))),
855
+ rownames = FALSE,
856
+ caption = "Linkage map β€” positions in cM") %>%
857
+ formatRound("Position", 2)
858
+ } else {
859
+ datatable(data.frame(Message = "No positioned markers."),
860
+ options = list(dom = "t"), rownames = FALSE)
861
+ }
862
  })
863
+
864
+ # ── Summary stats ───────────────────────────────────────────────────────────
865
  output$summary_stats <- renderText({
866
  req(analysis_results())
867
+ lm <- analysis_results()$linkage_map
868
+ rec <- analysis_results()$recombination_data
869
+ if (nrow(lm) == 0) return("No positioned markers found.")
870
+
871
+ n_total <- nrow(lm)
872
+ n_pos <- sum(!is.na(lm$Position))
873
+ n_chr <- length(unique(lm$Chromosome))
874
+ chr_lengths <- lm %>% filter(!is.na(Position)) %>%
875
+ group_by(Chromosome) %>%
876
+ summarise(Length = max(Position, na.rm = TRUE), .groups = "drop")
877
+ total_len <- sum(chr_lengths$Length)
878
+ avg_len <- mean(chr_lengths$Length)
879
+
880
+ chr_detail <- paste(
881
+ apply(chr_lengths, 1, function(x)
882
+ paste0(" Chr ", x[1], ": ", round(as.numeric(x[2]), 2), " cM")),
883
+ collapse = "\n")
884
+
885
+ paste0(
886
+ "LINKAGE MAP SUMMARY\n",
887
+ "===================\n",
888
+ "Total markers : ", n_total, "\n",
889
+ "Positioned markers : ", n_pos, "\n",
890
+ "Chromosomes : ", n_chr, "\n",
891
+ "Total map length : ", round(total_len, 2), " cM\n",
892
+ "Avg chromosome length : ", round(avg_len, 2), " cM\n",
893
+ "Marker pairs analysed : ", nrow(rec), "\n\n",
894
+ "CHROMOSOME DETAILS:\n", chr_detail
895
+ )
896
  })
897
+
898
+ # ── Palette preview ─────────────────────────────────────────────────────────
899
+ output$palette_preview <- renderPlot({
900
+ req(input$color_palette)
901
+ cols <- tryCatch(brewer.pal(8, input$color_palette),
902
+ error = function(e) brewer.pal(8, "Set2"))
903
+ n <- length(cols)
904
+ df <- data.frame(x = 1:n, y = 1, col = cols)
905
+ ggplot(df, aes(x, y, fill = I(col))) +
906
+ geom_tile(width = 0.9, height = 0.9) +
907
+ scale_x_continuous(breaks = 1:n, labels = 1:n) +
908
+ labs(title = paste("Preview β€”", input$color_palette)) +
909
+ theme_minimal() +
910
+ theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(),
911
+ axis.title = element_blank(), panel.grid = element_blank(),
912
+ plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))
913
+ }, height = 200)
914
+
915
+ # ── Chromosome plot ─────────────────────────────────────────────────────────
916
  output$chromosome_plot <- renderPlot({
917
  req(analysis_results(), input$chromosome_select)
 
918
  create_multi_chromosome_plot(
919
+ analysis_results()$linkage_map,
920
  input$chromosome_select,
921
+ label_size = input$marker_label_size,
922
+ show_labels = input$show_labels,
923
  color_palette = input$color_palette,
924
+ plot_width = input$plot_width,
925
+ plot_height = input$plot_height
926
  )
927
  }, height = function() input$plot_height)
928
+
929
+ # ── Downloads ────────────────────────────────────────────────────────────────
930
  output$download_results <- downloadHandler(
931
+ filename = function() paste0("linkage_map_", Sys.Date(), ".xlsx"),
932
+ content = function(file) {
933
  req(analysis_results())
934
  wb <- createWorkbook()
935
  addWorksheet(wb, "Original_Data")
936
  addWorksheet(wb, "Recombination_Fractions")
937
  addWorksheet(wb, "Linkage_Map")
938
+ writeData(wb, "Original_Data", analysis_results()$original_data)
939
+ writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
940
+ writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
941
  saveWorkbook(wb, file, overwrite = TRUE)
942
  }
943
  )
944
+
945
  output$download_plot <- downloadHandler(
946
  filename = function() paste0("chromosome_map_", Sys.Date(), ".png"),
947
+ content = function(file) {
948
  req(analysis_results(), input$chromosome_select)
949
+ p <- create_multi_chromosome_plot(
950
+ analysis_results()$linkage_map,
 
951
  input$chromosome_select,
952
+ label_size = input$marker_label_size,
953
+ show_labels = input$show_labels,
954
  color_palette = input$color_palette,
955
+ plot_width = input$plot_width,
956
+ plot_height = input$plot_height
957
  )
958
+ ggsave(file, p,
959
+ width = input$plot_width / 300,
960
+ height = input$plot_height / 300,
961
+ dpi = 300, bg = "white")
962
  }
963
  )
964
  }