International Rice Research Institute
Update app.R
172e3e3 verified
Raw History Blame
35.2 kB
library(shiny)
library(openxlsx)
library(igraph)
library(DT)
library(ggplot2)
library(dplyr)
library(RColorBrewer)
library(ggrepel)
# UI definition
ui <- fluidPage(
tags$head(
tags$style(HTML("
body { background-color: #ffffff; color: #333333; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
.navbar { background-color: #1E3A8A !important; border-bottom: 2px solid #1E40AF; }
.navbar-brand { color: #ffffff !important; font-weight: bold; }
.nav-tabs { background-color: #1E3A8A; border-bottom: 2px solid #1E40AF; }
.nav-tabs > li > a { color: #cccccc !important; background-color: #1E3A8A; border: 1px solid #1E40AF; margin-right: 5px; }
.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; }
.nav-tabs > li > a:hover { background-color: #2563EB; color: #ffffff !important; }
.well { background-color: #EFF6FF; border: 1px solid #BFDBFE; color: #333333; }
.form-control { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
.form-control:focus { background-color: #FFFFFF; color: #333333; border-color: #3B82F6; box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25); }
.btn { border: 1px solid; }
.btn-default { background-color: #3B82F6; color: #ffffff; border-color: #2563EB; }
.btn-default:hover { background-color: #2563EB; color: #ffffff; border-color: #1D4ED8; }
.btn-primary { background-color: #1D4ED8; color: #ffffff; border-color: #1E40AF; }
.btn-primary:hover { background-color: #1E40AF; color: #ffffff; border-color: #1E3A8A; }
.btn-success { background-color: #059669; color: #ffffff; border-color: #047857; }
.btn-success:hover { background-color: #047857; color: #ffffff; border-color: #065F46; }
.btn-info { background-color: #0891B2; color: #ffffff; border-color: #0E7490; }
.btn-info:hover { background-color: #0E7490; color: #ffffff; border-color: #155E75; }
.irs-bar, .irs-bar-edge { background: #3B82F6; border: 1px solid #2563EB; }
.irs-single, .irs-from, .irs-to { background: #2563EB; color: #ffffff; }
.shiny-input-container { color: #333333; }
.help-block { color: #666666; }
.dataTables_wrapper { color: #333333; }
table.dataTable { border: 1px solid #BFDBFE; }
.dataTables_filter input { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
.selectize-input { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
.selectize-dropdown { background-color: #FFFFFF; color: #333333; border: 1px solid #93C5FD; }
.selectize-dropdown .active { background-color: #DBEAFE; color: #333333; }
.footer { position: fixed; bottom: 0; width: 100%; background-color: #1E3A8A; color: #cccccc; text-align: center; padding: 10px; border-top: 1px solid #1E40AF; }
.tab-content { color: #666666; }
.tab-content h3, .tab-content h4 { color: #1E3A8A; }
.tab-content ul, .tab-content li, .tab-content p { color: #666666; }
"))
),
navbarPage(
"Linkage Map Creator",
id = "nav",
tabPanel("Data Upload", icon = icon("upload"), sidebarLayout(
sidebarPanel(width = 4, wellPanel(
h3("Upload Data", icon("file-import")),
fileInput("file", "Choose Excel File", accept = c(".xlsx", ".xls"), buttonLabel = "Browse...", placeholder = "No file selected"),
selectInput("population_type", "Population Type:", choices = c("RIL" = "RIL", "F2" = "F2"), selected = "RIL"),
helpText("Note: File must contain 'Marker' and 'Chromosome' columns with genotype data in subsequent columns.")
)),
mainPanel(width = 8, wellPanel(
h3("Data Preview"),
div(style = "overflow-x: auto;", dataTableOutput("preview_table"))
))
)),
tabPanel("Parameters", icon = icon("sliders-h"), sidebarLayout(
sidebarPanel(width = 4, wellPanel(
h3("Analysis Parameters", icon("cog")),
sliderInput("missing_threshold", "Missing Data Threshold:", min = 0, max = 1, value = 0.1, step = 0.01),
sliderInput("recombination_threshold", "Recombination Threshold:", min = 0, max = 1, value = 0.5, step = 0.01),
sliderInput("chi_square_threshold", "Chi-Square Threshold:", min = 0, max = 0.2, value = 0.05, step = 0.01),
sliderInput("cluster_threshold", "Cluster Threshold:", min = 10, max = 100, value = 40, step = 5),
h4("Map Scaling Options", icon("expand")),
numericInput("max_total_cm", "Maximum Total Map Length (cM):", min = 100, max = 5000, value = 1500, step = 100),
selectInput("scaling_method", "Scaling Method:", choices = c("Proportional" = "proportional", "Uniform" = "uniform"), selected = "proportional"),
helpText("Note: First marker of each chromosome will remain at 0 cM."),
actionButton("run_analysis", "Run Analysis", class = "btn-primary btn-block", icon = icon("play"))
)),
mainPanel(width = 8, wellPanel(
h3("Parameter Descriptions"),
tags$ul(
tags$li(tags$b("Missing Data Threshold:"), "Maximum allowed fraction of missing data per marker"),
tags$li(tags$b("Recombination Threshold:"), "Maximum recombination fraction for linkage"),
tags$li(tags$b("Chi-Square Threshold:"), "P-value threshold for segregation distortion"),
tags$li(tags$b("Cluster Threshold:"), "Distance threshold for marker grouping"),
tags$li(tags$b("Maximum Total Map Length:"), "Sets the upper limit for the sum of all chromosome lengths"),
tags$li(tags$b("Proportional Scaling:"), "Each chromosome is scaled proportionally to its original length"),
tags$li(tags$b("Uniform Scaling:"), "All chromosomes are scaled by the same factor")
),
br(),
h4("Scaling Summary"),
verbatimTextOutput("scaling_summary"),
br(),
h4("Before Scaling"),
verbatimTextOutput("before_scaling_stats"),
br(),
h4("After Scaling"),
verbatimTextOutput("after_scaling_stats")
))
)),
tabPanel("Results", icon = icon("table"), fluidRow(
column(12, wellPanel(
h3("Analysis Results", icon("chart-bar")),
conditionalPanel(
condition = "output.analysis_run",
downloadButton("download_results", "Download Excel Results", class = "btn-success"),
br(), br(),
h4("Linkage Map Data"),
div(style = "overflow-x: auto;", dataTableOutput("result_table")),
h4("Summary Statistics"),
verbatimTextOutput("summary_stats")
),
conditionalPanel(
condition = "!output.analysis_run",
p("Please upload data and run analysis to see results.", style = "color: #888; font-style: italic; text-align: center; padding: 40px;")
)
))
)),
tabPanel("Visualization", icon = icon("chart-bar"), fluidRow(
column(12, wellPanel(
h3("Chromosome Map Visualization", icon("image")),
conditionalPanel(
condition = "output.analysis_run",
selectInput("chromosome_select", "Select Chromosomes:", choices = NULL, multiple = TRUE),
#checkboxInput("show_density", "Show Marker Density", value = FALSE),
sliderInput("marker_label_size", "Marker Label Size:", min = 2, max = 10, value = 3, step = 0.5),
sliderInput("plot_height", "Plot Height (px):", min = 400, max = 1200, value = 600, step = 50),
downloadButton("download_plot", "Download Plot as PNG", class = "btn-success"),
br(), br(),
plotOutput("chromosome_plot", height = "auto")
),
conditionalPanel(
condition = "!output.analysis_run",
p("Please upload data and run analysis to see visualizations.", style = "color: #888; font-style: italic; text-align: center; padding: 40px;")
)
))
)),
tabPanel("Help", icon = icon("question-circle"), wellPanel(
h3("Application Guide", icon("info-circle")),
h4("Input File Format:"),
p("Excel file with the following structure:"),
tags$ul(
tags$li("'Marker' column: Marker names"),
tags$li("'Chromosome' column: Chromosome assignments"),
tags$li("Subsequent columns: Genotype data for each individual (use 'a', 'b', 'ab', or '-' for missing)")
),
h4("Parameters Explanation:"),
tags$ul(
tags$li(tags$b("Missing Data Threshold:"), "Maximum allowed fraction of missing data per marker"),
tags$li(tags$b("Recombination Threshold:"), "Maximum recombination fraction for linkage"),
tags$li(tags$b("Chi-Square Threshold:"), "P-value threshold for segregation distortion test"),
tags$li(tags$b("Cluster Threshold:"), "Distance threshold for marker grouping"),
tags$li(tags$b("Maximum Total Map Length:"), "Sets the upper limit for the sum of all chromosome lengths"),
tags$li(tags$b("Proportional Scaling:"), "Each chromosome is scaled proportionally to its original length"),
tags$li(tags$b("Uniform Scaling:"), "All chromosomes are scaled by the same factor")
),
h4("Population Types:"),
tags$ul(
tags$li(tags$b("RIL:"), "Recombinant Inbred Lines"),
tags$li(tags$b("F2:"), "Second filial generation")
),
h4("Output:"),
p("The application generates:"),
tags$ul(
tags$li("Excel file with three sheets: Original Data, Recombination Fractions, and Linkage Map"),
tags$li("Interactive chromosome visualization with customizable appearance"),
tags$li("High-resolution PNG export for publications and presentations")
)
))
),
div(class = "footer", "Linkage Map Creator v2.0 | Created with Shiny | © 2023 Bioinformatics Tool")
)
# Server logic
server <- function(input, output, session) {
uploaded_data <- reactiveVal(NULL)
analysis_results <- reactiveVal(NULL)
pre_scaling_stats <- reactiveVal(NULL)
observeEvent(input$file, {
req(input$file)
tryCatch({
df <- read.xlsx(input$file$datapath, sheet = 1)
required_columns <- c('Marker', 'Chromosome')
if (!all(required_columns %in% colnames(df))) {
stop("Required columns ('Marker' and 'Chromosome') not found in the uploaded file.")
}
if (ncol(df) < 3 || nrow(df) == 0) {
stop("Uploaded file contains no valid genotype data.")
}
genotype_data <- df[, 3:ncol(df)]
if (all(genotype_data == '-', na.rm = TRUE)) {
stop("Uploaded file contains no valid genotype data (all missing).")
}
uploaded_data(df)
showNotification("File uploaded successfully!", type = "message")
}, error = function(e) {
showNotification(paste("Error:", e$message), type = "error")
})
})
output$preview_table <- renderDataTable({
req(uploaded_data())
datatable(head(uploaded_data(), 10), options = list(scrollX = TRUE, dom = 't', pageLength = 10), rownames = FALSE)
})
calculate_recombination <- function(population_type, genotype1, genotype2) {
valid_pairs <- data.frame(g1 = genotype1, g2 = genotype2)
valid_pairs <- valid_pairs[!(genotype1 == '-' | genotype2 == '-'), ]
if (nrow(valid_pairs) == 0) {
return(NA)
}
recombination_events <- sum(valid_pairs$g1 != valid_pairs$g2)
if (population_type == 'RIL') {
recombination_fraction <- recombination_events / nrow(valid_pairs)
rf_ril <- 1 / (2 * (1 + 2 * recombination_fraction))
return(rf_ril)
} else if (population_type == 'F2') {
recombination_fraction_F2 <- recombination_events / nrow(valid_pairs)
return(recombination_fraction_F2)
} else {
stop("Invalid population type. Use 'RIL' or 'F2'.")
}
}
calculate_cM_kosambi <- function(recombination_fraction) {
if (is.na(recombination_fraction)) return(NA)
if (recombination_fraction >= 0.5) return(50)
if (recombination_fraction <= 0) return(0)
return(25 * log((1 + 2 * recombination_fraction) / (1 - 2 * recombination_fraction)))
}
correct_errors_and_impute_missing <- function(df) {
df[df == '-'] <- NA
if (ncol(df) > 2) {
na_fractions <- colMeans(is.na(df[, 3:ncol(df)]))
valid_individuals <- na_fractions < 1
df <- df[, c(TRUE, TRUE, valid_individuals)]
}
if (ncol(df) > 2) {
df[, 3:ncol(df)] <- lapply(df[, 3:ncol(df)], function(x) {
if (all(is.na(x))) {
return(x)
}
mode_val <- names(which.max(table(x[!is.na(x)])))
if (length(mode_val) == 0 || is.null(mode_val)) {
mode_val <- 'a'
}
x[is.na(x)] <- mode_val
return(x)
})
}
return(df)
}
quality_control <- function(df, missing_threshold = 0.1) {
if (ncol(df) < 3 || nrow(df) == 0) {
return(df[0, ])
}
missing_data_fraction <- rowMeans(is.na(df[, 3:ncol(df)]))
missing_data_fraction[is.na(missing_data_fraction)] <- 1
return(df[missing_data_fraction <= missing_threshold, ])
}
perform_chi_square_test <- function(genotype_data, population_type, chi_square_threshold = 0.05) {
if (nrow(genotype_data) == 0 || ncol(genotype_data) == 0) {
return(logical(0))
}
if (population_type == 'RIL') expected_ratio <- c(0.5, 0.5)
else if (population_type == 'F2') expected_ratio <- c(0.25, 0.5, 0.25)
else stop("Invalid population type. Use 'RIL' or 'F2'.")
chi_square_results <- apply(genotype_data, 1, function(marker) {
observed <- table(factor(marker, levels = c('a', 'b', 'ab')))
if (length(observed) != length(expected_ratio)) return(1)
expected <- expected_ratio * sum(observed)
chi_square_stat <- sum((observed - expected)^2 / expected)
p_value <- pchisq(chi_square_stat, df = length(observed) - 1, lower.tail = FALSE)
return(p_value)
})
non_distorted_markers <- chi_square_results > chi_square_threshold
return(non_distorted_markers)
}
group_and_order_markers <- function(map_distance_df, threshold = 40) {
markers <- unique(c(map_distance_df$Marker1, map_distance_df$Marker2))
if (nrow(map_distance_df) == 0 || length(markers) == 0) {
return(data.frame(Marker = character(0), Group = integer(0), Order = integer(0)))
}
if (length(markers) <= 1) return(data.frame(Marker = markers, Group = 1, Order = seq_along(markers)))
distance_matrix <- matrix(Inf, nrow = length(markers), ncol = length(markers))
rownames(distance_matrix) <- markers
colnames(distance_matrix) <- markers
for (i in 1:nrow(map_distance_df)) {
marker1 <- as.character(map_distance_df[i, 'Marker1'])
marker2 <- as.character(map_distance_df[i, 'Marker2'])
distance <- map_distance_df[i, 'MapDistance_cM']
idx1 <- which(markers == marker1)
idx2 <- which(markers == marker2)
if (length(idx1) > 0 && length(idx2) > 0) {
distance_matrix[idx1, idx2] <- distance
distance_matrix[idx2, idx1] <- distance
}
}
diag(distance_matrix) <- 0
max_finite <- max(distance_matrix[is.finite(distance_matrix)])
if (!is.finite(max_finite)) max_finite <- 100
distance_matrix[is.infinite(distance_matrix)] <- max_finite * 1.5
dist_obj <- as.dist(distance_matrix)
tryCatch({
clustering <- hclust(dist_obj, method = 'average')
if (any(diff(clustering$height) < 0)) clustering$height <- sort(clustering$height)
labels <- cutree(clustering, h = threshold)
grouped_markers <- data.frame(Marker = markers, Group = labels)
ordered_markers <- markers[clustering$order]
grouped_markers$Order <- match(grouped_markers$Marker, ordered_markers)
return(grouped_markers)
}, error = function(e) {
warning("Hierarchical clustering failed: ", e$message)
return(data.frame(Marker = markers, Group = seq_along(markers), Order = seq_along(markers)))
})
}
scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
positioned_markers <- linkage_map[!is.na(linkage_map$Position), ]
if (nrow(positioned_markers) == 0) {
return(list(scaled_map = linkage_map, chrom_lengths_before = data.frame(), chrom_lengths_after = data.frame()))
}
chrom_lengths_before <- positioned_markers %>% group_by(Chromosome) %>% summarise(Original_Length = max(Position, na.rm = TRUE), .groups = 'drop')
total_current_length <- sum(chrom_lengths_before$Original_Length, na.rm = TRUE)
scaled_map <- linkage_map
if (total_current_length <= max_total_cm || total_current_length == 0) {
return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_before))
}
if (method == "proportional") {
scaling_factor <- max_total_cm / total_current_length
chrom_lengths_before$Scaling_Factor <- scaling_factor
} else if (method == "uniform") {
n_chromosomes <- nrow(chrom_lengths_before)
if (n_chromosomes == 0) {
return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_before))
}
target_per_chromosome <- max_total_cm / n_chromosomes
chrom_lengths_before$Scaling_Factor <- ifelse(chrom_lengths_before$Original_Length > 0, target_per_chromosome / chrom_lengths_before$Original_Length, 1)
}
for (chrom in chrom_lengths_before$Chromosome) {
scaling_factor <- chrom_lengths_before$Scaling_Factor[chrom_lengths_before$Chromosome == chrom]
if (is.na(scaling_factor) || !is.finite(scaling_factor)) next
chrom_indices <- which(scaled_map$Chromosome == chrom & !is.na(scaled_map$Position))
if (length(chrom_indices) > 0) {
min_pos <- min(scaled_map$Position[chrom_indices], na.rm = TRUE)
scaled_map$Position[chrom_indices] <- (scaled_map$Position[chrom_indices] - min_pos) * scaling_factor
}
}
chrom_lengths_after <- scaled_map %>% filter(!is.na(Position)) %>% group_by(Chromosome) %>% summarise(Original_Length = max(Position, na.rm = TRUE), .groups = 'drop')
return(list(scaled_map = scaled_map, chrom_lengths_before = chrom_lengths_before, chrom_lengths_after = chrom_lengths_after))
}
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") {
df <- correct_errors_and_impute_missing(df)
df <- quality_control(df, missing_threshold)
if (nrow(df) == 0 || ncol(df) < 3) {
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()))
}
genotype_data <- df[, 3:ncol(df)]
non_distorted_markers <- perform_chi_square_test(genotype_data, population_type, chi_square_threshold)
df <- df[non_distorted_markers, ]
markers <- unique(df$Marker)
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()))
G <- graph(edges = NULL, n = length(markers), directed = FALSE)
V(G)$name <- markers
map_distance_df <- data.frame()
chromosomes <- unique(df$Chromosome)
for (chromosome in chromosomes) {
markers_on_chromosome <- subset(df, Chromosome == chromosome)
if (nrow(markers_on_chromosome) < 2) next
marker_combinations <- combn(markers_on_chromosome$Marker, 2, simplify = TRUE)
for (i in 1:ncol(marker_combinations)) {
marker1 <- as.character(marker_combinations[1, i])
marker2 <- as.character(marker_combinations[2, i])
genotype1 <- as.character(markers_on_chromosome[markers_on_chromosome$Marker == marker1, 3:ncol(df)])
genotype2 <- as.character(markers_on_chromosome[markers_on_chromosome$Marker == marker2, 3:ncol(df)])
recombination_fraction <- calculate_recombination(population_type, genotype1, genotype2)
if (!is.na(recombination_fraction) && recombination_fraction < recombination_threshold) {
map_distance_cM <- calculate_cM_kosambi(recombination_fraction)
G <- add_edges(G, edges = c(marker1, marker2), weight = map_distance_cM)
new_row <- data.frame(Marker1 = marker1, Marker2 = marker2, RecombinationFraction = recombination_fraction, MapDistance_cM = map_distance_cM)
map_distance_df <- rbind(map_distance_df, new_row)
}
}
}
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()))
grouped_markers <- group_and_order_markers(map_distance_df, threshold)
positions <- list()
for (chromosome in chromosomes) {
markers_on_chromosome <- subset(df, Chromosome == chromosome)$Marker
if (length(markers_on_chromosome) == 0) next
chrom_grouped <- grouped_markers[grouped_markers$Marker %in% markers_on_chromosome, ]
if (nrow(chrom_grouped) == 0) {
ordered_markers <- markers_on_chromosome
} else {
chrom_grouped <- chrom_grouped[order(chrom_grouped$Order), ]
ordered_markers <- chrom_grouped$Marker
}
if (length(ordered_markers) > 0) {
positions[[ordered_markers[1]]] <- 0
if (length(ordered_markers) > 1) {
for (i in 2:length(ordered_markers)) {
marker <- ordered_markers[i]
prev_marker <- ordered_markers[i-1]
edge_id <- get.edge.ids(G, c(marker, prev_marker))
if (edge_id != 0 && length(edge_id) > 0) {
distance <- edge_attr(G, 'weight', edge_id)
} else {
distance <- 1
}
positions[[marker]] <- positions[[prev_marker]] + distance
}
}
}
}
if (length(positions) == 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()))
}
positions_df <- data.frame(Marker = names(positions), Position = unlist(positions))
linkage_map <- merge(df[, c('Marker', 'Chromosome')], positions_df, by = "Marker", all.x = TRUE)
linkage_map <- linkage_map[order(linkage_map$Chromosome, linkage_map$Position), ]
scaled_results <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
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))
}
create_multi_chromosome_plot <- function(linkage_data, selected_chromosomes,
label_size = 3, show_density = FALSE,
plot_width = 1200, plot_height = 800,
chrom_width = 0.5, point_size = 2,
chrom_spacing = 5.0) {
library(ggplot2)
library(dplyr)
library(RColorBrewer)
# Filter data
plot_data <- linkage_data %>%
filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
arrange(Chromosome, Position)
if (nrow(plot_data) == 0) {
return(ggplot() +
annotate("text", x = 0.5, y = 0.5,
label = "No valid marker positions available",
size = 6, color = "red") +
theme_void())
}
# Chromosome summary
chrom_stats <- plot_data %>%
group_by(Chromosome) %>%
summarise(
max_pos = max(Position),
min_pos = min(Position),
num_markers = n(),
.groups = "drop"
) %>%
arrange(Chromosome) %>%
mutate(
chrom_x = seq(1, by = chrom_spacing, length.out = n()),
chrom_center = chrom_x
)
plot_data <- plot_data %>%
left_join(chrom_stats %>% select(Chromosome, chrom_x, chrom_center), by = "Chromosome")
# Distinct colors
n_chrom <- nrow(chrom_stats)
chrom_colors <- if (n_chrom <= 8) {
brewer.pal(max(3, n_chrom), "Set2")
} else {
colorRampPalette(brewer.pal(20, "Set2"))(n_chrom)
}
# Build plot
p <- ggplot() +
# Chromosome lines (vertical lines instead of rectangles)
geom_segment(
data = chrom_stats,
aes(x = chrom_center, xend = chrom_center,
y = min_pos, yend = max_pos,
color = as.factor(Chromosome)),
size = chrom_width * 20, # Thicker line for chromosome
alpha = 0.7,
lineend = "round"
) +
# Marker points (instead of ticks)
geom_point(
data = plot_data,
aes(x = chrom_center, y = Position,
color = as.factor(Chromosome)),
size = point_size,
alpha = 0.8
) +
# Optional: Add marker names if available
{if("Marker" %in% names(plot_data))
geom_text(
data = plot_data,
aes(x = chrom_center + chrom_width * 0.6,
y = Position,
label = Marker,
color = as.factor(Chromosome)),
size = label_size,
hjust = 0,
vjust = 0.5,
check_overlap = TRUE,
alpha = 0.7
)
} +
# Chromosome labels at the top
geom_text(
data = chrom_stats,
aes(x = chrom_center, y = max_pos * 1.05,
label = paste0("Chr", Chromosome),
color = as.factor(Chromosome)),
size = label_size + 1,
fontface = "bold",
vjust = 0
) +
scale_color_manual(values = chrom_colors) +
scale_fill_manual(values = chrom_colors) +
scale_y_reverse(
name = "Genetic Position (cM)",
expand = expansion(mult = c(0.05, 0.1)) # More space at top for labels
) +
scale_x_continuous(
breaks = chrom_stats$chrom_center,
labels = chrom_stats$Chromosome,
name = "Chromosome",
expand = expansion(mult = 0.1)
) +
theme_minimal() +
theme(
legend.position = "none",
axis.text.y = element_text(size = 10, color = "black"),
axis.text.x = element_text(size = 12, angle = 0, hjust = 0.5, face = "bold"),
axis.title.y = element_text(size = 12, face = "bold", margin = margin(r = 10)),
axis.title.x = element_text(size = 12, face = "bold", margin = margin(t = 10)),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_line(color = "grey90", size = 0.2),
panel.grid.minor.y = element_line(color = "grey95", size = 0.1),
plot.margin = margin(20, 20, 20, 20)
)
# Add density plot if requested
if (show_density) {
p <- p +
geom_density_2d_filled(
data = plot_data,
aes(x = chrom_center, y = Position),
alpha = 0.2,
show.legend = FALSE
)
}
return(p)
}
create_single_chromosome_plot <- function(linkage_data, selected_chromosome, label_size = 3) {
plot_data <- linkage_data %>% filter(Chromosome == selected_chromosome, !is.na(Position)) %>% arrange(Position)
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())
p <- ggplot(plot_data, aes(x = Position, y = 1)) +
geom_segment(aes(x = 0, xend = max(Position, na.rm = TRUE), y = 1, yend = 1), color = "darkblue", size = 2) +
geom_point(aes(x = Position, y = 1), color = "red", size = 3) +
geom_text_repel(aes(label = Marker), size = label_size, box.padding = 0.5, segment.color = "gray") +
labs(title = paste("Chromosome", selected_chromosome, "Linkage Map"), x = "Position (cM)", y = "") +
theme_minimal() +
theme(
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
axis.title.x = element_text(size = 12),
axis.text.x = element_text(size = 10)
)
return(p)
}
observeEvent(input$run_analysis, {
req(uploaded_data())
showModal(modalDialog(title = "Processing", "Creating and scaling linkage map... This may take a few moments.", footer = NULL))
tryCatch({
result <- create_linkage_map(
df = uploaded_data(),
population_type = input$population_type,
missing_threshold = input$missing_threshold,
recombination_threshold = input$recombination_threshold,
chi_square_threshold = input$chi_square_threshold,
threshold = input$cluster_threshold,
max_total_cm = input$max_total_cm,
scaling_method = input$scaling_method
)
analysis_results(result)
pre_scaling_stats(result$chrom_lengths_before)
chromosomes <- unique(result$linkage_map$Chromosome)
updateSelectInput(session, "chromosome_select", choices = chromosomes, selected = if(length(chromosomes) > 0) chromosomes[1:2] else NULL)
removeModal()
showNotification("Analysis and scaling completed successfully!", type = "message")
}, error = function(e) {
removeModal()
showNotification(paste("Error in analysis:", e$message), type = "error")
})
})
output$analysis_run <- reactive({ !is.null(analysis_results()) })
outputOptions(output, 'analysis_run', suspendWhenHidden = FALSE)
output$scaling_summary <- renderText({
req(analysis_results())
paste0("SCALING SUMMARY\n==================\nScaling Method: ", input$scaling_method, "\nMaximum Total Map Length: ", input$max_total_cm, " cM\n")
})
output$before_scaling_stats <- renderText({
req(analysis_results(), pre_scaling_stats())
chrom_lengths_before <- pre_scaling_stats()
if (nrow(chrom_lengths_before) > 0) {
total_length <- sum(chrom_lengths_before$Original_Length, na.rm = TRUE)
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"))
} else "No chromosome length data available before scaling."
})
output$after_scaling_stats <- renderText({
req(analysis_results())
chrom_lengths_after <- analysis_results()$chrom_lengths_after
if (nrow(chrom_lengths_after) > 0) {
total_length <- sum(chrom_lengths_after$Original_Length, na.rm = TRUE)
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"))
} else "No chromosome length data available after scaling."
})
output$result_table <- renderDataTable({
req(analysis_results())
linkage_map <- analysis_results()$linkage_map
if (nrow(linkage_map) > 0) {
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)
} else datatable(data.frame(Message = "No linkage map data available"), options = list(dom = 't'), rownames = FALSE)
})
output$summary_stats <- renderText({
req(analysis_results())
linkage_map <- analysis_results()$linkage_map
recomb_data <- analysis_results()$recombination_data
if (nrow(linkage_map) > 0) {
n_markers <- nrow(linkage_map)
n_chromosomes <- length(unique(linkage_map$Chromosome))
n_positioned <- sum(!is.na(linkage_map$Position))
chrom_lengths <- linkage_map %>% filter(!is.na(Position)) %>% group_by(Chromosome) %>% summarise(Length = max(Position, na.rm = TRUE), .groups = 'drop')
total_length <- sum(chrom_lengths$Length, na.rm = TRUE)
avg_length <- mean(chrom_lengths$Length, na.rm = TRUE)
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"))
} else "No summary statistics available - no positioned markers found."
})
output$chromosome_plot <- renderPlot({
req(analysis_results(), input$chromosome_select)
linkage_map <- analysis_results()$linkage_map
create_multi_chromosome_plot(
linkage_map,
input$chromosome_select,
label_size = input$marker_label_size,
#show_density = input$show_density,
plot_width = input$plot_width,
plot_height = input$plot_height
)
}, height = function() input$plot_height)
output$download_results <- downloadHandler(
filename = function() paste0("linkage_map_results_", Sys.Date(), ".xlsx"),
content = function(file) {
req(analysis_results())
wb <- createWorkbook()
addWorksheet(wb, "Original_Data")
addWorksheet(wb, "Recombination_Fractions")
addWorksheet(wb, "Linkage_Map")
writeData(wb, "Original_Data", analysis_results()$original_data)
writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
saveWorkbook(wb, file, overwrite = TRUE)
}
)
output$download_plot <- downloadHandler(
filename = function() paste0("chromosome_map_", Sys.Date(), ".png"),
content = function(file) {
req(analysis_results(), input$chromosome_select)
linkage_map <- analysis_results()$linkage_map
plot <- create_multi_chromosome_plot(
linkage_map,
input$chromosome_select,
label_size = input$marker_label_size,
show_density = input$show_density,
plot_width = input$plot_width,
plot_height = input$plot_height
)
width_inches <- input$plot_width / 300
height_inches <- input$plot_height / 300
ggsave(file, plot, width = width_inches, height = height_inches, dpi = 300, bg = "white")
}
)
}
shinyApp(ui = ui, server = server)