softwareDevelopment commited on
Commit
a3a626b
Β·
verified Β·
1 Parent(s): 325b000

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +300 -293
app.R CHANGED
@@ -17,17 +17,13 @@ library(ggrepel)
17
 
18
  load_and_convert_data <- function(filepath) {
19
 
20
- # ── 1. Read with data_only = TRUE so Excel caches / formula results are read
21
  wb_raw <- tryCatch(
22
  loadWorkbook(filepath),
23
  error = function(e) stop("Cannot open workbook: ", e$message)
24
  )
25
 
26
- # Read sheet 1 using openxlsx (returns formula strings for uneval cells)
27
  df_raw <- read.xlsx(filepath, sheet = 1, colNames = TRUE)
28
 
29
- # ── 2. Detect if Chromosome column contains VLOOKUP formula strings
30
- # If so, try to extract chromosome from marker name (e.g. chr01_xxx β†’ 1)
31
  if (!("Chromosome" %in% colnames(df_raw))) {
32
  stop("Column 'Chromosome' not found. Please check your file.")
33
  }
@@ -39,24 +35,18 @@ load_and_convert_data <- function(filepath) {
39
  has_formula <- any(grepl("^=", chr_col, ignore.case = FALSE), na.rm = TRUE)
40
 
41
  if (has_formula) {
42
- # Strategy A: parse chromosome number from marker name
43
- # Supports: chr01_xxx, IRGSP1_C01_xxx, MSU7_1_xxx, DTY1-1_xxx, Gn1a_x, etc.
44
  inferred <- infer_chromosome_from_marker(df_raw$Marker)
45
-
46
- # If inference succeeded for most markers, use it
47
  n_inferred <- sum(!is.na(inferred))
48
  if (n_inferred / nrow(df_raw) >= 0.5) {
49
  df_raw$Chromosome <- inferred
50
  message(sprintf("[Auto] Chromosome inferred from marker names for %d/%d markers.",
51
  n_inferred, nrow(df_raw)))
52
  } else {
53
- # Strategy B: assign a placeholder group number so analysis can proceed
54
  df_raw$Chromosome <- seq_len(nrow(df_raw))
55
- warning("Could not infer chromosomes from marker names. Each marker placed on its own group. Please supply correct Chromosome values.")
56
  }
57
  }
58
 
59
- # ── 3. Detect genotype encoding and recode to a/ab/b/-
60
  geno_cols <- df_raw[, 3:ncol(df_raw), drop = FALSE]
61
  sample_vals <- unique(unlist(geno_cols[1:min(50, nrow(geno_cols)), ]))
62
  sample_vals <- sample_vals[!is.na(sample_vals)]
@@ -65,8 +55,6 @@ load_and_convert_data <- function(filepath) {
65
  text_encoding <- all(sample_vals %in% c("a", "b", "ab", "-", NA, "NA"))
66
 
67
  if (numeric_encoding) {
68
- # Recode: 2β†’"a", 1β†’"b", 0β†’"ab", -1β†’"-"
69
- recode_map <- c(`2` = "a", `1` = "b", `0` = "ab", `-1` = "-")
70
  df_raw[, 3:ncol(df_raw)] <- lapply(
71
  df_raw[, 3:ncol(df_raw), drop = FALSE],
72
  function(col) {
@@ -82,7 +70,6 @@ load_and_convert_data <- function(filepath) {
82
  message("[Auto] Numeric genotype encoding (2/1/0/-1) detected and converted to a/b/ab/-.")
83
 
84
  } else if (!text_encoding) {
85
- # Try mixed / unknown β€” convert anything not in {a,b,ab} to "-"
86
  df_raw[, 3:ncol(df_raw)] <- lapply(
87
  df_raw[, 3:ncol(df_raw), drop = FALSE],
88
  function(col) {
@@ -94,10 +81,12 @@ load_and_convert_data <- function(filepath) {
94
  message("[Auto] Unknown genotype encoding β€” non-standard values set to missing.")
95
  }
96
 
97
- # ── 4. Ensure Chromosome is clean character (no NA)
98
  df_raw$Chromosome <- as.character(df_raw$Chromosome)
99
  df_raw$Chromosome[is.na(df_raw$Chromosome) | df_raw$Chromosome == "NA"] <- "Unknown"
100
 
 
 
 
101
  df_raw
102
  }
103
 
@@ -107,31 +96,21 @@ infer_chromosome_from_marker <- function(marker_names) {
107
  chrom <- rep(NA_character_, length(markers))
108
 
109
  patterns <- list(
110
- # chr01_xxx or Chr01_xxx
111
- list(regex = "(?i)chr(\\d{1,2})[_\\-]", group = 1),
112
- # IRGSP1_C01_xxx
113
- list(regex = "(?i)[_\\-]C(\\d{1,2})[_\\-]", group = 1),
114
- # MSU7_1_xxx (second field is chromosome)
115
- list(regex = "(?i)^MSU\\d+_(\\d{1,2})_", group = 1),
116
- # DTY1-1_xxx β†’ chromosome 1
117
- list(regex = "(?i)^DTY(\\d{1,2})[\\-_]", group = 1),
118
- # Gn1a β†’ chromosome 1 (gene names like GnXy)
119
- list(regex = "(?i)^[A-Za-z]{1,6}(\\d{1,2})[a-zA-Z_]", group = 1),
120
- # Saltol β†’ chr01 (known rice gene on chr1)
121
- list(regex = "(?i)^Saltol", group = NA),
122
- # SCT markers β†’ extract from name
123
- list(regex = "(?i)^SCT(\\d{1,2})[_\\-]", group = 1),
124
- # R prefix (e.g. R1056S)
125
- list(regex = "(?i)^R(\\d{1,2})", group = 1),
126
- # Pi prefix blast resistance genes (e.g. Pi35)
127
- list(regex = "(?i)^Pi(\\d{1,2})", group = 1)
128
  )
129
 
130
  for (i in seq_along(markers)) {
131
  m <- markers[i]
132
  for (pat in patterns) {
133
  if (is.na(pat$group)) {
134
- # Special case: Saltol β†’ chr1
135
  if (grepl(pat$regex, m, perl = TRUE)) {
136
  chrom[i] <- "1"; break
137
  }
@@ -153,7 +132,7 @@ infer_chromosome_from_marker <- function(marker_names) {
153
  }
154
 
155
  # ═══════════════════════════════════════════════════════════════════════════════
156
- # CORE GENETIC FUNCTIONS (Fixed for F2 / RIL)
157
  # ═══════════════════════════════════════════════════════════════════════════════
158
 
159
  ## 1. Recombination fraction --------------------------------------------------
@@ -164,7 +143,7 @@ calculate_recombination <- function(population_type, genotype1, genotype2) {
164
  keep <- !(g1 %in% c("-", "NA", NA) | g2 %in% c("-", "NA", NA))
165
  g1 <- g1[keep]; g2 <- g2[keep]
166
  n <- length(g1)
167
- if (n < 4) return(NA_real_) # too few observations
168
 
169
  if (population_type == "RIL") {
170
  hom <- !(g1 == "ab" | g2 == "ab")
@@ -176,7 +155,6 @@ calculate_recombination <- function(population_type, genotype1, genotype2) {
176
  return(rf)
177
 
178
  } else if (population_type == "F2") {
179
- # EM-MLE for F2 (phase-unknown, Mather 1936)
180
  AA_AA <- sum(g1 == "a" & g2 == "a")
181
  AA_Aa <- sum(g1 == "a" & g2 == "ab")
182
  AA_BB <- sum(g1 == "a" & g2 == "b")
@@ -195,7 +173,7 @@ calculate_recombination <- function(population_type, genotype1, genotype2) {
195
  p_recomb <- 2 * r * q
196
  norm <- p_parental + p_recomb
197
 
198
- n_recomb_AaAa <- if (norm > 0) Aa_Aa * p_recomb / norm else 0
199
 
200
  recomb_count <- 2 * (AA_BB + BB_AA) +
201
  (AA_Aa + Aa_AA + Aa_BB + BB_Aa) +
@@ -222,19 +200,36 @@ calculate_cM_kosambi <- function(r) {
222
  ## 3. Impute / correct --------------------------------------------------------
223
  correct_errors_and_impute_missing <- function(df) {
224
  valid_geno <- c("a", "b", "ab")
225
- for (j in seq(3, ncol(df))) {
 
 
 
 
 
 
 
226
  x <- as.character(df[[j]])
227
  x[x %in% c("-", "NA", "", " ", "na")] <- NA
228
  x[!is.na(x) & !(x %in% valid_geno)] <- NA
229
  df[[j]] <- x
230
  }
231
- if (ncol(df) > 2) {
232
- na_col <- colMeans(is.na(df[, 3:ncol(df), drop = FALSE]))
233
- keep <- c(TRUE, TRUE, na_col < 1)
234
- df <- df[, keep, drop = FALSE]
 
 
 
 
 
235
  }
236
- if (ncol(df) > 2) {
237
- df[, 3:ncol(df)] <- t(apply(df[, 3:ncol(df), drop = FALSE], 1, function(row) {
 
 
 
 
 
238
  nas <- is.na(row)
239
  if (all(nas) || !any(nas)) return(row)
240
  tbl <- table(row[!nas])
@@ -249,22 +244,27 @@ correct_errors_and_impute_missing <- function(df) {
249
  ## 4. Quality control ---------------------------------------------------------
250
  quality_control <- function(df, missing_threshold = 0.1) {
251
  if (ncol(df) < 3 || nrow(df) == 0) return(df[0, ])
252
- geno <- df[, 3:ncol(df), drop = FALSE]
 
 
 
 
253
  miss_frac <- rowMeans(is.na(geno))
254
  miss_frac[is.na(miss_frac)] <- 1
255
  df[miss_frac <= missing_threshold, ]
256
  }
257
 
258
- ## 5. Chi-square test -- FIXED for F2 skewed data ----------------------------
259
- # Uses relaxed expected ratios when data is visibly distorted
260
  perform_chi_square_test <- function(df, population_type,
261
- chi_square_threshold = 0.05,
262
- allow_distorted_f2 = TRUE) {
263
  if (nrow(df) == 0) return(logical(0))
264
- geno_mat <- as.matrix(df[, 3:ncol(df), 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
 
@@ -276,19 +276,13 @@ perform_chi_square_test <- function(df, population_type,
276
  pval <- pchisq(stat, df = 1, lower.tail = FALSE)
277
 
278
  } else {
279
- # F2: test 1:2:1 first
280
  exp3 <- c(total * 0.25, total * 0.50, total * 0.25)
281
  valid <- exp3 > 0
282
  stat <- sum(((obs[valid] - exp3[valid])^2) / exp3[valid])
283
  pval <- pchisq(stat, df = sum(valid) - 1, lower.tail = FALSE)
284
 
285
- # If strict 1:2:1 fails BUT allow_distorted_f2 is TRUE, test whether
286
- # het class is at least present (> 0) to still be informative.
287
- # Markers with 0 het AND failing chi-sq are removed.
288
- # Markers that are heterozygous but skewed are KEPT (they carry info).
289
  if (allow_distorted_f2 && pval <= chi_square_threshold) {
290
  het_frac <- obs["ab"] / total
291
- # Keep marker if it has any heterozygotes (informative for linkage)
292
  if (het_frac > 0.02) return(TRUE)
293
  }
294
  }
@@ -297,69 +291,86 @@ perform_chi_square_test <- function(df, population_type,
297
  keep
298
  }
299
 
300
- ## 6. MDS marker ordering -----------------------------------------------------
301
- order_markers_mds <- function(map_distance_df, markers) {
302
- n <- length(markers)
303
- if (n <= 1) return(markers)
304
- D <- matrix(Inf, n, n, dimnames = list(markers, markers))
305
- diag(D) <- 0
306
- for (i in seq_len(nrow(map_distance_df))) {
307
- m1 <- as.character(map_distance_df$Marker1[i])
308
- m2 <- as.character(map_distance_df$Marker2[i])
309
- d <- map_distance_df$MapDistance_cM[i]
310
- if (m1 %in% markers && m2 %in% markers && is.finite(d)) {
311
- D[m1, m2] <- min(D[m1, m2], d)
312
- D[m2, m1] <- min(D[m2, m1], d)
313
- }
314
- }
315
- max_d <- max(D[is.finite(D)], na.rm = TRUE)
316
- if (!is.finite(max_d) || max_d == 0) max_d <- 100
317
- D[!is.finite(D)] <- max_d * 2
318
- tryCatch({
319
- mds <- cmdscale(as.dist(D), k = 1)
320
- markers[order(mds[, 1])]
321
- }, error = function(e) {
322
- remaining <- markers; ordered <- remaining[1]; remaining <- remaining[-1]
323
- while (length(remaining) > 0) {
324
- last <- ordered[length(ordered)]
325
- next_m <- remaining[which.min(D[last, remaining])]
326
- ordered <- c(ordered, next_m)
327
- remaining <- remaining[remaining != next_m]
328
- }
329
- ordered
330
- })
331
- }
332
 
333
- ## 7. Cluster into linkage groups ---------------------------------------------
334
- group_markers <- function(map_distance_df, markers, threshold = 40) {
335
- n <- length(markers)
336
- if (n <= 1) return(setNames(seq_len(n), markers))
337
- D <- matrix(Inf, n, n, dimnames = list(markers, markers))
338
- diag(D) <- 0
339
- for (i in seq_len(nrow(map_distance_df))) {
340
- m1 <- as.character(map_distance_df$Marker1[i])
341
- m2 <- as.character(map_distance_df$Marker2[i])
342
- d <- map_distance_df$MapDistance_cM[i]
343
- if (m1 %in% markers && m2 %in% markers && is.finite(d)) {
344
- D[m1, m2] <- min(D[m1, m2], d)
345
- D[m2, m1] <- min(D[m2, m1], d)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  }
 
 
347
  }
348
- max_d <- max(D[is.finite(D)], na.rm = TRUE)
349
- if (!is.finite(max_d) || max_d == 0) max_d <- 100
350
- D[!is.finite(D)] <- max_d * 2
351
- tryCatch({
352
- hc <- hclust(as.dist(D), method = "average")
353
- hc$height <- pmax(hc$height, 0)
354
- cutree(hc, h = threshold)
355
- }, error = function(e) setNames(seq_len(n), markers))
356
  }
357
 
358
- ## 8. Scaling -----------------------------------------------------------------
359
  scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
360
  pos_map <- linkage_map[!is.na(linkage_map$Position), ]
361
  if (nrow(pos_map) == 0)
362
- return(list(scaled_map = linkage_map,
363
  chrom_lengths_before = data.frame(),
364
  chrom_lengths_after = data.frame()))
365
 
@@ -369,7 +380,7 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
369
 
370
  total <- sum(before$Original_Length, na.rm = TRUE)
371
  if (total <= max_total_cm || total == 0)
372
- return(list(scaled_map = linkage_map,
373
  chrom_lengths_before = before,
374
  chrom_lengths_after = before))
375
 
@@ -396,10 +407,12 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
396
  group_by(Chromosome) %>%
397
  summarise(Original_Length = max(Position, na.rm = TRUE), .groups = "drop")
398
 
399
- list(scaled_map = scaled, chrom_lengths_before = before, chrom_lengths_after = after)
 
 
400
  }
401
 
402
- ## 9. Master analysis function ------------------------------------------------
403
  create_linkage_map <- function(df,
404
  population_type = "F2",
405
  missing_threshold = 0.1,
@@ -424,14 +437,20 @@ create_linkage_map <- function(df,
424
 
425
  # ── Pre-processing ────────────────────────────────────────────────────────
426
  df_orig <- df
427
- df <- correct_errors_and_impute_missing(df)
428
- df <- quality_control(df, missing_threshold)
 
 
 
 
 
 
429
 
430
  if (nrow(df) == 0 || ncol(df) < 3) return(empty_result(df_orig))
431
 
432
  n_before_chi <- nrow(df)
433
 
434
- # ── Chi-square filter (with F2 relaxation) ─────────────────────────────────
435
  keep <- perform_chi_square_test(df, population_type,
436
  chi_square_threshold, allow_distorted_f2)
437
  removed_markers <- df$Marker[!keep]
@@ -447,8 +466,11 @@ create_linkage_map <- function(df,
447
  " Markers removed (chi-sq): ",
448
  if (length(removed_markers) == 0) "none"
449
  else paste(head(removed_markers, 10), collapse = ", "),
450
- if (length(removed_markers) > 10) paste0(" ... and ", length(removed_markers) - 10, " more.") else "",
451
- "\n"
 
 
 
452
  )
453
 
454
  if (nrow(df) == 0) {
@@ -457,88 +479,51 @@ create_linkage_map <- function(df,
457
  return(res)
458
  }
459
 
460
- chromosomes <- sort(unique(df$Chromosome))
461
-
462
- # ── Pairwise recombination ─────────────────────────────────────────────────
463
- rec_rows <- list()
464
- for (chr in chromosomes) {
465
- sub <- df[df$Chromosome == chr, ]
466
- mks <- sub$Marker
467
- if (length(mks) < 2) next
468
-
469
- pairs <- combn(mks, 2, simplify = FALSE)
470
- for (pr in pairs) {
471
- m1 <- pr[1]; m2 <- pr[2]
472
- g1 <- unlist(sub[sub$Marker == m1, 3:ncol(df)])
473
- g2 <- unlist(sub[sub$Marker == m2, 3:ncol(df)])
474
- rf <- calculate_recombination(population_type, g1, g2)
475
- if (!is.na(rf) && rf < recombination_threshold) {
476
- cM <- calculate_cM_kosambi(rf)
477
- rec_rows[[length(rec_rows) + 1]] <-
478
- data.frame(Marker1 = m1, Marker2 = m2,
479
- RecombinationFraction = rf,
480
- MapDistance_cM = cM,
481
- Chromosome = chr,
482
- stringsAsFactors = FALSE)
483
- }
484
- }
485
- }
486
-
487
- if (length(rec_rows) == 0) {
488
- lm_empty <- data.frame(Marker = df$Marker, Chromosome = df$Chromosome,
489
- Position = NA_real_)
490
- return(list(original_data = df_orig, recombination_data = data.frame(),
491
- linkage_map = lm_empty, chrom_lengths_before = data.frame(),
492
- chrom_lengths_after = data.frame(), markers_removed = removed_markers,
493
- qc_report = paste0(qc_msg, "WARNING: No linked marker pairs found.\n")))
494
- }
495
-
496
- rec_df <- do.call(rbind, rec_rows)
497
 
498
- # ── Build positions per chromosome ────────────────────────────────────────
499
- positions_list <- list()
500
 
501
- for (chr in chromosomes) {
502
- sub <- df[df$Chromosome == chr, ]
503
- mks <- sub$Marker
504
- if (length(mks) == 0) next
505
- chr_rec <- rec_df[rec_df$Chromosome == chr, ]
506
-
507
- ordered_mks <- order_markers_mds(chr_rec, mks)
508
- pos <- numeric(length(ordered_mks))
509
- names(pos) <- ordered_mks
510
-
511
- if (length(ordered_mks) > 1) {
512
- for (i in 2:length(ordered_mks)) {
513
- m_prev <- ordered_mks[i - 1]
514
- m_curr <- ordered_mks[i]
515
- d_row <- chr_rec[
516
- (chr_rec$Marker1 == m_prev & chr_rec$Marker2 == m_curr) |
517
- (chr_rec$Marker1 == m_curr & chr_rec$Marker2 == m_prev), ]
518
- d <- if (nrow(d_row) > 0) d_row$MapDistance_cM[1] else 5
519
- pos[i] <- pos[i - 1] + abs(d)
520
- }
521
- }
522
- for (mk in names(pos)) positions_list[[mk]] <- pos[mk]
523
  }
524
 
525
  if (length(positions_list) == 0) {
526
- lm_empty <- data.frame(Marker = df$Marker, Chromosome = df$Chromosome,
527
- Position = NA_real_)
528
- return(list(original_data = df_orig, recombination_data = rec_df,
529
- linkage_map = lm_empty, chrom_lengths_before = data.frame(),
530
- chrom_lengths_after = data.frame(), markers_removed = removed_markers,
531
- qc_report = qc_msg))
 
 
 
 
532
  }
533
 
534
- pos_df <- data.frame(Marker = names(positions_list),
535
- Position = unlist(positions_list),
536
- stringsAsFactors = FALSE)
 
 
 
 
 
 
 
 
537
 
538
- linkage_map <- merge(df[, c("Marker", "Chromosome")], pos_df,
539
- by = "Marker", all.x = TRUE)
540
  linkage_map <- linkage_map[order(linkage_map$Chromosome,
541
- linkage_map$Position), ]
 
 
 
542
 
543
  # ── Scaling ─────────────────────────��──────────────────────────────────────
544
  scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
@@ -567,7 +552,6 @@ create_multi_chromosome_plot <- function(linkage_data,
567
  point_size = 2,
568
  chrom_spacing = 5.0) {
569
 
570
- # Sort chromosomes numerically if possible
571
  chr_sorted <- tryCatch(
572
  selected_chromosomes[order(as.numeric(selected_chromosomes))],
573
  warning = function(w) sort(selected_chromosomes),
@@ -588,7 +572,8 @@ create_multi_chromosome_plot <- function(linkage_data,
588
 
589
  chrom_stats <- plot_data %>%
590
  group_by(Chromosome) %>%
591
- summarise(max_pos = max(Position), min_pos = min(Position),
 
592
  num_markers = n(), .groups = "drop") %>%
593
  mutate(Chromosome = factor(Chromosome, levels = chr_sorted)) %>%
594
  arrange(Chromosome) %>%
@@ -715,7 +700,7 @@ ui <- fluidPage(
715
  display:inline-block; }
716
  "))),
717
 
718
- navbarPage("Linkage Map Creator v4.0", id = "nav",
719
 
720
  # ── Tab 1: Upload ────────────────────────────────────────────────────────
721
  tabPanel("Data Upload", icon = icon("upload"),
@@ -734,9 +719,12 @@ ui <- fluidPage(
734
  value = TRUE),
735
  hr(),
736
  div(class = "alert alert-info",
737
- tags$b("Auto-detection:"), br(),
738
- "β€’ Numeric genotype codes (2/1/0/–1) β†’ converted to a/b/ab/–", br(),
739
- "β€’ VLOOKUP formulas in Chromosome column β†’ chromosome inferred from marker name"
 
 
 
740
  )
741
  )),
742
  mainPanel(width = 8,
@@ -791,20 +779,19 @@ ui <- fluidPage(
791
  tags$ul(
792
  tags$li(tags$b("Missing Data Threshold:"),
793
  " Markers with > this fraction missing are removed. ",
794
- tags$em("Default raised to 0.30 for datasets with high missing data.")),
795
  tags$li(tags$b("Max Recombination Fraction:"),
796
- " Pairs with r β‰₯ this value are treated as unlinked. ",
797
- tags$em("0.45 recommended for F2.")),
798
  tags$li(tags$b("Chi-Square P Threshold:"),
799
- " Markers failing 1:2:1 test with p < threshold are removed. ",
800
- tags$em("Set to 0.001 to be very permissive for skewed F2 data; ",
801
- "raise to 0.05 for strict filtering.")),
802
- tags$li(tags$b("Cluster Threshold:"),
803
- " cM cut-off for grouping markers into linkage groups."),
804
- tags$li(tags$b("Keep distorted F2 markers (on Upload tab):"),
805
- " When checked, heterozygous markers that fail 1:2:1 are ",
806
- "kept anyway β€” recommended for real F2 data with allele ",
807
- "frequency distortion.")
808
  ),
809
  br(),
810
  h4("Scaling Summary"),
@@ -833,7 +820,7 @@ ui <- fluidPage(
833
  downloadButton("download_results", "⬇ Download Excel Results",
834
  class = "btn-success"),
835
  br(), br(),
836
- h4("Linkage Map"),
837
  div(style = "overflow-x:auto;", dataTableOutput("result_table")),
838
  h4("Summary Statistics"),
839
  verbatimTextOutput("summary_stats")
@@ -897,36 +884,38 @@ ui <- fluidPage(
897
  # ── Tab 7: Help ──────────────────────────────────────────────────────────
898
  tabPanel("Help", icon = icon("question-circle"),
899
  wellPanel(
900
- h3("Application Guide β€” v4.0"),
901
- h4("What's New in v4.0"),
902
  div(class = "alert alert-info",
903
  tags$ul(
904
- tags$li(tags$b("Auto-detects numeric genotype codes"),
905
- ": 2=AAβ†’a, 1=BBβ†’b, 0=Hetβ†’ab, –1=Missing→–"),
906
- tags$li(tags$b("Auto-infers chromosomes"),
907
- ": reads chromosome from marker names when Excel ",
908
- "VLOOKUP formulas cannot be evaluated"),
909
- tags$li(tags$b("Relaxed F2 filtering"),
910
- ": keeps heterozygous markers even if segregation ratio ",
911
- "is distorted β€” critical for real F2 populations"),
912
- tags$li(tags$b("QC Report tab"),
913
- ": shows exactly how many markers were removed and why")
 
 
914
  )
915
  ),
 
 
 
 
 
 
 
 
 
916
  h4("Required Input Format"),
917
  tags$ul(
918
  tags$li("Excel (.xlsx): Column 1 = 'Marker', Column 2 = 'Chromosome'"),
919
- tags$li("Genotype columns: values a/b/ab/- ",
920
- tags$em("OR numeric 2/1/0/–1")),
921
- tags$li("Chromosome column: integer chromosome numbers ",
922
- tags$em("OR Excel formulas (auto-extracted from marker names)"))
923
- ),
924
- h4("Recommended Settings for Skewed F2 Data"),
925
- tags$ul(
926
- tags$li("Missing data threshold: 0.30"),
927
- tags$li("Chi-square threshold: 0.001"),
928
- tags$li("Keep distorted F2 markers: βœ“ checked"),
929
- tags$li("Recombination threshold: 0.45")
930
  ),
931
  h4("Genotype Encoding Reference"),
932
  tableOutput("encoding_table")
@@ -935,7 +924,7 @@ ui <- fluidPage(
935
  ),
936
 
937
  div(class = "footer",
938
- "Linkage Map Creator v4.0 | F2 / RIL | Auto-converts numeric codes | Β© 2024")
939
  )
940
 
941
  # ═══════════════════════════════════════════════════════════════════════════════
@@ -944,11 +933,11 @@ ui <- fluidPage(
944
 
945
  server <- function(input, output, session) {
946
 
947
- uploaded_data <- reactiveVal(NULL)
948
- analysis_results <- reactiveVal(NULL)
949
- upload_log <- reactiveVal("")
950
 
951
- # ── Encoding reference table ────────────────────────────────────────────────
952
  output$encoding_table <- renderTable({
953
  data.frame(
954
  `Numeric Code` = c("2", "1", "0", "-1"),
@@ -957,23 +946,24 @@ server <- function(input, output, session) {
957
  "Homozygous Parent 2 (BB)",
958
  "Heterozygous (Aa)",
959
  "Missing data"),
960
- check.names = FALSE
961
  )
962
  }, striped = TRUE, hover = TRUE, bordered = TRUE)
963
 
964
- # ── File upload ─────────────────────────────────────────────────────────────
965
  observeEvent(input$file, {
966
  req(input$file)
967
  tryCatch({
968
- df <- load_and_convert_data(input$file$datapath)
969
  n_chr <- length(unique(df$Chromosome))
970
  log_msg <- paste0(
971
  "βœ“ File loaded: ", input$file$name, "\n",
972
  " Markers : ", nrow(df), "\n",
973
- " Individuals : ", ncol(df) - 2, "\n",
974
  " Chromosomes : ", n_chr,
975
  " (", paste(sort(unique(df$Chromosome)), collapse = ", "), ")\n",
976
- " Genotype codes converted to a/b/ab/-\n"
 
977
  )
978
  uploaded_data(df)
979
  upload_log(log_msg)
@@ -989,6 +979,8 @@ server <- function(input, output, session) {
989
  output$preview_table <- renderDataTable({
990
  req(uploaded_data())
991
  df_show <- head(uploaded_data(), 10)
 
 
992
  datatable(df_show,
993
  options = list(scrollX = TRUE, dom = "t", pageLength = 10),
994
  rownames = FALSE)
@@ -1000,20 +992,21 @@ server <- function(input, output, session) {
1000
  chr_tab <- df %>%
1001
  group_by(Chromosome) %>%
1002
  summarise(N_Markers = n(), .groups = "drop") %>%
1003
- arrange(as.numeric(Chromosome))
1004
  datatable(chr_tab,
1005
  options = list(dom = "t", pageLength = 30),
1006
  rownames = FALSE,
1007
- caption = "Markers per chromosome")
1008
  })
1009
 
1010
- # ── Run analysis ────────────────────────────────────────────────────────────
1011
  observeEvent(input$run_analysis, {
1012
  req(uploaded_data())
1013
  showModal(modalDialog(
1014
  title = "Building Linkage Map…",
1015
  paste0("Population type: ", input$population_type, "\n",
1016
- "This may take a minute for large datasets."),
 
1017
  footer = NULL
1018
  ))
1019
  tryCatch({
@@ -1030,18 +1023,19 @@ server <- function(input, output, session) {
1030
  )
1031
  analysis_results(result)
1032
 
1033
- chromosomes <- sort(unique(result$linkage_map$Chromosome))
1034
- # Numeric sort if possible
1035
- chr_sorted <- tryCatch(chromosomes[order(as.numeric(chromosomes))],
1036
- warning = function(w) sort(chromosomes),
1037
- error = function(e) sort(chromosomes))
 
1038
  updateSelectInput(session, "chromosome_select",
1039
  choices = chr_sorted,
1040
  selected = chr_sorted)
1041
  removeModal()
1042
  n_pos <- sum(!is.na(result$linkage_map$Position))
1043
  showNotification(
1044
- paste0("Analysis complete! ", n_pos, " markers positioned."),
1045
  type = "message"
1046
  )
1047
  }, error = function(e) {
@@ -1053,13 +1047,13 @@ server <- function(input, output, session) {
1053
  output$analysis_run <- reactive({ !is.null(analysis_results()) })
1054
  outputOptions(output, "analysis_run", suspendWhenHidden = FALSE)
1055
 
1056
- # ── QC report ───────────────────────────────────────────────────────────────
1057
  output$qc_report_output <- renderText({
1058
  if (is.null(analysis_results())) return("No analysis run yet.")
1059
  analysis_results()$qc_report
1060
  })
1061
 
1062
- # ── Scaling outputs ─────────────────────────────────────────────────────────
1063
  output$scaling_summary <- renderText({
1064
  req(analysis_results())
1065
  paste0("Method : ", input$scaling_method,
@@ -1075,48 +1069,54 @@ server <- function(input, output, session) {
1075
  }
1076
 
1077
  output$before_scaling_stats <- renderText({
1078
- req(analysis_results())
1079
- fmt_chr(analysis_results()$chrom_lengths_before)
1080
  })
1081
  output$after_scaling_stats <- renderText({
1082
- req(analysis_results())
1083
- fmt_chr(analysis_results()$chrom_lengths_after)
1084
  })
1085
 
1086
- # ── Result table ────────────────────────────────────────────────────────────
1087
  output$result_table <- renderDataTable({
1088
  req(analysis_results())
1089
  lm <- analysis_results()$linkage_map
1090
  if (nrow(lm) > 0) {
1091
  datatable(lm,
1092
- options = list(scrollX = TRUE, pageLength = 25,
1093
- order = list(list(1, "asc"), list(2, "asc"))),
 
 
1094
  rownames = FALSE,
1095
- caption = "Linkage map β€” positions in cM") %>%
 
 
 
 
1096
  formatRound("Position", 2)
1097
  } else {
1098
- datatable(data.frame(Message = "No positioned markers found. Try relaxing QC parameters."),
1099
- options = list(dom = "t"), rownames = FALSE)
 
 
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) return("No positioned markers. Try relaxing chi-square threshold or missing data threshold.")
 
1109
 
1110
- n_total <- nrow(lm)
1111
- n_pos <- sum(!is.na(lm$Position))
1112
- n_chr <- length(unique(lm$Chromosome))
1113
 
1114
  chr_lengths <- lm %>%
1115
  filter(!is.na(Position)) %>%
1116
  group_by(Chromosome) %>%
1117
- summarise(Length = max(Position, na.rm = TRUE),
1118
  N_markers = n(), .groups = "drop") %>%
1119
- arrange(as.numeric(Chromosome))
1120
 
1121
  total_len <- sum(chr_lengths$Length)
1122
  avg_len <- mean(chr_lengths$Length)
@@ -1128,37 +1128,39 @@ server <- function(input, output, session) {
1128
  collapse = "\n")
1129
 
1130
  paste0(
1131
- "LINKAGE MAP SUMMARY\n",
1132
- "===================\n",
1133
  "Population type : ", input$population_type, "\n",
 
 
1134
  "Total markers input : ", nrow(analysis_results()$original_data), "\n",
1135
- "Markers positioned : ", n_pos, "\n",
1136
- "Chromosomes / LGs : ", n_chr, "\n",
1137
  "Total map length : ", round(total_len, 2), " cM\n",
1138
- "Avg chromosome length : ", round(avg_len, 2), " cM\n",
1139
  "Marker pairs analysed : ", nrow(rec), "\n\n",
1140
  "PER-CHROMOSOME DETAILS:\n", chr_detail
1141
  )
1142
  })
1143
 
1144
- # ── Palette preview ─────────────────────────────────────────────────────────
1145
  output$palette_preview <- renderPlot({
1146
  req(input$color_palette)
1147
  cols <- tryCatch(brewer.pal(8, input$color_palette),
1148
  error = function(e) brewer.pal(8, "Set2"))
1149
- n <- length(cols)
1150
- df <- data.frame(x = 1:n, y = 1, col = cols)
1151
  ggplot(df, aes(x, y, fill = I(col))) +
1152
  geom_tile(width = 0.9, height = 0.9) +
1153
  scale_x_continuous(breaks = 1:n, labels = 1:n) +
1154
  labs(title = paste("Preview β€”", input$color_palette)) +
1155
  theme_minimal() +
1156
- theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(),
1157
- axis.title = element_blank(), panel.grid = element_blank(),
1158
- plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))
1159
  }, height = 180)
1160
 
1161
- # ── Chromosome plot ─────────────────────────────────────────────────────────
1162
  output$chromosome_plot <- renderPlot({
1163
  req(analysis_results(), input$chromosome_select)
1164
  create_multi_chromosome_plot(
@@ -1174,9 +1176,9 @@ server <- function(input, output, session) {
1174
  )
1175
  }, height = function() input$plot_height)
1176
 
1177
- # ── Downloads ────────────────────────────────────────────────────────────────
1178
  output$download_results <- downloadHandler(
1179
- filename = function() paste0("linkage_map_", Sys.Date(), ".xlsx"),
1180
  content = function(file) {
1181
  req(analysis_results())
1182
  wb <- createWorkbook()
@@ -1184,9 +1186,14 @@ server <- function(input, output, session) {
1184
  addWorksheet(wb, "Recombination_Fractions")
1185
  addWorksheet(wb, "Linkage_Map")
1186
  addWorksheet(wb, "QC_Report")
1187
- writeData(wb, "Original_Data", analysis_results()$original_data)
1188
- writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
1189
- writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
 
 
 
 
 
1190
  writeData(wb, "QC_Report",
1191
  data.frame(Report = analysis_results()$qc_report))
1192
  saveWorkbook(wb, file, overwrite = TRUE)
@@ -1194,7 +1201,7 @@ server <- function(input, output, session) {
1194
  )
1195
 
1196
  output$download_plot <- downloadHandler(
1197
- filename = function() paste0("linkage_map_", Sys.Date(), ".png"),
1198
  content = function(file) {
1199
  req(analysis_results(), input$chromosome_select)
1200
  p <- create_multi_chromosome_plot(
 
17
 
18
  load_and_convert_data <- function(filepath) {
19
 
 
20
  wb_raw <- tryCatch(
21
  loadWorkbook(filepath),
22
  error = function(e) stop("Cannot open workbook: ", e$message)
23
  )
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
  }
 
35
  has_formula <- any(grepl("^=", chr_col, ignore.case = FALSE), na.rm = TRUE)
36
 
37
  if (has_formula) {
 
 
38
  inferred <- infer_chromosome_from_marker(df_raw$Marker)
 
 
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. Each marker placed on its own group.")
47
  }
48
  }
49
 
 
50
  geno_cols <- df_raw[, 3:ncol(df_raw), drop = FALSE]
51
  sample_vals <- unique(unlist(geno_cols[1:min(50, nrow(geno_cols)), ]))
52
  sample_vals <- sample_vals[!is.na(sample_vals)]
 
55
  text_encoding <- all(sample_vals %in% c("a", "b", "ab", "-", NA, "NA"))
56
 
57
  if (numeric_encoding) {
 
 
58
  df_raw[, 3:ncol(df_raw)] <- lapply(
59
  df_raw[, 3:ncol(df_raw), drop = FALSE],
60
  function(col) {
 
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],
75
  function(col) {
 
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
 
 
96
  chrom <- rep(NA_character_, length(markers))
97
 
98
  patterns <- list(
99
+ list(regex = "(?i)chr(\\d{1,2})[_\\-]", group = 1),
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),
103
+ list(regex = "(?i)^[A-Za-z]{1,6}(\\d{1,2})[a-zA-Z_]",group = 1),
104
+ list(regex = "(?i)^Saltol", group = NA),
105
+ list(regex = "(?i)^SCT(\\d{1,2})[_\\-]", group = 1),
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
  }
 
132
  }
133
 
134
  # ═══════════════════════════════════════════════════════════════════════════════
135
+ # CORE GENETIC FUNCTIONS
136
  # ═══════════════════════════════════════════════════════════════════════════════
137
 
138
  ## 1. Recombination fraction --------------------------------------------------
 
143
  keep <- !(g1 %in% c("-", "NA", NA) | g2 %in% c("-", "NA", NA))
144
  g1 <- g1[keep]; g2 <- g2[keep]
145
  n <- length(g1)
146
+ if (n < 4) return(NA_real_)
147
 
148
  if (population_type == "RIL") {
149
  hom <- !(g1 == "ab" | g2 == "ab")
 
155
  return(rf)
156
 
157
  } else if (population_type == "F2") {
 
158
  AA_AA <- sum(g1 == "a" & g2 == "a")
159
  AA_Aa <- sum(g1 == "a" & g2 == "ab")
160
  AA_BB <- sum(g1 == "a" & g2 == "b")
 
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
  recomb_count <- 2 * (AA_BB + BB_AA) +
179
  (AA_Aa + Aa_AA + Aa_BB + BB_Aa) +
 
200
  ## 3. Impute / correct --------------------------------------------------------
201
  correct_errors_and_impute_missing <- function(df) {
202
  valid_geno <- c("a", "b", "ab")
203
+
204
+ # Identify genotype columns (skip Marker, Chromosome, .input_order)
205
+ geno_start <- which(colnames(df) == "Chromosome") + 1
206
+ # exclude .input_order from genotype processing
207
+ geno_cols_idx <- setdiff(geno_start:ncol(df),
208
+ which(colnames(df) == ".input_order"))
209
+
210
+ for (j in geno_cols_idx) {
211
  x <- as.character(df[[j]])
212
  x[x %in% c("-", "NA", "", " ", "na")] <- NA
213
  x[!is.na(x) & !(x %in% valid_geno)] <- NA
214
  df[[j]] <- x
215
  }
216
+
217
+ if (length(geno_cols_idx) > 0) {
218
+ na_col <- colMeans(is.na(df[, geno_cols_idx, drop = FALSE]))
219
+ keep_flags <- na_col < 1
220
+ keep_idx <- c(seq_len(geno_start - 1),
221
+ geno_cols_idx[keep_flags],
222
+ which(colnames(df) == ".input_order"))
223
+ keep_idx <- keep_idx[keep_idx <= ncol(df)]
224
+ df <- df[, sort(unique(keep_idx)), drop = FALSE]
225
  }
226
+
227
+ # Re-identify geno cols after column removal
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)
234
  if (all(nas) || !any(nas)) return(row)
235
  tbl <- table(row[!nas])
 
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
 
 
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
  }
 
291
  keep
292
  }
293
 
294
+ # ═══════════════════════════════════════════════════════════════════════════════
295
+ # KEY CHANGE: Preserve input file order β€” NO MDS reordering
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
+ recombination_threshold) {
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 - 1]
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) + 1]] <-
336
+ data.frame(
337
+ Marker1 = m_prev,
338
+ Marker2 = m_curr,
339
+ RecombinationFraction = rf,
340
+ MapDistance_cM = cM,
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
+ # Cannot compute rf (too few observations) β€” use small default gap
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 = linkage_map,
374
  chrom_lengths_before = data.frame(),
375
  chrom_lengths_after = data.frame()))
376
 
 
380
 
381
  total <- sum(before$Original_Length, na.rm = TRUE)
382
  if (total <= max_total_cm || total == 0)
383
+ return(list(scaled_map = linkage_map,
384
  chrom_lengths_before = before,
385
  chrom_lengths_after = before))
386
 
 
407
  group_by(Chromosome) %>%
408
  summarise(Original_Length = max(Position, na.rm = TRUE), .groups = "drop")
409
 
410
+ list(scaled_map = scaled,
411
+ chrom_lengths_before = before,
412
+ chrom_lengths_after = after)
413
  }
414
 
415
+ ## 7. Master analysis function ------------------------------------------------
416
  create_linkage_map <- function(df,
417
  population_type = "F2",
418
  missing_threshold = 0.1,
 
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
+ df <- correct_errors_and_impute_missing(df)
447
+ df <- quality_control(df, missing_threshold)
448
 
449
  if (nrow(df) == 0 || ncol(df) < 3) return(empty_result(df_orig))
450
 
451
  n_before_chi <- nrow(df)
452
 
453
+ # ── Chi-square filter ──────────────────────────────────────────────────────
454
  keep <- perform_chi_square_test(df, population_type,
455
  chi_square_threshold, allow_distorted_f2)
456
  removed_markers <- df$Marker[!keep]
 
466
  " Markers removed (chi-sq): ",
467
  if (length(removed_markers) == 0) "none"
468
  else paste(head(removed_markers, 10), collapse = ", "),
469
+ if (length(removed_markers) > 10)
470
+ paste0(" ... and ", length(removed_markers) - 10, " more.") else "",
471
+ "\n",
472
+ "\n NOTE: Marker ORDER is preserved exactly from input file.\n",
473
+ " First marker of each chromosome is fixed at 0 cM.\n"
474
  )
475
 
476
  if (nrow(df) == 0) {
 
479
  return(res)
480
  }
481
 
482
+ # ── Build positions using INPUT ORDER (no MDS) ─────────────────────────────
483
+ pos_result <- build_positions_from_input_order(
484
+ df, population_type, recombination_threshold
485
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
 
487
+ positions_list <- pos_result$positions_list
488
+ recombination_rows <- pos_result$recombination_rows
489
 
490
+ if (length(recombination_rows) > 0) {
491
+ rec_df <- do.call(rbind, recombination_rows)
492
+ } else {
493
+ rec_df <- data.frame()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494
  }
495
 
496
  if (length(positions_list) == 0) {
497
+ lm_empty <- df[, c("Marker", "Chromosome")]
498
+ lm_empty$Position <- NA_real_
499
+ lm_empty$.input_order <- df$.input_order
500
+ return(list(original_data = df_orig,
501
+ recombination_data = rec_df,
502
+ linkage_map = lm_empty[, c("Marker","Chromosome","Position")],
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
+ Marker = names(positions_list),
511
+ Position = unlist(positions_list),
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
+ # Drop helper column before returning
526
+ linkage_map$.input_order <- NULL
527
 
528
  # ── Scaling ─────────────────────────��──────────────────────────────────────
529
  scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
 
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),
 
572
 
573
  chrom_stats <- plot_data %>%
574
  group_by(Chromosome) %>%
575
+ summarise(max_pos = max(Position),
576
+ min_pos = min(Position),
577
  num_markers = n(), .groups = "drop") %>%
578
  mutate(Chromosome = factor(Chromosome, levels = chr_sorted)) %>%
579
  arrange(Chromosome) %>%
 
700
  display:inline-block; }
701
  "))),
702
 
703
+ navbarPage("Linkage Map Creator v4.1 β€” Input Order Preserved", id = "nav",
704
 
705
  # ── Tab 1: Upload ────────────────────────────────────────────────────────
706
  tabPanel("Data Upload", icon = icon("upload"),
 
719
  value = TRUE),
720
  hr(),
721
  div(class = "alert alert-info",
722
+ tags$b("v4.1 Key Behaviour:"), br(),
723
+ tags$b("β€’ Marker order from input file is PRESERVED"), br(),
724
+ tags$b("β€’ First marker of every chromosome = 0 cM"), br(),
725
+ "β€’ Subsequent markers: cumulative Kosambi cM", br(),
726
+ "β€’ Numeric codes (2/1/0/–1) β†’ a/b/ab/–", br(),
727
+ "β€’ VLOOKUP formulas β†’ chromosome inferred from marker name"
728
  )
729
  )),
730
  mainPanel(width = 8,
 
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 β‰₯ this value get a 50 cM placeholder gap ",
785
+ "in the output. 0.45 recommended for F2."),
786
  tags$li(tags$b("Chi-Square P Threshold:"),
787
+ " Markers failing segregation test below this p are removed. ",
788
+ tags$em("0.001 = permissive; 0.05 = strict.")),
789
+ tags$li(tags$b("Marker Order:"),
790
+ tags$b(" Preserved exactly from input file. "),
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"),
 
820
  downloadButton("download_results", "⬇ Download Excel Results",
821
  class = "btn-success"),
822
  br(), br(),
823
+ h4("Linkage Map (Input Order Preserved, First Marker = 0 cM)"),
824
  div(style = "overflow-x:auto;", dataTableOutput("result_table")),
825
  h4("Summary Statistics"),
826
  verbatimTextOutput("summary_stats")
 
884
  # ── Tab 7: Help ──────────────────────────────────────────────────────────
885
  tabPanel("Help", icon = icon("question-circle"),
886
  wellPanel(
887
+ h3("Application Guide β€” v4.1"),
888
+ h4("What's New in v4.1 (vs v4.0)"),
889
  div(class = "alert alert-info",
890
  tags$ul(
891
+ tags$li(tags$b("Input marker order fully preserved:"),
892
+ " MDS reordering removed. Markers appear in output exactly ",
893
+ "as they appear in the input file."),
894
+ tags$li(tags$b("First marker of each chromosome = 0 cM:"),
895
+ " Position accumulation always starts at 0 for the first ",
896
+ "marker of each chromosome."),
897
+ tags$li(tags$b("Consecutive pairwise distances only:"),
898
+ " cM is computed between adjacent markers in input order ",
899
+ "(marker i–1 β†’ marker i), then accumulated."),
900
+ tags$li(tags$b("Unlinked adjacent markers:"),
901
+ " If r β‰₯ recombination threshold, a 50 cM placeholder gap ",
902
+ "is inserted so they still appear on the map.")
903
  )
904
  ),
905
+ h4("Position Calculation Logic"),
906
+ tags$ol(
907
+ tags$li("Read markers in input file order."),
908
+ tags$li("For each chromosome, set position of first marker = 0 cM."),
909
+ tags$li("For each subsequent marker i: compute r between markers i-1 and i."),
910
+ tags$li("Convert r to cM using Kosambi function."),
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: values a/b/ab/- OR numeric 2/1/0/–1"),
918
+ tags$li("Chromosome column: integer chromosome numbers OR Excel formulas")
 
 
 
 
 
 
 
 
 
919
  ),
920
  h4("Genotype Encoding Reference"),
921
  tableOutput("encoding_table")
 
924
  ),
925
 
926
  div(class = "footer",
927
+ "Linkage Map Creator v4.1 | Input Order Preserved | First Marker = 0 cM | Β© 2024")
928
  )
929
 
930
  # ═══════════════════════════════════════════════════════════════════════════════
 
933
 
934
  server <- function(input, output, session) {
935
 
936
+ uploaded_data <- reactiveVal(NULL)
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", "1", "0", "-1"),
 
946
  "Homozygous Parent 2 (BB)",
947
  "Heterozygous (Aa)",
948
  "Missing data"),
949
+ check.names = FALSE
950
  )
951
  }, striped = TRUE, hover = TRUE, bordered = TRUE)
952
 
953
+ # ── File upload ───��──────────────────────────────────────────────────────
954
  observeEvent(input$file, {
955
  req(input$file)
956
  tryCatch({
957
+ df <- load_and_convert_data(input$file$datapath)
958
  n_chr <- length(unique(df$Chromosome))
959
  log_msg <- paste0(
960
  "βœ“ File loaded: ", input$file$name, "\n",
961
  " Markers : ", nrow(df), "\n",
962
+ " Individuals : ", ncol(df) - 3, " (excl. Marker, Chromosome, order cols)\n",
963
  " Chromosomes : ", n_chr,
964
  " (", paste(sort(unique(df$Chromosome)), collapse = ", "), ")\n",
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)
 
979
  output$preview_table <- renderDataTable({
980
  req(uploaded_data())
981
  df_show <- head(uploaded_data(), 10)
982
+ # Hide .input_order from preview
983
+ df_show <- df_show[, colnames(df_show) != ".input_order", drop = FALSE]
984
  datatable(df_show,
985
  options = list(scrollX = TRUE, dom = "t", pageLength = 10),
986
  rownames = FALSE)
 
992
  chr_tab <- df %>%
993
  group_by(Chromosome) %>%
994
  summarise(N_Markers = n(), .groups = "drop") %>%
995
+ arrange(suppressWarnings(as.numeric(Chromosome)))
996
  datatable(chr_tab,
997
  options = list(dom = "t", pageLength = 30),
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 = "Building Linkage Map…",
1007
  paste0("Population type: ", input$population_type, "\n",
1008
+ "Preserving input marker order. First marker of each chromosome = 0 cM.\n",
1009
+ "This may take a moment for large datasets."),
1010
  footer = NULL
1011
  ))
1012
  tryCatch({
 
1023
  )
1024
  analysis_results(result)
1025
 
1026
+ chromosomes <- unique(result$linkage_map$Chromosome)
1027
+ chr_sorted <- tryCatch(
1028
+ chromosomes[order(as.numeric(chromosomes))],
1029
+ warning = function(w) sort(chromosomes),
1030
+ error = function(e) sort(chromosomes)
1031
+ )
1032
  updateSelectInput(session, "chromosome_select",
1033
  choices = chr_sorted,
1034
  selected = chr_sorted)
1035
  removeModal()
1036
  n_pos <- sum(!is.na(result$linkage_map$Position))
1037
  showNotification(
1038
+ paste0("Analysis complete! ", n_pos, " markers positioned (input order preserved)."),
1039
  type = "message"
1040
  )
1041
  }, error = function(e) {
 
1047
  output$analysis_run <- reactive({ !is.null(analysis_results()) })
1048
  outputOptions(output, "analysis_run", suspendWhenHidden = FALSE)
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
+ # ── Scaling outputs ───────────────────────────────────────────────────────
1057
  output$scaling_summary <- renderText({
1058
  req(analysis_results())
1059
  paste0("Method : ", input$scaling_method,
 
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
+ options = list(scrollX = TRUE,
1085
+ pageLength = 25,
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
+ data.frame(Message = "No positioned markers. Try relaxing QC parameters."),
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
+ return("No positioned markers. Try relaxing chi-square or missing data threshold.")
1110
 
1111
+ n_pos <- sum(!is.na(lm$Position))
1112
+ n_chr <- length(unique(lm$Chromosome))
 
1113
 
1114
  chr_lengths <- lm %>%
1115
  filter(!is.na(Position)) %>%
1116
  group_by(Chromosome) %>%
1117
+ summarise(Length = max(Position, na.rm = TRUE),
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)
 
1128
  collapse = "\n")
1129
 
1130
  paste0(
1131
+ "LINKAGE MAP SUMMARY (v4.1)\n",
1132
+ "===========================\n",
1133
  "Population type : ", input$population_type, "\n",
1134
+ "Marker order : Preserved from input file\n",
1135
+ "First marker position : 0 cM (per chromosome)\n",
1136
  "Total markers input : ", nrow(analysis_results()$original_data), "\n",
1137
+ "Markers positioned : ", n_pos, "\n",
1138
+ "Chromosomes / LGs : ", n_chr, "\n",
1139
  "Total map length : ", round(total_len, 2), " cM\n",
1140
+ "Avg chromosome length : ", round(avg_len, 2), " cM\n",
1141
  "Marker pairs analysed : ", nrow(rec), "\n\n",
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 = 1:n, y = 1, col = cols)
1153
  ggplot(df, aes(x, y, fill = I(col))) +
1154
  geom_tile(width = 0.9, height = 0.9) +
1155
  scale_x_continuous(breaks = 1:n, labels = 1:n) +
1156
  labs(title = paste("Preview β€”", input$color_palette)) +
1157
  theme_minimal() +
1158
+ theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(),
1159
+ axis.title = element_blank(), panel.grid = element_blank(),
1160
+ plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))
1161
  }, height = 180)
1162
 
1163
+ # ── Chromosome plot ───────────────────────────────────────────────────────
1164
  output$chromosome_plot <- renderPlot({
1165
  req(analysis_results(), input$chromosome_select)
1166
  create_multi_chromosome_plot(
 
1176
  )
1177
  }, height = function() input$plot_height)
1178
 
1179
+ # ── Downloads ─────────────────────────────────────────────────────────────
1180
  output$download_results <- downloadHandler(
1181
+ filename = function() paste0("linkage_map_v41_", Sys.Date(), ".xlsx"),
1182
  content = function(file) {
1183
  req(analysis_results())
1184
  wb <- createWorkbook()
 
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 = FALSE]
1193
+
1194
+ writeData(wb, "Original_Data", orig)
1195
+ writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
1196
+ writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
1197
  writeData(wb, "QC_Report",
1198
  data.frame(Report = analysis_results()$qc_report))
1199
  saveWorkbook(wb, file, overwrite = TRUE)
 
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(