International Rice Research Institute commited on
Commit
172e3e3
·
verified ·
1 Parent(s): 0ebcf95

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +703 -45
app.R CHANGED
@@ -1,58 +1,716 @@
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(openxlsx)
3
+ library(igraph)
4
+ library(DT)
5
  library(ggplot2)
6
+ 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("Visualization", icon = icon("chart-bar"), fluidRow(
119
+ column(12, wellPanel(
120
+ h3("Chromosome Map Visualization", icon("image")),
121
+ conditionalPanel(
122
+ condition = "output.analysis_run",
123
+ selectInput("chromosome_select", "Select Chromosomes:", choices = NULL, multiple = TRUE),
124
+ #checkboxInput("show_density", "Show Marker Density", value = FALSE),
125
+ sliderInput("marker_label_size", "Marker Label Size:", min = 2, max = 10, value = 3, step = 0.5),
126
+ sliderInput("plot_height", "Plot Height (px):", min = 400, max = 1200, value = 600, step = 50),
127
+ downloadButton("download_plot", "Download Plot as PNG", class = "btn-success"),
128
+ br(), br(),
129
+ plotOutput("chromosome_plot", height = "auto")
130
+ ),
131
+ conditionalPanel(
132
+ condition = "!output.analysis_run",
133
+ p("Please upload data and run analysis to see visualizations.", style = "color: #888; font-style: italic; text-align: center; padding: 40px;")
134
+ )
135
+ ))
136
+ )),
137
+ tabPanel("Help", icon = icon("question-circle"), wellPanel(
138
+ h3("Application Guide", icon("info-circle")),
139
+ h4("Input File Format:"),
140
+ p("Excel file with the following structure:"),
141
+ tags$ul(
142
+ tags$li("'Marker' column: Marker names"),
143
+ tags$li("'Chromosome' column: Chromosome assignments"),
144
+ tags$li("Subsequent columns: Genotype data for each individual (use 'a', 'b', 'ab', or '-' for missing)")
145
+ ),
146
+ h4("Parameters Explanation:"),
147
+ tags$ul(
148
+ tags$li(tags$b("Missing Data Threshold:"), "Maximum allowed fraction of missing data per marker"),
149
+ tags$li(tags$b("Recombination Threshold:"), "Maximum recombination fraction for linkage"),
150
+ tags$li(tags$b("Chi-Square Threshold:"), "P-value threshold for segregation distortion test"),
151
+ tags$li(tags$b("Cluster Threshold:"), "Distance threshold for marker grouping"),
152
+ tags$li(tags$b("Maximum Total Map Length:"), "Sets the upper limit for the sum of all chromosome lengths"),
153
+ tags$li(tags$b("Proportional Scaling:"), "Each chromosome is scaled proportionally to its original length"),
154
+ tags$li(tags$b("Uniform Scaling:"), "All chromosomes are scaled by the same factor")
155
+ ),
156
+ h4("Population Types:"),
157
+ tags$ul(
158
+ tags$li(tags$b("RIL:"), "Recombinant Inbred Lines"),
159
+ tags$li(tags$b("F2:"), "Second filial generation")
160
+ ),
161
+ h4("Output:"),
162
+ p("The application generates:"),
163
+ tags$ul(
164
+ tags$li("Excel file with three sheets: Original Data, Recombination Fractions, and Linkage Map"),
165
+ tags$li("Interactive chromosome visualization with customizable appearance"),
166
+ tags$li("High-resolution PNG export for publications and presentations")
167
+ )
168
+ ))
169
+ ),
170
+ div(class = "footer", "Linkage Map Creator v2.0 | Created with Shiny | © 2023 Bioinformatics Tool")
171
  )
172
 
173
+ # Server logic
174
  server <- function(input, output, session) {
175
+ uploaded_data <- reactiveVal(NULL)
176
+ analysis_results <- reactiveVal(NULL)
177
+ pre_scaling_stats <- reactiveVal(NULL)
178
+
179
+ observeEvent(input$file, {
180
+ req(input$file)
181
+ tryCatch({
182
+ df <- read.xlsx(input$file$datapath, sheet = 1)
183
+ required_columns <- c('Marker', 'Chromosome')
184
+ if (!all(required_columns %in% colnames(df))) {
185
+ stop("Required columns ('Marker' and 'Chromosome') not found in the uploaded file.")
186
+ }
187
+ if (ncol(df) < 3 || nrow(df) == 0) {
188
+ stop("Uploaded file contains no valid genotype data.")
189
+ }
190
+ genotype_data <- df[, 3:ncol(df)]
191
+ if (all(genotype_data == '-', na.rm = TRUE)) {
192
+ stop("Uploaded file contains no valid genotype data (all missing).")
193
+ }
194
+ uploaded_data(df)
195
+ showNotification("File uploaded successfully!", type = "message")
196
+ }, error = function(e) {
197
+ showNotification(paste("Error:", e$message), type = "error")
198
+ })
199
  })
200
+
201
+ output$preview_table <- renderDataTable({
202
+ req(uploaded_data())
203
+ datatable(head(uploaded_data(), 10), options = list(scrollX = TRUE, dom = 't', pageLength = 10), rownames = FALSE)
204
+ })
205
+
206
+ calculate_recombination <- function(population_type, genotype1, genotype2) {
207
+ valid_pairs <- data.frame(g1 = genotype1, g2 = genotype2)
208
+ valid_pairs <- valid_pairs[!(genotype1 == '-' | genotype2 == '-'), ]
209
+ if (nrow(valid_pairs) == 0) {
210
+ return(NA)
211
+ }
212
+ recombination_events <- sum(valid_pairs$g1 != valid_pairs$g2)
213
+ if (population_type == 'RIL') {
214
+ recombination_fraction <- recombination_events / nrow(valid_pairs)
215
+ rf_ril <- 1 / (2 * (1 + 2 * recombination_fraction))
216
+ return(rf_ril)
217
+ } else if (population_type == 'F2') {
218
+ recombination_fraction_F2 <- recombination_events / nrow(valid_pairs)
219
+ return(recombination_fraction_F2)
220
+ } else {
221
+ stop("Invalid population type. Use 'RIL' or 'F2'.")
222
+ }
223
+ }
224
+
225
+ calculate_cM_kosambi <- function(recombination_fraction) {
226
+ if (is.na(recombination_fraction)) return(NA)
227
+ if (recombination_fraction >= 0.5) return(50)
228
+ if (recombination_fraction <= 0) return(0)
229
+ return(25 * log((1 + 2 * recombination_fraction) / (1 - 2 * recombination_fraction)))
230
+ }
231
+
232
+ correct_errors_and_impute_missing <- function(df) {
233
+ df[df == '-'] <- NA
234
+ if (ncol(df) > 2) {
235
+ na_fractions <- colMeans(is.na(df[, 3:ncol(df)]))
236
+ valid_individuals <- na_fractions < 1
237
+ df <- df[, c(TRUE, TRUE, valid_individuals)]
238
+ }
239
+ if (ncol(df) > 2) {
240
+ df[, 3:ncol(df)] <- lapply(df[, 3:ncol(df)], function(x) {
241
+ if (all(is.na(x))) {
242
+ return(x)
243
+ }
244
+ mode_val <- names(which.max(table(x[!is.na(x)])))
245
+ if (length(mode_val) == 0 || is.null(mode_val)) {
246
+ mode_val <- 'a'
247
+ }
248
+ x[is.na(x)] <- mode_val
249
+ return(x)
250
+ })
251
+ }
252
+ return(df)
253
+ }
254
+
255
+ quality_control <- function(df, missing_threshold = 0.1) {
256
+ if (ncol(df) < 3 || nrow(df) == 0) {
257
+ return(df[0, ])
258
+ }
259
+ missing_data_fraction <- rowMeans(is.na(df[, 3:ncol(df)]))
260
+ missing_data_fraction[is.na(missing_data_fraction)] <- 1
261
+ return(df[missing_data_fraction <= missing_threshold, ])
262
+ }
263
+
264
+ perform_chi_square_test <- function(genotype_data, population_type, chi_square_threshold = 0.05) {
265
+ if (nrow(genotype_data) == 0 || ncol(genotype_data) == 0) {
266
+ return(logical(0))
267
+ }
268
+ if (population_type == 'RIL') expected_ratio <- c(0.5, 0.5)
269
+ else if (population_type == 'F2') expected_ratio <- c(0.25, 0.5, 0.25)
270
+ else stop("Invalid population type. Use 'RIL' or 'F2'.")
271
+ chi_square_results <- apply(genotype_data, 1, function(marker) {
272
+ observed <- table(factor(marker, levels = c('a', 'b', 'ab')))
273
+ if (length(observed) != length(expected_ratio)) return(1)
274
+ expected <- expected_ratio * sum(observed)
275
+ chi_square_stat <- sum((observed - expected)^2 / expected)
276
+ p_value <- pchisq(chi_square_stat, df = length(observed) - 1, lower.tail = FALSE)
277
+ return(p_value)
278
+ })
279
+ non_distorted_markers <- chi_square_results > chi_square_threshold
280
+ return(non_distorted_markers)
281
+ }
282
+
283
+ group_and_order_markers <- function(map_distance_df, threshold = 40) {
284
+ markers <- unique(c(map_distance_df$Marker1, map_distance_df$Marker2))
285
+ if (nrow(map_distance_df) == 0 || length(markers) == 0) {
286
+ return(data.frame(Marker = character(0), Group = integer(0), Order = integer(0)))
287
+ }
288
+ if (length(markers) <= 1) return(data.frame(Marker = markers, Group = 1, Order = seq_along(markers)))
289
+ distance_matrix <- matrix(Inf, nrow = length(markers), ncol = length(markers))
290
+ rownames(distance_matrix) <- markers
291
+ colnames(distance_matrix) <- markers
292
+ for (i in 1:nrow(map_distance_df)) {
293
+ marker1 <- as.character(map_distance_df[i, 'Marker1'])
294
+ marker2 <- as.character(map_distance_df[i, 'Marker2'])
295
+ distance <- map_distance_df[i, 'MapDistance_cM']
296
+ idx1 <- which(markers == marker1)
297
+ idx2 <- which(markers == marker2)
298
+ if (length(idx1) > 0 && length(idx2) > 0) {
299
+ distance_matrix[idx1, idx2] <- distance
300
+ distance_matrix[idx2, idx1] <- distance
301
+ }
302
+ }
303
+ diag(distance_matrix) <- 0
304
+ max_finite <- max(distance_matrix[is.finite(distance_matrix)])
305
+ if (!is.finite(max_finite)) max_finite <- 100
306
+ distance_matrix[is.infinite(distance_matrix)] <- max_finite * 1.5
307
+ dist_obj <- as.dist(distance_matrix)
308
+ tryCatch({
309
+ clustering <- hclust(dist_obj, method = 'average')
310
+ if (any(diff(clustering$height) < 0)) clustering$height <- sort(clustering$height)
311
+ labels <- cutree(clustering, h = threshold)
312
+ grouped_markers <- data.frame(Marker = markers, Group = labels)
313
+ ordered_markers <- markers[clustering$order]
314
+ grouped_markers$Order <- match(grouped_markers$Marker, ordered_markers)
315
+ return(grouped_markers)
316
+ }, error = function(e) {
317
+ warning("Hierarchical clustering failed: ", e$message)
318
+ return(data.frame(Marker = markers, Group = seq_along(markers), Order = seq_along(markers)))
319
+ })
320
+ }
321
+
322
+ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
323
+ positioned_markers <- linkage_map[!is.na(linkage_map$Position), ]
324
+ if (nrow(positioned_markers) == 0) {
325
+ return(list(scaled_map = linkage_map, chrom_lengths_before = data.frame(), chrom_lengths_after = data.frame()))
326
+ }
327
+ chrom_lengths_before <- positioned_markers %>% group_by(Chromosome) %>% summarise(Original_Length = max(Position, na.rm = TRUE), .groups = 'drop')
328
+ total_current_length <- sum(chrom_lengths_before$Original_Length, na.rm = TRUE)
329
+ scaled_map <- linkage_map
330
+ if (total_current_length <= max_total_cm || total_current_length == 0) {
331
+ return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_before))
332
+ }
333
+ if (method == "proportional") {
334
+ scaling_factor <- max_total_cm / total_current_length
335
+ chrom_lengths_before$Scaling_Factor <- scaling_factor
336
+ } else if (method == "uniform") {
337
+ n_chromosomes <- nrow(chrom_lengths_before)
338
+ if (n_chromosomes == 0) {
339
+ return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_before))
340
+ }
341
+ target_per_chromosome <- max_total_cm / n_chromosomes
342
+ chrom_lengths_before$Scaling_Factor <- ifelse(chrom_lengths_before$Original_Length > 0, target_per_chromosome / chrom_lengths_before$Original_Length, 1)
343
+ }
344
+ for (chrom in chrom_lengths_before$Chromosome) {
345
+ scaling_factor <- chrom_lengths_before$Scaling_Factor[chrom_lengths_before$Chromosome == chrom]
346
+ if (is.na(scaling_factor) || !is.finite(scaling_factor)) next
347
+ chrom_indices <- which(scaled_map$Chromosome == chrom & !is.na(scaled_map$Position))
348
+ if (length(chrom_indices) > 0) {
349
+ min_pos <- min(scaled_map$Position[chrom_indices], na.rm = TRUE)
350
+ scaled_map$Position[chrom_indices] <- (scaled_map$Position[chrom_indices] - min_pos) * scaling_factor
351
+ }
352
+ }
353
+ chrom_lengths_after <- scaled_map %>% filter(!is.na(Position)) %>% group_by(Chromosome) %>% summarise(Original_Length = max(Position, na.rm = TRUE), .groups = 'drop')
354
+ return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_after))
355
+ }
356
+
357
+ 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") {
358
+ df <- correct_errors_and_impute_missing(df)
359
+ df <- quality_control(df, missing_threshold)
360
+ if (nrow(df) == 0 || ncol(df) < 3) {
361
+ 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()))
362
+ }
363
+ genotype_data <- df[, 3:ncol(df)]
364
+ non_distorted_markers <- perform_chi_square_test(genotype_data, population_type, chi_square_threshold)
365
+ df <- df[non_distorted_markers, ]
366
+ markers <- unique(df$Marker)
367
+ 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()))
368
+ G <- graph(edges = NULL, n = length(markers), directed = FALSE)
369
+ V(G)$name <- markers
370
+ map_distance_df <- data.frame()
371
+ chromosomes <- unique(df$Chromosome)
372
+ for (chromosome in chromosomes) {
373
+ markers_on_chromosome <- subset(df, Chromosome == chromosome)
374
+ if (nrow(markers_on_chromosome) < 2) next
375
+ marker_combinations <- combn(markers_on_chromosome$Marker, 2, simplify = TRUE)
376
+ for (i in 1:ncol(marker_combinations)) {
377
+ marker1 <- as.character(marker_combinations[1, i])
378
+ marker2 <- as.character(marker_combinations[2, i])
379
+ genotype1 <- as.character(markers_on_chromosome[markers_on_chromosome$Marker == marker1, 3:ncol(df)])
380
+ genotype2 <- as.character(markers_on_chromosome[markers_on_chromosome$Marker == marker2, 3:ncol(df)])
381
+ recombination_fraction <- calculate_recombination(population_type, genotype1, genotype2)
382
+ if (!is.na(recombination_fraction) && recombination_fraction < recombination_threshold) {
383
+ map_distance_cM <- calculate_cM_kosambi(recombination_fraction)
384
+ G <- add_edges(G, edges = c(marker1, marker2), weight = map_distance_cM)
385
+ new_row <- data.frame(Marker1 = marker1, Marker2 = marker2, RecombinationFraction = recombination_fraction, MapDistance_cM = map_distance_cM)
386
+ map_distance_df <- rbind(map_distance_df, new_row)
387
+ }
388
+ }
389
+ }
390
+ 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()))
391
+ grouped_markers <- group_and_order_markers(map_distance_df, threshold)
392
+ positions <- list()
393
+ for (chromosome in chromosomes) {
394
+ markers_on_chromosome <- subset(df, Chromosome == chromosome)$Marker
395
+ if (length(markers_on_chromosome) == 0) next
396
+ chrom_grouped <- grouped_markers[grouped_markers$Marker %in% markers_on_chromosome, ]
397
+ if (nrow(chrom_grouped) == 0) {
398
+ ordered_markers <- markers_on_chromosome
399
+ } else {
400
+ chrom_grouped <- chrom_grouped[order(chrom_grouped$Order), ]
401
+ ordered_markers <- chrom_grouped$Marker
402
+ }
403
+ if (length(ordered_markers) > 0) {
404
+ positions[[ordered_markers[1]]] <- 0
405
+ if (length(ordered_markers) > 1) {
406
+ for (i in 2:length(ordered_markers)) {
407
+ marker <- ordered_markers[i]
408
+ prev_marker <- ordered_markers[i-1]
409
+ edge_id <- get.edge.ids(G, c(marker, prev_marker))
410
+ if (edge_id != 0 && length(edge_id) > 0) {
411
+ distance <- edge_attr(G, 'weight', edge_id)
412
+ } else {
413
+ distance <- 1
414
+ }
415
+ positions[[marker]] <- positions[[prev_marker]] + distance
416
+ }
417
+ }
418
+ }
419
+ }
420
+ if (length(positions) == 0) {
421
+ 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()))
422
+ }
423
+ positions_df <- data.frame(Marker = names(positions), Position = unlist(positions))
424
+ linkage_map <- merge(df[, c('Marker', 'Chromosome')], positions_df, by = "Marker", all.x = TRUE)
425
+ linkage_map <- linkage_map[order(linkage_map$Chromosome, linkage_map$Position), ]
426
+ scaled_results <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
427
+ 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))
428
+ }
429
+
430
+ create_multi_chromosome_plot <- function(linkage_data, selected_chromosomes,
431
+ label_size = 3, show_density = FALSE,
432
+ plot_width = 1200, plot_height = 800,
433
+ chrom_width = 0.5, point_size = 2,
434
+ chrom_spacing = 5.0) {
435
+ library(ggplot2)
436
+ library(dplyr)
437
+ library(RColorBrewer)
438
+
439
+ # Filter data
440
+ plot_data <- linkage_data %>%
441
+ filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
442
+ arrange(Chromosome, Position)
443
+
444
+ if (nrow(plot_data) == 0) {
445
+ return(ggplot() +
446
+ annotate("text", x = 0.5, y = 0.5,
447
+ label = "No valid marker positions available",
448
+ size = 6, color = "red") +
449
+ theme_void())
450
+ }
451
+
452
+ # Chromosome summary
453
+ chrom_stats <- plot_data %>%
454
+ group_by(Chromosome) %>%
455
+ summarise(
456
+ max_pos = max(Position),
457
+ min_pos = min(Position),
458
+ num_markers = n(),
459
+ .groups = "drop"
460
+ ) %>%
461
+ arrange(Chromosome) %>%
462
+ mutate(
463
+ chrom_x = seq(1, by = chrom_spacing, length.out = n()),
464
+ chrom_center = chrom_x
465
+ )
466
+
467
+ plot_data <- plot_data %>%
468
+ left_join(chrom_stats %>% select(Chromosome, chrom_x, chrom_center), by = "Chromosome")
469
+
470
+ # Distinct colors
471
+ n_chrom <- nrow(chrom_stats)
472
+ chrom_colors <- if (n_chrom <= 8) {
473
+ brewer.pal(max(3, n_chrom), "Set2")
474
+ } else {
475
+ colorRampPalette(brewer.pal(20, "Set2"))(n_chrom)
476
+ }
477
+
478
+ # Build plot
479
+ p <- ggplot() +
480
+
481
+ # Chromosome lines (vertical lines instead of rectangles)
482
+ geom_segment(
483
+ data = chrom_stats,
484
+ aes(x = chrom_center, xend = chrom_center,
485
+ y = min_pos, yend = max_pos,
486
+ color = as.factor(Chromosome)),
487
+ size = chrom_width * 20, # Thicker line for chromosome
488
+ alpha = 0.7,
489
+ lineend = "round"
490
+ ) +
491
+
492
+ # Marker points (instead of ticks)
493
+ geom_point(
494
+ data = plot_data,
495
+ aes(x = chrom_center, y = Position,
496
+ color = as.factor(Chromosome)),
497
+ size = point_size,
498
+ alpha = 0.8
499
+ ) +
500
+
501
+ # Optional: Add marker names if available
502
+ {if("Marker" %in% names(plot_data))
503
+ geom_text(
504
+ data = plot_data,
505
+ aes(x = chrom_center + chrom_width * 0.6,
506
+ y = Position,
507
+ label = Marker,
508
+ color = as.factor(Chromosome)),
509
+ size = label_size,
510
+ hjust = 0,
511
+ vjust = 0.5,
512
+ check_overlap = TRUE,
513
+ alpha = 0.7
514
  )
515
+ } +
516
+
517
+ # Chromosome labels at the top
518
+ geom_text(
519
+ data = chrom_stats,
520
+ aes(x = chrom_center, y = max_pos * 1.05,
521
+ label = paste0("Chr", Chromosome),
522
+ color = as.factor(Chromosome)),
523
+ size = label_size + 1,
524
+ fontface = "bold",
525
+ vjust = 0
526
+ ) +
527
+
528
+ scale_color_manual(values = chrom_colors) +
529
+ scale_fill_manual(values = chrom_colors) +
530
+
531
+ scale_y_reverse(
532
+ name = "Genetic Position (cM)",
533
+ expand = expansion(mult = c(0.05, 0.1)) # More space at top for labels
534
+ ) +
535
+
536
+ scale_x_continuous(
537
+ breaks = chrom_stats$chrom_center,
538
+ labels = chrom_stats$Chromosome,
539
+ name = "Chromosome",
540
+ expand = expansion(mult = 0.1)
541
+ ) +
542
+
543
+ theme_minimal() +
544
+ theme(
545
+ legend.position = "none",
546
+ axis.text.y = element_text(size = 10, color = "black"),
547
+ axis.text.x = element_text(size = 12, angle = 0, hjust = 0.5, face = "bold"),
548
+ axis.title.y = element_text(size = 12, face = "bold", margin = margin(r = 10)),
549
+ axis.title.x = element_text(size = 12, face = "bold", margin = margin(t = 10)),
550
+ panel.grid.major.x = element_blank(),
551
+ panel.grid.minor.x = element_blank(),
552
+ panel.grid.major.y = element_line(color = "grey90", size = 0.2),
553
+ panel.grid.minor.y = element_line(color = "grey95", size = 0.1),
554
+ plot.margin = margin(20, 20, 20, 20)
555
+ )
556
+
557
+ # Add density plot if requested
558
+ if (show_density) {
559
+ p <- p +
560
+ geom_density_2d_filled(
561
+ data = plot_data,
562
+ aes(x = chrom_center, y = Position),
563
+ alpha = 0.2,
564
+ show.legend = FALSE
565
  )
566
+ }
567
+
568
+ return(p)
569
+ }
570
+
571
+
572
+ create_single_chromosome_plot <- function(linkage_data, selected_chromosome, label_size = 3) {
573
+ plot_data <- linkage_data %>% filter(Chromosome == selected_chromosome, !is.na(Position)) %>% arrange(Position)
574
+ 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())
575
+ p <- ggplot(plot_data, aes(x = Position, y = 1)) +
576
+ geom_segment(aes(x = 0, xend = max(Position, na.rm = TRUE), y = 1, yend = 1), color = "darkblue", size = 2) +
577
+ geom_point(aes(x = Position, y = 1), color = "red", size = 3) +
578
+ geom_text_repel(aes(label = Marker), size = label_size, box.padding = 0.5, segment.color = "gray") +
579
+ labs(title = paste("Chromosome", selected_chromosome, "Linkage Map"), x = "Position (cM)", y = "") +
580
+ theme_minimal() +
581
+ theme(
582
+ axis.text.y = element_blank(),
583
+ axis.ticks.y = element_blank(),
584
+ panel.grid.major.y = element_blank(),
585
+ panel.grid.minor.y = element_blank(),
586
+ plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
587
+ axis.title.x = element_text(size = 12),
588
+ axis.text.x = element_text(size = 10)
589
+ )
590
+ return(p)
591
+ }
592
+
593
+ observeEvent(input$run_analysis, {
594
+ req(uploaded_data())
595
+ showModal(modalDialog(title = "Processing", "Creating and scaling linkage map... This may take a few moments.", footer = NULL))
596
+ tryCatch({
597
+ result <- create_linkage_map(
598
+ df = uploaded_data(),
599
+ population_type = input$population_type,
600
+ missing_threshold = input$missing_threshold,
601
+ recombination_threshold = input$recombination_threshold,
602
+ chi_square_threshold = input$chi_square_threshold,
603
+ threshold = input$cluster_threshold,
604
+ max_total_cm = input$max_total_cm,
605
+ scaling_method = input$scaling_method
606
+ )
607
+ analysis_results(result)
608
+ pre_scaling_stats(result$chrom_lengths_before)
609
+ chromosomes <- unique(result$linkage_map$Chromosome)
610
+ updateSelectInput(session, "chromosome_select", choices = chromosomes, selected = if(length(chromosomes) > 0) chromosomes[1:2] else NULL)
611
+ removeModal()
612
+ showNotification("Analysis and scaling completed successfully!", type = "message")
613
+ }, error = function(e) {
614
+ removeModal()
615
+ showNotification(paste("Error in analysis:", e$message), type = "error")
616
+ })
617
+ })
618
+
619
+ output$analysis_run <- reactive({ !is.null(analysis_results()) })
620
+ outputOptions(output, 'analysis_run', suspendWhenHidden = FALSE)
621
+
622
+ output$scaling_summary <- renderText({
623
+ req(analysis_results())
624
+ paste0("SCALING SUMMARY\n==================\nScaling Method: ", input$scaling_method, "\nMaximum Total Map Length: ", input$max_total_cm, " cM\n")
625
+ })
626
+
627
+ output$before_scaling_stats <- renderText({
628
+ req(analysis_results(), pre_scaling_stats())
629
+ chrom_lengths_before <- pre_scaling_stats()
630
+ if (nrow(chrom_lengths_before) > 0) {
631
+ total_length <- sum(chrom_lengths_before$Original_Length, na.rm = TRUE)
632
+ 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"))
633
+ } else "No chromosome length data available before scaling."
634
+ })
635
+
636
+ output$after_scaling_stats <- renderText({
637
+ req(analysis_results())
638
+ chrom_lengths_after <- analysis_results()$chrom_lengths_after
639
+ if (nrow(chrom_lengths_after) > 0) {
640
+ total_length <- sum(chrom_lengths_after$Original_Length, na.rm = TRUE)
641
+ 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"))
642
+ } else "No chromosome length data available after scaling."
643
+ })
644
+
645
+ output$result_table <- renderDataTable({
646
+ req(analysis_results())
647
+ linkage_map <- analysis_results()$linkage_map
648
+ if (nrow(linkage_map) > 0) {
649
+ 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)
650
+ } else datatable(data.frame(Message = "No linkage map data available"), options = list(dom = 't'), rownames = FALSE)
651
+ })
652
+
653
+ output$summary_stats <- renderText({
654
+ req(analysis_results())
655
+ linkage_map <- analysis_results()$linkage_map
656
+ recomb_data <- analysis_results()$recombination_data
657
+ if (nrow(linkage_map) > 0) {
658
+ n_markers <- nrow(linkage_map)
659
+ n_chromosomes <- length(unique(linkage_map$Chromosome))
660
+ n_positioned <- sum(!is.na(linkage_map$Position))
661
+ chrom_lengths <- linkage_map %>% filter(!is.na(Position)) %>% group_by(Chromosome) %>% summarise(Length = max(Position, na.rm = TRUE), .groups = 'drop')
662
+ total_length <- sum(chrom_lengths$Length, na.rm = TRUE)
663
+ avg_length <- mean(chrom_lengths$Length, na.rm = TRUE)
664
+ 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"))
665
+ } else "No summary statistics available - no positioned markers found."
666
+ })
667
+
668
+ output$chromosome_plot <- renderPlot({
669
+ req(analysis_results(), input$chromosome_select)
670
+ linkage_map <- analysis_results()$linkage_map
671
+ create_multi_chromosome_plot(
672
+ linkage_map,
673
+ input$chromosome_select,
674
+ label_size = input$marker_label_size,
675
+ #show_density = input$show_density,
676
+ plot_width = input$plot_width,
677
+ plot_height = input$plot_height
678
+ )
679
+ }, height = function() input$plot_height)
680
+
681
+ output$download_results <- downloadHandler(
682
+ filename = function() paste0("linkage_map_results_", Sys.Date(), ".xlsx"),
683
+ content = function(file) {
684
+ req(analysis_results())
685
+ wb <- createWorkbook()
686
+ addWorksheet(wb, "Original_Data")
687
+ addWorksheet(wb, "Recombination_Fractions")
688
+ addWorksheet(wb, "Linkage_Map")
689
+ writeData(wb, "Original_Data", analysis_results()$original_data)
690
+ writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
691
+ writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
692
+ saveWorkbook(wb, file, overwrite = TRUE)
693
+ }
694
+ )
695
+
696
+ output$download_plot <- downloadHandler(
697
+ filename = function() paste0("chromosome_map_", Sys.Date(), ".png"),
698
+ content = function(file) {
699
+ req(analysis_results(), input$chromosome_select)
700
+ linkage_map <- analysis_results()$linkage_map
701
+ plot <- create_multi_chromosome_plot(
702
+ linkage_map,
703
+ input$chromosome_select,
704
+ label_size = input$marker_label_size,
705
+ show_density = input$show_density,
706
+ plot_width = input$plot_width,
707
+ plot_height = input$plot_height
708
+ )
709
+ width_inches <- input$plot_width / 300
710
+ height_inches <- input$plot_height / 300
711
+ ggsave(file, plot, width = width_inches, height = height_inches, dpi = 300, bg = "white")
712
+ }
713
  )
714
  }
715
 
716
+ shinyApp(ui = ui, server = server)