Spaces:
Sleeping
Sleeping
Update app.R
Browse files
app.R
CHANGED
|
@@ -9,10 +9,6 @@ library(ggrepel)
|
|
| 9 |
|
| 10 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 11 |
# DATA LOADING & AUTO-CONVERSION
|
| 12 |
-
# Handles:
|
| 13 |
-
# 1. Excel VLOOKUP formulas in Chromosome column (reads cached values)
|
| 14 |
-
# 2. Numeric genotype encoding 2=AA(a), 1=BB(b), 0=Het(ab), -1=Missing
|
| 15 |
-
# 3. Standard text encoding a/b/ab/- (pass-through)
|
| 16 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 17 |
|
| 18 |
load_and_convert_data <- function(filepath) {
|
|
@@ -24,30 +20,26 @@ load_and_convert_data <- function(filepath) {
|
|
| 24 |
|
| 25 |
df_raw <- read.xlsx(filepath, sheet = 1, colNames = TRUE)
|
| 26 |
|
| 27 |
-
if (!("Chromosome" %in% colnames(df_raw)))
|
| 28 |
stop("Column 'Chromosome' not found. Please check your file.")
|
| 29 |
-
|
| 30 |
-
if (!("Marker" %in% colnames(df_raw))) {
|
| 31 |
stop("Column 'Marker' not found. Please check your file.")
|
| 32 |
-
}
|
| 33 |
|
| 34 |
-
chr_col
|
| 35 |
has_formula <- any(grepl("^=", chr_col, ignore.case = FALSE), na.rm = TRUE)
|
| 36 |
|
| 37 |
if (has_formula) {
|
| 38 |
-
inferred
|
| 39 |
n_inferred <- sum(!is.na(inferred))
|
| 40 |
if (n_inferred / nrow(df_raw) >= 0.5) {
|
| 41 |
df_raw$Chromosome <- inferred
|
| 42 |
-
message(sprintf("[Auto] Chromosome inferred from marker names for %d/%d markers.",
|
| 43 |
-
n_inferred, nrow(df_raw)))
|
| 44 |
} else {
|
| 45 |
df_raw$Chromosome <- seq_len(nrow(df_raw))
|
| 46 |
-
warning("Could not infer chromosomes from marker names.
|
| 47 |
}
|
| 48 |
}
|
| 49 |
|
| 50 |
-
geno_cols
|
| 51 |
sample_vals <- unique(unlist(geno_cols[1:min(50, nrow(geno_cols)), ]))
|
| 52 |
sample_vals <- sample_vals[!is.na(sample_vals)]
|
| 53 |
|
|
@@ -67,8 +59,6 @@ load_and_convert_data <- function(filepath) {
|
|
| 67 |
col
|
| 68 |
}
|
| 69 |
)
|
| 70 |
-
message("[Auto] Numeric genotype encoding (2/1/0/-1) detected and converted to a/b/ab/-.")
|
| 71 |
-
|
| 72 |
} else if (!text_encoding) {
|
| 73 |
df_raw[, 3:ncol(df_raw)] <- lapply(
|
| 74 |
df_raw[, 3:ncol(df_raw), drop = FALSE],
|
|
@@ -78,25 +68,19 @@ load_and_convert_data <- function(filepath) {
|
|
| 78 |
col
|
| 79 |
}
|
| 80 |
)
|
| 81 |
-
message("[Auto] Unknown genotype encoding — non-standard values set to missing.")
|
| 82 |
}
|
| 83 |
|
| 84 |
df_raw$Chromosome <- as.character(df_raw$Chromosome)
|
| 85 |
df_raw$Chromosome[is.na(df_raw$Chromosome) | df_raw$Chromosome == "NA"] <- "Unknown"
|
| 86 |
-
|
| 87 |
-
# ── IMPORTANT: add a row-index column to preserve original input order ──────
|
| 88 |
df_raw$.input_order <- seq_len(nrow(df_raw))
|
| 89 |
-
|
| 90 |
df_raw
|
| 91 |
}
|
| 92 |
|
| 93 |
-
# ── Infer chromosome number from common rice marker naming conventions ─────────
|
| 94 |
infer_chromosome_from_marker <- function(marker_names) {
|
| 95 |
markers <- as.character(marker_names)
|
| 96 |
chrom <- rep(NA_character_, length(markers))
|
| 97 |
-
|
| 98 |
patterns <- list(
|
| 99 |
-
list(regex = "(?i)chr(\\d{1,2})[_\\-]",
|
| 100 |
list(regex = "(?i)[_\\-]C(\\d{1,2})[_\\-]", group = 1),
|
| 101 |
list(regex = "(?i)^MSU\\d+_(\\d{1,2})_", group = 1),
|
| 102 |
list(regex = "(?i)^DTY(\\d{1,2})[\\-_]", group = 1),
|
|
@@ -106,14 +90,11 @@ infer_chromosome_from_marker <- function(marker_names) {
|
|
| 106 |
list(regex = "(?i)^R(\\d{1,2})", group = 1),
|
| 107 |
list(regex = "(?i)^Pi(\\d{1,2})", group = 1)
|
| 108 |
)
|
| 109 |
-
|
| 110 |
for (i in seq_along(markers)) {
|
| 111 |
m <- markers[i]
|
| 112 |
for (pat in patterns) {
|
| 113 |
if (is.na(pat$group)) {
|
| 114 |
-
if (grepl(pat$regex, m, perl = TRUE)) {
|
| 115 |
-
chrom[i] <- "1"; break
|
| 116 |
-
}
|
| 117 |
} else {
|
| 118 |
mt <- regmatches(m, regexpr(pat$regex, m, perl = TRUE))
|
| 119 |
if (length(mt) > 0) {
|
|
@@ -135,77 +116,69 @@ infer_chromosome_from_marker <- function(marker_names) {
|
|
| 135 |
# CORE GENETIC FUNCTIONS
|
| 136 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 137 |
|
| 138 |
-
## 1. Recombination fraction --------------------------------------------------
|
| 139 |
calculate_recombination <- function(population_type, genotype1, genotype2) {
|
| 140 |
g1 <- as.character(genotype1)
|
| 141 |
g2 <- as.character(genotype2)
|
| 142 |
-
|
| 143 |
keep <- !(g1 %in% c("-", "NA", NA) | g2 %in% c("-", "NA", NA))
|
| 144 |
-
g1 <- g1[keep];
|
| 145 |
n <- length(g1)
|
| 146 |
if (n < 4) return(NA_real_)
|
| 147 |
|
| 148 |
if (population_type == "RIL") {
|
| 149 |
hom <- !(g1 == "ab" | g2 == "ab")
|
| 150 |
-
g1h <- g1[hom];
|
| 151 |
if (length(g1h) < 4) return(NA_real_)
|
| 152 |
r_obs <- mean(g1h != g2h)
|
| 153 |
rf <- r_obs / (2 * (1 - r_obs))
|
| 154 |
-
|
| 155 |
-
return(rf)
|
| 156 |
|
| 157 |
} else if (population_type == "F2") {
|
| 158 |
-
AA_AA <- sum(g1
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
Aa_BB <- sum(g1 == "ab" & g2 == "b")
|
| 164 |
-
BB_AA <- sum(g1 == "b" & g2 == "a")
|
| 165 |
-
BB_Aa <- sum(g1 == "b" & g2 == "ab")
|
| 166 |
-
BB_BB <- sum(g1 == "b" & g2 == "b")
|
| 167 |
-
|
| 168 |
r <- 0.25
|
| 169 |
for (iter in 1:200) {
|
| 170 |
-
r_old <- r
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
p_recomb <- 2 * r * q
|
| 174 |
-
norm <- p_parental + p_recomb
|
| 175 |
-
|
| 176 |
n_recomb_AaAa <- if (norm > 0) Aa_Aa * p_recomb / norm else 0
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
(AA_Aa + Aa_AA + Aa_BB + BB_Aa) +
|
| 180 |
-
2 * n_recomb_AaAa
|
| 181 |
-
total_gametes <- 2 * n
|
| 182 |
-
r_new <- max(1e-6, min(recomb_count / total_gametes, 0.4999))
|
| 183 |
r <- r_new
|
| 184 |
if (abs(r - r_old) < 1e-8) break
|
| 185 |
}
|
| 186 |
return(r)
|
| 187 |
-
} else
|
| 188 |
-
stop("population_type must be 'RIL' or 'F2'")
|
| 189 |
-
}
|
| 190 |
}
|
| 191 |
|
| 192 |
-
## 2. Kosambi map function ----------------------------------------------------
|
| 193 |
calculate_cM_kosambi <- function(r) {
|
| 194 |
if (is.na(r)) return(NA_real_)
|
| 195 |
r <- max(0, min(r, 0.4999))
|
| 196 |
if (r == 0) return(0)
|
| 197 |
-
25 * log((1 + 2
|
| 198 |
}
|
| 199 |
|
| 200 |
-
#
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
|
| 210 |
for (j in geno_cols_idx) {
|
| 211 |
x <- as.character(df[[j]])
|
|
@@ -215,19 +188,15 @@ correct_errors_and_impute_missing <- function(df) {
|
|
| 215 |
}
|
| 216 |
|
| 217 |
if (length(geno_cols_idx) > 0) {
|
| 218 |
-
na_col
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
df <- df[, sort(unique(keep_idx)), drop = FALSE]
|
| 225 |
}
|
| 226 |
|
| 227 |
-
|
| 228 |
-
geno_cols_idx2 <- setdiff(geno_start:ncol(df),
|
| 229 |
-
which(colnames(df) == ".input_order"))
|
| 230 |
-
|
| 231 |
if (length(geno_cols_idx2) > 0) {
|
| 232 |
df[, geno_cols_idx2] <- t(apply(df[, geno_cols_idx2, drop = FALSE], 1, function(row) {
|
| 233 |
nas <- is.na(row)
|
|
@@ -241,148 +210,71 @@ correct_errors_and_impute_missing <- function(df) {
|
|
| 241 |
df
|
| 242 |
}
|
| 243 |
|
| 244 |
-
## 4. Quality control ---------------------------------------------------------
|
| 245 |
quality_control <- function(df, missing_threshold = 0.1) {
|
| 246 |
if (ncol(df) < 3 || nrow(df) == 0) return(df[0, ])
|
| 247 |
-
|
| 248 |
geno_cols_idx <- setdiff(3:(ncol(df)), which(colnames(df) == ".input_order"))
|
| 249 |
if (length(geno_cols_idx) == 0) return(df)
|
| 250 |
-
|
| 251 |
geno <- df[, geno_cols_idx, drop = FALSE]
|
| 252 |
miss_frac <- rowMeans(is.na(geno))
|
| 253 |
miss_frac[is.na(miss_frac)] <- 1
|
| 254 |
df[miss_frac <= missing_threshold, ]
|
| 255 |
}
|
| 256 |
|
| 257 |
-
## 5. Chi-square test ---------------------------------------------------------
|
| 258 |
-
perform_chi_square_test <- function(df, population_type,
|
| 259 |
-
chi_square_threshold = 0.05,
|
| 260 |
-
allow_distorted_f2 = TRUE) {
|
| 261 |
-
if (nrow(df) == 0) return(logical(0))
|
| 262 |
-
|
| 263 |
-
geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
|
| 264 |
-
geno_mat <- as.matrix(df[, geno_cols_idx, drop = FALSE])
|
| 265 |
-
|
| 266 |
-
keep <- apply(geno_mat, 1, function(row) {
|
| 267 |
-
obs <- table(factor(row, levels = c("a", "ab", "b")))
|
| 268 |
-
total <- sum(obs)
|
| 269 |
-
if (total == 0) return(TRUE)
|
| 270 |
-
|
| 271 |
-
if (population_type == "RIL") {
|
| 272 |
-
obs2 <- c(obs["a"], obs["b"])
|
| 273 |
-
if (sum(obs2) == 0) return(TRUE)
|
| 274 |
-
exp2 <- rep(sum(obs2) / 2, 2)
|
| 275 |
-
stat <- sum((obs2 - exp2)^2 / exp2)
|
| 276 |
-
pval <- pchisq(stat, df = 1, lower.tail = FALSE)
|
| 277 |
-
|
| 278 |
-
} else {
|
| 279 |
-
exp3 <- c(total * 0.25, total * 0.50, total * 0.25)
|
| 280 |
-
valid <- exp3 > 0
|
| 281 |
-
stat <- sum(((obs[valid] - exp3[valid])^2) / exp3[valid])
|
| 282 |
-
pval <- pchisq(stat, df = sum(valid) - 1, lower.tail = FALSE)
|
| 283 |
-
|
| 284 |
-
if (allow_distorted_f2 && pval <= chi_square_threshold) {
|
| 285 |
-
het_frac <- obs["ab"] / total
|
| 286 |
-
if (het_frac > 0.02) return(TRUE)
|
| 287 |
-
}
|
| 288 |
-
}
|
| 289 |
-
return(pval > chi_square_threshold)
|
| 290 |
-
})
|
| 291 |
-
keep
|
| 292 |
-
}
|
| 293 |
-
|
| 294 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 295 |
-
#
|
| 296 |
-
# Markers are used exactly in the order they appear in the input file.
|
| 297 |
-
# The first marker of each chromosome starts at position 0 cM.
|
| 298 |
-
# Subsequent markers accumulate cM from consecutive pairwise rf calculations.
|
| 299 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 300 |
|
| 301 |
-
build_positions_from_input_order <- function(df, population_type,
|
| 302 |
-
|
| 303 |
-
# df still contains .input_order column
|
| 304 |
-
chromosomes <- unique(df$Chromosome[order(df$.input_order)])
|
| 305 |
-
|
| 306 |
geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
|
| 307 |
-
|
| 308 |
-
positions_list <- list()
|
| 309 |
recombination_rows <- list()
|
| 310 |
|
| 311 |
for (chr in chromosomes) {
|
| 312 |
-
# Subset and sort by original input order
|
| 313 |
sub <- df[df$Chromosome == chr, ]
|
| 314 |
sub <- sub[order(sub$.input_order), ]
|
| 315 |
mks <- sub$Marker
|
| 316 |
-
|
| 317 |
if (length(mks) == 0) next
|
| 318 |
-
|
| 319 |
-
# First marker always starts at 0 cM
|
| 320 |
pos <- setNames(numeric(length(mks)), mks)
|
| 321 |
|
| 322 |
if (length(mks) > 1) {
|
| 323 |
for (i in 2:length(mks)) {
|
| 324 |
-
m_prev <- mks[i -
|
| 325 |
-
m_curr <- mks[i]
|
| 326 |
-
|
| 327 |
g1 <- unlist(sub[sub$Marker == m_prev, geno_cols_idx])
|
| 328 |
g2 <- unlist(sub[sub$Marker == m_curr, geno_cols_idx])
|
| 329 |
-
|
| 330 |
rf <- calculate_recombination(population_type, g1, g2)
|
| 331 |
-
|
| 332 |
-
# Store recombination data
|
| 333 |
if (!is.na(rf)) {
|
| 334 |
cM <- calculate_cM_kosambi(rf)
|
| 335 |
-
recombination_rows[[length(recombination_rows)
|
| 336 |
-
data.frame(
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
Chromosome = chr,
|
| 342 |
-
stringsAsFactors = FALSE
|
| 343 |
-
)
|
| 344 |
-
|
| 345 |
-
# Only accumulate distance if markers are within linkage threshold
|
| 346 |
-
if (rf < recombination_threshold) {
|
| 347 |
-
pos[i] <- pos[i - 1] + abs(cM)
|
| 348 |
-
} else {
|
| 349 |
-
# Markers appear unlinked — still place them but flag with large gap
|
| 350 |
-
# Use 50 cM as placeholder so they appear on the map
|
| 351 |
-
pos[i] <- pos[i - 1] + 50
|
| 352 |
-
}
|
| 353 |
} else {
|
| 354 |
-
|
| 355 |
-
pos[i] <- pos[i - 1] + 5
|
| 356 |
}
|
| 357 |
}
|
| 358 |
}
|
| 359 |
-
|
| 360 |
for (mk in names(pos)) positions_list[[mk]] <- pos[mk]
|
| 361 |
}
|
| 362 |
-
|
| 363 |
-
list(
|
| 364 |
-
positions_list = positions_list,
|
| 365 |
-
recombination_rows = recombination_rows
|
| 366 |
-
)
|
| 367 |
}
|
| 368 |
|
| 369 |
-
## 6. Scaling -----------------------------------------------------------------
|
| 370 |
scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
|
| 371 |
pos_map <- linkage_map[!is.na(linkage_map$Position), ]
|
| 372 |
if (nrow(pos_map) == 0)
|
| 373 |
-
return(list(scaled_map
|
| 374 |
-
|
| 375 |
-
chrom_lengths_after = data.frame()))
|
| 376 |
|
| 377 |
before <- pos_map %>%
|
| 378 |
group_by(Chromosome) %>%
|
| 379 |
-
summarise(Original_Length = max(Position, na.rm
|
| 380 |
|
| 381 |
-
total <- sum(before$Original_Length, na.rm
|
| 382 |
if (total <= max_total_cm || total == 0)
|
| 383 |
-
return(list(scaled_map
|
| 384 |
-
|
| 385 |
-
chrom_lengths_after = before))
|
| 386 |
|
| 387 |
scaled <- linkage_map
|
| 388 |
if (method == "proportional") {
|
|
@@ -390,9 +282,8 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
|
|
| 390 |
} else {
|
| 391 |
n_chr <- nrow(before)
|
| 392 |
before$sf <- ifelse(before$Original_Length > 0,
|
| 393 |
-
(max_total_cm
|
| 394 |
}
|
| 395 |
-
|
| 396 |
for (chr in before$Chromosome) {
|
| 397 |
sf <- before$sf[before$Chromosome == chr]
|
| 398 |
idx <- which(scaled$Chromosome == chr & !is.na(scaled$Position))
|
|
@@ -401,131 +292,152 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
|
|
| 401 |
scaled$Position[idx] <- (scaled$Position[idx] - mn) * sf
|
| 402 |
}
|
| 403 |
}
|
| 404 |
-
|
| 405 |
after <- scaled %>%
|
| 406 |
filter(!is.na(Position)) %>%
|
| 407 |
group_by(Chromosome) %>%
|
| 408 |
-
summarise(Original_Length = max(Position, na.rm
|
| 409 |
|
| 410 |
-
list(scaled_map
|
| 411 |
-
chrom_lengths_before = before,
|
| 412 |
-
chrom_lengths_after = after)
|
| 413 |
}
|
| 414 |
|
| 415 |
-
#
|
|
|
|
|
|
|
|
|
|
| 416 |
create_linkage_map <- function(df,
|
| 417 |
population_type = "F2",
|
| 418 |
missing_threshold = 0.1,
|
| 419 |
recombination_threshold = 0.5,
|
| 420 |
-
chi_square_threshold = 0.05,
|
| 421 |
-
cluster_threshold = 40,
|
| 422 |
max_total_cm = 1500,
|
| 423 |
-
scaling_method = "proportional"
|
| 424 |
-
allow_distorted_f2 = TRUE) {
|
| 425 |
|
| 426 |
empty_result <- function(df_in = df) {
|
| 427 |
list(original_data = df_in,
|
| 428 |
recombination_data = data.frame(),
|
| 429 |
-
linkage_map = data.frame(Marker
|
| 430 |
-
Chromosome
|
| 431 |
-
Position
|
| 432 |
chrom_lengths_before = data.frame(),
|
| 433 |
chrom_lengths_after = data.frame(),
|
| 434 |
-
|
| 435 |
qc_report = "No data passed QC.")
|
| 436 |
}
|
| 437 |
|
| 438 |
-
# ── Pre-processing ────────────────────────────────────────────────────────
|
| 439 |
df_orig <- df
|
| 440 |
-
|
| 441 |
-
# Store original order before any filtering
|
| 442 |
-
if (!(".input_order" %in% colnames(df))) {
|
| 443 |
df$.input_order <- seq_len(nrow(df))
|
| 444 |
-
}
|
| 445 |
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
|
| 451 |
-
|
| 452 |
|
| 453 |
-
# ──
|
| 454 |
-
|
| 455 |
-
chi_square_threshold, allow_distorted_f2)
|
| 456 |
-
removed_markers <- df$Marker[!keep]
|
| 457 |
-
if (length(keep) == nrow(df)) df <- df[keep, ]
|
| 458 |
|
| 459 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
|
| 476 |
if (nrow(df) == 0) {
|
| 477 |
-
res <- empty_result(df_orig)
|
| 478 |
-
res$qc_report <- qc_msg
|
| 479 |
-
return(res)
|
| 480 |
}
|
| 481 |
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
)
|
| 486 |
|
|
|
|
|
|
|
| 487 |
positions_list <- pos_result$positions_list
|
| 488 |
recombination_rows <- pos_result$recombination_rows
|
| 489 |
|
| 490 |
-
if (length(recombination_rows) > 0)
|
| 491 |
-
|
| 492 |
-
} else {
|
| 493 |
-
rec_df <- data.frame()
|
| 494 |
-
}
|
| 495 |
|
| 496 |
if (length(positions_list) == 0) {
|
| 497 |
-
lm_empty <- df[, c("Marker",
|
| 498 |
lm_empty$Position <- NA_real_
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
chrom_lengths_before = data.frame(),
|
| 504 |
-
chrom_lengths_after = data.frame(),
|
| 505 |
-
markers_removed = removed_markers,
|
| 506 |
-
qc_report = qc_msg))
|
| 507 |
}
|
| 508 |
|
| 509 |
-
pos_df <- data.frame(
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
stringsAsFactors = FALSE
|
| 513 |
-
)
|
| 514 |
-
|
| 515 |
-
# Merge keeping input order
|
| 516 |
-
linkage_map <- merge(
|
| 517 |
-
df[, c("Marker", "Chromosome", ".input_order")],
|
| 518 |
-
pos_df, by = "Marker", all.x = TRUE
|
| 519 |
-
)
|
| 520 |
-
|
| 521 |
-
# ── Sort by chromosome then by ORIGINAL INPUT ORDER (not position) ─────────
|
| 522 |
-
linkage_map <- linkage_map[order(linkage_map$Chromosome,
|
| 523 |
-
linkage_map$.input_order), ]
|
| 524 |
|
| 525 |
-
|
|
|
|
|
|
|
| 526 |
linkage_map$.input_order <- NULL
|
| 527 |
|
| 528 |
-
# ── Scaling ────────────────────────────────────────────────────────────────
|
| 529 |
scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
|
| 530 |
|
| 531 |
list(original_data = df_orig,
|
|
@@ -533,7 +445,7 @@ create_linkage_map <- function(df,
|
|
| 533 |
linkage_map = scaled$scaled_map,
|
| 534 |
chrom_lengths_before = scaled$chrom_lengths_before,
|
| 535 |
chrom_lengths_after = scaled$chrom_lengths_after,
|
| 536 |
-
|
| 537 |
qc_report = qc_msg)
|
| 538 |
}
|
| 539 |
|
|
@@ -541,111 +453,90 @@ create_linkage_map <- function(df,
|
|
| 541 |
# PLOTTING
|
| 542 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 543 |
|
| 544 |
-
create_multi_chromosome_plot <- function(linkage_data,
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
plot_height = 800,
|
| 551 |
-
chrom_width = 0.5,
|
| 552 |
-
point_size = 2,
|
| 553 |
-
chrom_spacing = 5.0) {
|
| 554 |
-
|
| 555 |
chr_sorted <- tryCatch(
|
| 556 |
selected_chromosomes[order(as.numeric(selected_chromosomes))],
|
| 557 |
warning = function(w) sort(selected_chromosomes),
|
| 558 |
error = function(e) sort(selected_chromosomes)
|
| 559 |
)
|
| 560 |
-
|
| 561 |
plot_data <- linkage_data %>%
|
| 562 |
filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
|
| 563 |
arrange(match(Chromosome, chr_sorted), Position)
|
| 564 |
|
| 565 |
if (nrow(plot_data) == 0) {
|
| 566 |
return(ggplot() +
|
| 567 |
-
annotate("text", x
|
| 568 |
-
label
|
| 569 |
-
size
|
| 570 |
-
theme_void())
|
| 571 |
}
|
| 572 |
|
| 573 |
chrom_stats <- plot_data %>%
|
| 574 |
group_by(Chromosome) %>%
|
| 575 |
-
summarise(max_pos
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
mutate(Chromosome = factor(Chromosome, levels = chr_sorted)) %>%
|
| 579 |
arrange(Chromosome) %>%
|
| 580 |
-
mutate(chrom_x
|
| 581 |
-
chrom_center
|
| 582 |
|
| 583 |
plot_data <- plot_data %>%
|
| 584 |
-
left_join(chrom_stats %>% select(Chromosome, chrom_x, chrom_center),
|
| 585 |
-
by = "Chromosome")
|
| 586 |
|
| 587 |
-
n_chrom
|
| 588 |
palette_ok <- tryCatch({ brewer.pal(max(3, n_chrom), color_palette); TRUE },
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
chrom_colors <- if (palette_ok && n_chrom <= 8) {
|
| 592 |
brewer.pal(max(3, n_chrom), color_palette)[seq_len(n_chrom)]
|
| 593 |
-
|
| 594 |
colorRampPalette(brewer.pal(8, color_palette))(n_chrom)
|
| 595 |
-
|
| 596 |
colorRampPalette(brewer.pal(8, "Set2"))(n_chrom)
|
| 597 |
-
}
|
| 598 |
|
| 599 |
p <- ggplot() +
|
| 600 |
-
geom_segment(data
|
| 601 |
-
aes(x
|
| 602 |
-
y
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
axis.
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
panel.grid.minor.x = element_blank(),
|
| 633 |
-
panel.grid.major.y = element_line(color = "grey88", linewidth = 0.3),
|
| 634 |
-
panel.grid.minor.y = element_line(color = "grey94", linewidth = 0.15),
|
| 635 |
-
plot.margin = margin(20, 20, 20, 20))
|
| 636 |
|
| 637 |
if (show_labels && "Marker" %in% names(plot_data) && nrow(plot_data) <= 500) {
|
| 638 |
p <- p + geom_text_repel(
|
| 639 |
-
data
|
| 640 |
-
aes(x
|
| 641 |
-
|
| 642 |
-
size
|
| 643 |
-
direction = "y",
|
| 644 |
-
nudge_x = 0.3,
|
| 645 |
-
segment.size = 0.3,
|
| 646 |
-
segment.alpha = 0.5,
|
| 647 |
-
max.overlaps = 20,
|
| 648 |
-
show.legend = FALSE
|
| 649 |
)
|
| 650 |
}
|
| 651 |
p
|
|
@@ -656,266 +547,247 @@ create_multi_chromosome_plot <- function(linkage_data,
|
|
| 656 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 657 |
|
| 658 |
ui <- fluidPage(
|
| 659 |
-
tags$head(
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
navbarPage("Linkage Map Creator v4.
|
| 704 |
|
| 705 |
# ── Tab 1: Upload ────────────────────────────────────────────────────────
|
| 706 |
-
tabPanel("Data Upload", icon
|
| 707 |
sidebarLayout(
|
| 708 |
-
sidebarPanel(width
|
| 709 |
h3("Upload Data"),
|
| 710 |
fileInput("file", "Choose Excel File (.xlsx)",
|
| 711 |
-
accept
|
| 712 |
-
buttonLabel
|
| 713 |
-
placeholder = "No file selected"),
|
| 714 |
selectInput("population_type", "Population Type:",
|
| 715 |
-
choices
|
| 716 |
-
selected = "F2"),
|
| 717 |
-
checkboxInput("allow_distorted_f2",
|
| 718 |
-
"Keep distorted-but-heterozygous F2 markers",
|
| 719 |
-
value = TRUE),
|
| 720 |
hr(),
|
| 721 |
-
div(class
|
| 722 |
-
tags$b("v4.
|
| 723 |
-
tags$b("•
|
| 724 |
-
tags$b("•
|
| 725 |
-
"•
|
| 726 |
-
"•
|
| 727 |
-
"•
|
| 728 |
)
|
| 729 |
)),
|
| 730 |
-
mainPanel(width
|
| 731 |
-
wellPanel(
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
),
|
| 735 |
-
|
| 736 |
-
h3("Data Preview (first 10 rows, converted)"),
|
| 737 |
-
div(style = "overflow-x:auto;", dataTableOutput("preview_table"))
|
| 738 |
-
),
|
| 739 |
-
wellPanel(
|
| 740 |
-
h3("Chromosome Assignments"),
|
| 741 |
-
div(style = "overflow-x:auto;", dataTableOutput("chr_summary_table"))
|
| 742 |
-
)
|
| 743 |
)
|
| 744 |
)
|
| 745 |
),
|
| 746 |
|
| 747 |
# ── Tab 2: Parameters ───────────────────────────────────────────────────
|
| 748 |
-
tabPanel("Parameters", icon
|
| 749 |
sidebarLayout(
|
| 750 |
-
sidebarPanel(width
|
| 751 |
h3("Analysis Parameters"),
|
| 752 |
-
sliderInput("missing_threshold",
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
"Max Recombination Fraction (r):",
|
| 757 |
-
min = 0, max = 0.5, value = 0.45, step = 0.01),
|
| 758 |
-
sliderInput("chi_square_threshold",
|
| 759 |
-
"Chi-Square P-value Threshold:",
|
| 760 |
-
min = 0, max = 0.2, value = 0.001, step = 0.001),
|
| 761 |
-
sliderInput("cluster_threshold",
|
| 762 |
-
"Linkage Group Cluster Threshold (cM):",
|
| 763 |
-
min = 10, max = 100, value = 40, step = 5),
|
| 764 |
hr(),
|
| 765 |
h4("Map Scaling"),
|
| 766 |
-
numericInput("max_total_cm",
|
| 767 |
-
|
| 768 |
-
min = 100, max = 10000, value = 1500, step = 100),
|
| 769 |
selectInput("scaling_method", "Scaling Method:",
|
| 770 |
-
choices
|
| 771 |
-
|
| 772 |
-
selected = "proportional"),
|
| 773 |
hr(),
|
| 774 |
actionButton("run_analysis", "▶ Run Analysis",
|
| 775 |
-
class
|
| 776 |
)),
|
| 777 |
-
mainPanel(width
|
| 778 |
h3("Parameter Guide"),
|
| 779 |
tags$ul(
|
| 780 |
tags$li(tags$b("Missing Data Threshold:"),
|
| 781 |
-
" Markers with > this fraction missing are removed.
|
| 782 |
-
tags$em("Default 0.30.")),
|
| 783 |
tags$li(tags$b("Max Recombination Fraction:"),
|
| 784 |
-
" Pairs with r ≥
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
"
|
| 788 |
-
|
|
|
|
|
|
|
| 789 |
tags$li(tags$b("Marker Order:"),
|
| 790 |
-
tags$b(" Preserved
|
| 791 |
-
"No MDS or other reordering is applied."),
|
| 792 |
-
tags$li(tags$b("First Marker Position:"),
|
| 793 |
-
tags$b(" Always 0 cM per chromosome."),
|
| 794 |
-
" Positions are cumulative Kosambi cM from consecutive pairs.")
|
| 795 |
),
|
| 796 |
br(),
|
| 797 |
-
h4("Scaling Summary"),
|
| 798 |
-
verbatimTextOutput("
|
| 799 |
-
h4("
|
| 800 |
-
verbatimTextOutput("before_scaling_stats"),
|
| 801 |
-
h4("After Scaling"),
|
| 802 |
-
verbatimTextOutput("after_scaling_stats")
|
| 803 |
))
|
| 804 |
)
|
| 805 |
),
|
| 806 |
|
| 807 |
# ── Tab 3: QC Report ────────────────────────────────────────────────────
|
| 808 |
-
tabPanel("QC Report", icon
|
| 809 |
wellPanel(
|
| 810 |
h3("Quality Control Report"),
|
| 811 |
verbatimTextOutput("qc_report_output")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 812 |
)
|
| 813 |
),
|
| 814 |
|
| 815 |
# ── Tab 4: Results ───────────────────────────────────────────────────────
|
| 816 |
-
tabPanel("Results", icon
|
| 817 |
fluidRow(column(12, wellPanel(
|
| 818 |
h3("Analysis Results"),
|
| 819 |
conditionalPanel("output.analysis_run",
|
| 820 |
downloadButton("download_results", "⬇ Download Excel Results",
|
| 821 |
-
class
|
| 822 |
br(), br(),
|
| 823 |
h4("Linkage Map (Input Order Preserved, First Marker = 0 cM)"),
|
| 824 |
-
div(style
|
| 825 |
-
h4("Summary Statistics"),
|
| 826 |
-
verbatimTextOutput("summary_stats")
|
| 827 |
),
|
| 828 |
conditionalPanel("!output.analysis_run",
|
| 829 |
p("Upload data and click 'Run Analysis' to see results.",
|
| 830 |
-
style
|
| 831 |
)
|
| 832 |
)))
|
| 833 |
),
|
| 834 |
|
| 835 |
# ── Tab 5: Plot Options ──────────────────────────────────────────────────
|
| 836 |
-
tabPanel("Plot Options", icon
|
| 837 |
sidebarLayout(
|
| 838 |
-
sidebarPanel(width
|
| 839 |
h3("Visualization Options"),
|
| 840 |
selectInput("color_palette", "Color Palette:",
|
| 841 |
-
choices
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
sliderInput("
|
| 846 |
-
|
| 847 |
-
sliderInput("
|
| 848 |
-
|
| 849 |
-
sliderInput("plot_height", "Plot Height (px):",
|
| 850 |
-
min = 400, max = 1600, value = 800, step = 50),
|
| 851 |
-
sliderInput("chrom_spacing", "Chromosome Spacing:",
|
| 852 |
-
min = 2, max = 15, value = 5, step = 0.5),
|
| 853 |
-
sliderInput("point_size", "Marker Point Size:",
|
| 854 |
-
min = 0.5, max = 5, value = 1.5, step = 0.25)
|
| 855 |
)),
|
| 856 |
-
mainPanel(width
|
| 857 |
h3("Palette Preview"),
|
| 858 |
-
plotOutput("palette_preview", height
|
| 859 |
))
|
| 860 |
)
|
| 861 |
),
|
| 862 |
|
| 863 |
# ── Tab 6: Visualization ─────────────────────────────────────────────────
|
| 864 |
-
tabPanel("Visualization", icon
|
| 865 |
fluidRow(column(12, wellPanel(
|
| 866 |
h3("Chromosome Map"),
|
| 867 |
conditionalPanel("output.analysis_run",
|
| 868 |
fluidRow(
|
| 869 |
column(8, selectInput("chromosome_select", "Select Chromosomes:",
|
| 870 |
-
choices
|
| 871 |
column(4, br(),
|
| 872 |
-
|
| 873 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 874 |
),
|
| 875 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 876 |
),
|
| 877 |
conditionalPanel("!output.analysis_run",
|
| 878 |
p("Run analysis first.",
|
| 879 |
-
style
|
| 880 |
)
|
| 881 |
)))
|
| 882 |
),
|
| 883 |
|
| 884 |
# ── Tab 7: Help ──────────────────────────────────────────────────────────
|
| 885 |
-
tabPanel("Help", icon
|
| 886 |
wellPanel(
|
| 887 |
-
h3("Application Guide — v4.
|
| 888 |
-
h4("What's New in v4.
|
| 889 |
-
div(class
|
| 890 |
tags$ul(
|
| 891 |
-
tags$li(tags$b("
|
| 892 |
-
"
|
| 893 |
-
"
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
"
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
"
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
"
|
|
|
|
|
|
|
| 903 |
)
|
| 904 |
),
|
| 905 |
-
h4("
|
| 906 |
tags$ol(
|
| 907 |
-
tags$li("
|
| 908 |
-
tags$li("
|
| 909 |
-
tags$li("
|
| 910 |
-
tags$li("
|
| 911 |
-
tags$li("position[i] = position[i-1] + cM_distance."),
|
| 912 |
-
tags$li("If r ≥ threshold (unlinked): add 50 cM placeholder gap.")
|
| 913 |
),
|
| 914 |
h4("Required Input Format"),
|
| 915 |
tags$ul(
|
| 916 |
tags$li("Excel (.xlsx): Column 1 = 'Marker', Column 2 = 'Chromosome'"),
|
| 917 |
-
tags$li("Genotype columns:
|
| 918 |
-
tags$li("Chromosome column: integer
|
| 919 |
),
|
| 920 |
h4("Genotype Encoding Reference"),
|
| 921 |
tableOutput("encoding_table")
|
|
@@ -923,8 +795,29 @@ ui <- fluidPage(
|
|
| 923 |
)
|
| 924 |
),
|
| 925 |
|
| 926 |
-
|
| 927 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 928 |
)
|
| 929 |
|
| 930 |
# ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -937,40 +830,36 @@ server <- function(input, output, session) {
|
|
| 937 |
analysis_results <- reactiveVal(NULL)
|
| 938 |
upload_log <- reactiveVal("")
|
| 939 |
|
| 940 |
-
# ── Encoding reference table ─────────────────────────────────────────────
|
| 941 |
output$encoding_table <- renderTable({
|
| 942 |
data.frame(
|
| 943 |
-
`Numeric Code` = c("2",
|
| 944 |
-
`Text Code` = c("a",
|
| 945 |
-
Meaning = c("Homozygous Parent 1 (AA)",
|
| 946 |
-
"
|
| 947 |
-
|
| 948 |
-
"Missing data"),
|
| 949 |
-
check.names = FALSE
|
| 950 |
)
|
| 951 |
-
}, striped
|
| 952 |
|
| 953 |
-
# ── File upload ──────────────────────────────────────────────────────────
|
| 954 |
observeEvent(input$file, {
|
| 955 |
req(input$file)
|
| 956 |
tryCatch({
|
| 957 |
-
df
|
| 958 |
-
n_chr
|
| 959 |
log_msg <- paste0(
|
| 960 |
"✓ File loaded: ", input$file$name, "\n",
|
| 961 |
" Markers : ", nrow(df), "\n",
|
| 962 |
-
" Individuals : ", ncol(df) - 3, "
|
| 963 |
" Chromosomes : ", n_chr,
|
| 964 |
-
" (", paste(sort(unique(df$Chromosome)), collapse
|
| 965 |
" Genotype codes converted to a/b/ab/-\n",
|
| 966 |
" Marker order will be PRESERVED from input file.\n"
|
| 967 |
)
|
| 968 |
uploaded_data(df)
|
| 969 |
upload_log(log_msg)
|
| 970 |
-
showNotification("File uploaded and converted successfully!", type
|
| 971 |
-
}, error
|
| 972 |
upload_log(paste0("✗ Error: ", e$message))
|
| 973 |
-
showNotification(paste("Upload error:", e$message), type
|
| 974 |
})
|
| 975 |
})
|
| 976 |
|
|
@@ -979,35 +868,28 @@ server <- function(input, output, session) {
|
|
| 979 |
output$preview_table <- renderDataTable({
|
| 980 |
req(uploaded_data())
|
| 981 |
df_show <- head(uploaded_data(), 10)
|
| 982 |
-
|
| 983 |
-
df_show
|
| 984 |
-
datatable(df_show,
|
| 985 |
-
options = list(scrollX = TRUE, dom = "t", pageLength = 10),
|
| 986 |
-
rownames = FALSE)
|
| 987 |
})
|
| 988 |
|
| 989 |
output$chr_summary_table <- renderDataTable({
|
| 990 |
req(uploaded_data())
|
| 991 |
df <- uploaded_data()
|
| 992 |
-
chr_tab <- df %>%
|
| 993 |
-
|
| 994 |
-
summarise(N_Markers = n(), .groups = "drop") %>%
|
| 995 |
arrange(suppressWarnings(as.numeric(Chromosome)))
|
| 996 |
-
datatable(chr_tab,
|
| 997 |
-
|
| 998 |
-
rownames = FALSE,
|
| 999 |
-
caption = "Markers per chromosome (in input order)")
|
| 1000 |
})
|
| 1001 |
|
| 1002 |
-
# ── Run analysis ─────────────────────────────────────────────────────────
|
| 1003 |
observeEvent(input$run_analysis, {
|
| 1004 |
req(uploaded_data())
|
| 1005 |
showModal(modalDialog(
|
| 1006 |
-
title
|
| 1007 |
paste0("Population type: ", input$population_type, "\n",
|
| 1008 |
-
"
|
| 1009 |
-
"
|
| 1010 |
-
footer
|
| 1011 |
))
|
| 1012 |
tryCatch({
|
| 1013 |
result <- create_linkage_map(
|
|
@@ -1015,212 +897,191 @@ server <- function(input, output, session) {
|
|
| 1015 |
population_type = input$population_type,
|
| 1016 |
missing_threshold = input$missing_threshold,
|
| 1017 |
recombination_threshold = input$recombination_threshold,
|
| 1018 |
-
chi_square_threshold = input$chi_square_threshold,
|
| 1019 |
-
cluster_threshold = input$cluster_threshold,
|
| 1020 |
max_total_cm = input$max_total_cm,
|
| 1021 |
-
scaling_method = input$scaling_method
|
| 1022 |
-
allow_distorted_f2 = input$allow_distorted_f2
|
| 1023 |
)
|
| 1024 |
analysis_results(result)
|
| 1025 |
-
|
| 1026 |
chromosomes <- unique(result$linkage_map$Chromosome)
|
| 1027 |
-
chr_sorted <- tryCatch(
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
error = function(e) sort(chromosomes)
|
| 1031 |
-
)
|
| 1032 |
updateSelectInput(session, "chromosome_select",
|
| 1033 |
-
choices
|
| 1034 |
-
selected = chr_sorted)
|
| 1035 |
removeModal()
|
| 1036 |
-
n_pos
|
|
|
|
| 1037 |
showNotification(
|
| 1038 |
-
paste0("Analysis complete! ", n_pos, " markers positioned
|
| 1039 |
-
|
|
|
|
| 1040 |
)
|
| 1041 |
-
}, error
|
| 1042 |
removeModal()
|
| 1043 |
-
showNotification(paste("Analysis error:", e$message), type
|
| 1044 |
})
|
| 1045 |
})
|
| 1046 |
|
| 1047 |
output$analysis_run <- reactive({ !is.null(analysis_results()) })
|
| 1048 |
-
outputOptions(output, "analysis_run", suspendWhenHidden
|
| 1049 |
|
| 1050 |
-
# ── QC report ────────────────────────────────────────────────────────────
|
| 1051 |
output$qc_report_output <- renderText({
|
| 1052 |
if (is.null(analysis_results())) return("No analysis run yet.")
|
| 1053 |
analysis_results()$qc_report
|
| 1054 |
})
|
| 1055 |
|
| 1056 |
-
# ──
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1057 |
output$scaling_summary <- renderText({
|
| 1058 |
req(analysis_results())
|
| 1059 |
-
paste0("Method : ", input$scaling_method,
|
| 1060 |
-
"\nMax cM : ", input$max_total_cm)
|
| 1061 |
})
|
| 1062 |
|
| 1063 |
fmt_chr <- function(df) {
|
| 1064 |
if (is.null(df) || nrow(df) == 0) return("No data.")
|
| 1065 |
-
total <- sum(df$Original_Length, na.rm
|
| 1066 |
rows <- apply(df, 1, function(x)
|
| 1067 |
-
paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),
|
| 1068 |
-
paste0("Total : ", round(total,
|
| 1069 |
}
|
|
|
|
|
|
|
| 1070 |
|
| 1071 |
-
output$before_scaling_stats <- renderText({
|
| 1072 |
-
req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_before)
|
| 1073 |
-
})
|
| 1074 |
-
output$after_scaling_stats <- renderText({
|
| 1075 |
-
req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_after)
|
| 1076 |
-
})
|
| 1077 |
-
|
| 1078 |
-
# ── Result table ──────────────────────────────────────────────────────────
|
| 1079 |
output$result_table <- renderDataTable({
|
| 1080 |
req(analysis_results())
|
| 1081 |
lm <- analysis_results()$linkage_map
|
| 1082 |
if (nrow(lm) > 0) {
|
| 1083 |
-
datatable(lm,
|
| 1084 |
-
|
| 1085 |
-
|
| 1086 |
-
# Do NOT auto-sort — preserve display order
|
| 1087 |
-
order = list()),
|
| 1088 |
-
rownames = FALSE,
|
| 1089 |
-
caption = paste0(
|
| 1090 |
-
"Linkage map — positions in cM | ",
|
| 1091 |
-
"Marker order: exactly as in input file | ",
|
| 1092 |
-
"First marker per chromosome = 0 cM"
|
| 1093 |
-
)) %>%
|
| 1094 |
formatRound("Position", 2)
|
| 1095 |
} else {
|
| 1096 |
-
datatable(
|
| 1097 |
-
|
| 1098 |
-
options = list(dom = "t"), rownames = FALSE
|
| 1099 |
-
)
|
| 1100 |
}
|
| 1101 |
})
|
| 1102 |
|
| 1103 |
-
# ── Summary stats ─────────────────────────────────────────────────────────
|
| 1104 |
output$summary_stats <- renderText({
|
| 1105 |
req(analysis_results())
|
| 1106 |
lm <- analysis_results()$linkage_map
|
| 1107 |
rec <- analysis_results()$recombination_data
|
| 1108 |
-
if (nrow(lm) == 0)
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
|
| 1112 |
-
n_chr <- length(unique(lm$Chromosome))
|
| 1113 |
-
|
| 1114 |
-
chr_lengths <- lm %>%
|
| 1115 |
-
filter(!is.na(Position)) %>%
|
| 1116 |
group_by(Chromosome) %>%
|
| 1117 |
-
summarise(Length
|
| 1118 |
-
N_markers = n(), .groups = "drop") %>%
|
| 1119 |
arrange(suppressWarnings(as.numeric(Chromosome)))
|
| 1120 |
-
|
| 1121 |
total_len <- sum(chr_lengths$Length)
|
| 1122 |
avg_len <- mean(chr_lengths$Length)
|
| 1123 |
-
|
| 1124 |
-
|
| 1125 |
-
|
| 1126 |
-
|
| 1127 |
-
|
| 1128 |
-
|
| 1129 |
-
|
| 1130 |
paste0(
|
| 1131 |
-
"LINKAGE MAP SUMMARY (v4.
|
| 1132 |
"===========================\n",
|
| 1133 |
"Population type : ", input$population_type, "\n",
|
| 1134 |
"Marker order : Preserved from input file\n",
|
| 1135 |
-
"
|
|
|
|
| 1136 |
"Total markers input : ", nrow(analysis_results()$original_data), "\n",
|
| 1137 |
-
"
|
| 1138 |
-
"
|
| 1139 |
-
"Total
|
| 1140 |
-
"
|
| 1141 |
-
"
|
|
|
|
|
|
|
|
|
|
| 1142 |
"PER-CHROMOSOME DETAILS:\n", chr_detail
|
| 1143 |
)
|
| 1144 |
})
|
| 1145 |
|
| 1146 |
-
# ── Palette preview ───────────────────────────────────────────────────────
|
| 1147 |
output$palette_preview <- renderPlot({
|
| 1148 |
req(input$color_palette)
|
| 1149 |
-
cols <- tryCatch(brewer.pal(8, input$color_palette),
|
| 1150 |
-
error = function(e) brewer.pal(8, "Set2"))
|
| 1151 |
n <- length(cols)
|
| 1152 |
-
df <- data.frame(x
|
| 1153 |
-
ggplot(df, aes(x, y, fill
|
| 1154 |
-
geom_tile(width
|
| 1155 |
-
scale_x_continuous(breaks
|
| 1156 |
-
labs(title
|
| 1157 |
theme_minimal() +
|
| 1158 |
-
theme(axis.text.y
|
| 1159 |
-
axis.title
|
| 1160 |
-
plot.title
|
| 1161 |
-
}, height
|
| 1162 |
|
| 1163 |
-
# ── Chromosome plot ───────────────────────────────────────────────────────
|
| 1164 |
output$chromosome_plot <- renderPlot({
|
| 1165 |
req(analysis_results(), input$chromosome_select)
|
| 1166 |
create_multi_chromosome_plot(
|
| 1167 |
-
analysis_results()$linkage_map,
|
| 1168 |
-
input$
|
| 1169 |
-
|
| 1170 |
-
|
| 1171 |
-
|
| 1172 |
-
plot_width = input$plot_width,
|
| 1173 |
-
plot_height = input$plot_height,
|
| 1174 |
-
chrom_spacing = input$chrom_spacing,
|
| 1175 |
-
point_size = input$point_size
|
| 1176 |
)
|
| 1177 |
-
}, height
|
| 1178 |
|
| 1179 |
-
# ── Downloads ─────────────────────────────────────────────────────────────
|
| 1180 |
output$download_results <- downloadHandler(
|
| 1181 |
-
filename
|
| 1182 |
-
content
|
| 1183 |
req(analysis_results())
|
| 1184 |
wb <- createWorkbook()
|
| 1185 |
addWorksheet(wb, "Original_Data")
|
| 1186 |
addWorksheet(wb, "Recombination_Fractions")
|
| 1187 |
addWorksheet(wb, "Linkage_Map")
|
|
|
|
| 1188 |
addWorksheet(wb, "QC_Report")
|
| 1189 |
-
|
| 1190 |
-
# Strip .input_order from export
|
| 1191 |
orig <- analysis_results()$original_data
|
| 1192 |
-
orig <- orig[, colnames(orig) != ".input_order", drop
|
| 1193 |
-
|
| 1194 |
-
writeData(wb, "
|
| 1195 |
-
writeData(wb, "
|
| 1196 |
-
writeData(wb, "
|
| 1197 |
writeData(wb, "QC_Report",
|
| 1198 |
-
data.frame(Report
|
| 1199 |
-
saveWorkbook(wb, file, overwrite
|
| 1200 |
-
}
|
| 1201 |
-
)
|
| 1202 |
-
|
| 1203 |
-
output$download_plot <- downloadHandler(
|
| 1204 |
-
filename = function() paste0("linkage_map_v41_", Sys.Date(), ".png"),
|
| 1205 |
-
content = function(file) {
|
| 1206 |
-
req(analysis_results(), input$chromosome_select)
|
| 1207 |
-
p <- create_multi_chromosome_plot(
|
| 1208 |
-
analysis_results()$linkage_map,
|
| 1209 |
-
input$chromosome_select,
|
| 1210 |
-
label_size = input$marker_label_size,
|
| 1211 |
-
show_labels = input$show_labels,
|
| 1212 |
-
color_palette = input$color_palette,
|
| 1213 |
-
plot_width = input$plot_width,
|
| 1214 |
-
plot_height = input$plot_height,
|
| 1215 |
-
chrom_spacing = input$chrom_spacing,
|
| 1216 |
-
point_size = input$point_size
|
| 1217 |
-
)
|
| 1218 |
-
ggsave(file, p,
|
| 1219 |
-
width = input$plot_width / 300,
|
| 1220 |
-
height = input$plot_height / 300,
|
| 1221 |
-
dpi = 300, bg = "white")
|
| 1222 |
}
|
| 1223 |
)
|
| 1224 |
}
|
| 1225 |
|
| 1226 |
-
shinyApp(ui
|
|
|
|
| 9 |
|
| 10 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 11 |
# DATA LOADING & AUTO-CONVERSION
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 13 |
|
| 14 |
load_and_convert_data <- function(filepath) {
|
|
|
|
| 20 |
|
| 21 |
df_raw <- read.xlsx(filepath, sheet = 1, colNames = TRUE)
|
| 22 |
|
| 23 |
+
if (!("Chromosome" %in% colnames(df_raw)))
|
| 24 |
stop("Column 'Chromosome' not found. Please check your file.")
|
| 25 |
+
if (!("Marker" %in% colnames(df_raw)))
|
|
|
|
| 26 |
stop("Column 'Marker' not found. Please check your file.")
|
|
|
|
| 27 |
|
| 28 |
+
chr_col <- as.character(df_raw$Chromosome)
|
| 29 |
has_formula <- any(grepl("^=", chr_col, ignore.case = FALSE), na.rm = TRUE)
|
| 30 |
|
| 31 |
if (has_formula) {
|
| 32 |
+
inferred <- infer_chromosome_from_marker(df_raw$Marker)
|
| 33 |
n_inferred <- sum(!is.na(inferred))
|
| 34 |
if (n_inferred / nrow(df_raw) >= 0.5) {
|
| 35 |
df_raw$Chromosome <- inferred
|
|
|
|
|
|
|
| 36 |
} else {
|
| 37 |
df_raw$Chromosome <- seq_len(nrow(df_raw))
|
| 38 |
+
warning("Could not infer chromosomes from marker names.")
|
| 39 |
}
|
| 40 |
}
|
| 41 |
|
| 42 |
+
geno_cols <- df_raw[, 3:ncol(df_raw), drop = FALSE]
|
| 43 |
sample_vals <- unique(unlist(geno_cols[1:min(50, nrow(geno_cols)), ]))
|
| 44 |
sample_vals <- sample_vals[!is.na(sample_vals)]
|
| 45 |
|
|
|
|
| 59 |
col
|
| 60 |
}
|
| 61 |
)
|
|
|
|
|
|
|
| 62 |
} else if (!text_encoding) {
|
| 63 |
df_raw[, 3:ncol(df_raw)] <- lapply(
|
| 64 |
df_raw[, 3:ncol(df_raw), drop = FALSE],
|
|
|
|
| 68 |
col
|
| 69 |
}
|
| 70 |
)
|
|
|
|
| 71 |
}
|
| 72 |
|
| 73 |
df_raw$Chromosome <- as.character(df_raw$Chromosome)
|
| 74 |
df_raw$Chromosome[is.na(df_raw$Chromosome) | df_raw$Chromosome == "NA"] <- "Unknown"
|
|
|
|
|
|
|
| 75 |
df_raw$.input_order <- seq_len(nrow(df_raw))
|
|
|
|
| 76 |
df_raw
|
| 77 |
}
|
| 78 |
|
|
|
|
| 79 |
infer_chromosome_from_marker <- function(marker_names) {
|
| 80 |
markers <- as.character(marker_names)
|
| 81 |
chrom <- rep(NA_character_, length(markers))
|
|
|
|
| 82 |
patterns <- list(
|
| 83 |
+
list(regex = "(?i)chr(\\d{1,2})[_\\-]", group = 1),
|
| 84 |
list(regex = "(?i)[_\\-]C(\\d{1,2})[_\\-]", group = 1),
|
| 85 |
list(regex = "(?i)^MSU\\d+_(\\d{1,2})_", group = 1),
|
| 86 |
list(regex = "(?i)^DTY(\\d{1,2})[\\-_]", group = 1),
|
|
|
|
| 90 |
list(regex = "(?i)^R(\\d{1,2})", group = 1),
|
| 91 |
list(regex = "(?i)^Pi(\\d{1,2})", group = 1)
|
| 92 |
)
|
|
|
|
| 93 |
for (i in seq_along(markers)) {
|
| 94 |
m <- markers[i]
|
| 95 |
for (pat in patterns) {
|
| 96 |
if (is.na(pat$group)) {
|
| 97 |
+
if (grepl(pat$regex, m, perl = TRUE)) { chrom[i] <- "1"; break }
|
|
|
|
|
|
|
| 98 |
} else {
|
| 99 |
mt <- regmatches(m, regexpr(pat$regex, m, perl = TRUE))
|
| 100 |
if (length(mt) > 0) {
|
|
|
|
| 116 |
# CORE GENETIC FUNCTIONS
|
| 117 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 118 |
|
|
|
|
| 119 |
calculate_recombination <- function(population_type, genotype1, genotype2) {
|
| 120 |
g1 <- as.character(genotype1)
|
| 121 |
g2 <- as.character(genotype2)
|
|
|
|
| 122 |
keep <- !(g1 %in% c("-", "NA", NA) | g2 %in% c("-", "NA", NA))
|
| 123 |
+
g1 <- g1[keep]; g2 <- g2[keep]
|
| 124 |
n <- length(g1)
|
| 125 |
if (n < 4) return(NA_real_)
|
| 126 |
|
| 127 |
if (population_type == "RIL") {
|
| 128 |
hom <- !(g1 == "ab" | g2 == "ab")
|
| 129 |
+
g1h <- g1[hom]; g2h <- g2[hom]
|
| 130 |
if (length(g1h) < 4) return(NA_real_)
|
| 131 |
r_obs <- mean(g1h != g2h)
|
| 132 |
rf <- r_obs / (2 * (1 - r_obs))
|
| 133 |
+
return(min(rf, 0.4999))
|
|
|
|
| 134 |
|
| 135 |
} else if (population_type == "F2") {
|
| 136 |
+
AA_AA <- sum(g1=="a" & g2=="a"); AA_Aa <- sum(g1=="a" & g2=="ab")
|
| 137 |
+
AA_BB <- sum(g1=="a" & g2=="b"); Aa_AA <- sum(g1=="ab" & g2=="a")
|
| 138 |
+
Aa_Aa <- sum(g1=="ab" & g2=="ab"); Aa_BB <- sum(g1=="ab" & g2=="b")
|
| 139 |
+
BB_AA <- sum(g1=="b" & g2=="a"); BB_Aa <- sum(g1=="b" & g2=="ab")
|
| 140 |
+
BB_BB <- sum(g1=="b" & g2=="b")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
r <- 0.25
|
| 142 |
for (iter in 1:200) {
|
| 143 |
+
r_old <- r; q <- 1 - r
|
| 144 |
+
p_parental <- q^2 + r^2; p_recomb <- 2 * r * q
|
| 145 |
+
norm <- p_parental + p_recomb
|
|
|
|
|
|
|
|
|
|
| 146 |
n_recomb_AaAa <- if (norm > 0) Aa_Aa * p_recomb / norm else 0
|
| 147 |
+
recomb_count <- 2*(AA_BB+BB_AA) + (AA_Aa+Aa_AA+Aa_BB+BB_Aa) + 2*n_recomb_AaAa
|
| 148 |
+
r_new <- max(1e-6, min(recomb_count / (2*n), 0.4999))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
r <- r_new
|
| 150 |
if (abs(r - r_old) < 1e-8) break
|
| 151 |
}
|
| 152 |
return(r)
|
| 153 |
+
} else stop("population_type must be 'RIL' or 'F2'")
|
|
|
|
|
|
|
| 154 |
}
|
| 155 |
|
|
|
|
| 156 |
calculate_cM_kosambi <- function(r) {
|
| 157 |
if (is.na(r)) return(NA_real_)
|
| 158 |
r <- max(0, min(r, 0.4999))
|
| 159 |
if (r == 0) return(0)
|
| 160 |
+
25 * log((1 + 2*r) / (1 - 2*r))
|
| 161 |
}
|
| 162 |
|
| 163 |
+
# ── Monomorphic marker detection ─────────────────────────────────────────────
|
| 164 |
+
detect_monomorphic_markers <- function(df) {
|
| 165 |
+
geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
|
| 166 |
+
is_mono <- apply(df[, geno_cols_idx, drop = FALSE], 1, function(row) {
|
| 167 |
+
vals <- row[!is.na(row) & !(row %in% c("-", "NA", ""))]
|
| 168 |
+
if (length(vals) == 0) return(FALSE)
|
| 169 |
+
unique_vals <- unique(vals[vals %in% c("a", "b", "ab")])
|
| 170 |
+
# Monomorphic = only one allele class (e.g. all "a" or all "b"), no variation
|
| 171 |
+
length(unique_vals) <= 1
|
| 172 |
+
})
|
| 173 |
+
names(is_mono) <- df$Marker
|
| 174 |
+
is_mono
|
| 175 |
+
}
|
| 176 |
|
| 177 |
+
# ── Impute / correct ─────────────────────────────────────────────────────────
|
| 178 |
+
correct_errors_and_impute_missing <- function(df) {
|
| 179 |
+
valid_geno <- c("a", "b", "ab")
|
| 180 |
+
geno_start <- which(colnames(df) == "Chromosome") + 1
|
| 181 |
+
geno_cols_idx <- setdiff(geno_start:ncol(df), which(colnames(df) == ".input_order"))
|
| 182 |
|
| 183 |
for (j in geno_cols_idx) {
|
| 184 |
x <- as.character(df[[j]])
|
|
|
|
| 188 |
}
|
| 189 |
|
| 190 |
if (length(geno_cols_idx) > 0) {
|
| 191 |
+
na_col <- colMeans(is.na(df[, geno_cols_idx, drop = FALSE]))
|
| 192 |
+
keep_idx <- c(seq_len(geno_start - 1),
|
| 193 |
+
geno_cols_idx[na_col < 1],
|
| 194 |
+
which(colnames(df) == ".input_order"))
|
| 195 |
+
keep_idx <- keep_idx[keep_idx <= ncol(df)]
|
| 196 |
+
df <- df[, sort(unique(keep_idx)), drop = FALSE]
|
|
|
|
| 197 |
}
|
| 198 |
|
| 199 |
+
geno_cols_idx2 <- setdiff(geno_start:ncol(df), which(colnames(df) == ".input_order"))
|
|
|
|
|
|
|
|
|
|
| 200 |
if (length(geno_cols_idx2) > 0) {
|
| 201 |
df[, geno_cols_idx2] <- t(apply(df[, geno_cols_idx2, drop = FALSE], 1, function(row) {
|
| 202 |
nas <- is.na(row)
|
|
|
|
| 210 |
df
|
| 211 |
}
|
| 212 |
|
|
|
|
| 213 |
quality_control <- function(df, missing_threshold = 0.1) {
|
| 214 |
if (ncol(df) < 3 || nrow(df) == 0) return(df[0, ])
|
|
|
|
| 215 |
geno_cols_idx <- setdiff(3:(ncol(df)), which(colnames(df) == ".input_order"))
|
| 216 |
if (length(geno_cols_idx) == 0) return(df)
|
|
|
|
| 217 |
geno <- df[, geno_cols_idx, drop = FALSE]
|
| 218 |
miss_frac <- rowMeans(is.na(geno))
|
| 219 |
miss_frac[is.na(miss_frac)] <- 1
|
| 220 |
df[miss_frac <= missing_threshold, ]
|
| 221 |
}
|
| 222 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 224 |
+
# POSITION BUILDING (input order preserved)
|
|
|
|
|
|
|
|
|
|
| 225 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 226 |
|
| 227 |
+
build_positions_from_input_order <- function(df, population_type, recombination_threshold) {
|
| 228 |
+
chromosomes <- unique(df$Chromosome[order(df$.input_order)])
|
|
|
|
|
|
|
|
|
|
| 229 |
geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
|
| 230 |
+
positions_list <- list()
|
|
|
|
| 231 |
recombination_rows <- list()
|
| 232 |
|
| 233 |
for (chr in chromosomes) {
|
|
|
|
| 234 |
sub <- df[df$Chromosome == chr, ]
|
| 235 |
sub <- sub[order(sub$.input_order), ]
|
| 236 |
mks <- sub$Marker
|
|
|
|
| 237 |
if (length(mks) == 0) next
|
|
|
|
|
|
|
| 238 |
pos <- setNames(numeric(length(mks)), mks)
|
| 239 |
|
| 240 |
if (length(mks) > 1) {
|
| 241 |
for (i in 2:length(mks)) {
|
| 242 |
+
m_prev <- mks[i-1]; m_curr <- mks[i]
|
|
|
|
|
|
|
| 243 |
g1 <- unlist(sub[sub$Marker == m_prev, geno_cols_idx])
|
| 244 |
g2 <- unlist(sub[sub$Marker == m_curr, geno_cols_idx])
|
|
|
|
| 245 |
rf <- calculate_recombination(population_type, g1, g2)
|
|
|
|
|
|
|
| 246 |
if (!is.na(rf)) {
|
| 247 |
cM <- calculate_cM_kosambi(rf)
|
| 248 |
+
recombination_rows[[length(recombination_rows)+1]] <-
|
| 249 |
+
data.frame(Marker1=m_prev, Marker2=m_curr,
|
| 250 |
+
RecombinationFraction=rf, MapDistance_cM=cM,
|
| 251 |
+
Chromosome=chr, stringsAsFactors=FALSE)
|
| 252 |
+
pos[i] <- if (rf < recombination_threshold) pos[i-1] + abs(cM)
|
| 253 |
+
else pos[i-1] + 50
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
} else {
|
| 255 |
+
pos[i] <- pos[i-1] + 5
|
|
|
|
| 256 |
}
|
| 257 |
}
|
| 258 |
}
|
|
|
|
| 259 |
for (mk in names(pos)) positions_list[[mk]] <- pos[mk]
|
| 260 |
}
|
| 261 |
+
list(positions_list=positions_list, recombination_rows=recombination_rows)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
}
|
| 263 |
|
|
|
|
| 264 |
scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
|
| 265 |
pos_map <- linkage_map[!is.na(linkage_map$Position), ]
|
| 266 |
if (nrow(pos_map) == 0)
|
| 267 |
+
return(list(scaled_map=linkage_map, chrom_lengths_before=data.frame(),
|
| 268 |
+
chrom_lengths_after=data.frame()))
|
|
|
|
| 269 |
|
| 270 |
before <- pos_map %>%
|
| 271 |
group_by(Chromosome) %>%
|
| 272 |
+
summarise(Original_Length = max(Position, na.rm=TRUE), .groups="drop")
|
| 273 |
|
| 274 |
+
total <- sum(before$Original_Length, na.rm=TRUE)
|
| 275 |
if (total <= max_total_cm || total == 0)
|
| 276 |
+
return(list(scaled_map=linkage_map, chrom_lengths_before=before,
|
| 277 |
+
chrom_lengths_after=before))
|
|
|
|
| 278 |
|
| 279 |
scaled <- linkage_map
|
| 280 |
if (method == "proportional") {
|
|
|
|
| 282 |
} else {
|
| 283 |
n_chr <- nrow(before)
|
| 284 |
before$sf <- ifelse(before$Original_Length > 0,
|
| 285 |
+
(max_total_cm/n_chr)/before$Original_Length, 1)
|
| 286 |
}
|
|
|
|
| 287 |
for (chr in before$Chromosome) {
|
| 288 |
sf <- before$sf[before$Chromosome == chr]
|
| 289 |
idx <- which(scaled$Chromosome == chr & !is.na(scaled$Position))
|
|
|
|
| 292 |
scaled$Position[idx] <- (scaled$Position[idx] - mn) * sf
|
| 293 |
}
|
| 294 |
}
|
|
|
|
| 295 |
after <- scaled %>%
|
| 296 |
filter(!is.na(Position)) %>%
|
| 297 |
group_by(Chromosome) %>%
|
| 298 |
+
summarise(Original_Length = max(Position, na.rm=TRUE), .groups="drop")
|
| 299 |
|
| 300 |
+
list(scaled_map=scaled, chrom_lengths_before=before, chrom_lengths_after=after)
|
|
|
|
|
|
|
| 301 |
}
|
| 302 |
|
| 303 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 304 |
+
# MASTER ANALYSIS — no chi-square, monomorphic removal added
|
| 305 |
+
# ═══════════════════════════════════════════════════════════════════════════════
|
| 306 |
+
|
| 307 |
create_linkage_map <- function(df,
|
| 308 |
population_type = "F2",
|
| 309 |
missing_threshold = 0.1,
|
| 310 |
recombination_threshold = 0.5,
|
|
|
|
|
|
|
| 311 |
max_total_cm = 1500,
|
| 312 |
+
scaling_method = "proportional") {
|
|
|
|
| 313 |
|
| 314 |
empty_result <- function(df_in = df) {
|
| 315 |
list(original_data = df_in,
|
| 316 |
recombination_data = data.frame(),
|
| 317 |
+
linkage_map = data.frame(Marker=character(0),
|
| 318 |
+
Chromosome=character(0),
|
| 319 |
+
Position=numeric(0)),
|
| 320 |
chrom_lengths_before = data.frame(),
|
| 321 |
chrom_lengths_after = data.frame(),
|
| 322 |
+
removal_log = data.frame(),
|
| 323 |
qc_report = "No data passed QC.")
|
| 324 |
}
|
| 325 |
|
|
|
|
| 326 |
df_orig <- df
|
| 327 |
+
if (!(".input_order" %in% colnames(df)))
|
|
|
|
|
|
|
| 328 |
df$.input_order <- seq_len(nrow(df))
|
|
|
|
| 329 |
|
| 330 |
+
# ── Removal log accumulator ────────────────────────────────────────────────
|
| 331 |
+
removal_log <- data.frame(
|
| 332 |
+
Marker = character(0),
|
| 333 |
+
Chromosome = character(0),
|
| 334 |
+
Reason = character(0),
|
| 335 |
+
Detail = character(0),
|
| 336 |
+
stringsAsFactors = FALSE
|
| 337 |
+
)
|
| 338 |
|
| 339 |
+
n_input <- nrow(df)
|
| 340 |
|
| 341 |
+
# ── Step 1: Imputation / error correction ──────────────────────────────────
|
| 342 |
+
df <- correct_errors_and_impute_missing(df)
|
|
|
|
|
|
|
|
|
|
| 343 |
|
| 344 |
+
# ── Step 2: Missing data QC ────────────────────────────────────────────────
|
| 345 |
+
geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
|
| 346 |
+
geno_mat <- df[, geno_cols_idx, drop = FALSE]
|
| 347 |
+
miss_frac <- rowMeans(is.na(geno_mat))
|
| 348 |
+
miss_frac[is.na(miss_frac)] <- 1
|
| 349 |
+
failed_miss <- df$Marker[miss_frac > missing_threshold]
|
| 350 |
+
|
| 351 |
+
if (length(failed_miss) > 0) {
|
| 352 |
+
removal_log <- rbind(removal_log, data.frame(
|
| 353 |
+
Marker = failed_miss,
|
| 354 |
+
Chromosome = df$Chromosome[miss_frac > missing_threshold],
|
| 355 |
+
Reason = "Excess missing data",
|
| 356 |
+
Detail = paste0(round(miss_frac[miss_frac > missing_threshold]*100,1),
|
| 357 |
+
"% missing (threshold: ",
|
| 358 |
+
round(missing_threshold*100,1), "%)"),
|
| 359 |
+
stringsAsFactors = FALSE
|
| 360 |
+
))
|
| 361 |
+
}
|
| 362 |
+
df <- df[miss_frac <= missing_threshold, ]
|
| 363 |
+
if (nrow(df) == 0 || ncol(df) < 3) {
|
| 364 |
+
res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
|
| 365 |
+
}
|
| 366 |
|
| 367 |
+
# ── Step 3: Monomorphic marker removal ────────────────────────────────────
|
| 368 |
+
is_mono <- detect_monomorphic_markers(df)
|
| 369 |
+
mono_markers <- names(is_mono)[is_mono]
|
| 370 |
+
|
| 371 |
+
if (length(mono_markers) > 0) {
|
| 372 |
+
mono_df <- df[df$Marker %in% mono_markers, ]
|
| 373 |
+
# For each monomorphic marker, determine which allele is fixed
|
| 374 |
+
geno_cols_idx2 <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
|
| 375 |
+
details <- sapply(mono_markers, function(mk) {
|
| 376 |
+
row <- df[df$Marker == mk, geno_cols_idx2, drop = FALSE]
|
| 377 |
+
vals <- unlist(row)
|
| 378 |
+
vals <- vals[!is.na(vals) & vals %in% c("a","b","ab")]
|
| 379 |
+
if (length(vals) == 0) return("No informative genotypes")
|
| 380 |
+
tbl <- table(vals)
|
| 381 |
+
dominant <- names(which.max(tbl))
|
| 382 |
+
allele_name <- switch(dominant, a="Homozygous Parent 1 (AA)",
|
| 383 |
+
b="Homozygous Parent 2 (BB)",
|
| 384 |
+
ab="Heterozygous only (ab)", dominant)
|
| 385 |
+
paste0("Fixed as: ", allele_name, " (", round(max(tbl)/sum(tbl)*100,1), "% of genotyped individuals)")
|
| 386 |
+
})
|
| 387 |
+
removal_log <- rbind(removal_log, data.frame(
|
| 388 |
+
Marker = mono_markers,
|
| 389 |
+
Chromosome = mono_df$Chromosome,
|
| 390 |
+
Reason = "Monomorphic marker",
|
| 391 |
+
Detail = details,
|
| 392 |
+
stringsAsFactors = FALSE
|
| 393 |
+
))
|
| 394 |
+
df <- df[!df$Marker %in% mono_markers, ]
|
| 395 |
+
}
|
| 396 |
|
| 397 |
if (nrow(df) == 0) {
|
| 398 |
+
res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
|
|
|
|
|
|
|
| 399 |
}
|
| 400 |
|
| 401 |
+
n_after_qc <- nrow(df)
|
| 402 |
+
|
| 403 |
+
qc_msg <- paste0(
|
| 404 |
+
"QC Report (v4.2 — no chi-square filtering)\n",
|
| 405 |
+
"==========================================\n",
|
| 406 |
+
" Markers input : ", n_input, "\n",
|
| 407 |
+
" Removed (missing data) : ", length(failed_miss), "\n",
|
| 408 |
+
" Removed (monomorphic) : ", length(mono_markers), "\n",
|
| 409 |
+
" Markers retained : ", n_after_qc, "\n\n",
|
| 410 |
+
" NOTE: Chi-square / segregation distortion filtering is DISABLED.\n",
|
| 411 |
+
" Marker ORDER preserved from input file.\n",
|
| 412 |
+
" First marker of each chromosome = 0 cM.\n"
|
| 413 |
)
|
| 414 |
|
| 415 |
+
# ── Build positions ────────────────────────────────────────────────────────
|
| 416 |
+
pos_result <- build_positions_from_input_order(df, population_type, recombination_threshold)
|
| 417 |
positions_list <- pos_result$positions_list
|
| 418 |
recombination_rows <- pos_result$recombination_rows
|
| 419 |
|
| 420 |
+
rec_df <- if (length(recombination_rows) > 0) do.call(rbind, recombination_rows)
|
| 421 |
+
else data.frame()
|
|
|
|
|
|
|
|
|
|
| 422 |
|
| 423 |
if (length(positions_list) == 0) {
|
| 424 |
+
lm_empty <- df[, c("Marker","Chromosome")]
|
| 425 |
lm_empty$Position <- NA_real_
|
| 426 |
+
return(list(original_data=df_orig, recombination_data=rec_df,
|
| 427 |
+
linkage_map=lm_empty, chrom_lengths_before=data.frame(),
|
| 428 |
+
chrom_lengths_after=data.frame(), removal_log=removal_log,
|
| 429 |
+
qc_report=qc_msg))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
}
|
| 431 |
|
| 432 |
+
pos_df <- data.frame(Marker=names(positions_list),
|
| 433 |
+
Position=unlist(positions_list),
|
| 434 |
+
stringsAsFactors=FALSE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
|
| 436 |
+
linkage_map <- merge(df[, c("Marker","Chromosome",".input_order")],
|
| 437 |
+
pos_df, by="Marker", all.x=TRUE)
|
| 438 |
+
linkage_map <- linkage_map[order(linkage_map$Chromosome, linkage_map$.input_order), ]
|
| 439 |
linkage_map$.input_order <- NULL
|
| 440 |
|
|
|
|
| 441 |
scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
|
| 442 |
|
| 443 |
list(original_data = df_orig,
|
|
|
|
| 445 |
linkage_map = scaled$scaled_map,
|
| 446 |
chrom_lengths_before = scaled$chrom_lengths_before,
|
| 447 |
chrom_lengths_after = scaled$chrom_lengths_after,
|
| 448 |
+
removal_log = removal_log,
|
| 449 |
qc_report = qc_msg)
|
| 450 |
}
|
| 451 |
|
|
|
|
| 453 |
# PLOTTING
|
| 454 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 455 |
|
| 456 |
+
create_multi_chromosome_plot <- function(linkage_data, selected_chromosomes,
|
| 457 |
+
label_size=3, show_labels=TRUE,
|
| 458 |
+
color_palette="Set2",
|
| 459 |
+
plot_width=1200, plot_height=800,
|
| 460 |
+
chrom_width=0.5, point_size=2,
|
| 461 |
+
chrom_spacing=5.0) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
chr_sorted <- tryCatch(
|
| 463 |
selected_chromosomes[order(as.numeric(selected_chromosomes))],
|
| 464 |
warning = function(w) sort(selected_chromosomes),
|
| 465 |
error = function(e) sort(selected_chromosomes)
|
| 466 |
)
|
|
|
|
| 467 |
plot_data <- linkage_data %>%
|
| 468 |
filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
|
| 469 |
arrange(match(Chromosome, chr_sorted), Position)
|
| 470 |
|
| 471 |
if (nrow(plot_data) == 0) {
|
| 472 |
return(ggplot() +
|
| 473 |
+
annotate("text", x=0.5, y=0.5,
|
| 474 |
+
label="No valid marker positions available.\nTry relaxing QC parameters.",
|
| 475 |
+
size=5, color="red", hjust=0.5) + theme_void())
|
|
|
|
| 476 |
}
|
| 477 |
|
| 478 |
chrom_stats <- plot_data %>%
|
| 479 |
group_by(Chromosome) %>%
|
| 480 |
+
summarise(max_pos=max(Position), min_pos=min(Position),
|
| 481 |
+
num_markers=n(), .groups="drop") %>%
|
| 482 |
+
mutate(Chromosome=factor(Chromosome, levels=chr_sorted)) %>%
|
|
|
|
| 483 |
arrange(Chromosome) %>%
|
| 484 |
+
mutate(chrom_x=seq(1, by=chrom_spacing, length.out=n()),
|
| 485 |
+
chrom_center=chrom_x)
|
| 486 |
|
| 487 |
plot_data <- plot_data %>%
|
| 488 |
+
left_join(chrom_stats %>% select(Chromosome, chrom_x, chrom_center), by="Chromosome")
|
|
|
|
| 489 |
|
| 490 |
+
n_chrom <- nrow(chrom_stats)
|
| 491 |
palette_ok <- tryCatch({ brewer.pal(max(3, n_chrom), color_palette); TRUE },
|
| 492 |
+
error=function(e) FALSE)
|
| 493 |
+
chrom_colors <- if (palette_ok && n_chrom <= 8)
|
|
|
|
| 494 |
brewer.pal(max(3, n_chrom), color_palette)[seq_len(n_chrom)]
|
| 495 |
+
else if (palette_ok)
|
| 496 |
colorRampPalette(brewer.pal(8, color_palette))(n_chrom)
|
| 497 |
+
else
|
| 498 |
colorRampPalette(brewer.pal(8, "Set2"))(n_chrom)
|
|
|
|
| 499 |
|
| 500 |
p <- ggplot() +
|
| 501 |
+
geom_segment(data=chrom_stats,
|
| 502 |
+
aes(x=chrom_center, xend=chrom_center,
|
| 503 |
+
y=min_pos, yend=max_pos, color=as.factor(Chromosome)),
|
| 504 |
+
linewidth=chrom_width*10, alpha=0.6, lineend="round") +
|
| 505 |
+
geom_point(data=plot_data,
|
| 506 |
+
aes(x=chrom_center, y=Position, color=as.factor(Chromosome)),
|
| 507 |
+
size=point_size, alpha=0.9) +
|
| 508 |
+
geom_text(data=chrom_stats,
|
| 509 |
+
aes(x=chrom_center,
|
| 510 |
+
y=-(max(chrom_stats$max_pos)*0.03),
|
| 511 |
+
label=paste0("Chr\n", Chromosome),
|
| 512 |
+
color=as.factor(Chromosome)),
|
| 513 |
+
size=label_size+1, fontface="bold", vjust=1) +
|
| 514 |
+
scale_color_manual(values=setNames(chrom_colors,
|
| 515 |
+
levels(factor(chrom_stats$Chromosome)))) +
|
| 516 |
+
scale_y_reverse(name="Genetic Position (cM)",
|
| 517 |
+
expand=expansion(mult=c(0.02, 0.12))) +
|
| 518 |
+
scale_x_continuous(breaks=chrom_stats$chrom_center,
|
| 519 |
+
labels=chrom_stats$Chromosome,
|
| 520 |
+
name="Chromosome",
|
| 521 |
+
expand=expansion(mult=0.1)) +
|
| 522 |
+
theme_minimal(base_size=12) +
|
| 523 |
+
theme(legend.position="none",
|
| 524 |
+
axis.text.x=element_blank(), axis.ticks.x=element_blank(),
|
| 525 |
+
axis.title.y=element_text(size=12, face="bold", margin=margin(r=10)),
|
| 526 |
+
axis.title.x=element_text(size=12, face="bold", margin=margin(t=10)),
|
| 527 |
+
panel.grid.major.x=element_blank(), panel.grid.minor.x=element_blank(),
|
| 528 |
+
panel.grid.major.y=element_line(color="grey88", linewidth=0.3),
|
| 529 |
+
panel.grid.minor.y=element_line(color="grey94", linewidth=0.15),
|
| 530 |
+
plot.background=element_rect(fill="white", color=NA),
|
| 531 |
+
panel.background=element_rect(fill="white", color=NA),
|
| 532 |
+
plot.margin=margin(20, 20, 20, 20))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
|
| 534 |
if (show_labels && "Marker" %in% names(plot_data) && nrow(plot_data) <= 500) {
|
| 535 |
p <- p + geom_text_repel(
|
| 536 |
+
data=plot_data,
|
| 537 |
+
aes(x=chrom_center, y=Position, label=Marker, color=as.factor(Chromosome)),
|
| 538 |
+
size=label_size, direction="y", nudge_x=0.3,
|
| 539 |
+
segment.size=0.3, segment.alpha=0.5, max.overlaps=20, show.legend=FALSE
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 540 |
)
|
| 541 |
}
|
| 542 |
p
|
|
|
|
| 547 |
# ═══════════════════════════════════════════════════════════════════════════════
|
| 548 |
|
| 549 |
ui <- fluidPage(
|
| 550 |
+
tags$head(
|
| 551 |
+
tags$script(src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"),
|
| 552 |
+
tags$style(HTML("
|
| 553 |
+
body { background-color:#ffffff; color:#333333;
|
| 554 |
+
font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif; }
|
| 555 |
+
.navbar { background-color:#1E3A8A !important; border-bottom:2px solid #1E40AF; }
|
| 556 |
+
.navbar-brand { color:#ffffff !important; font-weight:bold; }
|
| 557 |
+
.nav-tabs { background-color:#1E3A8A; border-bottom:2px solid #1E40AF; }
|
| 558 |
+
.nav-tabs > li > a { color:#cccccc !important; background-color:#1E3A8A;
|
| 559 |
+
border:1px solid #1E40AF; margin-right:5px; }
|
| 560 |
+
.nav-tabs > li.active > a,
|
| 561 |
+
.nav-tabs > li.active > a:hover,
|
| 562 |
+
.nav-tabs > li.active > a:focus { color:#ffffff !important;
|
| 563 |
+
background-color:#1E40AF; font-weight:bold; }
|
| 564 |
+
.nav-tabs > li > a:hover { background-color:#2563EB; color:#ffffff !important; }
|
| 565 |
+
.well { background-color:#EFF6FF; border:1px solid #BFDBFE; color:#333333; }
|
| 566 |
+
.form-control { background-color:#FFFFFF; color:#333333; border:1px solid #93C5FD; }
|
| 567 |
+
.form-control:focus { border-color:#3B82F6; box-shadow:0 0 0 .2rem rgba(59,130,246,.25); }
|
| 568 |
+
.btn { border:1px solid; }
|
| 569 |
+
.btn-primary { background-color:#1D4ED8; color:#ffffff; border-color:#1E40AF; }
|
| 570 |
+
.btn-primary:hover { background-color:#1E40AF; border-color:#1E3A8A; }
|
| 571 |
+
.btn-success { background-color:#059669; color:#ffffff; border-color:#047857; }
|
| 572 |
+
.btn-success:hover { background-color:#047857; border-color:#065F46; }
|
| 573 |
+
.alert-info { background-color:#DBEAFE; border-color:#93C5FD; color:#1E3A8A; }
|
| 574 |
+
.dataTables_wrapper { color:#333333; }
|
| 575 |
+
table.dataTable { border:1px solid #BFDBFE; }
|
| 576 |
+
.footer { position:fixed; bottom:0; width:100%; background-color:#1E3A8A;
|
| 577 |
+
color:#cccccc; text-align:center; padding:10px;
|
| 578 |
+
border-top:1px solid #1E40AF; font-size:12px; }
|
| 579 |
+
.tab-content h3, .tab-content h4 { color:#1E3A8A; }
|
| 580 |
+
.removal-reason-missing { color:#c0392b; font-weight:bold; }
|
| 581 |
+
.removal-reason-mono { color:#8e44ad; font-weight:bold; }
|
| 582 |
+
/* Camera capture button */
|
| 583 |
+
#camera-btn {
|
| 584 |
+
background: none; border: none; cursor: pointer; padding: 6px 10px;
|
| 585 |
+
border-radius: 6px; color: #1D4ED8; font-size: 22px;
|
| 586 |
+
display: inline-flex; align-items: center; gap: 6px;
|
| 587 |
+
transition: background 0.2s;
|
| 588 |
+
}
|
| 589 |
+
#camera-btn:hover { background: #DBEAFE; }
|
| 590 |
+
#camera-btn span.label { font-size: 13px; vertical-align: middle; color: #1D4ED8; }
|
| 591 |
+
"))
|
| 592 |
+
),
|
| 593 |
+
|
| 594 |
+
navbarPage("Linkage Map Creator v4.2 — Input Order Preserved", id="nav",
|
| 595 |
|
| 596 |
# ── Tab 1: Upload ────────────────────────────────────────────────────────
|
| 597 |
+
tabPanel("Data Upload", icon=icon("upload"),
|
| 598 |
sidebarLayout(
|
| 599 |
+
sidebarPanel(width=4, wellPanel(
|
| 600 |
h3("Upload Data"),
|
| 601 |
fileInput("file", "Choose Excel File (.xlsx)",
|
| 602 |
+
accept=c(".xlsx",".xls"),
|
| 603 |
+
buttonLabel="Browse…", placeholder="No file selected"),
|
|
|
|
| 604 |
selectInput("population_type", "Population Type:",
|
| 605 |
+
choices=c("F2"="F2","RIL"="RIL"), selected="F2"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 606 |
hr(),
|
| 607 |
+
div(class="alert alert-info",
|
| 608 |
+
tags$b("v4.2 Key Behaviour:"), br(),
|
| 609 |
+
tags$b("• Monomorphic markers removed automatically"), br(),
|
| 610 |
+
tags$b("• Chi-square / segregation filter DISABLED"), br(),
|
| 611 |
+
tags$b("• Marker order from input file preserved"), br(),
|
| 612 |
+
"• First marker of every chromosome = 0 cM", br(),
|
| 613 |
+
"• Removal details shown in QC Report tab"
|
| 614 |
)
|
| 615 |
)),
|
| 616 |
+
mainPanel(width=8,
|
| 617 |
+
wellPanel(h3("Upload Status"), verbatimTextOutput("upload_status")),
|
| 618 |
+
wellPanel(h3("Data Preview (first 10 rows, converted)"),
|
| 619 |
+
div(style="overflow-x:auto;", dataTableOutput("preview_table"))),
|
| 620 |
+
wellPanel(h3("Chromosome Assignments"),
|
| 621 |
+
div(style="overflow-x:auto;", dataTableOutput("chr_summary_table")))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
)
|
| 623 |
)
|
| 624 |
),
|
| 625 |
|
| 626 |
# ── Tab 2: Parameters ───────────────────────────────────────────────────
|
| 627 |
+
tabPanel("Parameters", icon=icon("sliders-h"),
|
| 628 |
sidebarLayout(
|
| 629 |
+
sidebarPanel(width=4, wellPanel(
|
| 630 |
h3("Analysis Parameters"),
|
| 631 |
+
sliderInput("missing_threshold", "Missing Data Threshold (per marker):",
|
| 632 |
+
min=0, max=1, value=0.3, step=0.05),
|
| 633 |
+
sliderInput("recombination_threshold", "Max Recombination Fraction (r):",
|
| 634 |
+
min=0, max=0.5, value=0.45, step=0.01),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 635 |
hr(),
|
| 636 |
h4("Map Scaling"),
|
| 637 |
+
numericInput("max_total_cm", "Max Total Map Length (cM):",
|
| 638 |
+
min=100, max=10000, value=1500, step=100),
|
|
|
|
| 639 |
selectInput("scaling_method", "Scaling Method:",
|
| 640 |
+
choices=c("Proportional"="proportional","Uniform"="uniform"),
|
| 641 |
+
selected="proportional"),
|
|
|
|
| 642 |
hr(),
|
| 643 |
actionButton("run_analysis", "▶ Run Analysis",
|
| 644 |
+
class="btn-primary btn-block", icon=icon("play"))
|
| 645 |
)),
|
| 646 |
+
mainPanel(width=8, wellPanel(
|
| 647 |
h3("Parameter Guide"),
|
| 648 |
tags$ul(
|
| 649 |
tags$li(tags$b("Missing Data Threshold:"),
|
| 650 |
+
" Markers with > this fraction missing are removed."),
|
|
|
|
| 651 |
tags$li(tags$b("Max Recombination Fraction:"),
|
| 652 |
+
" Pairs with r ≥ threshold get a 50 cM placeholder gap."),
|
| 653 |
+
tags$li(tags$b("Monomorphic Removal:"),
|
| 654 |
+
tags$b(" Automatic — no parameter needed."),
|
| 655 |
+
" Any marker fixed as a single allele class across all individuals is removed."),
|
| 656 |
+
tags$li(tags$b("Chi-Square Filter:"),
|
| 657 |
+
tags$b(" Disabled in v4.2."),
|
| 658 |
+
" All markers passing missing-data and monomorphic checks are retained."),
|
| 659 |
tags$li(tags$b("Marker Order:"),
|
| 660 |
+
tags$b(" Preserved from input file."), " No MDS reordering.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 661 |
),
|
| 662 |
br(),
|
| 663 |
+
h4("Scaling Summary"), verbatimTextOutput("scaling_summary"),
|
| 664 |
+
h4("Before Scaling"), verbatimTextOutput("before_scaling_stats"),
|
| 665 |
+
h4("After Scaling"), verbatimTextOutput("after_scaling_stats")
|
|
|
|
|
|
|
|
|
|
| 666 |
))
|
| 667 |
)
|
| 668 |
),
|
| 669 |
|
| 670 |
# ── Tab 3: QC Report ────────────────────────────────────────────────────
|
| 671 |
+
tabPanel("QC Report", icon=icon("clipboard-check"),
|
| 672 |
wellPanel(
|
| 673 |
h3("Quality Control Report"),
|
| 674 |
verbatimTextOutput("qc_report_output")
|
| 675 |
+
),
|
| 676 |
+
wellPanel(
|
| 677 |
+
h3("Removed Markers — Full Detail"),
|
| 678 |
+
p("Every marker removed during QC is listed below with the exact reason and supporting statistics."),
|
| 679 |
+
div(style="overflow-x:auto;", dataTableOutput("removal_log_table")),
|
| 680 |
+
br(),
|
| 681 |
+
downloadButton("download_removal_log", "⬇ Download Removal Log (.xlsx)",
|
| 682 |
+
class="btn-success")
|
| 683 |
)
|
| 684 |
),
|
| 685 |
|
| 686 |
# ── Tab 4: Results ───────────────────────────────────────────────────────
|
| 687 |
+
tabPanel("Results", icon=icon("table"),
|
| 688 |
fluidRow(column(12, wellPanel(
|
| 689 |
h3("Analysis Results"),
|
| 690 |
conditionalPanel("output.analysis_run",
|
| 691 |
downloadButton("download_results", "⬇ Download Excel Results",
|
| 692 |
+
class="btn-success"),
|
| 693 |
br(), br(),
|
| 694 |
h4("Linkage Map (Input Order Preserved, First Marker = 0 cM)"),
|
| 695 |
+
div(style="overflow-x:auto;", dataTableOutput("result_table")),
|
| 696 |
+
h4("Summary Statistics"), verbatimTextOutput("summary_stats")
|
|
|
|
| 697 |
),
|
| 698 |
conditionalPanel("!output.analysis_run",
|
| 699 |
p("Upload data and click 'Run Analysis' to see results.",
|
| 700 |
+
style="color:#888;font-style:italic;text-align:center;padding:40px;")
|
| 701 |
)
|
| 702 |
)))
|
| 703 |
),
|
| 704 |
|
| 705 |
# ── Tab 5: Plot Options ──────────────────────────────────────────────────
|
| 706 |
+
tabPanel("Plot Options", icon=icon("palette"),
|
| 707 |
sidebarLayout(
|
| 708 |
+
sidebarPanel(width=4, wellPanel(
|
| 709 |
h3("Visualization Options"),
|
| 710 |
selectInput("color_palette", "Color Palette:",
|
| 711 |
+
choices=c("Set1","Set2","Set3","Paired","Dark2","Accent","Spectral","RdBu"),
|
| 712 |
+
selected="Set2"),
|
| 713 |
+
checkboxInput("show_labels", "Show Marker Labels", value=FALSE),
|
| 714 |
+
sliderInput("marker_label_size", "Label Size:", min=1, max=8, value=2, step=0.5),
|
| 715 |
+
sliderInput("plot_width", "Plot Width (px):", min=600, max=2400, value=1400, step=100),
|
| 716 |
+
sliderInput("plot_height", "Plot Height (px):", min=400, max=1600, value=800, step=50),
|
| 717 |
+
sliderInput("chrom_spacing", "Chromosome Spacing:", min=2, max=15, value=5, step=0.5),
|
| 718 |
+
sliderInput("point_size", "Marker Point Size:", min=0.5, max=5, value=1.5, step=0.25)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 719 |
)),
|
| 720 |
+
mainPanel(width=8, wellPanel(
|
| 721 |
h3("Palette Preview"),
|
| 722 |
+
plotOutput("palette_preview", height="180px")
|
| 723 |
))
|
| 724 |
)
|
| 725 |
),
|
| 726 |
|
| 727 |
# ── Tab 6: Visualization ─────────────────────────────────────────────────
|
| 728 |
+
tabPanel("Visualization", icon=icon("chart-bar"),
|
| 729 |
fluidRow(column(12, wellPanel(
|
| 730 |
h3("Chromosome Map"),
|
| 731 |
conditionalPanel("output.analysis_run",
|
| 732 |
fluidRow(
|
| 733 |
column(8, selectInput("chromosome_select", "Select Chromosomes:",
|
| 734 |
+
choices=NULL, multiple=TRUE)),
|
| 735 |
column(4, br(),
|
| 736 |
+
# Camera icon button (replaces download button)
|
| 737 |
+
tags$button(id="camera-btn", onclick="captureChromPlot()",
|
| 738 |
+
tags$span("\U0001F4F7"), # camera emoji
|
| 739 |
+
tags$span("Save image", class="label")
|
| 740 |
+
)
|
| 741 |
+
)
|
| 742 |
),
|
| 743 |
+
# Wrapper div for html2canvas capture
|
| 744 |
+
div(id="chrom-plot-wrapper",
|
| 745 |
+
style="background:white;",
|
| 746 |
+
plotOutput("chromosome_plot", height="auto")
|
| 747 |
+
)
|
| 748 |
),
|
| 749 |
conditionalPanel("!output.analysis_run",
|
| 750 |
p("Run analysis first.",
|
| 751 |
+
style="color:#888;font-style:italic;text-align:center;padding:40px;")
|
| 752 |
)
|
| 753 |
)))
|
| 754 |
),
|
| 755 |
|
| 756 |
# ── Tab 7: Help ──────────────────────────────────────────────────────────
|
| 757 |
+
tabPanel("Help", icon=icon("question-circle"),
|
| 758 |
wellPanel(
|
| 759 |
+
h3("Application Guide — v4.2"),
|
| 760 |
+
h4("What's New in v4.2"),
|
| 761 |
+
div(class="alert alert-info",
|
| 762 |
tags$ul(
|
| 763 |
+
tags$li(tags$b("Monomorphic marker removal added:"),
|
| 764 |
+
" Any marker where all genotyped individuals share the same allele class ",
|
| 765 |
+
"(e.g. all AA, or all BB) is automatically removed and logged with the ",
|
| 766 |
+
"fixed allele and frequency."),
|
| 767 |
+
tags$li(tags$b("Chi-square / segregation distortion filter removed:"),
|
| 768 |
+
" All markers passing missing-data and monomorphic filters are retained. ",
|
| 769 |
+
"Distorted but polymorphic markers are now kept."),
|
| 770 |
+
tags$li(tags$b("Full removal log:"),
|
| 771 |
+
" Every removed marker is listed in the QC Report tab with Marker, ",
|
| 772 |
+
"Chromosome, Reason, and Detail columns. Downloadable as Excel."),
|
| 773 |
+
tags$li(tags$b("Camera icon for plot saving:"),
|
| 774 |
+
" The download button on the Visualization tab has been replaced by a ",
|
| 775 |
+
"camera icon that uses html2canvas to capture the rendered plot exactly ",
|
| 776 |
+
"as displayed — preventing the distortion caused by ggplot PNG export.")
|
| 777 |
)
|
| 778 |
),
|
| 779 |
+
h4("Monomorphic Marker Logic"),
|
| 780 |
tags$ol(
|
| 781 |
+
tags$li("Missing and non-standard genotype values are excluded before the check."),
|
| 782 |
+
tags$li("A marker is monomorphic if only one allele class (a, b, or ab) is observed."),
|
| 783 |
+
tags$li("The fixed allele and its frequency are reported in the removal log."),
|
| 784 |
+
tags$li("Markers with zero informative genotypes are also flagged.")
|
|
|
|
|
|
|
| 785 |
),
|
| 786 |
h4("Required Input Format"),
|
| 787 |
tags$ul(
|
| 788 |
tags$li("Excel (.xlsx): Column 1 = 'Marker', Column 2 = 'Chromosome'"),
|
| 789 |
+
tags$li("Genotype columns: a/b/ab/- OR numeric 2/1/0/-1"),
|
| 790 |
+
tags$li("Chromosome column: integer numbers OR Excel VLOOKUP formulas")
|
| 791 |
),
|
| 792 |
h4("Genotype Encoding Reference"),
|
| 793 |
tableOutput("encoding_table")
|
|
|
|
| 795 |
)
|
| 796 |
),
|
| 797 |
|
| 798 |
+
# JavaScript for camera capture
|
| 799 |
+
tags$script(HTML("
|
| 800 |
+
function captureChromPlot() {
|
| 801 |
+
var el = document.getElementById('chrom-plot-wrapper');
|
| 802 |
+
if (!el) { alert('Plot not found.'); return; }
|
| 803 |
+
html2canvas(el, {
|
| 804 |
+
backgroundColor: '#ffffff',
|
| 805 |
+
scale: 2,
|
| 806 |
+
useCORS: true,
|
| 807 |
+
logging: false
|
| 808 |
+
}).then(function(canvas) {
|
| 809 |
+
var link = document.createElement('a');
|
| 810 |
+
link.download = 'linkage_map_' + new Date().toISOString().slice(0,10) + '.png';
|
| 811 |
+
link.href = canvas.toDataURL('image/png');
|
| 812 |
+
link.click();
|
| 813 |
+
}).catch(function(err) {
|
| 814 |
+
alert('Capture failed: ' + err);
|
| 815 |
+
});
|
| 816 |
+
}
|
| 817 |
+
")),
|
| 818 |
+
|
| 819 |
+
div(class="footer",
|
| 820 |
+
"Linkage Map Creator v4.2 | Monomorphic removal | No chi-square | Input order preserved | © 2024")
|
| 821 |
)
|
| 822 |
|
| 823 |
# ═══════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 830 |
analysis_results <- reactiveVal(NULL)
|
| 831 |
upload_log <- reactiveVal("")
|
| 832 |
|
|
|
|
| 833 |
output$encoding_table <- renderTable({
|
| 834 |
data.frame(
|
| 835 |
+
`Numeric Code` = c("2","1","0","-1"),
|
| 836 |
+
`Text Code` = c("a","b","ab","-"),
|
| 837 |
+
Meaning = c("Homozygous Parent 1 (AA)","Homozygous Parent 2 (BB)",
|
| 838 |
+
"Heterozygous (Aa)","Missing data"),
|
| 839 |
+
check.names=FALSE
|
|
|
|
|
|
|
| 840 |
)
|
| 841 |
+
}, striped=TRUE, hover=TRUE, bordered=TRUE)
|
| 842 |
|
|
|
|
| 843 |
observeEvent(input$file, {
|
| 844 |
req(input$file)
|
| 845 |
tryCatch({
|
| 846 |
+
df <- load_and_convert_data(input$file$datapath)
|
| 847 |
+
n_chr <- length(unique(df$Chromosome))
|
| 848 |
log_msg <- paste0(
|
| 849 |
"✓ File loaded: ", input$file$name, "\n",
|
| 850 |
" Markers : ", nrow(df), "\n",
|
| 851 |
+
" Individuals : ", ncol(df) - 3, "\n",
|
| 852 |
" Chromosomes : ", n_chr,
|
| 853 |
+
" (", paste(sort(unique(df$Chromosome)), collapse=", "), ")\n",
|
| 854 |
" Genotype codes converted to a/b/ab/-\n",
|
| 855 |
" Marker order will be PRESERVED from input file.\n"
|
| 856 |
)
|
| 857 |
uploaded_data(df)
|
| 858 |
upload_log(log_msg)
|
| 859 |
+
showNotification("File uploaded and converted successfully!", type="message")
|
| 860 |
+
}, error=function(e) {
|
| 861 |
upload_log(paste0("✗ Error: ", e$message))
|
| 862 |
+
showNotification(paste("Upload error:", e$message), type="error")
|
| 863 |
})
|
| 864 |
})
|
| 865 |
|
|
|
|
| 868 |
output$preview_table <- renderDataTable({
|
| 869 |
req(uploaded_data())
|
| 870 |
df_show <- head(uploaded_data(), 10)
|
| 871 |
+
df_show <- df_show[, colnames(df_show) != ".input_order", drop=FALSE]
|
| 872 |
+
datatable(df_show, options=list(scrollX=TRUE, dom="t", pageLength=10), rownames=FALSE)
|
|
|
|
|
|
|
|
|
|
| 873 |
})
|
| 874 |
|
| 875 |
output$chr_summary_table <- renderDataTable({
|
| 876 |
req(uploaded_data())
|
| 877 |
df <- uploaded_data()
|
| 878 |
+
chr_tab <- df %>% group_by(Chromosome) %>%
|
| 879 |
+
summarise(N_Markers=n(), .groups="drop") %>%
|
|
|
|
| 880 |
arrange(suppressWarnings(as.numeric(Chromosome)))
|
| 881 |
+
datatable(chr_tab, options=list(dom="t", pageLength=30), rownames=FALSE,
|
| 882 |
+
caption="Markers per chromosome (input order)")
|
|
|
|
|
|
|
| 883 |
})
|
| 884 |
|
|
|
|
| 885 |
observeEvent(input$run_analysis, {
|
| 886 |
req(uploaded_data())
|
| 887 |
showModal(modalDialog(
|
| 888 |
+
title="Building Linkage Map…",
|
| 889 |
paste0("Population type: ", input$population_type, "\n",
|
| 890 |
+
"Removing monomorphic markers. Chi-square filter disabled.\n",
|
| 891 |
+
"Preserving input marker order…"),
|
| 892 |
+
footer=NULL
|
| 893 |
))
|
| 894 |
tryCatch({
|
| 895 |
result <- create_linkage_map(
|
|
|
|
| 897 |
population_type = input$population_type,
|
| 898 |
missing_threshold = input$missing_threshold,
|
| 899 |
recombination_threshold = input$recombination_threshold,
|
|
|
|
|
|
|
| 900 |
max_total_cm = input$max_total_cm,
|
| 901 |
+
scaling_method = input$scaling_method
|
|
|
|
| 902 |
)
|
| 903 |
analysis_results(result)
|
|
|
|
| 904 |
chromosomes <- unique(result$linkage_map$Chromosome)
|
| 905 |
+
chr_sorted <- tryCatch(chromosomes[order(as.numeric(chromosomes))],
|
| 906 |
+
warning=function(w) sort(chromosomes),
|
| 907 |
+
error=function(e) sort(chromosomes))
|
|
|
|
|
|
|
| 908 |
updateSelectInput(session, "chromosome_select",
|
| 909 |
+
choices=chr_sorted, selected=chr_sorted)
|
|
|
|
| 910 |
removeModal()
|
| 911 |
+
n_pos <- sum(!is.na(result$linkage_map$Position))
|
| 912 |
+
n_removed <- nrow(result$removal_log)
|
| 913 |
showNotification(
|
| 914 |
+
paste0("Analysis complete! ", n_pos, " markers positioned. ",
|
| 915 |
+
n_removed, " markers removed (see QC Report)."),
|
| 916 |
+
type="message"
|
| 917 |
)
|
| 918 |
+
}, error=function(e) {
|
| 919 |
removeModal()
|
| 920 |
+
showNotification(paste("Analysis error:", e$message), type="error")
|
| 921 |
})
|
| 922 |
})
|
| 923 |
|
| 924 |
output$analysis_run <- reactive({ !is.null(analysis_results()) })
|
| 925 |
+
outputOptions(output, "analysis_run", suspendWhenHidden=FALSE)
|
| 926 |
|
|
|
|
| 927 |
output$qc_report_output <- renderText({
|
| 928 |
if (is.null(analysis_results())) return("No analysis run yet.")
|
| 929 |
analysis_results()$qc_report
|
| 930 |
})
|
| 931 |
|
| 932 |
+
# ── Removal log table ─────────────────────────────────────────────────────
|
| 933 |
+
output$removal_log_table <- renderDataTable({
|
| 934 |
+
if (is.null(analysis_results())) {
|
| 935 |
+
return(datatable(data.frame(Message="Run analysis first."),
|
| 936 |
+
options=list(dom="t"), rownames=FALSE))
|
| 937 |
+
}
|
| 938 |
+
log_df <- analysis_results()$removal_log
|
| 939 |
+
if (nrow(log_df) == 0) {
|
| 940 |
+
return(datatable(data.frame(Message="No markers were removed during QC."),
|
| 941 |
+
options=list(dom="t"), rownames=FALSE))
|
| 942 |
+
}
|
| 943 |
+
datatable(log_df,
|
| 944 |
+
options=list(scrollX=TRUE, pageLength=25,
|
| 945 |
+
columnDefs=list(list(width="40%", targets=3))),
|
| 946 |
+
rownames=FALSE,
|
| 947 |
+
caption=paste0(nrow(log_df), " marker(s) removed during QC")) %>%
|
| 948 |
+
formatStyle("Reason",
|
| 949 |
+
color=styleEqual(
|
| 950 |
+
c("Excess missing data","Monomorphic marker"),
|
| 951 |
+
c("#c0392b","#8e44ad")
|
| 952 |
+
),
|
| 953 |
+
fontWeight="bold")
|
| 954 |
+
})
|
| 955 |
+
|
| 956 |
+
output$download_removal_log <- downloadHandler(
|
| 957 |
+
filename=function() paste0("removal_log_", Sys.Date(), ".xlsx"),
|
| 958 |
+
content=function(file) {
|
| 959 |
+
req(analysis_results())
|
| 960 |
+
wb <- createWorkbook()
|
| 961 |
+
addWorksheet(wb, "Removed_Markers")
|
| 962 |
+
log_df <- analysis_results()$removal_log
|
| 963 |
+
if (nrow(log_df) == 0)
|
| 964 |
+
log_df <- data.frame(Message="No markers were removed during QC.")
|
| 965 |
+
writeData(wb, "Removed_Markers", log_df)
|
| 966 |
+
saveWorkbook(wb, file, overwrite=TRUE)
|
| 967 |
+
}
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
output$scaling_summary <- renderText({
|
| 971 |
req(analysis_results())
|
| 972 |
+
paste0("Method : ", input$scaling_method, "\nMax cM : ", input$max_total_cm)
|
|
|
|
| 973 |
})
|
| 974 |
|
| 975 |
fmt_chr <- function(df) {
|
| 976 |
if (is.null(df) || nrow(df) == 0) return("No data.")
|
| 977 |
+
total <- sum(df$Original_Length, na.rm=TRUE)
|
| 978 |
rows <- apply(df, 1, function(x)
|
| 979 |
+
paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),2), " cM"))
|
| 980 |
+
paste0("Total : ", round(total,2), " cM\n", paste(rows, collapse="\n"))
|
| 981 |
}
|
| 982 |
+
output$before_scaling_stats <- renderText({ req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_before) })
|
| 983 |
+
output$after_scaling_stats <- renderText({ req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_after) })
|
| 984 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 985 |
output$result_table <- renderDataTable({
|
| 986 |
req(analysis_results())
|
| 987 |
lm <- analysis_results()$linkage_map
|
| 988 |
if (nrow(lm) > 0) {
|
| 989 |
+
datatable(lm, options=list(scrollX=TRUE, pageLength=25, order=list()),
|
| 990 |
+
rownames=FALSE,
|
| 991 |
+
caption="Linkage map — cM positions | Input order preserved | First marker = 0 cM") %>%
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 992 |
formatRound("Position", 2)
|
| 993 |
} else {
|
| 994 |
+
datatable(data.frame(Message="No positioned markers. Try relaxing QC parameters."),
|
| 995 |
+
options=list(dom="t"), rownames=FALSE)
|
|
|
|
|
|
|
| 996 |
}
|
| 997 |
})
|
| 998 |
|
|
|
|
| 999 |
output$summary_stats <- renderText({
|
| 1000 |
req(analysis_results())
|
| 1001 |
lm <- analysis_results()$linkage_map
|
| 1002 |
rec <- analysis_results()$recombination_data
|
| 1003 |
+
if (nrow(lm) == 0) return("No positioned markers.")
|
| 1004 |
+
n_pos <- sum(!is.na(lm$Position))
|
| 1005 |
+
n_chr <- length(unique(lm$Chromosome))
|
| 1006 |
+
chr_lengths <- lm %>% filter(!is.na(Position)) %>%
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1007 |
group_by(Chromosome) %>%
|
| 1008 |
+
summarise(Length=max(Position,na.rm=TRUE), N_markers=n(), .groups="drop") %>%
|
|
|
|
| 1009 |
arrange(suppressWarnings(as.numeric(Chromosome)))
|
|
|
|
| 1010 |
total_len <- sum(chr_lengths$Length)
|
| 1011 |
avg_len <- mean(chr_lengths$Length)
|
| 1012 |
+
chr_detail <- paste(apply(chr_lengths, 1, function(x)
|
| 1013 |
+
paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),2),
|
| 1014 |
+
" cM (", x[3], " markers)")), collapse="\n")
|
| 1015 |
+
n_removed_total <- nrow(analysis_results()$removal_log)
|
| 1016 |
+
n_mono <- sum(analysis_results()$removal_log$Reason == "Monomorphic marker")
|
| 1017 |
+
n_miss <- sum(analysis_results()$removal_log$Reason == "Excess missing data")
|
|
|
|
| 1018 |
paste0(
|
| 1019 |
+
"LINKAGE MAP SUMMARY (v4.2)\n",
|
| 1020 |
"===========================\n",
|
| 1021 |
"Population type : ", input$population_type, "\n",
|
| 1022 |
"Marker order : Preserved from input file\n",
|
| 1023 |
+
"Chi-square filter : DISABLED\n",
|
| 1024 |
+
"First marker position : 0 cM (per chromosome)\n\n",
|
| 1025 |
"Total markers input : ", nrow(analysis_results()$original_data), "\n",
|
| 1026 |
+
" Removed (missing) : ", n_miss, "\n",
|
| 1027 |
+
" Removed (monomorphic): ", n_mono, "\n",
|
| 1028 |
+
" Total removed : ", n_removed_total, "\n",
|
| 1029 |
+
"Markers positioned : ", n_pos, "\n",
|
| 1030 |
+
"Chromosomes / LGs : ", n_chr, "\n",
|
| 1031 |
+
"Total map length : ", round(total_len,2), " cM\n",
|
| 1032 |
+
"Avg chromosome length : ", round(avg_len, 2), " cM\n",
|
| 1033 |
+
"Marker pairs analysed : ", nrow(rec), "\n\n",
|
| 1034 |
"PER-CHROMOSOME DETAILS:\n", chr_detail
|
| 1035 |
)
|
| 1036 |
})
|
| 1037 |
|
|
|
|
| 1038 |
output$palette_preview <- renderPlot({
|
| 1039 |
req(input$color_palette)
|
| 1040 |
+
cols <- tryCatch(brewer.pal(8, input$color_palette), error=function(e) brewer.pal(8,"Set2"))
|
|
|
|
| 1041 |
n <- length(cols)
|
| 1042 |
+
df <- data.frame(x=1:n, y=1, col=cols)
|
| 1043 |
+
ggplot(df, aes(x, y, fill=I(col))) +
|
| 1044 |
+
geom_tile(width=0.9, height=0.9) +
|
| 1045 |
+
scale_x_continuous(breaks=1:n, labels=1:n) +
|
| 1046 |
+
labs(title=paste("Preview —", input$color_palette)) +
|
| 1047 |
theme_minimal() +
|
| 1048 |
+
theme(axis.text.y=element_blank(), axis.ticks.y=element_blank(),
|
| 1049 |
+
axis.title=element_blank(), panel.grid=element_blank(),
|
| 1050 |
+
plot.title=element_text(hjust=0.5, size=14, face="bold"))
|
| 1051 |
+
}, height=180)
|
| 1052 |
|
|
|
|
| 1053 |
output$chromosome_plot <- renderPlot({
|
| 1054 |
req(analysis_results(), input$chromosome_select)
|
| 1055 |
create_multi_chromosome_plot(
|
| 1056 |
+
analysis_results()$linkage_map, input$chromosome_select,
|
| 1057 |
+
label_size=input$marker_label_size, show_labels=input$show_labels,
|
| 1058 |
+
color_palette=input$color_palette, plot_width=input$plot_width,
|
| 1059 |
+
plot_height=input$plot_height, chrom_spacing=input$chrom_spacing,
|
| 1060 |
+
point_size=input$point_size
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1061 |
)
|
| 1062 |
+
}, height=function() input$plot_height)
|
| 1063 |
|
|
|
|
| 1064 |
output$download_results <- downloadHandler(
|
| 1065 |
+
filename=function() paste0("linkage_map_v42_", Sys.Date(), ".xlsx"),
|
| 1066 |
+
content=function(file) {
|
| 1067 |
req(analysis_results())
|
| 1068 |
wb <- createWorkbook()
|
| 1069 |
addWorksheet(wb, "Original_Data")
|
| 1070 |
addWorksheet(wb, "Recombination_Fractions")
|
| 1071 |
addWorksheet(wb, "Linkage_Map")
|
| 1072 |
+
addWorksheet(wb, "Removal_Log")
|
| 1073 |
addWorksheet(wb, "QC_Report")
|
|
|
|
|
|
|
| 1074 |
orig <- analysis_results()$original_data
|
| 1075 |
+
orig <- orig[, colnames(orig) != ".input_order", drop=FALSE]
|
| 1076 |
+
writeData(wb, "Original_Data", orig)
|
| 1077 |
+
writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
|
| 1078 |
+
writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
|
| 1079 |
+
writeData(wb, "Removal_Log", analysis_results()$removal_log)
|
| 1080 |
writeData(wb, "QC_Report",
|
| 1081 |
+
data.frame(Report=analysis_results()$qc_report))
|
| 1082 |
+
saveWorkbook(wb, file, overwrite=TRUE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1083 |
}
|
| 1084 |
)
|
| 1085 |
}
|
| 1086 |
|
| 1087 |
+
shinyApp(ui=ui, server=server)
|