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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +581 -328
app.R CHANGED
@@ -7,46 +7,176 @@ library(dplyr)
7
  library(RColorBrewer)
8
  library(ggrepel)
9
 
10
- # ─────────────────────────────────────────────
11
- # CORE GENETIC FUNCTIONS (Fixed for F2/RIL)
12
- # ─────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  ## 1. Recombination fraction --------------------------------------------------
15
- # F2: uses all three genotype classes (a, ab, b)
16
- # RIL: only homozygous classes used; RIL correction applied
17
  calculate_recombination <- function(population_type, genotype1, genotype2) {
18
  g1 <- as.character(genotype1)
19
  g2 <- as.character(genotype2)
20
 
21
- # remove pairs where either marker is missing
22
- keep <- !(g1 %in% c('-', 'NA', NA) | g2 %in% c('-', 'NA', NA))
23
  g1 <- g1[keep]; g2 <- g2[keep]
24
  n <- length(g1)
25
- if (n == 0) return(NA_real_)
26
 
27
  if (population_type == "RIL") {
28
- # RIL: only homozygous calls informative
29
  hom <- !(g1 == "ab" | g2 == "ab")
30
  g1h <- g1[hom]; g2h <- g2[hom]
31
- if (length(g1h) == 0) return(NA_real_)
32
- r_obs <- mean(g1h != g2h) # observed recombination
33
- # Haldane correction for RIL (Rezvoy et al.)
34
- rf <- r_obs / (2 * (1 - r_obs)) # r_RIL -> r_meiosis
35
- rf <- min(rf, 0.4999)
36
  return(rf)
37
 
38
  } else if (population_type == "F2") {
39
- # Maximum-likelihood estimate of r from F2 data
40
- # Genotype coding: a=AA, ab=Aa, b=BB
41
- # Expected frequencies as function of r (Mather 1936):
42
- # AA: (1-r)^2 / D
43
- # Aa: 2r(1-r) / D (repulsion) or different formula for coupling
44
- # Simple approach: count recombinant gametes
45
- # For each individual: infer number of recombinant gametes
46
- # Treat hetΓ—het as uninformative for phase-unknown F2
47
-
48
- # Phase-unknown EM for F2 (simplified Kosambi/Haldane MLE)
49
- # Observed counts
50
  AA_AA <- sum(g1 == "a" & g2 == "a")
51
  AA_Aa <- sum(g1 == "a" & g2 == "ab")
52
  AA_BB <- sum(g1 == "a" & g2 == "b")
@@ -57,40 +187,25 @@ calculate_recombination <- function(population_type, genotype1, genotype2) {
57
  BB_Aa <- sum(g1 == "b" & g2 == "ab")
58
  BB_BB <- sum(g1 == "b" & g2 == "b")
59
 
60
- # EM algorithm for F2 recombination fraction
61
- # Starting value
62
  r <- 0.25
63
  for (iter in 1:200) {
64
  r_old <- r
65
  q <- 1 - r
 
 
 
66
 
67
- # E-step for AaΓ—Aa class: partition into parental and recombinant
68
- denom_AaAa <- 2 * r^2 + 4 * r * q + 2 * q^2 # = 2*(r+q)^2 = 2 but keep explicit
69
- # Expected proportion of each gamete combination within AaΓ—Aa
70
- # Coupling: (AA+BB from parental) vs (AB+BA from recombinant)
71
- p_parental <- (q^2 + r^2) # AA/BB gamete combos
72
- p_recomb <- 2 * r * q # AB/BA gamete combos
73
- norm <- p_parental + p_recomb # = (r+q)^2 = 1
74
-
75
- n_parental_AaAa <- if (norm > 0) Aa_Aa * p_parental / norm else 0
76
  n_recomb_AaAa <- if (norm > 0) Aa_Aa * p_recomb / norm else 0
77
 
78
- # M-step: recombinant gametes
79
- # Each AAΓ—BB or BBΓ—AA individual contributes 2 recombinant gametes
80
- # Each AAΓ—Aa or similar contributes 1 recombinant gamete (one het parent)
81
- recomb_count <- 2 * (AA_BB + BB_AA) +
82
- (AA_Aa + Aa_AA + Aa_BB + BB_Aa) +
83
- 2 * n_recomb_AaAa
84
-
85
  total_gametes <- 2 * n
86
-
87
- r_new <- recomb_count / total_gametes
88
- r_new <- max(1e-6, min(r_new, 0.4999))
89
  r <- r_new
90
  if (abs(r - r_old) < 1e-8) break
91
  }
92
  return(r)
93
-
94
  } else {
95
  stop("population_type must be 'RIL' or 'F2'")
96
  }
@@ -101,34 +216,28 @@ calculate_cM_kosambi <- function(r) {
101
  if (is.na(r)) return(NA_real_)
102
  r <- max(0, min(r, 0.4999))
103
  if (r == 0) return(0)
104
- 25 * log((1 + 2*r) / (1 - 2*r)) # Kosambi: cM = 25*ln((1+2r)/(1-2r))
105
  }
106
 
107
- ## 3. Impute missing / correct errors ----------------------------------------
108
  correct_errors_and_impute_missing <- function(df) {
109
  valid_geno <- c("a", "b", "ab")
110
-
111
- # Replace '-', NA, blanks with NA
112
  for (j in seq(3, ncol(df))) {
113
  x <- as.character(df[[j]])
114
- x[x %in% c("-", "NA", "", " ")] <- NA
115
- x[!is.na(x) & !(x %in% valid_geno)] <- NA
116
  df[[j]] <- x
117
  }
118
-
119
- # Drop individuals (columns) that are entirely missing
120
  if (ncol(df) > 2) {
121
- na_col <- colMeans(is.na(df[, 3:ncol(df), drop = FALSE]))
122
- keep_cols <- c(TRUE, TRUE, na_col < 1)
123
- df <- df[, keep_cols, drop = FALSE]
124
  }
125
-
126
- # Impute remaining NAs per marker (row) with mode of observed values
127
  if (ncol(df) > 2) {
128
  df[, 3:ncol(df)] <- t(apply(df[, 3:ncol(df), drop = FALSE], 1, function(row) {
129
  nas <- is.na(row)
130
- if (all(nas)) return(row)
131
- tbl <- table(row[!nas])
132
  mode_val <- names(which.max(tbl))
133
  row[nas] <- mode_val
134
  row
@@ -140,52 +249,60 @@ correct_errors_and_impute_missing <- function(df) {
140
  ## 4. Quality control ---------------------------------------------------------
141
  quality_control <- function(df, missing_threshold = 0.1) {
142
  if (ncol(df) < 3 || nrow(df) == 0) return(df[0, ])
143
- geno <- df[, 3:ncol(df), drop = FALSE]
144
  miss_frac <- rowMeans(is.na(geno))
145
  miss_frac[is.na(miss_frac)] <- 1
146
  df[miss_frac <= missing_threshold, ]
147
  }
148
 
149
- ## 5. Chi-square segregation distortion test ----------------------------------
150
- perform_chi_square_test <- function(df, population_type, chi_square_threshold = 0.05) {
 
 
 
151
  if (nrow(df) == 0) return(logical(0))
152
  geno_mat <- as.matrix(df[, 3:ncol(df), drop = FALSE])
153
 
154
  keep <- apply(geno_mat, 1, function(row) {
155
  obs <- table(factor(row, levels = c("a", "ab", "b")))
 
 
156
 
157
  if (population_type == "RIL") {
158
- # Expected 1:1 (a : b), ignore ab
159
  obs2 <- c(obs["a"], obs["b"])
160
- if (sum(obs2) == 0) return(TRUE) # can't test β†’ keep
161
  exp2 <- rep(sum(obs2) / 2, 2)
162
  stat <- sum((obs2 - exp2)^2 / exp2)
163
  pval <- pchisq(stat, df = 1, lower.tail = FALSE)
 
164
  } else {
165
- # F2: Expected 1:2:1 (a : ab : b)
166
- total <- sum(obs)
167
- if (total == 0) return(TRUE)
168
- exp3 <- c(total * 0.25, total * 0.50, total * 0.25)
169
- # avoid division by zero
170
  valid <- exp3 > 0
171
- stat <- sum(((obs[valid] - exp3[valid])^2) / exp3[valid])
172
- pval <- pchisq(stat, df = sum(valid) - 1, lower.tail = FALSE)
 
 
 
 
 
 
 
 
 
 
173
  }
174
-
175
  return(pval > chi_square_threshold)
176
  })
177
  keep
178
  }
179
 
180
- ## 6. Marker ordering using MDS on pairwise distances ------------------------
181
  order_markers_mds <- function(map_distance_df, markers) {
182
  n <- length(markers)
183
  if (n <= 1) return(markers)
184
-
185
- # Build distance matrix
186
  D <- matrix(Inf, n, n, dimnames = list(markers, markers))
187
  diag(D) <- 0
188
-
189
  for (i in seq_len(nrow(map_distance_df))) {
190
  m1 <- as.character(map_distance_df$Marker1[i])
191
  m2 <- as.character(map_distance_df$Marker2[i])
@@ -195,25 +312,17 @@ order_markers_mds <- function(map_distance_df, markers) {
195
  D[m2, m1] <- min(D[m2, m1], d)
196
  }
197
  }
198
-
199
- # Replace Inf with large value
200
  max_d <- max(D[is.finite(D)], na.rm = TRUE)
201
  if (!is.finite(max_d) || max_d == 0) max_d <- 100
202
  D[!is.finite(D)] <- max_d * 2
203
-
204
- # Classical MDS β†’ project onto 1D β†’ sort
205
  tryCatch({
206
  mds <- cmdscale(as.dist(D), k = 1)
207
  markers[order(mds[, 1])]
208
  }, error = function(e) {
209
- # Fallback: greedy nearest-neighbour starting from first marker
210
- remaining <- markers
211
- ordered <- remaining[1]
212
- remaining <- remaining[-1]
213
  while (length(remaining) > 0) {
214
- last <- ordered[length(ordered)]
215
- dists_to_last <- D[last, remaining]
216
- next_m <- remaining[which.min(dists_to_last)]
217
  ordered <- c(ordered, next_m)
218
  remaining <- remaining[remaining != next_m]
219
  }
@@ -221,14 +330,12 @@ order_markers_mds <- function(map_distance_df, markers) {
221
  })
222
  }
223
 
224
- ## 7. Cluster markers into linkage groups (hclust) ---------------------------
225
  group_markers <- function(map_distance_df, markers, threshold = 40) {
226
  n <- length(markers)
227
  if (n <= 1) return(setNames(seq_len(n), markers))
228
-
229
  D <- matrix(Inf, n, n, dimnames = list(markers, markers))
230
  diag(D) <- 0
231
-
232
  for (i in seq_len(nrow(map_distance_df))) {
233
  m1 <- as.character(map_distance_df$Marker1[i])
234
  m2 <- as.character(map_distance_df$Marker2[i])
@@ -238,21 +345,17 @@ group_markers <- function(map_distance_df, markers, threshold = 40) {
238
  D[m2, m1] <- min(D[m2, m1], d)
239
  }
240
  }
241
-
242
  max_d <- max(D[is.finite(D)], na.rm = TRUE)
243
  if (!is.finite(max_d) || max_d == 0) max_d <- 100
244
  D[!is.finite(D)] <- max_d * 2
245
-
246
  tryCatch({
247
- hc <- hclust(as.dist(D), method = "average")
248
- hc$height <- pmax(hc$height, 0) # ensure non-negative
249
  cutree(hc, h = threshold)
250
- }, error = function(e) {
251
- setNames(seq_len(n), markers)
252
- })
253
  }
254
 
255
- ## 8. Map scaling -------------------------------------------------------------
256
  scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional") {
257
  pos_map <- linkage_map[!is.na(linkage_map$Position), ]
258
  if (nrow(pos_map) == 0)
@@ -265,19 +368,16 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
265
  summarise(Original_Length = max(Position, na.rm = TRUE), .groups = "drop")
266
 
267
  total <- sum(before$Original_Length, na.rm = TRUE)
268
-
269
  if (total <= max_total_cm || total == 0)
270
  return(list(scaled_map = linkage_map,
271
  chrom_lengths_before = before,
272
  chrom_lengths_after = before))
273
 
274
  scaled <- linkage_map
275
-
276
  if (method == "proportional") {
277
- sf <- max_total_cm / total
278
- before$sf <- sf
279
  } else {
280
- n_chr <- nrow(before)
281
  before$sf <- ifelse(before$Original_Length > 0,
282
  (max_total_cm / n_chr) / before$Original_Length, 1)
283
  }
@@ -301,13 +401,14 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
301
 
302
  ## 9. Master analysis function ------------------------------------------------
303
  create_linkage_map <- function(df,
304
- population_type = "F2",
305
- missing_threshold = 0.1,
306
  recombination_threshold = 0.5,
307
- chi_square_threshold = 0.05,
308
- cluster_threshold = 40,
309
- max_total_cm = 1500,
310
- scaling_method = "proportional") {
 
311
 
312
  empty_result <- function(df_in = df) {
313
  list(original_data = df_in,
@@ -316,24 +417,49 @@ create_linkage_map <- function(df,
316
  Chromosome = character(0),
317
  Position = numeric(0)),
318
  chrom_lengths_before = data.frame(),
319
- chrom_lengths_after = data.frame())
 
 
320
  }
321
 
322
- # ── pre-processing ──────────────────────────────────────────────────────────
323
- df <- correct_errors_and_impute_missing(df)
324
- df <- quality_control(df, missing_threshold)
 
 
 
325
 
326
- if (nrow(df) == 0 || ncol(df) < 3) return(empty_result())
327
 
328
- # ── segregation distortion filter ───────────────────────────────────────────
329
- keep <- perform_chi_square_test(df, population_type, chi_square_threshold)
 
 
330
  if (length(keep) == nrow(df)) df <- df[keep, ]
331
 
332
- if (nrow(df) == 0) return(empty_result())
 
 
 
 
 
 
 
 
 
 
 
 
333
 
334
- chromosomes <- unique(df$Chromosome)
 
 
 
 
335
 
336
- # ── pairwise recombination fractions ────────────────────────────────────────
 
 
337
  rec_rows <- list()
338
  for (chr in chromosomes) {
339
  sub <- df[df$Chromosome == chr, ]
@@ -361,62 +487,48 @@ create_linkage_map <- function(df,
361
  if (length(rec_rows) == 0) {
362
  lm_empty <- data.frame(Marker = df$Marker, Chromosome = df$Chromosome,
363
  Position = NA_real_)
364
- return(list(original_data = df, recombination_data = data.frame(),
365
- linkage_map = lm_empty,
366
- chrom_lengths_before = data.frame(),
367
- chrom_lengths_after = data.frame()))
368
  }
369
 
370
  rec_df <- do.call(rbind, rec_rows)
371
 
372
- # ── build linkage map per chromosome ────────────────────────────────────────
373
  positions_list <- list()
374
 
375
  for (chr in chromosomes) {
376
- sub <- df[df$Chromosome == chr, ]
377
- mks <- sub$Marker
378
  if (length(mks) == 0) next
379
-
380
  chr_rec <- rec_df[rec_df$Chromosome == chr, ]
381
 
382
- # Order markers using MDS
383
  ordered_mks <- order_markers_mds(chr_rec, mks)
384
-
385
- # Assign cumulative positions using consecutive pairwise distances
386
  pos <- numeric(length(ordered_mks))
387
  names(pos) <- ordered_mks
388
- pos[1] <- 0
389
 
390
  if (length(ordered_mks) > 1) {
391
  for (i in 2:length(ordered_mks)) {
392
  m_prev <- ordered_mks[i - 1]
393
  m_curr <- ordered_mks[i]
394
-
395
- # Find distance in rec_df (either direction)
396
- d_row <- chr_rec[(chr_rec$Marker1 == m_prev & chr_rec$Marker2 == m_curr) |
397
- (chr_rec$Marker1 == m_curr & chr_rec$Marker2 == m_prev), ]
398
- if (nrow(d_row) > 0) {
399
- d <- d_row$MapDistance_cM[1]
400
- } else {
401
- # Use nearest available distance or default
402
- d <- 1
403
- }
404
  pos[i] <- pos[i - 1] + abs(d)
405
  }
406
  }
407
-
408
- for (mk in names(pos)) {
409
- positions_list[[mk]] <- pos[mk]
410
- }
411
  }
412
 
413
  if (length(positions_list) == 0) {
414
  lm_empty <- data.frame(Marker = df$Marker, Chromosome = df$Chromosome,
415
  Position = NA_real_)
416
- return(list(original_data = df, recombination_data = rec_df,
417
- linkage_map = lm_empty,
418
- chrom_lengths_before = data.frame(),
419
- chrom_lengths_after = data.frame()))
420
  }
421
 
422
  pos_df <- data.frame(Marker = names(positions_list),
@@ -425,21 +537,24 @@ create_linkage_map <- function(df,
425
 
426
  linkage_map <- merge(df[, c("Marker", "Chromosome")], pos_df,
427
  by = "Marker", all.x = TRUE)
428
- linkage_map <- linkage_map[order(linkage_map$Chromosome, linkage_map$Position), ]
 
429
 
430
- # ── scaling ─────────────────────────────────────────────────────────────────
431
  scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
432
 
433
- list(original_data = df,
434
  recombination_data = rec_df,
435
  linkage_map = scaled$scaled_map,
436
  chrom_lengths_before = scaled$chrom_lengths_before,
437
- chrom_lengths_after = scaled$chrom_lengths_after)
 
 
438
  }
439
 
440
- # ─────────────────────────────────────────────
441
- # PLOTTING FUNCTIONS
442
- # ─────────────────────────────────────────────
443
 
444
  create_multi_chromosome_plot <- function(linkage_data,
445
  selected_chromosomes,
@@ -452,15 +567,22 @@ create_multi_chromosome_plot <- function(linkage_data,
452
  point_size = 2,
453
  chrom_spacing = 5.0) {
454
 
 
 
 
 
 
 
 
455
  plot_data <- linkage_data %>%
456
  filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
457
- arrange(Chromosome, Position)
458
 
459
  if (nrow(plot_data) == 0) {
460
  return(ggplot() +
461
  annotate("text", x = 0.5, y = 0.5,
462
- label = "No valid marker positions available",
463
- size = 6, color = "red") +
464
  theme_void())
465
  }
466
 
@@ -468,6 +590,7 @@ create_multi_chromosome_plot <- function(linkage_data,
468
  group_by(Chromosome) %>%
469
  summarise(max_pos = max(Position), min_pos = min(Position),
470
  num_markers = n(), .groups = "drop") %>%
 
471
  arrange(Chromosome) %>%
472
  mutate(chrom_x = seq(1, by = chrom_spacing, length.out = n()),
473
  chrom_center = chrom_x)
@@ -477,13 +600,11 @@ create_multi_chromosome_plot <- function(linkage_data,
477
  by = "Chromosome")
478
 
479
  n_chrom <- nrow(chrom_stats)
480
- # Robust palette selection
481
- palette_ok <- tryCatch({
482
- brewer.pal(max(3, n_chrom), color_palette); TRUE
483
- }, error = function(e) FALSE)
484
 
485
  chrom_colors <- if (palette_ok && n_chrom <= 8) {
486
- brewer.pal(max(3, n_chrom), color_palette)[1:n_chrom]
487
  } else if (palette_ok) {
488
  colorRampPalette(brewer.pal(8, color_palette))(n_chrom)
489
  } else {
@@ -501,35 +622,34 @@ create_multi_chromosome_plot <- function(linkage_data,
501
  color = as.factor(Chromosome)),
502
  size = point_size, alpha = 0.9) +
503
  geom_text(data = chrom_stats,
504
- aes(x = chrom_center, y = -(max(chrom_stats$max_pos) * 0.03),
 
505
  label = paste0("Chr\n", Chromosome),
506
  color = as.factor(Chromosome)),
507
  size = label_size + 1, fontface = "bold", vjust = 1) +
508
- scale_color_manual(values = chrom_colors) +
509
- scale_y_reverse(name = "Genetic Position (cM)",
 
510
  expand = expansion(mult = c(0.02, 0.12))) +
511
  scale_x_continuous(breaks = chrom_stats$chrom_center,
512
  labels = chrom_stats$Chromosome,
513
  name = "Chromosome",
514
  expand = expansion(mult = 0.1)) +
515
  theme_minimal(base_size = 12) +
516
- theme(
517
- legend.position = "none",
518
- axis.text.x = element_blank(),
519
- axis.ticks.x = element_blank(),
520
- axis.title.y = element_text(size = 12, face = "bold",
521
- margin = margin(r = 10)),
522
- axis.title.x = element_text(size = 12, face = "bold",
523
- margin = margin(t = 10)),
524
- panel.grid.major.x = element_blank(),
525
- panel.grid.minor.x = element_blank(),
526
- panel.grid.major.y = element_line(color = "grey88", linewidth = 0.3),
527
- panel.grid.minor.y = element_line(color = "grey94", linewidth = 0.15),
528
- plot.margin = margin(20, 20, 20, 20)
529
- )
530
-
531
- # Optionally add marker labels with ggrepel
532
- if (show_labels && "Marker" %in% names(plot_data)) {
533
  p <- p + geom_text_repel(
534
  data = plot_data,
535
  aes(x = chrom_center, y = Position, label = Marker,
@@ -546,9 +666,9 @@ create_multi_chromosome_plot <- function(linkage_data,
546
  p
547
  }
548
 
549
- # ─────────────────────────────────────────────
550
  # UI
551
- # ─────────────────────────────────────────────
552
 
553
  ui <- fluidPage(
554
  tags$head(tags$style(HTML("
@@ -566,231 +686,334 @@ ui <- fluidPage(
566
  .nav-tabs > li.active > a:focus { color:#ffffff !important;
567
  background-color:#1E40AF;
568
  font-weight:bold; }
569
- .nav-tabs > li > a:hover { background-color:#2563EB; color:#ffffff !important; }
 
570
  .well { background-color:#EFF6FF; border:1px solid #BFDBFE; color:#333333; }
571
  .form-control { background-color:#FFFFFF; color:#333333;
572
  border:1px solid #93C5FD; }
573
  .form-control:focus { border-color:#3B82F6;
574
  box-shadow:0 0 0 .2rem rgba(59,130,246,.25); }
575
  .btn { border:1px solid; }
576
- .btn-primary { background-color:#1D4ED8; color:#ffffff;
577
- border-color:#1E40AF; }
578
- .btn-primary:hover { background-color:#1E40AF; border-color:#1E3A8A; }
579
- .btn-success { background-color:#059669; color:#ffffff;
580
- border-color:#047857; }
581
- .btn-success:hover { background-color:#047857; border-color:#065F46; }
 
 
582
  .dataTables_wrapper { color:#333333; }
583
  table.dataTable { border:1px solid #BFDBFE; }
584
  .footer { position:fixed; bottom:0; width:100%;
585
  background-color:#1E3A8A; color:#cccccc;
586
  text-align:center; padding:10px;
587
- border-top:1px solid #1E40AF; }
588
  .tab-content h3, .tab-content h4 { color:#1E3A8A; }
 
 
 
 
589
  "))),
590
 
591
- navbarPage("Linkage Map Creator", id = "nav",
592
 
593
- # ── Tab 1: Upload ──────────────────────────────────────────────────────────
594
  tabPanel("Data Upload", icon = icon("upload"),
595
  sidebarLayout(
596
  sidebarPanel(width = 4, wellPanel(
597
  h3("Upload Data"),
598
- fileInput("file", "Choose Excel File",
599
  accept = c(".xlsx", ".xls"),
600
  buttonLabel = "Browse…",
601
  placeholder = "No file selected"),
602
  selectInput("population_type", "Population Type:",
603
- choices = c("RIL" = "RIL", "F2" = "F2"),
604
  selected = "F2"),
605
- helpText("Required columns: 'Marker', 'Chromosome'. ",
606
- "Genotype columns after that: use 'a', 'b', 'ab', or '-'.")
 
 
 
 
 
 
 
607
  )),
608
- mainPanel(width = 8, wellPanel(
609
- h3("Data Preview"),
610
- div(style = "overflow-x:auto;", dataTableOutput("preview_table"))
611
- ))
 
 
 
 
 
 
 
 
 
 
612
  )
613
  ),
614
 
615
- # ── Tab 2: Parameters ─────────────────────────────────────────────────────
616
  tabPanel("Parameters", icon = icon("sliders-h"),
617
  sidebarLayout(
618
  sidebarPanel(width = 4, wellPanel(
619
  h3("Analysis Parameters"),
620
- sliderInput("missing_threshold", "Missing Data Threshold:",
621
- min = 0, max = 1, value = 0.1, step = 0.01),
622
- sliderInput("recombination_threshold", "Recombination Threshold:",
 
 
623
  min = 0, max = 0.5, value = 0.45, step = 0.01),
624
- sliderInput("chi_square_threshold", "Chi-Square P Threshold:",
625
- min = 0, max = 0.2, value = 0.05, step = 0.01),
626
- sliderInput("cluster_threshold", "Cluster Threshold (cM):",
 
 
627
  min = 10, max = 100, value = 40, step = 5),
 
628
  h4("Map Scaling"),
629
- numericInput("max_total_cm", "Max Total Map Length (cM):",
630
- min = 100, max = 5000, value = 1500, step = 100),
 
631
  selectInput("scaling_method", "Scaling Method:",
632
- choices = c("Proportional" = "proportional",
633
- "Uniform" = "uniform"),
634
  selected = "proportional"),
635
- helpText("First marker of each chromosome stays at 0 cM."),
636
- actionButton("run_analysis", "Run Analysis",
637
  class = "btn-primary btn-block", icon = icon("play"))
638
  )),
639
  mainPanel(width = 8, wellPanel(
640
- h3("Parameter Descriptions"),
641
  tags$ul(
642
  tags$li(tags$b("Missing Data Threshold:"),
643
- "Max fraction of missing genotypes per marker."),
644
- tags$li(tags$b("Recombination Threshold:"),
645
- "Only marker pairs with r < this value are linked. ",
646
- "Recommended ≀ 0.45 for F2."),
 
647
  tags$li(tags$b("Chi-Square P Threshold:"),
648
- "Markers with segregation distortion p < threshold are removed."),
 
 
649
  tags$li(tags$b("Cluster Threshold:"),
650
- "cM cut-off for merging markers into the same linkage group."),
651
- tags$li(tags$b("Max Total Map Length:"),
652
- "Upper limit for sum of all chromosome lengths after scaling.")
 
 
653
  ),
654
- br(), h4("Scaling Summary"), verbatimTextOutput("scaling_summary"),
655
- br(), h4("Before Scaling"), verbatimTextOutput("before_scaling_stats"),
656
- br(), h4("After Scaling"), verbatimTextOutput("after_scaling_stats")
 
 
 
 
657
  ))
658
  )
659
  ),
660
 
661
- # ── Tab 3: Results ────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
662
  tabPanel("Results", icon = icon("table"),
663
  fluidRow(column(12, wellPanel(
664
  h3("Analysis Results"),
665
  conditionalPanel("output.analysis_run",
666
- downloadButton("download_results", "Download Excel Results",
667
  class = "btn-success"),
668
  br(), br(),
669
- h4("Linkage Map Data"),
670
  div(style = "overflow-x:auto;", dataTableOutput("result_table")),
671
  h4("Summary Statistics"),
672
  verbatimTextOutput("summary_stats")
673
  ),
674
  conditionalPanel("!output.analysis_run",
675
- p("Please upload data and run analysis to see results.",
676
  style = "color:#888;font-style:italic;text-align:center;padding:40px;")
677
  )
678
  )))
679
  ),
680
 
681
- # ── Tab 4: Plot Customization ──────────────────────────────────────────────
682
- tabPanel("Plot Customization", icon = icon("palette"),
683
  sidebarLayout(
684
  sidebarPanel(width = 4, wellPanel(
685
- h3("Plot Options"),
686
  selectInput("color_palette", "Color Palette:",
687
- choices = c("Set1","Set2","Set3","Paired","Dark2","Accent",
688
- "Blues","Reds","Greens","Purples","Oranges",
689
- "Greys","Spectral","RdBu"),
690
  selected = "Set2"),
691
- checkboxInput("show_labels", "Show Marker Labels", value = TRUE),
692
- sliderInput("marker_label_size", "Marker Label Size:",
693
- min = 2, max = 10, value = 3, step = 0.5),
694
  sliderInput("plot_width", "Plot Width (px):",
695
- min = 600, max = 1600, value = 1200, step = 50),
696
  sliderInput("plot_height", "Plot Height (px):",
697
- min = 400, max = 1200, value = 700, step = 50)
 
 
 
 
698
  )),
699
  mainPanel(width = 8, wellPanel(
700
- h3("Color Palette Preview"),
701
- plotOutput("palette_preview", height = "200px")
702
  ))
703
  )
704
  ),
705
 
706
- # ── Tab 5: Visualization ──────────────────────────────────────────────────
707
  tabPanel("Visualization", icon = icon("chart-bar"),
708
  fluidRow(column(12, wellPanel(
709
- h3("Chromosome Map Visualization"),
710
  conditionalPanel("output.analysis_run",
711
- selectInput("chromosome_select", "Select Chromosomes:",
712
- choices = NULL, multiple = TRUE),
713
- downloadButton("download_plot", "Download PNG",
714
- class = "btn-success"),
715
- br(), br(),
 
 
716
  plotOutput("chromosome_plot", height = "auto")
717
  ),
718
  conditionalPanel("!output.analysis_run",
719
- p("Please upload data and run analysis to see the map.",
720
  style = "color:#888;font-style:italic;text-align:center;padding:40px;")
721
  )
722
  )))
723
  ),
724
 
725
- # ── Tab 6: Help ───────────────────────────────────────────────────────────
726
  tabPanel("Help", icon = icon("question-circle"),
727
  wellPanel(
728
- h3("Application Guide"),
729
- h4("Input File Format"),
730
- p("Excel (.xlsx) with:"),
731
- tags$ul(
732
- tags$li("Column 1 β€” 'Marker': marker names"),
733
- tags$li("Column 2 β€” 'Chromosome': chromosome/linkage-group assignment"),
734
- tags$li("Columns 3+ β€” individual genotype calls: 'a' (AA), 'b' (BB), 'ab' (Aa), '-' (missing)")
 
 
 
 
 
 
 
 
735
  ),
736
- h4("F2 vs RIL"),
737
  tags$ul(
738
- tags$li(tags$b("F2:"), "heterozygotes (ab) are expected and informative; MLE used for r."),
739
- tags$li(tags$b("RIL:"), "homozygous lines; heterozygotes ignored; Haldane RIL correction applied.")
 
 
 
740
  ),
741
- h4("Output"),
742
  tags$ul(
743
- tags$li("Excel: Original Data | Recombination Fractions | Linkage Map"),
744
- tags$li("PNG: high-resolution chromosome map for publication")
745
- )
 
 
 
 
746
  )
747
  )
748
  ),
749
 
750
  div(class = "footer",
751
- "Linkage Map Creator v3.0 | F2 / RIL | Β© 2024 Bioinformatics Tool")
752
  )
753
 
754
- # ─────────────────────────────────────────────
755
  # SERVER
756
- # ─────────────────────────────────────────────
757
 
758
  server <- function(input, output, session) {
759
 
760
  uploaded_data <- reactiveVal(NULL)
761
  analysis_results <- reactiveVal(NULL)
762
- pre_scaling_stats <- reactiveVal(NULL)
 
 
 
 
 
 
 
 
 
 
 
 
 
763
 
764
  # ── File upload ─────────────────────────────────────────────────────────────
765
  observeEvent(input$file, {
766
  req(input$file)
767
  tryCatch({
768
- df <- read.xlsx(input$file$datapath, sheet = 1)
769
- if (!all(c("Marker", "Chromosome") %in% colnames(df)))
770
- stop("Required columns 'Marker' and 'Chromosome' not found.")
771
- if (ncol(df) < 3 || nrow(df) == 0)
772
- stop("File contains no genotype columns.")
 
 
 
 
 
773
  uploaded_data(df)
774
- showNotification("File uploaded successfully!", type = "message")
 
775
  }, error = function(e) {
 
776
  showNotification(paste("Upload error:", e$message), type = "error")
777
  })
778
  })
779
 
 
 
780
  output$preview_table <- renderDataTable({
781
  req(uploaded_data())
782
- datatable(head(uploaded_data(), 10),
783
- options = list(scrollX = TRUE, dom = "t", pageLength = 10),
 
784
  rownames = FALSE)
785
  })
786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787
  # ── Run analysis ────────────────────────────────────────────────────────────
788
  observeEvent(input$run_analysis, {
789
  req(uploaded_data())
790
  showModal(modalDialog(
791
- title = "Processing",
792
- paste0("Building linkage map for ", input$population_type,
793
- " population β€” this may take a few moments…"),
794
  footer = NULL
795
  ))
796
  tryCatch({
@@ -802,17 +1025,25 @@ server <- function(input, output, session) {
802
  chi_square_threshold = input$chi_square_threshold,
803
  cluster_threshold = input$cluster_threshold,
804
  max_total_cm = input$max_total_cm,
805
- scaling_method = input$scaling_method
 
806
  )
807
  analysis_results(result)
808
- pre_scaling_stats(result$chrom_lengths_before)
809
 
810
  chromosomes <- sort(unique(result$linkage_map$Chromosome))
 
 
 
 
811
  updateSelectInput(session, "chromosome_select",
812
- choices = chromosomes,
813
- selected = chromosomes)
814
  removeModal()
815
- showNotification("Analysis complete!", type = "message")
 
 
 
 
816
  }, error = function(e) {
817
  removeModal()
818
  showNotification(paste("Analysis error:", e$message), type = "error")
@@ -822,26 +1053,34 @@ server <- function(input, output, session) {
822
  output$analysis_run <- reactive({ !is.null(analysis_results()) })
823
  outputOptions(output, "analysis_run", suspendWhenHidden = FALSE)
824
 
825
- # ── Scaling text outputs ────────────────────────────────────────────────────
 
 
 
 
 
 
826
  output$scaling_summary <- renderText({
827
  req(analysis_results())
828
- paste0("Scaling Method : ", input$scaling_method,
829
- "\nMax Total cM : ", input$max_total_cm, " cM")
830
  })
831
 
832
- fmt_chrom_lengths <- function(df) {
833
  if (is.null(df) || nrow(df) == 0) return("No data.")
834
  total <- sum(df$Original_Length, na.rm = TRUE)
835
  rows <- apply(df, 1, function(x)
836
- paste0(" Chr ", x[1], ": ", round(as.numeric(x[2]), 2), " cM"))
837
  paste0("Total : ", round(total, 2), " cM\n", paste(rows, collapse = "\n"))
838
  }
839
 
840
  output$before_scaling_stats <- renderText({
841
- req(pre_scaling_stats()); fmt_chrom_lengths(pre_scaling_stats())
 
842
  })
843
  output$after_scaling_stats <- renderText({
844
- req(analysis_results()); fmt_chrom_lengths(analysis_results()$chrom_lengths_after)
 
845
  })
846
 
847
  # ── Result table ────────────────────────────────────────────────────────────
@@ -850,13 +1089,13 @@ server <- function(input, output, session) {
850
  lm <- analysis_results()$linkage_map
851
  if (nrow(lm) > 0) {
852
  datatable(lm,
853
- options = list(scrollX = TRUE, pageLength = 25,
854
- order = list(list(1, "asc"), list(2, "asc"))),
855
  rownames = FALSE,
856
  caption = "Linkage map β€” positions in cM") %>%
857
  formatRound("Position", 2)
858
  } else {
859
- datatable(data.frame(Message = "No positioned markers."),
860
  options = list(dom = "t"), rownames = FALSE)
861
  }
862
  })
@@ -866,32 +1105,39 @@ server <- function(input, output, session) {
866
  req(analysis_results())
867
  lm <- analysis_results()$linkage_map
868
  rec <- analysis_results()$recombination_data
869
- if (nrow(lm) == 0) return("No positioned markers found.")
 
 
 
 
870
 
871
- n_total <- nrow(lm)
872
- n_pos <- sum(!is.na(lm$Position))
873
- n_chr <- length(unique(lm$Chromosome))
874
- chr_lengths <- lm %>% filter(!is.na(Position)) %>%
875
  group_by(Chromosome) %>%
876
- summarise(Length = max(Position, na.rm = TRUE), .groups = "drop")
877
- total_len <- sum(chr_lengths$Length)
878
- avg_len <- mean(chr_lengths$Length)
 
 
 
879
 
880
  chr_detail <- paste(
881
  apply(chr_lengths, 1, function(x)
882
- paste0(" Chr ", x[1], ": ", round(as.numeric(x[2]), 2), " cM")),
 
883
  collapse = "\n")
884
 
885
  paste0(
886
  "LINKAGE MAP SUMMARY\n",
887
  "===================\n",
888
- "Total markers : ", n_total, "\n",
889
- "Positioned markers : ", n_pos, "\n",
890
- "Chromosomes : ", n_chr, "\n",
891
- "Total map length : ", round(total_len, 2), " cM\n",
892
- "Avg chromosome length : ", round(avg_len, 2), " cM\n",
893
- "Marker pairs analysed : ", nrow(rec), "\n\n",
894
- "CHROMOSOME DETAILS:\n", chr_detail
 
895
  )
896
  })
897
 
@@ -907,10 +1153,10 @@ server <- function(input, output, session) {
907
  scale_x_continuous(breaks = 1:n, labels = 1:n) +
908
  labs(title = paste("Preview β€”", input$color_palette)) +
909
  theme_minimal() +
910
- theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(),
911
- axis.title = element_blank(), panel.grid = element_blank(),
912
- plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))
913
- }, height = 200)
914
 
915
  # ── Chromosome plot ─────────────────────────────────────────────────────────
916
  output$chromosome_plot <- renderPlot({
@@ -922,7 +1168,9 @@ server <- function(input, output, session) {
922
  show_labels = input$show_labels,
923
  color_palette = input$color_palette,
924
  plot_width = input$plot_width,
925
- plot_height = input$plot_height
 
 
926
  )
927
  }, height = function() input$plot_height)
928
 
@@ -935,15 +1183,18 @@ server <- function(input, output, session) {
935
  addWorksheet(wb, "Original_Data")
936
  addWorksheet(wb, "Recombination_Fractions")
937
  addWorksheet(wb, "Linkage_Map")
938
- writeData(wb, "Original_Data", analysis_results()$original_data)
939
- writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
940
- writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
 
 
 
941
  saveWorkbook(wb, file, overwrite = TRUE)
942
  }
943
  )
944
 
945
  output$download_plot <- downloadHandler(
946
- filename = function() paste0("chromosome_map_", Sys.Date(), ".png"),
947
  content = function(file) {
948
  req(analysis_results(), input$chromosome_select)
949
  p <- create_multi_chromosome_plot(
@@ -953,7 +1204,9 @@ server <- function(input, output, session) {
953
  show_labels = input$show_labels,
954
  color_palette = input$color_palette,
955
  plot_width = input$plot_width,
956
- plot_height = input$plot_height
 
 
957
  )
958
  ggsave(file, p,
959
  width = input$plot_width / 300,
 
7
  library(RColorBrewer)
8
  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) {
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
+ }
34
+ if (!("Marker" %in% colnames(df_raw))) {
35
+ stop("Column 'Marker' not found. Please check your file.")
36
+ }
37
+
38
+ chr_col <- as.character(df_raw$Chromosome)
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)]
63
+
64
+ numeric_encoding <- all(sample_vals %in% c(-1, 0, 1, 2, NA))
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) {
73
+ col <- as.character(col)
74
+ col[col == "2"] <- "a"
75
+ col[col == "1"] <- "b"
76
+ col[col == "0"] <- "ab"
77
+ col[col == "-1"] <- "-"
78
+ col[is.na(col) | col == "NA"] <- "-"
79
+ col
80
+ }
81
+ )
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) {
89
+ col <- as.character(col)
90
+ col[!(col %in% c("a", "b", "ab"))] <- "-"
91
+ col
92
+ }
93
+ )
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
+
104
+ # ── Infer chromosome number from common rice marker naming conventions ─────────
105
+ infer_chromosome_from_marker <- function(marker_names) {
106
+ markers <- as.character(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
+ }
138
+ } else {
139
+ mt <- regmatches(m, regexpr(pat$regex, m, perl = TRUE))
140
+ if (length(mt) > 0) {
141
+ sub_mt <- regmatches(mt, regexec(pat$regex, mt, perl = TRUE))[[1]]
142
+ if (length(sub_mt) >= pat$group + 1) {
143
+ chr_num <- as.integer(sub_mt[pat$group + 1])
144
+ if (!is.na(chr_num) && chr_num >= 1 && chr_num <= 30) {
145
+ chrom[i] <- as.character(chr_num); break
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+ chrom
153
+ }
154
+
155
+ # ═══════════════════════════════════════════════════════════════════════════════
156
+ # CORE GENETIC FUNCTIONS (Fixed for F2 / RIL)
157
+ # ═══════════════════════════════════════════════════════════════════════════════
158
 
159
  ## 1. Recombination fraction --------------------------------------------------
 
 
160
  calculate_recombination <- function(population_type, genotype1, genotype2) {
161
  g1 <- as.character(genotype1)
162
  g2 <- as.character(genotype2)
163
 
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")
171
  g1h <- g1[hom]; g2h <- g2[hom]
172
+ if (length(g1h) < 4) return(NA_real_)
173
+ r_obs <- mean(g1h != g2h)
174
+ rf <- r_obs / (2 * (1 - r_obs))
175
+ rf <- min(rf, 0.4999)
 
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")
 
187
  BB_Aa <- sum(g1 == "b" & g2 == "ab")
188
  BB_BB <- sum(g1 == "b" & g2 == "b")
189
 
 
 
190
  r <- 0.25
191
  for (iter in 1:200) {
192
  r_old <- r
193
  q <- 1 - r
194
+ p_parental <- q^2 + r^2
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) +
202
+ 2 * n_recomb_AaAa
 
 
 
 
203
  total_gametes <- 2 * n
204
+ r_new <- max(1e-6, min(recomb_count / total_gametes, 0.4999))
 
 
205
  r <- r_new
206
  if (abs(r - r_old) < 1e-8) break
207
  }
208
  return(r)
 
209
  } else {
210
  stop("population_type must be 'RIL' or 'F2'")
211
  }
 
216
  if (is.na(r)) return(NA_real_)
217
  r <- max(0, min(r, 0.4999))
218
  if (r == 0) return(0)
219
+ 25 * log((1 + 2 * r) / (1 - 2 * r))
220
  }
221
 
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])
241
  mode_val <- names(which.max(tbl))
242
  row[nas] <- mode_val
243
  row
 
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
 
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
+ # 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
  }
 
295
  return(pval > chi_square_threshold)
296
  })
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])
 
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
  }
 
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])
 
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)
 
368
  summarise(Original_Length = max(Position, na.rm = TRUE), .groups = "drop")
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
 
376
  scaled <- linkage_map
 
377
  if (method == "proportional") {
378
+ before$sf <- max_total_cm / total
 
379
  } else {
380
+ n_chr <- nrow(before)
381
  before$sf <- ifelse(before$Original_Length > 0,
382
  (max_total_cm / n_chr) / before$Original_Length, 1)
383
  }
 
401
 
402
  ## 9. Master analysis function ------------------------------------------------
403
  create_linkage_map <- function(df,
404
+ population_type = "F2",
405
+ missing_threshold = 0.1,
406
  recombination_threshold = 0.5,
407
+ chi_square_threshold = 0.05,
408
+ cluster_threshold = 40,
409
+ max_total_cm = 1500,
410
+ scaling_method = "proportional",
411
+ allow_distorted_f2 = TRUE) {
412
 
413
  empty_result <- function(df_in = df) {
414
  list(original_data = df_in,
 
417
  Chromosome = character(0),
418
  Position = numeric(0)),
419
  chrom_lengths_before = data.frame(),
420
+ chrom_lengths_after = data.frame(),
421
+ markers_removed = character(0),
422
+ qc_report = "No data passed QC.")
423
  }
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]
438
  if (length(keep) == nrow(df)) df <- df[keep, ]
439
 
440
+ n_after_chi <- nrow(df)
441
+
442
+ qc_msg <- paste0(
443
+ "QC Report:\n",
444
+ " Markers input : ", nrow(df_orig), "\n",
445
+ " After missing-data QC : ", n_before_chi, "\n",
446
+ " After chi-square filter: ", n_after_chi, "\n",
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) {
455
+ res <- empty_result(df_orig)
456
+ res$qc_report <- qc_msg
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, ]
 
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),
 
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)
545
 
546
+ list(original_data = df_orig,
547
  recombination_data = rec_df,
548
  linkage_map = scaled$scaled_map,
549
  chrom_lengths_before = scaled$chrom_lengths_before,
550
+ chrom_lengths_after = scaled$chrom_lengths_after,
551
+ markers_removed = removed_markers,
552
+ qc_report = qc_msg)
553
  }
554
 
555
+ # ═══════════════════════════════════════════════════════════════════════════════
556
+ # PLOTTING
557
+ # ═══════════════════════════════════════════════════════════════════════════════
558
 
559
  create_multi_chromosome_plot <- function(linkage_data,
560
  selected_chromosomes,
 
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),
574
+ error = function(e) sort(selected_chromosomes)
575
+ )
576
+
577
  plot_data <- linkage_data %>%
578
  filter(Chromosome %in% selected_chromosomes, !is.na(Position)) %>%
579
+ arrange(match(Chromosome, chr_sorted), Position)
580
 
581
  if (nrow(plot_data) == 0) {
582
  return(ggplot() +
583
  annotate("text", x = 0.5, y = 0.5,
584
+ label = "No valid marker positions available.\nTry relaxing QC parameters.",
585
+ size = 5, color = "red", hjust = 0.5) +
586
  theme_void())
587
  }
588
 
 
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) %>%
595
  mutate(chrom_x = seq(1, by = chrom_spacing, length.out = n()),
596
  chrom_center = chrom_x)
 
600
  by = "Chromosome")
601
 
602
  n_chrom <- nrow(chrom_stats)
603
+ palette_ok <- tryCatch({ brewer.pal(max(3, n_chrom), color_palette); TRUE },
604
+ error = function(e) FALSE)
 
 
605
 
606
  chrom_colors <- if (palette_ok && n_chrom <= 8) {
607
+ brewer.pal(max(3, n_chrom), color_palette)[seq_len(n_chrom)]
608
  } else if (palette_ok) {
609
  colorRampPalette(brewer.pal(8, color_palette))(n_chrom)
610
  } else {
 
622
  color = as.factor(Chromosome)),
623
  size = point_size, alpha = 0.9) +
624
  geom_text(data = chrom_stats,
625
+ aes(x = chrom_center,
626
+ y = -(max(chrom_stats$max_pos) * 0.03),
627
  label = paste0("Chr\n", Chromosome),
628
  color = as.factor(Chromosome)),
629
  size = label_size + 1, fontface = "bold", vjust = 1) +
630
+ scale_color_manual(values = setNames(chrom_colors,
631
+ levels(factor(chrom_stats$Chromosome)))) +
632
+ scale_y_reverse(name = "Genetic Position (cM)",
633
  expand = expansion(mult = c(0.02, 0.12))) +
634
  scale_x_continuous(breaks = chrom_stats$chrom_center,
635
  labels = chrom_stats$Chromosome,
636
  name = "Chromosome",
637
  expand = expansion(mult = 0.1)) +
638
  theme_minimal(base_size = 12) +
639
+ theme(legend.position = "none",
640
+ axis.text.x = element_blank(),
641
+ axis.ticks.x = element_blank(),
642
+ axis.title.y = element_text(size = 12, face = "bold",
643
+ margin = margin(r = 10)),
644
+ axis.title.x = element_text(size = 12, face = "bold",
645
+ margin = margin(t = 10)),
646
+ panel.grid.major.x = element_blank(),
647
+ panel.grid.minor.x = element_blank(),
648
+ panel.grid.major.y = element_line(color = "grey88", linewidth = 0.3),
649
+ panel.grid.minor.y = element_line(color = "grey94", linewidth = 0.15),
650
+ plot.margin = margin(20, 20, 20, 20))
651
+
652
+ if (show_labels && "Marker" %in% names(plot_data) && nrow(plot_data) <= 500) {
 
 
 
653
  p <- p + geom_text_repel(
654
  data = plot_data,
655
  aes(x = chrom_center, y = Position, label = Marker,
 
666
  p
667
  }
668
 
669
+ # ═══════════════════════════════════════════════════════════════════════════════
670
  # UI
671
+ # ═══════════════════════════════════════════════════════════════════════════════
672
 
673
  ui <- fluidPage(
674
  tags$head(tags$style(HTML("
 
686
  .nav-tabs > li.active > a:focus { color:#ffffff !important;
687
  background-color:#1E40AF;
688
  font-weight:bold; }
689
+ .nav-tabs > li > a:hover { background-color:#2563EB;
690
+ color:#ffffff !important; }
691
  .well { background-color:#EFF6FF; border:1px solid #BFDBFE; color:#333333; }
692
  .form-control { background-color:#FFFFFF; color:#333333;
693
  border:1px solid #93C5FD; }
694
  .form-control:focus { border-color:#3B82F6;
695
  box-shadow:0 0 0 .2rem rgba(59,130,246,.25); }
696
  .btn { border:1px solid; }
697
+ .btn-primary { background-color:#1D4ED8; color:#ffffff;
698
+ border-color:#1E40AF; }
699
+ .btn-primary:hover { background-color:#1E40AF; border-color:#1E3A8A; }
700
+ .btn-success { background-color:#059669; color:#ffffff;
701
+ border-color:#047857; }
702
+ .btn-success:hover { background-color:#047857; border-color:#065F46; }
703
+ .alert-info { background-color:#DBEAFE; border-color:#93C5FD;
704
+ color:#1E3A8A; }
705
  .dataTables_wrapper { color:#333333; }
706
  table.dataTable { border:1px solid #BFDBFE; }
707
  .footer { position:fixed; bottom:0; width:100%;
708
  background-color:#1E3A8A; color:#cccccc;
709
  text-align:center; padding:10px;
710
+ border-top:1px solid #1E40AF; font-size:12px; }
711
  .tab-content h3, .tab-content h4 { color:#1E3A8A; }
712
+ .conversion-badge { background:#FEF3C7; border:1px solid #F59E0B;
713
+ padding:6px 12px; border-radius:6px;
714
+ color:#92400E; font-weight:bold; margin-bottom:10px;
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"),
722
  sidebarLayout(
723
  sidebarPanel(width = 4, wellPanel(
724
  h3("Upload Data"),
725
+ fileInput("file", "Choose Excel File (.xlsx)",
726
  accept = c(".xlsx", ".xls"),
727
  buttonLabel = "Browse…",
728
  placeholder = "No file selected"),
729
  selectInput("population_type", "Population Type:",
730
+ choices = c("F2" = "F2", "RIL" = "RIL"),
731
  selected = "F2"),
732
+ checkboxInput("allow_distorted_f2",
733
+ "Keep distorted-but-heterozygous F2 markers",
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,
743
+ wellPanel(
744
+ h3("Upload Status"),
745
+ verbatimTextOutput("upload_status")
746
+ ),
747
+ wellPanel(
748
+ h3("Data Preview (first 10 rows, converted)"),
749
+ div(style = "overflow-x:auto;", dataTableOutput("preview_table"))
750
+ ),
751
+ wellPanel(
752
+ h3("Chromosome Assignments"),
753
+ div(style = "overflow-x:auto;", dataTableOutput("chr_summary_table"))
754
+ )
755
+ )
756
  )
757
  ),
758
 
759
+ # ── Tab 2: Parameters ───────────────────────────────────────────────────
760
  tabPanel("Parameters", icon = icon("sliders-h"),
761
  sidebarLayout(
762
  sidebarPanel(width = 4, wellPanel(
763
  h3("Analysis Parameters"),
764
+ sliderInput("missing_threshold",
765
+ "Missing Data Threshold (per marker):",
766
+ min = 0, max = 1, value = 0.3, step = 0.05),
767
+ sliderInput("recombination_threshold",
768
+ "Max Recombination Fraction (r):",
769
  min = 0, max = 0.5, value = 0.45, step = 0.01),
770
+ sliderInput("chi_square_threshold",
771
+ "Chi-Square P-value Threshold:",
772
+ min = 0, max = 0.2, value = 0.001, step = 0.001),
773
+ sliderInput("cluster_threshold",
774
+ "Linkage Group Cluster Threshold (cM):",
775
  min = 10, max = 100, value = 40, step = 5),
776
+ hr(),
777
  h4("Map Scaling"),
778
+ numericInput("max_total_cm",
779
+ "Max Total Map Length (cM):",
780
+ min = 100, max = 10000, value = 1500, step = 100),
781
  selectInput("scaling_method", "Scaling Method:",
782
+ choices = c("Proportional" = "proportional",
783
+ "Uniform" = "uniform"),
784
  selected = "proportional"),
785
+ hr(),
786
+ actionButton("run_analysis", "β–Ά Run Analysis",
787
  class = "btn-primary btn-block", icon = icon("play"))
788
  )),
789
  mainPanel(width = 8, wellPanel(
790
+ h3("Parameter Guide"),
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"),
811
+ verbatimTextOutput("scaling_summary"),
812
+ h4("Before Scaling"),
813
+ verbatimTextOutput("before_scaling_stats"),
814
+ h4("After Scaling"),
815
+ verbatimTextOutput("after_scaling_stats")
816
  ))
817
  )
818
  ),
819
 
820
+ # ── Tab 3: QC Report ────────────────────────────────────────────────────
821
+ tabPanel("QC Report", icon = icon("clipboard-check"),
822
+ wellPanel(
823
+ h3("Quality Control Report"),
824
+ verbatimTextOutput("qc_report_output")
825
+ )
826
+ ),
827
+
828
+ # ── Tab 4: Results ───────────────────────────────────────────────────────
829
  tabPanel("Results", icon = icon("table"),
830
  fluidRow(column(12, wellPanel(
831
  h3("Analysis Results"),
832
  conditionalPanel("output.analysis_run",
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")
840
  ),
841
  conditionalPanel("!output.analysis_run",
842
+ p("Upload data and click 'Run Analysis' to see results.",
843
  style = "color:#888;font-style:italic;text-align:center;padding:40px;")
844
  )
845
  )))
846
  ),
847
 
848
+ # ── Tab 5: Plot Options ──────────────────────────────────────────────────
849
+ tabPanel("Plot Options", icon = icon("palette"),
850
  sidebarLayout(
851
  sidebarPanel(width = 4, wellPanel(
852
+ h3("Visualization Options"),
853
  selectInput("color_palette", "Color Palette:",
854
+ choices = c("Set1","Set2","Set3","Paired","Dark2",
855
+ "Accent","Spectral","RdBu"),
 
856
  selected = "Set2"),
857
+ checkboxInput("show_labels", "Show Marker Labels", value = FALSE),
858
+ sliderInput("marker_label_size", "Label Size:",
859
+ min = 1, max = 8, value = 2, step = 0.5),
860
  sliderInput("plot_width", "Plot Width (px):",
861
+ min = 600, max = 2400, value = 1400, step = 100),
862
  sliderInput("plot_height", "Plot Height (px):",
863
+ min = 400, max = 1600, value = 800, step = 50),
864
+ sliderInput("chrom_spacing", "Chromosome Spacing:",
865
+ min = 2, max = 15, value = 5, step = 0.5),
866
+ sliderInput("point_size", "Marker Point Size:",
867
+ min = 0.5, max = 5, value = 1.5, step = 0.25)
868
  )),
869
  mainPanel(width = 8, wellPanel(
870
+ h3("Palette Preview"),
871
+ plotOutput("palette_preview", height = "180px")
872
  ))
873
  )
874
  ),
875
 
876
+ # ── Tab 6: Visualization ─────────────────────────────────────────────────
877
  tabPanel("Visualization", icon = icon("chart-bar"),
878
  fluidRow(column(12, wellPanel(
879
+ h3("Chromosome Map"),
880
  conditionalPanel("output.analysis_run",
881
+ fluidRow(
882
+ column(8, selectInput("chromosome_select", "Select Chromosomes:",
883
+ choices = NULL, multiple = TRUE)),
884
+ column(4, br(),
885
+ downloadButton("download_plot", "⬇ Download PNG",
886
+ class = "btn-success"))
887
+ ),
888
  plotOutput("chromosome_plot", height = "auto")
889
  ),
890
  conditionalPanel("!output.analysis_run",
891
+ p("Run analysis first.",
892
  style = "color:#888;font-style:italic;text-align:center;padding:40px;")
893
  )
894
  )))
895
  ),
896
 
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")
933
  )
934
  )
935
  ),
936
 
937
  div(class = "footer",
938
+ "Linkage Map Creator v4.0 | F2 / RIL | Auto-converts numeric codes | Β© 2024")
939
  )
940
 
941
+ # ═══════════════════════════════════════════════════════════════════════════════
942
  # SERVER
943
+ # ═══════════════════════════════════════════════════════════════════════════════
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"),
955
+ `Text Code` = c("a", "b", "ab", "-"),
956
+ Meaning = c("Homozygous Parent 1 (AA)",
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)
980
+ showNotification("File uploaded and converted successfully!", type = "message")
981
  }, error = function(e) {
982
+ upload_log(paste0("βœ— Error: ", e$message))
983
  showNotification(paste("Upload error:", e$message), type = "error")
984
  })
985
  })
986
 
987
+ output$upload_status <- renderText({ upload_log() })
988
+
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)
995
  })
996
 
997
+ output$chr_summary_table <- renderDataTable({
998
+ req(uploaded_data())
999
+ df <- uploaded_data()
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({
 
1025
  chi_square_threshold = input$chi_square_threshold,
1026
  cluster_threshold = input$cluster_threshold,
1027
  max_total_cm = input$max_total_cm,
1028
+ scaling_method = input$scaling_method,
1029
+ allow_distorted_f2 = input$allow_distorted_f2
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) {
1048
  removeModal()
1049
  showNotification(paste("Analysis error:", e$message), type = "error")
 
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,
1066
+ "\nMax cM : ", input$max_total_cm)
1067
  })
1068
 
1069
+ fmt_chr <- function(df) {
1070
  if (is.null(df) || nrow(df) == 0) return("No data.")
1071
  total <- sum(df$Original_Length, na.rm = TRUE)
1072
  rows <- apply(df, 1, function(x)
1073
+ paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]), 2), " cM"))
1074
  paste0("Total : ", round(total, 2), " cM\n", paste(rows, collapse = "\n"))
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 ────────────────────────────────────────────────────────────
 
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
  })
 
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)
1123
 
1124
  chr_detail <- paste(
1125
  apply(chr_lengths, 1, function(x)
1126
+ paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]), 2),
1127
+ " cM (", x[3], " markers)")),
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
 
 
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({
 
1168
  show_labels = input$show_labels,
1169
  color_palette = input$color_palette,
1170
  plot_width = input$plot_width,
1171
+ plot_height = input$plot_height,
1172
+ chrom_spacing = input$chrom_spacing,
1173
+ point_size = input$point_size
1174
  )
1175
  }, height = function() input$plot_height)
1176
 
 
1183
  addWorksheet(wb, "Original_Data")
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)
1193
  }
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(
 
1204
  show_labels = input$show_labels,
1205
  color_palette = input$color_palette,
1206
  plot_width = input$plot_width,
1207
+ plot_height = input$plot_height,
1208
+ chrom_spacing = input$chrom_spacing,
1209
+ point_size = input$point_size
1210
  )
1211
  ggsave(file, p,
1212
  width = input$plot_width / 300,