softwareDevelopment commited on
Commit
3dd9c63
Β·
verified Β·
1 Parent(s): 8e45d02

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +887 -419
app.R CHANGED
@@ -12,24 +12,16 @@ library(ggrepel)
12
  # ═══════════════════════════════════════════════════════════════════════════════
13
 
14
  load_and_convert_data <- function(filepath) {
15
-
16
- wb_raw <- tryCatch(
17
- loadWorkbook(filepath),
18
- error = function(e) stop("Cannot open workbook: ", e$message)
19
- )
20
-
21
  df_raw <- read.xlsx(filepath, sheet = 1, colNames = TRUE)
 
 
22
 
23
- if (!("Chromosome" %in% colnames(df_raw)))
24
- stop("Column 'Chromosome' not found. Please check your file.")
25
- if (!("Marker" %in% colnames(df_raw)))
26
- stop("Column 'Marker' not found. Please check your file.")
27
-
28
- chr_col <- as.character(df_raw$Chromosome)
29
  has_formula <- any(grepl("^=", chr_col, ignore.case = FALSE), na.rm = TRUE)
30
-
31
  if (has_formula) {
32
- inferred <- infer_chromosome_from_marker(df_raw$Marker)
33
  n_inferred <- sum(!is.na(inferred))
34
  if (n_inferred / nrow(df_raw) >= 0.5) {
35
  df_raw$Chromosome <- inferred
@@ -57,8 +49,7 @@ load_and_convert_data <- function(filepath) {
57
  col[col == "-1"] <- "-"
58
  col[is.na(col) | col == "NA"] <- "-"
59
  col
60
- }
61
- )
62
  } else if (!text_encoding) {
63
  df_raw[, 3:ncol(df_raw)] <- lapply(
64
  df_raw[, 3:ncol(df_raw), drop = FALSE],
@@ -66,8 +57,7 @@ load_and_convert_data <- function(filepath) {
66
  col <- as.character(col)
67
  col[!(col %in% c("a", "b", "ab"))] <- "-"
68
  col
69
- }
70
- )
71
  }
72
 
73
  df_raw$Chromosome <- as.character(df_raw$Chromosome)
@@ -80,15 +70,15 @@ infer_chromosome_from_marker <- function(marker_names) {
80
  markers <- as.character(marker_names)
81
  chrom <- rep(NA_character_, length(markers))
82
  patterns <- list(
83
- list(regex = "(?i)chr(\\d{1,2})[_\\-]", group = 1),
84
- list(regex = "(?i)[_\\-]C(\\d{1,2})[_\\-]", group = 1),
85
- list(regex = "(?i)^MSU\\d+_(\\d{1,2})_", group = 1),
86
- list(regex = "(?i)^DTY(\\d{1,2})[\\-_]", group = 1),
87
- list(regex = "(?i)^[A-Za-z]{1,6}(\\d{1,2})[a-zA-Z_]",group = 1),
88
- list(regex = "(?i)^Saltol", group = NA),
89
- list(regex = "(?i)^SCT(\\d{1,2})[_\\-]", group = 1),
90
- list(regex = "(?i)^R(\\d{1,2})", group = 1),
91
- list(regex = "(?i)^Pi(\\d{1,2})", group = 1)
92
  )
93
  for (i in seq_along(markers)) {
94
  m <- markers[i]
@@ -96,7 +86,7 @@ infer_chromosome_from_marker <- function(marker_names) {
96
  if (is.na(pat$group)) {
97
  if (grepl(pat$regex, m, perl = TRUE)) { chrom[i] <- "1"; break }
98
  } else {
99
- mt <- regmatches(m, regexpr(pat$regex, m, perl = TRUE))
100
  if (length(mt) > 0) {
101
  sub_mt <- regmatches(mt, regexec(pat$regex, mt, perl = TRUE))[[1]]
102
  if (length(sub_mt) >= pat$group + 1) {
@@ -117,11 +107,11 @@ infer_chromosome_from_marker <- function(marker_names) {
117
  # ═══════════════════════════════════════════════════════════════════════════════
118
 
119
  calculate_recombination <- function(population_type, genotype1, genotype2) {
120
- g1 <- as.character(genotype1)
121
- g2 <- as.character(genotype2)
122
  keep <- !(g1 %in% c("-", "NA", NA) | g2 %in% c("-", "NA", NA))
123
- g1 <- g1[keep]; g2 <- g2[keep]
124
- n <- length(g1)
125
  if (n < 4) return(NA_real_)
126
 
127
  if (population_type == "RIL") {
@@ -131,7 +121,6 @@ calculate_recombination <- function(population_type, genotype1, genotype2) {
131
  r_obs <- mean(g1h != g2h)
132
  rf <- r_obs / (2 * (1 - r_obs))
133
  return(min(rf, 0.4999))
134
-
135
  } else if (population_type == "F2") {
136
  AA_AA <- sum(g1=="a" & g2=="a"); AA_Aa <- sum(g1=="a" & g2=="ab")
137
  AA_BB <- sum(g1=="a" & g2=="b"); Aa_AA <- sum(g1=="ab" & g2=="a")
@@ -160,11 +149,10 @@ calculate_cM_kosambi <- function(r) {
160
  25 * log((1 + 2*r) / (1 - 2*r))
161
  }
162
 
163
- # ── Monomorphic marker detection ─────────────────────────────────────────────
164
  detect_monomorphic_markers <- function(df) {
165
  geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
166
  is_mono <- apply(df[, geno_cols_idx, drop = FALSE], 1, function(row) {
167
- vals <- row[!is.na(row) & !(row %in% c("-", "NA", ""))]
168
  if (length(vals) == 0) return(FALSE)
169
  unique_vals <- unique(vals[vals %in% c("a", "b", "ab")])
170
  length(unique_vals) <= 1
@@ -173,52 +161,37 @@ detect_monomorphic_markers <- function(df) {
173
  is_mono
174
  }
175
 
176
- # ── Chi-square segregation distortion test ───────────────────────────────────
177
- # NEW in v4.3: Returns a named vector of p-values for each marker row in df.
178
- # Expected ratios:
179
- # F2 β†’ AA:Aa:BB = 1:2:1 β†’ c(a=0.25, ab=0.50, b=0.25)
180
- # RIL β†’ AA:BB = 1:1 β†’ c(a=0.50, b=0.50) (heterozygotes ignored)
181
  perform_chi_square_test <- function(df, population_type) {
182
  geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
183
-
184
  if (population_type == "F2") {
185
  expected <- c(a = 0.25, ab = 0.50, b = 0.25)
186
  valid_classes <- c("a", "ab", "b")
187
- } else { # RIL
188
  expected <- c(a = 0.50, b = 0.50)
189
  valid_classes <- c("a", "b")
190
  }
191
-
192
  p_values <- apply(df[, geno_cols_idx, drop = FALSE], 1, function(row) {
193
  vals <- row[!is.na(row) & row %in% valid_classes]
194
- if (length(vals) < 10) return(1.0) # too few observations β€” keep marker
195
-
196
- obs <- table(factor(vals, levels = valid_classes))
197
-
198
- # suppress warning about low expected counts (we already gate on n>=10)
199
- result <- tryCatch(
200
- suppressWarnings(chisq.test(obs, p = expected)),
201
- error = function(e) list(p.value = 1.0)
202
- )
203
  result$p.value
204
  })
205
  names(p_values) <- df$Marker
206
  p_values
207
  }
208
 
209
- # ── Impute / correct ─────────────────────────────────────────────────────────
210
  correct_errors_and_impute_missing <- function(df) {
211
- valid_geno <- c("a", "b", "ab")
212
- geno_start <- which(colnames(df) == "Chromosome") + 1
213
  geno_cols_idx <- setdiff(geno_start:ncol(df), which(colnames(df) == ".input_order"))
214
-
215
  for (j in geno_cols_idx) {
216
  x <- as.character(df[[j]])
217
  x[x %in% c("-", "NA", "", " ", "na")] <- NA
218
  x[!is.na(x) & !(x %in% valid_geno)] <- NA
219
  df[[j]] <- x
220
  }
221
-
222
  if (length(geno_cols_idx) > 0) {
223
  na_col <- colMeans(is.na(df[, geno_cols_idx, drop = FALSE]))
224
  keep_idx <- c(seq_len(geno_start - 1),
@@ -227,7 +200,6 @@ correct_errors_and_impute_missing <- function(df) {
227
  keep_idx <- keep_idx[keep_idx <= ncol(df)]
228
  df <- df[, sort(unique(keep_idx)), drop = FALSE]
229
  }
230
-
231
  geno_cols_idx2 <- setdiff(geno_start:ncol(df), which(colnames(df) == ".input_order"))
232
  if (length(geno_cols_idx2) > 0) {
233
  df[, geno_cols_idx2] <- t(apply(df[, geno_cols_idx2, drop = FALSE], 1, function(row) {
@@ -253,7 +225,7 @@ quality_control <- function(df, missing_threshold = 0.1) {
253
  }
254
 
255
  # ═══════════════════════════════════════════════════════════════════════════════
256
- # POSITION BUILDING (input order preserved)
257
  # ═══════════════════════════════════════════════════════════════════════════════
258
 
259
  build_positions_from_input_order <- function(df, population_type, recombination_threshold) {
@@ -268,7 +240,6 @@ build_positions_from_input_order <- function(df, population_type, recombination_
268
  mks <- sub$Marker
269
  if (length(mks) == 0) next
270
  pos <- setNames(numeric(length(mks)), mks)
271
-
272
  if (length(mks) > 1) {
273
  for (i in 2:length(mks)) {
274
  m_prev <- mks[i-1]; m_curr <- mks[i]
@@ -298,21 +269,18 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
298
  if (nrow(pos_map) == 0)
299
  return(list(scaled_map=linkage_map, chrom_lengths_before=data.frame(),
300
  chrom_lengths_after=data.frame()))
301
-
302
  before <- pos_map %>%
303
  group_by(Chromosome) %>%
304
  summarise(Original_Length = max(Position, na.rm=TRUE), .groups="drop")
305
-
306
  total <- sum(before$Original_Length, na.rm=TRUE)
307
  if (total <= max_total_cm || total == 0)
308
  return(list(scaled_map=linkage_map, chrom_lengths_before=before,
309
  chrom_lengths_after=before))
310
-
311
  scaled <- linkage_map
312
  if (method == "proportional") {
313
  before$sf <- max_total_cm / total
314
  } else {
315
- n_chr <- nrow(before)
316
  before$sf <- ifelse(before$Original_Length > 0,
317
  (max_total_cm/n_chr)/before$Original_Length, 1)
318
  }
@@ -328,12 +296,11 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
328
  filter(!is.na(Position)) %>%
329
  group_by(Chromosome) %>%
330
  summarise(Original_Length = max(Position, na.rm=TRUE), .groups="drop")
331
-
332
  list(scaled_map=scaled, chrom_lengths_before=before, chrom_lengths_after=after)
333
  }
334
 
335
  # ═══════════════════════════════════════════════════════════════════════════════
336
- # MASTER ANALYSIS β€” v4.3: chi-square filter OPTIONAL (toggle in UI)
337
  # ═══════════════════════════════════════════════════════════════════════════════
338
 
339
  create_linkage_map <- function(df,
@@ -342,9 +309,9 @@ create_linkage_map <- function(df,
342
  recombination_threshold = 0.5,
343
  max_total_cm = 1500,
344
  scaling_method = "proportional",
345
- enable_chi_square = FALSE, # NEW v4.3
346
- chi_square_alpha = 0.05, # NEW v4.3
347
- use_bonferroni = FALSE) { # NEW v4.3
348
 
349
  empty_result <- function(df_in = df) {
350
  list(original_data = df_in,
@@ -352,6 +319,8 @@ create_linkage_map <- function(df,
352
  linkage_map = data.frame(Marker=character(0),
353
  Chromosome=character(0),
354
  Position=numeric(0)),
 
 
355
  chrom_lengths_before = data.frame(),
356
  chrom_lengths_after = data.frame(),
357
  removal_log = data.frame(),
@@ -359,24 +328,20 @@ create_linkage_map <- function(df,
359
  }
360
 
361
  df_orig <- df
362
- if (!(".input_order" %in% colnames(df)))
363
- df$.input_order <- seq_len(nrow(df))
364
 
365
- # ── Removal log accumulator ────────────────────────────────────────────────
366
  removal_log <- data.frame(
367
- Marker = character(0),
368
- Chromosome = character(0),
369
- Reason = character(0),
370
- Detail = character(0),
371
  stringsAsFactors = FALSE
372
  )
373
 
374
  n_input <- nrow(df)
375
 
376
- # ── Step 1: Imputation / error correction ──────────────────────────────────
377
  df <- correct_errors_and_impute_missing(df)
378
 
379
- # ── Step 2: Missing data QC ────────────────────────────────────────────────
380
  geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
381
  geno_mat <- df[, geno_cols_idx, drop = FALSE]
382
  miss_frac <- rowMeans(is.na(geno_mat))
@@ -389,8 +354,7 @@ create_linkage_map <- function(df,
389
  Chromosome = df$Chromosome[miss_frac > missing_threshold],
390
  Reason = "Excess missing data",
391
  Detail = paste0(round(miss_frac[miss_frac > missing_threshold]*100,1),
392
- "% missing (threshold: ",
393
- round(missing_threshold*100,1), "%)"),
394
  stringsAsFactors = FALSE
395
  ))
396
  }
@@ -399,19 +363,18 @@ create_linkage_map <- function(df,
399
  res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
400
  }
401
 
402
- # ── Step 3: Monomorphic marker removal ────────────────────────────────────
403
- is_mono <- detect_monomorphic_markers(df)
404
  mono_markers <- names(is_mono)[is_mono]
405
-
406
  if (length(mono_markers) > 0) {
407
- mono_df <- df[df$Marker %in% mono_markers, ]
408
  geno_cols_idx2 <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
409
  details <- sapply(mono_markers, function(mk) {
410
- row <- df[df$Marker == mk, geno_cols_idx2, drop = FALSE]
411
  vals <- unlist(row)
412
  vals <- vals[!is.na(vals) & vals %in% c("a","b","ab")]
413
  if (length(vals) == 0) return("No informative genotypes")
414
- tbl <- table(vals)
415
  dominant <- names(which.max(tbl))
416
  allele_name <- switch(dominant,
417
  a = "Homozygous Parent 1 (AA)",
@@ -435,22 +398,19 @@ create_linkage_map <- function(df,
435
  res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
436
  }
437
 
438
- n_after_mono <- nrow(df)
439
-
440
- # ── Step 4 (NEW v4.3): Chi-square segregation distortion filter ──────────
441
  n_failed_chi <- 0
442
  chi_alpha_used <- NA_real_
443
- chi_note <- "Chi-square filter : DISABLED"
444
 
 
445
  if (enable_chi_square) {
446
- p_values <- perform_chi_square_test(df, population_type)
447
- alpha_used <- if (use_bonferroni) chi_square_alpha / nrow(df) else chi_square_alpha
448
  chi_alpha_used <- alpha_used
449
-
450
  failed_chi_markers <- names(p_values)[p_values < alpha_used]
451
-
452
  if (length(failed_chi_markers) > 0) {
453
- chi_df <- df[df$Marker %in% failed_chi_markers, ]
454
  chi_details <- sapply(failed_chi_markers, function(mk) {
455
  pv <- p_values[mk]
456
  paste0("p = ", formatC(pv, format="e", digits=3),
@@ -466,7 +426,6 @@ create_linkage_map <- function(df,
466
  df <- df[!df$Marker %in% failed_chi_markers, ]
467
  n_failed_chi <- length(failed_chi_markers)
468
  }
469
-
470
  bonf_label <- if (use_bonferroni)
471
  paste0("Bonferroni-corrected (alpha/", n_after_mono, ")")
472
  else "Uncorrected"
@@ -484,10 +443,9 @@ create_linkage_map <- function(df,
484
 
485
  n_after_qc <- nrow(df)
486
 
487
- # ── QC summary text ────────────────────────────────────────────────────────
488
  qc_msg <- paste0(
489
- "QC Report (v4.3 β€” chi-square optional)\n",
490
- "=======================================\n",
491
  " Markers input : ", n_input, "\n",
492
  " Removed (missing data) : ", length(failed_miss), "\n",
493
  " Removed (monomorphic) : ", length(mono_markers), "\n",
@@ -498,26 +456,31 @@ create_linkage_map <- function(df,
498
  " First marker of each chromosome = 0 cM.\n"
499
  )
500
 
501
- # ── Build positions ────────────────────────────────────────────────────────
502
- pos_result <- build_positions_from_input_order(df, population_type, recombination_threshold)
503
  positions_list <- pos_result$positions_list
504
  recombination_rows <- pos_result$recombination_rows
505
-
506
  rec_df <- if (length(recombination_rows) > 0) do.call(rbind, recombination_rows)
507
  else data.frame()
508
 
509
  if (length(positions_list) == 0) {
510
  lm_empty <- df[, c("Marker","Chromosome")]
511
  lm_empty$Position <- NA_real_
 
 
 
512
  return(list(original_data=df_orig, recombination_data=rec_df,
513
- linkage_map=lm_empty, chrom_lengths_before=data.frame(),
514
- chrom_lengths_after=data.frame(), removal_log=removal_log,
515
- qc_report=qc_msg))
 
 
 
516
  }
517
 
518
- pos_df <- data.frame(Marker=names(positions_list),
519
- Position=unlist(positions_list),
520
- stringsAsFactors=FALSE)
521
 
522
  linkage_map <- merge(df[, c("Marker","Chromosome",".input_order")],
523
  pos_df, by="Marker", all.x=TRUE)
@@ -526,17 +489,114 @@ create_linkage_map <- function(df,
526
 
527
  scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
528
 
529
- list(original_data = df_orig,
530
- recombination_data = rec_df,
531
- linkage_map = scaled$scaled_map,
532
- chrom_lengths_before = scaled$chrom_lengths_before,
533
- chrom_lengths_after = scaled$chrom_lengths_after,
534
- removal_log = removal_log,
535
- qc_report = qc_msg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
536
  }
537
 
538
  # ═══════════════════════════════════════════════════════════════════════════════
539
- # PLOTTING
540
  # ═══════════════════════════════════════════════════════════════════════════════
541
 
542
  create_multi_chromosome_plot <- function(linkage_data, selected_chromosomes,
@@ -592,19 +652,14 @@ create_multi_chromosome_plot <- function(linkage_data, selected_chromosomes,
592
  aes(x=chrom_center, y=Position, color=as.factor(Chromosome)),
593
  size=point_size, alpha=0.9) +
594
  geom_text(data=chrom_stats,
595
- aes(x=chrom_center,
596
- y=-(max(chrom_stats$max_pos)*0.03),
597
- label=paste0("Chr\n", Chromosome),
598
- color=as.factor(Chromosome)),
599
  size=label_size+1, fontface="bold", vjust=1) +
600
  scale_color_manual(values=setNames(chrom_colors,
601
  levels(factor(chrom_stats$Chromosome)))) +
602
- scale_y_reverse(name="Genetic Position (cM)",
603
- expand=expansion(mult=c(0.02, 0.12))) +
604
- scale_x_continuous(breaks=chrom_stats$chrom_center,
605
- labels=chrom_stats$Chromosome,
606
- name="Chromosome",
607
- expand=expansion(mult=0.1)) +
608
  theme_minimal(base_size=12) +
609
  theme(legend.position="none",
610
  axis.text.x=element_blank(), axis.ticks.x=element_blank(),
@@ -636,52 +691,73 @@ ui <- fluidPage(
636
  tags$head(
637
  tags$script(src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"),
638
  tags$style(HTML("
639
- body { background-color:#ffffff; color:#333333;
640
- font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif; }
641
  .navbar { background-color:#1E3A8A !important; border-bottom:2px solid #1E40AF; }
642
- .navbar-brand { color:#ffffff !important; font-weight:bold; }
643
- .nav-tabs { background-color:#1E3A8A; border-bottom:2px solid #1E40AF; }
644
- .nav-tabs > li > a { color:#cccccc !important; background-color:#1E3A8A;
645
- border:1px solid #1E40AF; margin-right:5px; }
646
  .nav-tabs > li.active > a,
647
- .nav-tabs > li.active > a:hover,
648
- .nav-tabs > li.active > a:focus { color:#ffffff !important;
649
- background-color:#1E40AF; font-weight:bold; }
650
- .nav-tabs > li > a:hover { background-color:#2563EB; color:#ffffff !important; }
651
- .well { background-color:#EFF6FF; border:1px solid #BFDBFE; color:#333333; }
652
- .form-control { background-color:#FFFFFF; color:#333333; border:1px solid #93C5FD; }
653
- .form-control:focus { border-color:#3B82F6; box-shadow:0 0 0 .2rem rgba(59,130,246,.25); }
654
  .btn { border:1px solid; }
655
- .btn-primary { background-color:#1D4ED8; color:#ffffff; border-color:#1E40AF; }
656
- .btn-primary:hover { background-color:#1E40AF; border-color:#1E3A8A; }
657
- .btn-success { background-color:#059669; color:#ffffff; border-color:#047857; }
658
- .btn-success:hover { background-color:#047857; border-color:#065F46; }
659
- .alert-info { background-color:#DBEAFE; border-color:#93C5FD; color:#1E3A8A; }
660
- .alert-warning { background-color:#FEF9C3; border-color:#FDE68A; color:#92400E; }
661
- .dataTables_wrapper { color:#333333; }
 
662
  table.dataTable { border:1px solid #BFDBFE; }
663
- .footer { position:fixed; bottom:0; width:100%; background-color:#1E3A8A;
664
- color:#cccccc; text-align:center; padding:10px;
665
  border-top:1px solid #1E40AF; font-size:12px; }
666
- .tab-content h3, .tab-content h4 { color:#1E3A8A; }
667
- /* Chi-square panel styling */
668
- .chi-panel { background:#F0FDF4; border:1px solid #86EFAC;
669
- border-radius:6px; padding:12px 14px; margin-top:8px; }
670
- .chi-disabled { background:#FEF2F2; border:1px solid #FCA5A5;
671
- border-radius:6px; padding:12px 14px; margin-top:8px; }
672
- /* Camera capture button */
673
- #camera-btn {
674
- background: none; border: none; cursor: pointer; padding: 6px 10px;
675
- border-radius: 6px; color: #1D4ED8; font-size: 22px;
676
- display: inline-flex; align-items: center; gap: 6px;
677
- transition: background 0.2s;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678
  }
679
- #camera-btn:hover { background: #DBEAFE; }
680
- #camera-btn span.label { font-size: 13px; vertical-align: middle; color: #1D4ED8; }
 
 
 
 
 
 
 
681
  "))
682
  ),
683
 
684
- navbarPage("Linkage Map Creator v4.3 β€” Chi-Square Optional", id="nav",
685
 
686
  # ── Tab 1: Upload ────────────────────────────────────────────────────────
687
  tabPanel("Data Upload", icon=icon("upload"),
@@ -695,12 +771,13 @@ ui <- fluidPage(
695
  choices=c("F2"="F2","RIL"="RIL"), selected="F2"),
696
  hr(),
697
  div(class="alert alert-info",
698
- tags$b("v4.3 Key Behaviour:"), br(),
699
- tags$b("β€’ Chi-square filter is now OPTIONAL (toggle in Parameters)"), br(),
700
- tags$b("β€’ Monomorphic markers removed automatically"), br(),
701
- tags$b("β€’ Marker order from input file preserved"), br(),
702
- "β€’ First marker of every chromosome = 0 cM", br(),
703
- "β€’ Removal details shown in QC Report tab"
 
704
  )
705
  )),
706
  mainPanel(width=8,
@@ -718,114 +795,95 @@ ui <- fluidPage(
718
  sidebarLayout(
719
  sidebarPanel(width=4, wellPanel(
720
  h3("Analysis Parameters"),
721
-
722
- sliderInput("missing_threshold",
723
- "Missing Data Threshold (per marker):",
724
- min=0, max=1, value=0.3, step=0.05),
725
-
726
- sliderInput("recombination_threshold",
727
- "Max Recombination Fraction (r):",
728
- min=0, max=0.5, value=0.45, step=0.01),
729
-
730
  hr(),
731
-
732
- # ── Chi-square section (NEW v4.3) ─────────────────────────────────
733
- h4(icon("vial"), " Chi-Square Filter (Segregation Distortion)"),
734
-
735
- checkboxInput("enable_chi_square",
736
- "Enable chi-square segregation distortion filter",
737
- value = FALSE),
738
-
739
- # Conditionally shown controls
740
  conditionalPanel("input.enable_chi_square == true",
741
  div(class="chi-panel",
742
- numericInput("chi_square_alpha",
743
- "Significance level (Ξ±):",
744
- min=0.001, max=0.2, value=0.05, step=0.005),
745
- checkboxInput("use_bonferroni",
746
- "Apply Bonferroni correction",
747
- value=FALSE),
748
  div(class="alert alert-warning", style="font-size:12px; margin-top:8px;",
749
- icon("triangle-exclamation"), " ",
750
- tags$b("Caution:"), " Chi-square filtering removes markers with ",
751
- "skewed allele ratios. This can discard biologically real distortion ",
752
- "(e.g. linked lethals, gametic selection). Use Bonferroni correction ",
753
- "to reduce false positives."
754
- )
755
  )
756
  ),
757
  conditionalPanel("input.enable_chi_square == false",
758
  div(class="chi-disabled", style="font-size:12px;",
759
- icon("info-circle"), " Chi-square filter is OFF. ",
760
- "All polymorphic markers passing missing-data and monomorphic checks ",
761
- "will be retained regardless of segregation ratios."
762
- )
763
  ),
764
-
765
  hr(),
766
  h4("Map Scaling"),
767
- numericInput("max_total_cm", "Max Total Map Length (cM):",
768
- min=100, max=10000, value=1500, step=100),
769
  selectInput("scaling_method", "Scaling Method:",
770
- choices=c("Proportional"="proportional","Uniform"="uniform"),
771
- selected="proportional"),
772
  hr(),
773
- actionButton("run_analysis", "β–Ά Run Analysis",
774
- class="btn-primary btn-block", icon=icon("play"))
775
  )),
776
  mainPanel(width=8, wellPanel(
777
  h3("Parameter Guide"),
778
  tags$ul(
779
- tags$li(tags$b("Missing Data Threshold:"),
780
- " Markers with > this fraction missing are removed."),
781
- tags$li(tags$b("Max Recombination Fraction:"),
782
- " Pairs with r β‰₯ threshold get a 50 cM placeholder gap."),
783
- tags$li(tags$b("Monomorphic Removal:"),
784
- tags$b(" Automatic β€” always applied."),
785
- " Any marker fixed as a single allele class is removed."),
786
- tags$li(tags$b("Chi-Square Filter (v4.3):"),
787
- tags$b(" Optional toggle."),
788
- " When enabled, markers deviating from expected Mendelian ratios ",
789
- "(1:2:1 for F2; 1:1 for RIL) are removed. ",
790
- "Set alpha and optionally apply Bonferroni correction."),
791
- tags$li(tags$b("Marker Order:"),
792
- tags$b(" Preserved from input file."), " No MDS reordering.")
793
  ),
794
- br(),
795
- h4("Scaling Summary"), verbatimTextOutput("scaling_summary"),
796
- h4("Before Scaling"), verbatimTextOutput("before_scaling_stats"),
797
- h4("After Scaling"), verbatimTextOutput("after_scaling_stats")
798
  ))
799
  )
800
  ),
801
 
802
  # ── Tab 3: QC Report ────────────────────────────────────────────────────
803
  tabPanel("QC Report", icon=icon("clipboard-check"),
804
- wellPanel(
805
- h3("Quality Control Report"),
806
- verbatimTextOutput("qc_report_output")
807
- ),
808
  wellPanel(
809
  h3("Removed Markers β€” Full Detail"),
810
- p("Every marker removed during QC is listed below with the exact reason and supporting statistics."),
811
  div(style="overflow-x:auto;", dataTableOutput("removal_log_table")),
812
  br(),
813
- downloadButton("download_removal_log", "⬇ Download Removal Log (.xlsx)",
814
- class="btn-success")
815
  )
816
  ),
817
 
818
- # ── Tab 4: Results ───────────────────────────────────────────────────────
819
  tabPanel("Results", icon=icon("table"),
820
  fluidRow(column(12, wellPanel(
821
  h3("Analysis Results"),
822
  conditionalPanel("output.analysis_run",
823
- downloadButton("download_results", "⬇ Download Excel Results",
824
- class="btn-success"),
825
- br(), br(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
826
  h4("Linkage Map (Input Order Preserved, First Marker = 0 cM)"),
827
  div(style="overflow-x:auto;", dataTableOutput("result_table")),
828
- h4("Summary Statistics"), verbatimTextOutput("summary_stats")
 
829
  ),
830
  conditionalPanel("!output.analysis_run",
831
  p("Upload data and click 'Run Analysis' to see results.",
@@ -839,6 +897,25 @@ ui <- fluidPage(
839
  sidebarLayout(
840
  sidebarPanel(width=4, wellPanel(
841
  h3("Visualization Options"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
842
  selectInput("color_palette", "Color Palette:",
843
  choices=c("Set1","Set2","Set3","Paired","Dark2","Accent","Spectral","RdBu"),
844
  selected="Set2"),
@@ -846,8 +923,8 @@ ui <- fluidPage(
846
  sliderInput("marker_label_size", "Label Size:", min=1, max=8, value=2, step=0.5),
847
  sliderInput("plot_width", "Plot Width (px):", min=600, max=2400, value=1400, step=100),
848
  sliderInput("plot_height", "Plot Height (px):", min=400, max=1600, value=800, step=50),
849
- sliderInput("chrom_spacing", "Chromosome Spacing:", min=2, max=15, value=5, step=0.5),
850
- sliderInput("point_size", "Marker Point Size:", min=0.5, max=5, value=1.5, step=0.25)
851
  )),
852
  mainPanel(width=8, wellPanel(
853
  h3("Palette Preview"),
@@ -856,25 +933,71 @@ ui <- fluidPage(
856
  )
857
  ),
858
 
859
- # ── Tab 6: Visualization ─────────────────────────────────────────────────
860
- tabPanel("Visualization", icon=icon("chart-bar"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
861
  fluidRow(column(12, wellPanel(
862
- h3("Chromosome Map"),
863
  conditionalPanel("output.analysis_run",
864
  fluidRow(
865
  column(8, selectInput("chromosome_select", "Select Chromosomes:",
866
  choices=NULL, multiple=TRUE)),
867
  column(4, br(),
868
- tags$button(id="camera-btn", onclick="captureChromPlot()",
869
- tags$span("\U0001F4F7"),
870
- tags$span("Save image", class="label")
 
 
871
  )
872
  )
873
  ),
874
- div(id="chrom-plot-wrapper",
875
- style="background:white;",
876
- plotOutput("chromosome_plot", height="auto")
877
- )
878
  ),
879
  conditionalPanel("!output.analysis_run",
880
  p("Run analysis first.",
@@ -883,86 +1006,342 @@ ui <- fluidPage(
883
  )))
884
  ),
885
 
886
- # ── Tab 7: Help ──────────────────────────────────────────────────────────
887
  tabPanel("Help", icon=icon("question-circle"),
888
  wellPanel(
889
- h3("Application Guide β€” v4.3"),
890
-
891
- h4("What's New in v4.3"),
892
  div(class="alert alert-info",
893
  tags$ul(
894
- tags$li(tags$b("Chi-square segregation distortion filter restored as optional:"),
895
- " Toggle it ON/OFF in the Parameters tab. When ON, you can set a custom",
896
- " significance level (Ξ±) and optionally apply Bonferroni correction for",
897
- " multiple testing. When OFF, all polymorphic markers passing missing-data",
898
- " and monomorphic checks are kept (v4.2 behaviour)."),
899
- tags$li(tags$b("Bonferroni correction:"),
900
- " Divides the chosen Ξ± by the number of markers tested,",
901
- " greatly reducing false-positive removal when large marker sets are used."),
902
- tags$li(tags$b("Monomorphic marker removal remains automatic:"),
903
- " Fixed markers are always removed regardless of the chi-square toggle."),
904
- tags$li(tags$b("QC Report updated:"),
905
- " A dedicated row now shows how many markers were removed by the",
906
- " chi-square filter (0 when disabled).")
907
  )
908
  ),
909
-
910
- h4("Chi-Square Test Details"),
911
- tags$ul(
912
- tags$li(tags$b("Hβ‚€:"), " Allele frequencies follow expected Mendelian ratios."),
913
- tags$li(tags$b("F2 expected:"), " AA : Aa : BB = 1 : 2 : 1 (p = 0.25, 0.50, 0.25)."),
914
- tags$li(tags$b("RIL expected:"), " AA : BB = 1 : 1 (p = 0.50, 0.50; heterozygotes excluded)."),
915
- tags$li("Markers with fewer than 10 informative genotypes are automatically kept ",
916
- "(insufficient power to test)."),
917
- tags$li("Markers rejected by the chi-square test are logged with their exact p-value ",
918
- "and the effective alpha used.")
919
- ),
920
-
921
- h4("When to Use / Avoid Chi-Square Filtering"),
922
- tags$ul(
923
- tags$li(tags$b("Use it"), " when you suspect genotyping errors are causing apparent distortion, ",
924
- "or when you need a clean Mendelian dataset for downstream QTL tools that assume no distortion."),
925
- tags$li(tags$b("Avoid it"), " when studying populations known to harbour transmission ratio ",
926
- "distortion (TRD), lethality-linked loci, or gametic selection β€” real biological signals ",
927
- "will be discarded.")
928
- ),
929
-
930
  h4("Required Input Format"),
931
  tags$ul(
932
  tags$li("Excel (.xlsx): Column 1 = 'Marker', Column 2 = 'Chromosome'"),
933
  tags$li("Genotype columns: a/b/ab/- OR numeric 2/1/0/-1"),
934
  tags$li("Chromosome column: integer numbers OR Excel VLOOKUP formulas")
935
  ),
936
-
937
  h4("Genotype Encoding Reference"),
938
  tableOutput("encoding_table")
939
  )
940
  )
941
  ),
942
 
943
- # JavaScript for camera capture
 
 
 
944
  tags$script(HTML("
945
- function captureChromPlot() {
946
- var el = document.getElementById('chrom-plot-wrapper');
947
- if (!el) { alert('Plot not found.'); return; }
948
- html2canvas(el, {
949
- backgroundColor: '#ffffff',
950
- scale: 2,
951
- useCORS: true,
952
- logging: false
953
- }).then(function(canvas) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
954
  var link = document.createElement('a');
955
- link.download = 'linkage_map_' + new Date().toISOString().slice(0,10) + '.png';
956
  link.href = canvas.toDataURL('image/png');
957
  link.click();
958
- }).catch(function(err) {
959
- alert('Capture failed: ' + err);
960
- });
 
 
 
 
 
 
 
 
 
 
 
961
  }
962
  ")),
963
 
964
  div(class="footer",
965
- "Linkage Map Creator v4.3 | Chi-square optional | Monomorphic removal | Input order preserved | Β© 2024")
966
  )
967
 
968
  # ═══════════════════════════════════════════════════════════════════════════════
@@ -976,13 +1355,10 @@ server <- function(input, output, session) {
976
  upload_log <- reactiveVal("")
977
 
978
  output$encoding_table <- renderTable({
979
- data.frame(
980
- `Numeric Code` = c("2","1","0","-1"),
981
- `Text Code` = c("a","b","ab","-"),
982
- Meaning = c("Homozygous Parent 1 (AA)","Homozygous Parent 2 (BB)",
983
- "Heterozygous (Aa)","Missing data"),
984
- check.names=FALSE
985
- )
986
  }, striped=TRUE, hover=TRUE, bordered=TRUE)
987
 
988
  observeEvent(input$file, {
@@ -991,7 +1367,7 @@ server <- function(input, output, session) {
991
  df <- load_and_convert_data(input$file$datapath)
992
  n_chr <- length(unique(df$Chromosome))
993
  log_msg <- paste0(
994
- "βœ“ File loaded: ", input$file$name, "\n",
995
  " Markers : ", nrow(df), "\n",
996
  " Individuals : ", ncol(df) - 3, "\n",
997
  " Chromosomes : ", n_chr,
@@ -999,53 +1375,39 @@ server <- function(input, output, session) {
999
  " Genotype codes converted to a/b/ab/-\n",
1000
  " Marker order will be PRESERVED from input file.\n"
1001
  )
1002
- uploaded_data(df)
1003
- upload_log(log_msg)
1004
- showNotification("File uploaded and converted successfully!", type="message")
1005
  }, error=function(e) {
1006
- upload_log(paste0("βœ— Error: ", e$message))
1007
  showNotification(paste("Upload error:", e$message), type="error")
1008
  })
1009
  })
1010
 
1011
- output$upload_status <- renderText({ upload_log() })
1012
-
1013
- output$preview_table <- renderDataTable({
1014
  req(uploaded_data())
1015
  df_show <- head(uploaded_data(), 10)
1016
  df_show <- df_show[, colnames(df_show) != ".input_order", drop=FALSE]
1017
  datatable(df_show, options=list(scrollX=TRUE, dom="t", pageLength=10), rownames=FALSE)
1018
  })
1019
-
1020
  output$chr_summary_table <- renderDataTable({
1021
  req(uploaded_data())
1022
  df <- uploaded_data()
1023
  chr_tab <- df %>% group_by(Chromosome) %>%
1024
  summarise(N_Markers=n(), .groups="drop") %>%
1025
  arrange(suppressWarnings(as.numeric(Chromosome)))
1026
- datatable(chr_tab, options=list(dom="t", pageLength=30), rownames=FALSE,
1027
- caption="Markers per chromosome (input order)")
1028
  })
1029
 
1030
  observeEvent(input$run_analysis, {
1031
  req(uploaded_data())
1032
-
1033
- chi_status <- if (input$enable_chi_square) {
1034
- bonf_str <- if (input$use_bonferroni) " + Bonferroni" else ""
1035
- paste0("Chi-square filter ENABLED (alpha=", input$chi_square_alpha, bonf_str, ")")
1036
- } else {
1037
- "Chi-square filter DISABLED"
1038
- }
1039
-
1040
- showModal(modalDialog(
1041
- title="Building Linkage Map…",
1042
- paste0("Population type: ", input$population_type, "\n",
1043
- chi_status, "\n",
1044
- "Removing monomorphic markers…\n",
1045
- "Preserving input marker order…"),
1046
- footer=NULL
1047
- ))
1048
-
1049
  tryCatch({
1050
  result <- create_linkage_map(
1051
  df = uploaded_data(),
@@ -1065,20 +1427,14 @@ server <- function(input, output, session) {
1065
  error=function(e) sort(chromosomes))
1066
  updateSelectInput(session, "chromosome_select",
1067
  choices=chr_sorted, selected=chr_sorted)
 
 
1068
  removeModal()
1069
-
1070
  n_pos <- sum(!is.na(result$linkage_map$Position))
1071
  n_removed <- nrow(result$removal_log)
1072
- n_chi_rem <- sum(result$removal_log$Reason == "Segregation distortion (chi-square)")
1073
-
1074
- notif_msg <- paste0(
1075
- "Analysis complete! ", n_pos, " markers positioned. ",
1076
- n_removed, " markers removed total",
1077
- if (n_chi_rem > 0) paste0(" (", n_chi_rem, " by chi-square)") else "",
1078
- ". See QC Report."
1079
- )
1080
- showNotification(notif_msg, type="message")
1081
-
1082
  }, error=function(e) {
1083
  removeModal()
1084
  showNotification(paste("Analysis error:", e$message), type="error")
@@ -1088,78 +1444,122 @@ server <- function(input, output, session) {
1088
  output$analysis_run <- reactive({ !is.null(analysis_results()) })
1089
  outputOptions(output, "analysis_run", suspendWhenHidden=FALSE)
1090
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1091
  output$qc_report_output <- renderText({
1092
  if (is.null(analysis_results())) return("No analysis run yet.")
1093
  analysis_results()$qc_report
1094
  })
1095
 
1096
- # ── Removal log table ─────────────────────────────────────────────────────
1097
  output$removal_log_table <- renderDataTable({
1098
  if (is.null(analysis_results())) {
1099
  return(datatable(data.frame(Message="Run analysis first."),
1100
  options=list(dom="t"), rownames=FALSE))
1101
  }
1102
  log_df <- analysis_results()$removal_log
1103
- if (nrow(log_df) == 0) {
1104
- return(datatable(data.frame(Message="No markers were removed during QC."),
1105
  options=list(dom="t"), rownames=FALSE))
1106
- }
1107
- datatable(log_df,
1108
- options=list(scrollX=TRUE, pageLength=25,
1109
- columnDefs=list(list(width="40%", targets=3))),
1110
- rownames=FALSE,
1111
- caption=paste0(nrow(log_df), " marker(s) removed during QC")) %>%
1112
  formatStyle("Reason",
1113
  color=styleEqual(
1114
- c("Excess missing data",
1115
- "Monomorphic marker",
1116
- "Segregation distortion (chi-square)"),
1117
- c("#c0392b", "#8e44ad", "#d97706")
1118
- ),
1119
  fontWeight="bold")
1120
  })
1121
 
1122
- output$download_removal_log <- downloadHandler(
1123
- filename=function() paste0("removal_log_", Sys.Date(), ".xlsx"),
1124
- content=function(file) {
1125
- req(analysis_results())
1126
- wb <- createWorkbook()
1127
- addWorksheet(wb, "Removed_Markers")
1128
- log_df <- analysis_results()$removal_log
1129
- if (nrow(log_df) == 0)
1130
- log_df <- data.frame(Message="No markers were removed during QC.")
1131
- writeData(wb, "Removed_Markers", log_df)
1132
- saveWorkbook(wb, file, overwrite=TRUE)
1133
- }
1134
- )
1135
 
1136
- output$scaling_summary <- renderText({
 
1137
  req(analysis_results())
1138
- paste0("Method : ", input$scaling_method, "\nMax cM : ", input$max_total_cm)
 
 
 
 
 
 
 
 
 
 
1139
  })
1140
 
 
 
 
 
1141
  fmt_chr <- function(df) {
1142
  if (is.null(df) || nrow(df) == 0) return("No data.")
1143
  total <- sum(df$Original_Length, na.rm=TRUE)
1144
- rows <- apply(df, 1, function(x)
1145
- paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),2), " cM"))
1146
  paste0("Total : ", round(total,2), " cM\n", paste(rows, collapse="\n"))
1147
  }
1148
  output$before_scaling_stats <- renderText({ req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_before) })
1149
- output$after_scaling_stats <- renderText({ req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_after) })
1150
 
1151
  output$result_table <- renderDataTable({
1152
  req(analysis_results())
1153
  lm <- analysis_results()$linkage_map
1154
- if (nrow(lm) > 0) {
1155
- datatable(lm, options=list(scrollX=TRUE, pageLength=25, order=list()),
1156
- rownames=FALSE,
1157
- caption="Linkage map β€” cM positions | Input order preserved | First marker = 0 cM") %>%
1158
  formatRound("Position", 2)
1159
- } else {
1160
- datatable(data.frame(Message="No positioned markers. Try relaxing QC parameters."),
1161
- options=list(dom="t"), rownames=FALSE)
1162
- }
1163
  })
1164
 
1165
  output$summary_stats <- renderText({
@@ -1167,44 +1567,36 @@ server <- function(input, output, session) {
1167
  lm <- analysis_results()$linkage_map
1168
  rec <- analysis_results()$recombination_data
1169
  if (nrow(lm) == 0) return("No positioned markers.")
1170
-
1171
  n_pos <- sum(!is.na(lm$Position))
1172
  n_chr <- length(unique(lm$Chromosome))
1173
  chr_lengths <- lm %>% filter(!is.na(Position)) %>%
1174
  group_by(Chromosome) %>%
1175
  summarise(Length=max(Position,na.rm=TRUE), N_markers=n(), .groups="drop") %>%
1176
  arrange(suppressWarnings(as.numeric(Chromosome)))
1177
- total_len <- sum(chr_lengths$Length)
1178
- avg_len <- mean(chr_lengths$Length)
1179
  chr_detail <- paste(apply(chr_lengths, 1, function(x)
1180
- paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),2),
1181
- " cM (", x[3], " markers)")), collapse="\n")
1182
-
1183
- log_df <- analysis_results()$removal_log
1184
- n_removed_total <- nrow(log_df)
1185
- n_mono <- sum(log_df$Reason == "Monomorphic marker")
1186
- n_miss <- sum(log_df$Reason == "Excess missing data")
1187
- n_chi <- sum(log_df$Reason == "Segregation distortion (chi-square)")
1188
-
1189
- chi_line <- if (input$enable_chi_square) {
1190
- bonf_str <- if (input$use_bonferroni) " (Bonferroni)" else ""
1191
  paste0(" Removed (chi-square) : ", n_chi,
1192
- " [alpha=", input$chi_square_alpha, bonf_str, "]")
1193
- } else {
1194
- " Chi-square filter : DISABLED"
1195
- }
1196
-
1197
  paste0(
1198
- "LINKAGE MAP SUMMARY (v4.3)\n",
1199
- "===========================\n",
1200
  "Population type : ", input$population_type, "\n",
1201
- "Marker order : Preserved from input file\n",
1202
- "First marker position : 0 cM (per chromosome)\n\n",
1203
  "Total markers input : ", nrow(analysis_results()$original_data), "\n",
1204
  " Removed (missing) : ", n_miss, "\n",
1205
  " Removed (monomorphic): ", n_mono, "\n",
1206
  chi_line, "\n",
1207
- " Total removed : ", n_removed_total, "\n",
1208
  "Markers positioned : ", n_pos, "\n",
1209
  "Chromosomes / LGs : ", n_chr, "\n",
1210
  "Total map length : ", round(total_len,2), " cM\n",
@@ -1240,14 +1632,89 @@ server <- function(input, output, session) {
1240
  )
1241
  }, height=function() input$plot_height)
1242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1243
  output$download_results <- downloadHandler(
1244
- filename=function() paste0("linkage_map_v43_", Sys.Date(), ".xlsx"),
1245
  content=function(file) {
1246
  req(analysis_results())
1247
  wb <- createWorkbook()
1248
  addWorksheet(wb, "Original_Data")
1249
  addWorksheet(wb, "Recombination_Fractions")
1250
  addWorksheet(wb, "Linkage_Map")
 
 
1251
  addWorksheet(wb, "Removal_Log")
1252
  addWorksheet(wb, "QC_Report")
1253
  orig <- analysis_results()$original_data
@@ -1255,9 +1722,10 @@ server <- function(input, output, session) {
1255
  writeData(wb, "Original_Data", orig)
1256
  writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
1257
  writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
 
 
1258
  writeData(wb, "Removal_Log", analysis_results()$removal_log)
1259
- writeData(wb, "QC_Report",
1260
- data.frame(Report=analysis_results()$qc_report))
1261
  saveWorkbook(wb, file, overwrite=TRUE)
1262
  }
1263
  )
 
12
  # ═══════════════════════════════════════════════════════════════════════════════
13
 
14
  load_and_convert_data <- function(filepath) {
15
+ wb_raw <- tryCatch(loadWorkbook(filepath),
16
+ error = function(e) stop("Cannot open workbook: ", e$message))
 
 
 
 
17
  df_raw <- read.xlsx(filepath, sheet = 1, colNames = TRUE)
18
+ if (!("Chromosome" %in% colnames(df_raw))) stop("Column 'Chromosome' not found.")
19
+ if (!("Marker" %in% colnames(df_raw))) stop("Column 'Marker' not found.")
20
 
21
+ chr_col <- as.character(df_raw$Chromosome)
 
 
 
 
 
22
  has_formula <- any(grepl("^=", chr_col, ignore.case = FALSE), na.rm = TRUE)
 
23
  if (has_formula) {
24
+ inferred <- infer_chromosome_from_marker(df_raw$Marker)
25
  n_inferred <- sum(!is.na(inferred))
26
  if (n_inferred / nrow(df_raw) >= 0.5) {
27
  df_raw$Chromosome <- inferred
 
49
  col[col == "-1"] <- "-"
50
  col[is.na(col) | col == "NA"] <- "-"
51
  col
52
+ })
 
53
  } else if (!text_encoding) {
54
  df_raw[, 3:ncol(df_raw)] <- lapply(
55
  df_raw[, 3:ncol(df_raw), drop = FALSE],
 
57
  col <- as.character(col)
58
  col[!(col %in% c("a", "b", "ab"))] <- "-"
59
  col
60
+ })
 
61
  }
62
 
63
  df_raw$Chromosome <- as.character(df_raw$Chromosome)
 
70
  markers <- as.character(marker_names)
71
  chrom <- rep(NA_character_, length(markers))
72
  patterns <- list(
73
+ list(regex = "(?i)chr(\\d{1,2})[_\\-]", group = 1),
74
+ list(regex = "(?i)[_\\-]C(\\d{1,2})[_\\-]", group = 1),
75
+ list(regex = "(?i)^MSU\\d+_(\\d{1,2})_", group = 1),
76
+ list(regex = "(?i)^DTY(\\d{1,2})[\\-_]", group = 1),
77
+ list(regex = "(?i)^[A-Za-z]{1,6}(\\d{1,2})[a-zA-Z_]", group = 1),
78
+ list(regex = "(?i)^Saltol", group = NA),
79
+ list(regex = "(?i)^SCT(\\d{1,2})[_\\-]", group = 1),
80
+ list(regex = "(?i)^R(\\d{1,2})", group = 1),
81
+ list(regex = "(?i)^Pi(\\d{1,2})", group = 1)
82
  )
83
  for (i in seq_along(markers)) {
84
  m <- markers[i]
 
86
  if (is.na(pat$group)) {
87
  if (grepl(pat$regex, m, perl = TRUE)) { chrom[i] <- "1"; break }
88
  } else {
89
+ mt <- regmatches(m, regexpr(pat$regex, m, perl = TRUE))
90
  if (length(mt) > 0) {
91
  sub_mt <- regmatches(mt, regexec(pat$regex, mt, perl = TRUE))[[1]]
92
  if (length(sub_mt) >= pat$group + 1) {
 
107
  # ═══════════════════════════════════════════════════════════════════════════════
108
 
109
  calculate_recombination <- function(population_type, genotype1, genotype2) {
110
+ g1 <- as.character(genotype1)
111
+ g2 <- as.character(genotype2)
112
  keep <- !(g1 %in% c("-", "NA", NA) | g2 %in% c("-", "NA", NA))
113
+ g1 <- g1[keep]; g2 <- g2[keep]
114
+ n <- length(g1)
115
  if (n < 4) return(NA_real_)
116
 
117
  if (population_type == "RIL") {
 
121
  r_obs <- mean(g1h != g2h)
122
  rf <- r_obs / (2 * (1 - r_obs))
123
  return(min(rf, 0.4999))
 
124
  } else if (population_type == "F2") {
125
  AA_AA <- sum(g1=="a" & g2=="a"); AA_Aa <- sum(g1=="a" & g2=="ab")
126
  AA_BB <- sum(g1=="a" & g2=="b"); Aa_AA <- sum(g1=="ab" & g2=="a")
 
149
  25 * log((1 + 2*r) / (1 - 2*r))
150
  }
151
 
 
152
  detect_monomorphic_markers <- function(df) {
153
  geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
154
  is_mono <- apply(df[, geno_cols_idx, drop = FALSE], 1, function(row) {
155
+ vals <- row[!is.na(row) & !(row %in% c("-", "NA", ""))]
156
  if (length(vals) == 0) return(FALSE)
157
  unique_vals <- unique(vals[vals %in% c("a", "b", "ab")])
158
  length(unique_vals) <= 1
 
161
  is_mono
162
  }
163
 
 
 
 
 
 
164
  perform_chi_square_test <- function(df, population_type) {
165
  geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
 
166
  if (population_type == "F2") {
167
  expected <- c(a = 0.25, ab = 0.50, b = 0.25)
168
  valid_classes <- c("a", "ab", "b")
169
+ } else {
170
  expected <- c(a = 0.50, b = 0.50)
171
  valid_classes <- c("a", "b")
172
  }
 
173
  p_values <- apply(df[, geno_cols_idx, drop = FALSE], 1, function(row) {
174
  vals <- row[!is.na(row) & row %in% valid_classes]
175
+ if (length(vals) < 10) return(1.0)
176
+ obs <- table(factor(vals, levels = valid_classes))
177
+ result <- tryCatch(suppressWarnings(chisq.test(obs, p = expected)),
178
+ error = function(e) list(p.value = 1.0))
 
 
 
 
 
179
  result$p.value
180
  })
181
  names(p_values) <- df$Marker
182
  p_values
183
  }
184
 
 
185
  correct_errors_and_impute_missing <- function(df) {
186
+ valid_geno <- c("a", "b", "ab")
187
+ geno_start <- which(colnames(df) == "Chromosome") + 1
188
  geno_cols_idx <- setdiff(geno_start:ncol(df), which(colnames(df) == ".input_order"))
 
189
  for (j in geno_cols_idx) {
190
  x <- as.character(df[[j]])
191
  x[x %in% c("-", "NA", "", " ", "na")] <- NA
192
  x[!is.na(x) & !(x %in% valid_geno)] <- NA
193
  df[[j]] <- x
194
  }
 
195
  if (length(geno_cols_idx) > 0) {
196
  na_col <- colMeans(is.na(df[, geno_cols_idx, drop = FALSE]))
197
  keep_idx <- c(seq_len(geno_start - 1),
 
200
  keep_idx <- keep_idx[keep_idx <= ncol(df)]
201
  df <- df[, sort(unique(keep_idx)), drop = FALSE]
202
  }
 
203
  geno_cols_idx2 <- setdiff(geno_start:ncol(df), which(colnames(df) == ".input_order"))
204
  if (length(geno_cols_idx2) > 0) {
205
  df[, geno_cols_idx2] <- t(apply(df[, geno_cols_idx2, drop = FALSE], 1, function(row) {
 
225
  }
226
 
227
  # ═══════════════════════════════════════════════════════════════════════════════
228
+ # POSITION BUILDING
229
  # ═══════════════════════════════════════════════════════════════════════════════
230
 
231
  build_positions_from_input_order <- function(df, population_type, recombination_threshold) {
 
240
  mks <- sub$Marker
241
  if (length(mks) == 0) next
242
  pos <- setNames(numeric(length(mks)), mks)
 
243
  if (length(mks) > 1) {
244
  for (i in 2:length(mks)) {
245
  m_prev <- mks[i-1]; m_curr <- mks[i]
 
269
  if (nrow(pos_map) == 0)
270
  return(list(scaled_map=linkage_map, chrom_lengths_before=data.frame(),
271
  chrom_lengths_after=data.frame()))
 
272
  before <- pos_map %>%
273
  group_by(Chromosome) %>%
274
  summarise(Original_Length = max(Position, na.rm=TRUE), .groups="drop")
 
275
  total <- sum(before$Original_Length, na.rm=TRUE)
276
  if (total <= max_total_cm || total == 0)
277
  return(list(scaled_map=linkage_map, chrom_lengths_before=before,
278
  chrom_lengths_after=before))
 
279
  scaled <- linkage_map
280
  if (method == "proportional") {
281
  before$sf <- max_total_cm / total
282
  } else {
283
+ n_chr <- nrow(before)
284
  before$sf <- ifelse(before$Original_Length > 0,
285
  (max_total_cm/n_chr)/before$Original_Length, 1)
286
  }
 
296
  filter(!is.na(Position)) %>%
297
  group_by(Chromosome) %>%
298
  summarise(Original_Length = max(Position, na.rm=TRUE), .groups="drop")
 
299
  list(scaled_map=scaled, chrom_lengths_before=before, chrom_lengths_after=after)
300
  }
301
 
302
  # ═══════════════════════════════════════════════════════════════════════════════
303
+ # MASTER ANALYSIS
304
  # ═══════════════════════════════════════════════════════════════════════════════
305
 
306
  create_linkage_map <- function(df,
 
309
  recombination_threshold = 0.5,
310
  max_total_cm = 1500,
311
  scaling_method = "proportional",
312
+ enable_chi_square = FALSE,
313
+ chi_square_alpha = 0.05,
314
+ use_bonferroni = FALSE) {
315
 
316
  empty_result <- function(df_in = df) {
317
  list(original_data = df_in,
 
319
  linkage_map = data.frame(Marker=character(0),
320
  Chromosome=character(0),
321
  Position=numeric(0)),
322
+ all_markers_positions = data.frame(),
323
+ retained_markers_list = data.frame(),
324
  chrom_lengths_before = data.frame(),
325
  chrom_lengths_after = data.frame(),
326
  removal_log = data.frame(),
 
328
  }
329
 
330
  df_orig <- df
331
+ if (!(".input_order" %in% colnames(df))) df$.input_order <- seq_len(nrow(df))
 
332
 
 
333
  removal_log <- data.frame(
334
+ Marker = character(0), Chromosome = character(0),
335
+ Reason = character(0), Detail = character(0),
 
 
336
  stringsAsFactors = FALSE
337
  )
338
 
339
  n_input <- nrow(df)
340
 
341
+ # Step 1: Imputation
342
  df <- correct_errors_and_impute_missing(df)
343
 
344
+ # Step 2: Missing data QC
345
  geno_cols_idx <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
346
  geno_mat <- df[, geno_cols_idx, drop = FALSE]
347
  miss_frac <- rowMeans(is.na(geno_mat))
 
354
  Chromosome = df$Chromosome[miss_frac > missing_threshold],
355
  Reason = "Excess missing data",
356
  Detail = paste0(round(miss_frac[miss_frac > missing_threshold]*100,1),
357
+ "% missing (threshold: ", round(missing_threshold*100,1), "%)"),
 
358
  stringsAsFactors = FALSE
359
  ))
360
  }
 
363
  res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
364
  }
365
 
366
+ # Step 3: Monomorphic removal
367
+ is_mono <- detect_monomorphic_markers(df)
368
  mono_markers <- names(is_mono)[is_mono]
 
369
  if (length(mono_markers) > 0) {
370
+ mono_df <- df[df$Marker %in% mono_markers, ]
371
  geno_cols_idx2 <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
372
  details <- sapply(mono_markers, function(mk) {
373
+ row <- df[df$Marker == mk, geno_cols_idx2, drop = FALSE]
374
  vals <- unlist(row)
375
  vals <- vals[!is.na(vals) & vals %in% c("a","b","ab")]
376
  if (length(vals) == 0) return("No informative genotypes")
377
+ tbl <- table(vals)
378
  dominant <- names(which.max(tbl))
379
  allele_name <- switch(dominant,
380
  a = "Homozygous Parent 1 (AA)",
 
398
  res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
399
  }
400
 
401
+ n_after_mono <- nrow(df)
 
 
402
  n_failed_chi <- 0
403
  chi_alpha_used <- NA_real_
404
+ chi_note <- "Chi-square filter : DISABLED"
405
 
406
+ # Step 4: Optional chi-square
407
  if (enable_chi_square) {
408
+ p_values <- perform_chi_square_test(df, population_type)
409
+ alpha_used <- if (use_bonferroni) chi_square_alpha / nrow(df) else chi_square_alpha
410
  chi_alpha_used <- alpha_used
 
411
  failed_chi_markers <- names(p_values)[p_values < alpha_used]
 
412
  if (length(failed_chi_markers) > 0) {
413
+ chi_df <- df[df$Marker %in% failed_chi_markers, ]
414
  chi_details <- sapply(failed_chi_markers, function(mk) {
415
  pv <- p_values[mk]
416
  paste0("p = ", formatC(pv, format="e", digits=3),
 
426
  df <- df[!df$Marker %in% failed_chi_markers, ]
427
  n_failed_chi <- length(failed_chi_markers)
428
  }
 
429
  bonf_label <- if (use_bonferroni)
430
  paste0("Bonferroni-corrected (alpha/", n_after_mono, ")")
431
  else "Uncorrected"
 
443
 
444
  n_after_qc <- nrow(df)
445
 
 
446
  qc_msg <- paste0(
447
+ "QC Report (v5.0)\n",
448
+ "================\n",
449
  " Markers input : ", n_input, "\n",
450
  " Removed (missing data) : ", length(failed_miss), "\n",
451
  " Removed (monomorphic) : ", length(mono_markers), "\n",
 
456
  " First marker of each chromosome = 0 cM.\n"
457
  )
458
 
459
+ # Build positions for retained markers
460
+ pos_result <- build_positions_from_input_order(df, population_type, recombination_threshold)
461
  positions_list <- pos_result$positions_list
462
  recombination_rows <- pos_result$recombination_rows
 
463
  rec_df <- if (length(recombination_rows) > 0) do.call(rbind, recombination_rows)
464
  else data.frame()
465
 
466
  if (length(positions_list) == 0) {
467
  lm_empty <- df[, c("Marker","Chromosome")]
468
  lm_empty$Position <- NA_real_
469
+ retained_list <- data.frame(Marker=df$Marker, Chromosome=df$Chromosome,
470
+ Status="Retained", stringsAsFactors=FALSE)
471
+ all_markers <- build_all_markers_positions(df_orig, removal_log, lm_empty)
472
  return(list(original_data=df_orig, recombination_data=rec_df,
473
+ linkage_map=lm_empty,
474
+ all_markers_positions=all_markers,
475
+ retained_markers_list=retained_list,
476
+ chrom_lengths_before=data.frame(),
477
+ chrom_lengths_after=data.frame(),
478
+ removal_log=removal_log, qc_report=qc_msg))
479
  }
480
 
481
+ pos_df <- data.frame(Marker = names(positions_list),
482
+ Position = unlist(positions_list),
483
+ stringsAsFactors = FALSE)
484
 
485
  linkage_map <- merge(df[, c("Marker","Chromosome",".input_order")],
486
  pos_df, by="Marker", all.x=TRUE)
 
489
 
490
  scaled <- scale_linkage_map(linkage_map, max_total_cm, scaling_method)
491
 
492
+ # ── NEW: Build all-markers positions table ────────────────────────────────
493
+ all_markers_positions <- build_all_markers_positions(df_orig, removal_log, scaled$scaled_map)
494
+
495
+ # ── NEW: Retained markers list ─────────────────────────────────────────────
496
+ retained_markers_list <- scaled$scaled_map %>%
497
+ select(Marker, Chromosome, Position) %>%
498
+ mutate(Status = "Retained") %>%
499
+ arrange(Chromosome, Position)
500
+
501
+ list(original_data = df_orig,
502
+ recombination_data = rec_df,
503
+ linkage_map = scaled$scaled_map,
504
+ all_markers_positions = all_markers_positions,
505
+ retained_markers_list = retained_markers_list,
506
+ chrom_lengths_before = scaled$chrom_lengths_before,
507
+ chrom_lengths_after = scaled$chrom_lengths_after,
508
+ removal_log = removal_log,
509
+ qc_report = qc_msg)
510
+ }
511
+
512
+ # ── Helper: Build all-markers position table (retained get position, removed get NA) ──
513
+ build_all_markers_positions <- function(df_orig, removal_log, linkage_map) {
514
+ df_all <- df_orig[, c("Marker","Chromosome"), drop=FALSE]
515
+ df_all$Chromosome <- as.character(df_all$Chromosome)
516
+
517
+ # Merge positions for retained markers
518
+ lm_sub <- linkage_map[, c("Marker","Position"), drop=FALSE]
519
+ df_all <- merge(df_all, lm_sub, by="Marker", all.x=TRUE)
520
+
521
+ # Add status
522
+ removed_markers <- unique(removal_log$Marker)
523
+ df_all$Status <- ifelse(df_all$Marker %in% removed_markers, "Removed", "Retained")
524
+
525
+ # Add removal reason for removed markers
526
+ if (nrow(removal_log) > 0) {
527
+ reason_df <- removal_log[, c("Marker","Reason","Detail"), drop=FALSE]
528
+ df_all <- merge(df_all, reason_df, by="Marker", all.x=TRUE)
529
+ } else {
530
+ df_all$Reason <- NA_character_
531
+ df_all$Detail <- NA_character_
532
+ }
533
+
534
+ df_all$Position[df_all$Status == "Removed"] <- NA_real_
535
+ df_all <- df_all[order(df_all$Chromosome, df_all$Marker), ]
536
+ df_all[, c("Marker","Chromosome","Status","Position","Reason","Detail")]
537
+ }
538
+
539
+ # ═══════════════════════════════════════════════════════════════════════════════
540
+ # CYTOGENETIC-STYLE PLOT DATA BUILDER
541
+ # Returns a JSON-ready list for the HTML canvas renderer
542
+ # ═══════════════════════════════════════════════════════════════════════════════
543
+
544
+ build_cyto_plot_data <- function(linkage_map, df_retained, selected_chromosomes) {
545
+ chr_sorted <- tryCatch(
546
+ selected_chromosomes[order(as.numeric(selected_chromosomes))],
547
+ warning = function(w) sort(selected_chromosomes),
548
+ error = function(e) sort(selected_chromosomes)
549
+ )
550
+
551
+ # Genotype columns (positions 3 onward, minus .input_order)
552
+ geno_cols <- setdiff(colnames(df_retained)[3:ncol(df_retained)],
553
+ c(".input_order", "Position", "Status", "Reason", "Detail"))
554
+
555
+ result <- list()
556
+ for (chr in chr_sorted) {
557
+ sub_map <- linkage_map[linkage_map$Chromosome == chr & !is.na(linkage_map$Position), ]
558
+ if (nrow(sub_map) == 0) next
559
+ sub_map <- sub_map[order(sub_map$Position), ]
560
+
561
+ # Get genotype data for these markers
562
+ sub_geno <- df_retained[df_retained$Marker %in% sub_map$Marker, ]
563
+
564
+ marker_data <- lapply(seq_len(nrow(sub_map)), function(i) {
565
+ mk <- sub_map$Marker[i]
566
+ pos <- sub_map$Position[i]
567
+
568
+ # Get row in genotype data
569
+ geno_row <- sub_geno[sub_geno$Marker == mk, geno_cols, drop=FALSE]
570
+ if (nrow(geno_row) == 0) {
571
+ return(list(marker=mk, position=round(pos,3),
572
+ allele_a=0, allele_b=0, allele_ab=0, allele_miss=0))
573
+ }
574
+ vals <- unlist(geno_row)
575
+ vals <- vals[!is.na(vals)]
576
+ n_total <- length(vals)
577
+ if (n_total == 0) n_total <- 1
578
+ list(
579
+ marker = mk,
580
+ position = round(pos, 3),
581
+ allele_a = round(sum(vals == "a") / n_total, 4),
582
+ allele_b = round(sum(vals == "b") / n_total, 4),
583
+ allele_ab = round(sum(vals == "ab") / n_total, 4),
584
+ allele_miss = round(sum(vals == "-" | is.na(vals)) / n_total, 4)
585
+ )
586
+ })
587
+
588
+ result[[chr]] <- list(
589
+ chromosome = chr,
590
+ max_pos = round(max(sub_map$Position), 2),
591
+ n_markers = nrow(sub_map),
592
+ markers = marker_data
593
+ )
594
+ }
595
+ result
596
  }
597
 
598
  # ═══════════════════════════════════════════════════════════════════════════════
599
+ # LEGACY GGPLOT (kept for fallback / download)
600
  # ═══════════════════════════════════════════════════════════════════════════════
601
 
602
  create_multi_chromosome_plot <- function(linkage_data, selected_chromosomes,
 
652
  aes(x=chrom_center, y=Position, color=as.factor(Chromosome)),
653
  size=point_size, alpha=0.9) +
654
  geom_text(data=chrom_stats,
655
+ aes(x=chrom_center, y=-(max(chrom_stats$max_pos)*0.03),
656
+ label=paste0("Chr\n", Chromosome), color=as.factor(Chromosome)),
 
 
657
  size=label_size+1, fontface="bold", vjust=1) +
658
  scale_color_manual(values=setNames(chrom_colors,
659
  levels(factor(chrom_stats$Chromosome)))) +
660
+ scale_y_reverse(name="Genetic Position (cM)", expand=expansion(mult=c(0.02, 0.12))) +
661
+ scale_x_continuous(breaks=chrom_stats$chrom_center, labels=chrom_stats$Chromosome,
662
+ name="Chromosome", expand=expansion(mult=0.1)) +
 
 
 
663
  theme_minimal(base_size=12) +
664
  theme(legend.position="none",
665
  axis.text.x=element_blank(), axis.ticks.x=element_blank(),
 
691
  tags$head(
692
  tags$script(src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"),
693
  tags$style(HTML("
694
+ body { background:#fff; color:#333; font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif; }
 
695
  .navbar { background-color:#1E3A8A !important; border-bottom:2px solid #1E40AF; }
696
+ .navbar-brand { color:#fff !important; font-weight:bold; }
697
+ .nav-tabs { background:#1E3A8A; border-bottom:2px solid #1E40AF; }
698
+ .nav-tabs > li > a { color:#ccc !important; background:#1E3A8A; border:1px solid #1E40AF; margin-right:5px; }
 
699
  .nav-tabs > li.active > a,
700
+ .nav-tabs > li.active > a:hover { color:#fff !important; background:#1E40AF; font-weight:bold; }
701
+ .nav-tabs > li > a:hover { background:#2563EB; color:#fff !important; }
702
+ .well { background:#EFF6FF; border:1px solid #BFDBFE; color:#333; }
703
+ .form-control { background:#fff; color:#333; border:1px solid #93C5FD; }
 
 
 
704
  .btn { border:1px solid; }
705
+ .btn-primary { background:#1D4ED8; color:#fff; border-color:#1E40AF; }
706
+ .btn-primary:hover { background:#1E40AF; border-color:#1E3A8A; }
707
+ .btn-success { background:#059669; color:#fff; border-color:#047857; }
708
+ .btn-success:hover { background:#047857; border-color:#065F46; }
709
+ .btn-info { background:#0891B2; color:#fff; border-color:#0E7490; }
710
+ .alert-info { background:#DBEAFE; border-color:#93C5FD; color:#1E3A8A; }
711
+ .alert-warning { background:#FEF9C3; border-color:#FDE68A; color:#92400E; }
712
+ .dataTables_wrapper { color:#333; }
713
  table.dataTable { border:1px solid #BFDBFE; }
714
+ .footer { position:fixed; bottom:0; width:100%; background:#1E3A8A;
715
+ color:#ccc; text-align:center; padding:10px;
716
  border-top:1px solid #1E40AF; font-size:12px; }
717
+ .chi-panel { background:#F0FDF4; border:1px solid #86EFAC; border-radius:6px; padding:12px 14px; margin-top:8px; }
718
+ .chi-disabled { background:#FEF2F2; border:1px solid #FCA5A5; border-radius:6px; padding:12px 14px; margin-top:8px; }
719
+
720
+ /* ── Cytogenetic canvas wrapper ── */
721
+ #cyto-scroll-wrapper {
722
+ overflow-x: auto;
723
+ overflow-y: hidden;
724
+ background: #fff;
725
+ border: 1px solid #BFDBFE;
726
+ border-radius: 6px;
727
+ padding: 8px;
728
+ }
729
+ #cytoCanvas {
730
+ display: block;
731
+ image-rendering: crisp-edges;
732
+ cursor: crosshair;
733
+ }
734
+ #cyto-tooltip {
735
+ position: fixed;
736
+ background: rgba(30,58,138,0.92);
737
+ color: #fff;
738
+ padding: 7px 12px;
739
+ border-radius: 6px;
740
+ font-size: 12px;
741
+ pointer-events: none;
742
+ display: none;
743
+ z-index: 9999;
744
+ max-width: 260px;
745
+ line-height: 1.6;
746
+ box-shadow: 0 2px 8px rgba(0,0,0,0.25);
747
  }
748
+ .cyto-controls { display:flex; flex-wrap:wrap; gap:10px; align-items:center; margin-bottom:12px; }
749
+ .cyto-controls label { font-size:13px; color:#555; margin:0; }
750
+ .cyto-controls input[type=range] { width:120px; }
751
+ .cyto-controls select { font-size:13px; padding:3px 6px; border:1px solid #93C5FD; border-radius:4px; }
752
+ #cyto-legend {
753
+ display:flex; flex-wrap:wrap; gap:12px; margin-top:8px; font-size:12px; align-items:center;
754
+ }
755
+ .legend-item { display:flex; align-items:center; gap:5px; }
756
+ .legend-swatch { width:16px; height:16px; border-radius:2px; border:1px solid #ccc; }
757
  "))
758
  ),
759
 
760
+ navbarPage("Linkage Map Creator v5.0 β€” Cytogenetic Visualization", id="nav",
761
 
762
  # ── Tab 1: Upload ────────────────────────────────────────────────────────
763
  tabPanel("Data Upload", icon=icon("upload"),
 
771
  choices=c("F2"="F2","RIL"="RIL"), selected="F2"),
772
  hr(),
773
  div(class="alert alert-info",
774
+ tags$b("v5.0 New Features:"), br(),
775
+ tags$b("β€’ Cytogenetic-style high-resolution HTML canvas plot"), br(),
776
+ tags$b("β€’ Download: All markers with positions (incl. removed)"), br(),
777
+ tags$b("β€’ Download: Retained markers list"), br(),
778
+ tags$b("β€’ Hover tooltips on chromosome plot"), br(),
779
+ "β€’ Chi-square filter optional (toggle in Parameters)", br(),
780
+ "β€’ Marker order from input file preserved"
781
  )
782
  )),
783
  mainPanel(width=8,
 
795
  sidebarLayout(
796
  sidebarPanel(width=4, wellPanel(
797
  h3("Analysis Parameters"),
798
+ sliderInput("missing_threshold", "Missing Data Threshold:", min=0, max=1, value=0.3, step=0.05),
799
+ sliderInput("recombination_threshold", "Max Recombination Fraction (r):", min=0, max=0.5, value=0.45, step=0.01),
 
 
 
 
 
 
 
800
  hr(),
801
+ h4(icon("vial"), " Chi-Square Filter"),
802
+ checkboxInput("enable_chi_square", "Enable chi-square segregation distortion filter", value=FALSE),
 
 
 
 
 
 
 
803
  conditionalPanel("input.enable_chi_square == true",
804
  div(class="chi-panel",
805
+ numericInput("chi_square_alpha", "Significance level (Ξ±):", min=0.001, max=0.2, value=0.05, step=0.005),
806
+ checkboxInput("use_bonferroni", "Apply Bonferroni correction", value=FALSE),
 
 
 
 
807
  div(class="alert alert-warning", style="font-size:12px; margin-top:8px;",
808
+ icon("triangle-exclamation"), " ", tags$b("Caution:"),
809
+ " Chi-square filtering removes markers with skewed allele ratios.")
 
 
 
 
810
  )
811
  ),
812
  conditionalPanel("input.enable_chi_square == false",
813
  div(class="chi-disabled", style="font-size:12px;",
814
+ icon("info-circle"), " Chi-square filter is OFF.")
 
 
 
815
  ),
 
816
  hr(),
817
  h4("Map Scaling"),
818
+ numericInput("max_total_cm", "Max Total Map Length (cM):", min=100, max=10000, value=1500, step=100),
 
819
  selectInput("scaling_method", "Scaling Method:",
820
+ choices=c("Proportional"="proportional","Uniform"="uniform"), selected="proportional"),
 
821
  hr(),
822
+ actionButton("run_analysis", "β–Ά Run Analysis", class="btn-primary btn-block", icon=icon("play"))
 
823
  )),
824
  mainPanel(width=8, wellPanel(
825
  h3("Parameter Guide"),
826
  tags$ul(
827
+ tags$li(tags$b("Missing Data Threshold:"), " Markers with > this fraction missing are removed."),
828
+ tags$li(tags$b("Max Recombination Fraction:"), " Pairs with r β‰₯ threshold get a 50 cM placeholder gap."),
829
+ tags$li(tags$b("Monomorphic Removal:"), tags$b(" Automatic."), " Fixed allele markers removed."),
830
+ tags$li(tags$b("Chi-Square Filter:"), tags$b(" Optional."), " Removes segregation-distorted markers.")
 
 
 
 
 
 
 
 
 
 
831
  ),
832
+ h4("Scaling Summary"), verbatimTextOutput("scaling_summary"),
833
+ h4("Before Scaling"), verbatimTextOutput("before_scaling_stats"),
834
+ h4("After Scaling"), verbatimTextOutput("after_scaling_stats")
 
835
  ))
836
  )
837
  ),
838
 
839
  # ── Tab 3: QC Report ────────────────────────────────────────────────────
840
  tabPanel("QC Report", icon=icon("clipboard-check"),
841
+ wellPanel(h3("Quality Control Report"), verbatimTextOutput("qc_report_output")),
 
 
 
842
  wellPanel(
843
  h3("Removed Markers β€” Full Detail"),
 
844
  div(style="overflow-x:auto;", dataTableOutput("removal_log_table")),
845
  br(),
846
+ downloadButton("download_removal_log", "⬇ Download Removal Log (.xlsx)", class="btn-success")
 
847
  )
848
  ),
849
 
850
+ # ── Tab 4: Results & Downloads ──────────────────────────────────────────
851
  tabPanel("Results", icon=icon("table"),
852
  fluidRow(column(12, wellPanel(
853
  h3("Analysis Results"),
854
  conditionalPanel("output.analysis_run",
855
+
856
+ # ── Download buttons row ──────────────────────────────────────────
857
+ fluidRow(
858
+ column(4,
859
+ downloadButton("download_results",
860
+ "⬇ Full Excel Results",
861
+ class="btn-success btn-block")),
862
+ column(4,
863
+ downloadButton("download_all_markers",
864
+ "⬇ All Markers + Positions",
865
+ class="btn-info btn-block")),
866
+ column(4,
867
+ downloadButton("download_retained_markers",
868
+ "⬇ Retained Markers List",
869
+ class="btn-info btn-block"))
870
+ ),
871
+ br(),
872
+
873
+ # ── Retained markers list ─────────────────────────────────────────
874
+ h4("Retained Markers (passed QC, with genetic positions)"),
875
+ div(style="overflow-x:auto;", dataTableOutput("retained_markers_table")),
876
+ br(),
877
+
878
+ # ── All markers table ─────────────────────────────────────────────
879
+ h4("All Markers β€” Positions + QC Status (retained & removed)"),
880
+ div(style="overflow-x:auto;", dataTableOutput("all_markers_table")),
881
+ br(),
882
+
883
  h4("Linkage Map (Input Order Preserved, First Marker = 0 cM)"),
884
  div(style="overflow-x:auto;", dataTableOutput("result_table")),
885
+ h4("Summary Statistics"),
886
+ verbatimTextOutput("summary_stats")
887
  ),
888
  conditionalPanel("!output.analysis_run",
889
  p("Upload data and click 'Run Analysis' to see results.",
 
897
  sidebarLayout(
898
  sidebarPanel(width=4, wellPanel(
899
  h3("Visualization Options"),
900
+
901
+ # ── Cytogenetic plot controls ─────────────────────────────────────
902
+ h4("Cytogenetic Plot Controls"),
903
+ sliderInput("cyto_chrom_width", "Chromosome Width (px):", min=10, max=80, value=28, step=2),
904
+ sliderInput("cyto_chrom_spacing", "Chromosome Spacing (px):", min=20, max=120, value=50, step=5),
905
+ sliderInput("cyto_px_per_cm", "Pixels per cM:", min=1, max=20, value=5, step=0.5),
906
+ sliderInput("cyto_font_size", "Label Font Size (px):", min=8, max=20, value=11, step=1),
907
+ selectInput("cyto_color_scheme", "Color Scheme:",
908
+ choices=c("Classic (dark/light/yellow)"="classic",
909
+ "Blue/Orange/White"="blue_orange",
910
+ "Green/Purple/White"="green_purple",
911
+ "Red/Blue/White"="red_blue"),
912
+ selected="classic"),
913
+ checkboxInput("cyto_show_scale", "Show cM scale bar", value=TRUE),
914
+ checkboxInput("cyto_show_marker_names", "Show marker names (≀200 markers)", value=FALSE),
915
+ hr(),
916
+
917
+ # ── Legacy ggplot controls ─────────────────────────────────────────
918
+ h4("Legacy Plot Controls"),
919
  selectInput("color_palette", "Color Palette:",
920
  choices=c("Set1","Set2","Set3","Paired","Dark2","Accent","Spectral","RdBu"),
921
  selected="Set2"),
 
923
  sliderInput("marker_label_size", "Label Size:", min=1, max=8, value=2, step=0.5),
924
  sliderInput("plot_width", "Plot Width (px):", min=600, max=2400, value=1400, step=100),
925
  sliderInput("plot_height", "Plot Height (px):", min=400, max=1600, value=800, step=50),
926
+ sliderInput("chrom_spacing", "LG Spacing:", min=2, max=15, value=5, step=0.5),
927
+ sliderInput("point_size", "Marker Point Size:", min=0.5, max=5, value=1.5, step=0.25)
928
  )),
929
  mainPanel(width=8, wellPanel(
930
  h3("Palette Preview"),
 
933
  )
934
  ),
935
 
936
+ # ── Tab 6: Cytogenetic Visualization (NEW v5.0) ──────────────────────────
937
+ tabPanel("Cytogenetic Plot", icon=icon("dna"),
938
+ fluidRow(column(12, wellPanel(
939
+ h3("High-Resolution Cytogenetic Linkage Map"),
940
+ conditionalPanel("output.analysis_run",
941
+ fluidRow(
942
+ column(8, selectInput("cyto_chromosome_select",
943
+ "Select Chromosomes:",
944
+ choices=NULL, multiple=TRUE)),
945
+ column(4, br(),
946
+ actionButton("cyto_save_png", "πŸ“· Save as PNG",
947
+ class="btn-primary", style="width:100%;"))
948
+ ),
949
+ br(),
950
+ div(class="cyto-controls",
951
+ tags$label("Zoom:"),
952
+ tags$input(type="range", id="cytoZoom", min="0.5", max="3",
953
+ value="1", step="0.1",
954
+ oninput="updateCytoZoom(this.value)"),
955
+ tags$span(id="cytoZoomLabel", "1.0x", style="font-size:13px; min-width:35px;")
956
+ ),
957
+ div(id="cyto-scroll-wrapper",
958
+ tags$canvas(id="cytoCanvas", width="1200", height="600")
959
+ ),
960
+ div(id="cyto-legend",
961
+ div(class="legend-item",
962
+ div(class="legend-swatch", id="sw-a"),
963
+ tags$span("Homozygous Parent A (aa)")),
964
+ div(class="legend-item",
965
+ div(class="legend-swatch", id="sw-b"),
966
+ tags$span("Homozygous Parent B (bb)")),
967
+ div(class="legend-item",
968
+ div(class="legend-swatch", id="sw-ab"),
969
+ tags$span("Heterozygous (ab)")),
970
+ div(class="legend-item",
971
+ div(class="legend-swatch", id="sw-miss", style="background:#e0e0e0;"),
972
+ tags$span("Missing / unknown"))
973
+ )
974
+ ),
975
+ conditionalPanel("!output.analysis_run",
976
+ p("Run analysis first.",
977
+ style="color:#888;font-style:italic;text-align:center;padding:40px;")
978
+ )
979
+ )))
980
+ ),
981
+
982
+ # ── Tab 7: Legacy Visualization ──────────────────────────────────────────
983
+ tabPanel("Legacy Plot", icon=icon("chart-bar"),
984
  fluidRow(column(12, wellPanel(
985
+ h3("Legacy Chromosome Map (ggplot2)"),
986
  conditionalPanel("output.analysis_run",
987
  fluidRow(
988
  column(8, selectInput("chromosome_select", "Select Chromosomes:",
989
  choices=NULL, multiple=TRUE)),
990
  column(4, br(),
991
+ tags$button(id="camera-btn",
992
+ onclick="captureChromPlot()",
993
+ style="background:none;border:1px solid #1D4ED8;cursor:pointer;
994
+ padding:6px 12px;border-radius:6px;color:#1D4ED8;font-size:13px;width:100%;",
995
+ "πŸ“· Save image"
996
  )
997
  )
998
  ),
999
+ div(id="chrom-plot-wrapper", style="background:white;",
1000
+ plotOutput("chromosome_plot", height="auto"))
 
 
1001
  ),
1002
  conditionalPanel("!output.analysis_run",
1003
  p("Run analysis first.",
 
1006
  )))
1007
  ),
1008
 
1009
+ # ── Tab 8: Help ──────────────────────────────────────────────────────────
1010
  tabPanel("Help", icon=icon("question-circle"),
1011
  wellPanel(
1012
+ h3("Application Guide β€” v5.0"),
1013
+ h4("What's New in v5.0"),
 
1014
  div(class="alert alert-info",
1015
  tags$ul(
1016
+ tags$li(tags$b("High-resolution cytogenetic-style HTML canvas plot:"),
1017
+ " Each chromosome rendered as a colour-banded ideogram. Band colour encodes the",
1018
+ " dominant allele class per marker (Parent A, Parent B, Heterozygous)."),
1019
+ tags$li(tags$b("Hover tooltips:"), " Hover over any chromosome band to see marker name,",
1020
+ " position (cM), and allele frequencies."),
1021
+ tags$li(tags$b("Download β€” All Markers + Positions (.xlsx):"),
1022
+ " Every marker from the input file, showing genetic position for retained markers,",
1023
+ " NA for removed markers, with the removal reason where applicable."),
1024
+ tags$li(tags$b("Download β€” Retained Markers List (.xlsx):"),
1025
+ " Clean list of only retained markers with chromosome and genetic position."),
1026
+ tags$li(tags$b("Zoom slider:"), " Rescale the canvas plot without re-running the analysis.")
 
 
1027
  )
1028
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1029
  h4("Required Input Format"),
1030
  tags$ul(
1031
  tags$li("Excel (.xlsx): Column 1 = 'Marker', Column 2 = 'Chromosome'"),
1032
  tags$li("Genotype columns: a/b/ab/- OR numeric 2/1/0/-1"),
1033
  tags$li("Chromosome column: integer numbers OR Excel VLOOKUP formulas")
1034
  ),
 
1035
  h4("Genotype Encoding Reference"),
1036
  tableOutput("encoding_table")
1037
  )
1038
  )
1039
  ),
1040
 
1041
+ # ── Tooltip div ─────────────────────────────────────────────────────────────
1042
+ div(id="cyto-tooltip"),
1043
+
1044
+ # ���─ JavaScript: Cytogenetic canvas renderer ──────────────────────────────────
1045
  tags$script(HTML("
1046
+ var cytoData = null;
1047
+ var cytoSettings = {};
1048
+ var cytoZoomVal = 1.0;
1049
+
1050
+ // Color scheme definitions
1051
+ var colorSchemes = {
1052
+ classic: { a:'#2c2c2c', b:'#f5f5f5', ab:'#f0c040', miss:'#e8e8e8', border:'#555', text:'#222' },
1053
+ blue_orange: { a:'#1565C0', b:'#FF6D00', ab:'#fff9c4', miss:'#e0e0e0', border:'#333', text:'#111' },
1054
+ green_purple: { a:'#1B5E20', b:'#4A148C', ab:'#fff9c4', miss:'#e0e0e0', border:'#333', text:'#111' },
1055
+ red_blue: { a:'#B71C1C', b:'#0D47A1', ab:'#F9A825', miss:'#e0e0e0', border:'#333', text:'#111' }
1056
+ };
1057
+
1058
+ function updateLegendSwatches(scheme) {
1059
+ var cs = colorSchemes[scheme] || colorSchemes.classic;
1060
+ var sa = document.getElementById('sw-a');
1061
+ var sb = document.getElementById('sw-b');
1062
+ var sab = document.getElementById('sw-ab');
1063
+ if (sa) sa.style.background = cs.a;
1064
+ if (sb) sb.style.background = cs.b;
1065
+ if (sab) sab.style.background = cs.ab;
1066
+ }
1067
+
1068
+ function updateCytoZoom(val) {
1069
+ cytoZoomVal = parseFloat(val);
1070
+ var lbl = document.getElementById('cytoZoomLabel');
1071
+ if (lbl) lbl.textContent = parseFloat(val).toFixed(1) + 'x';
1072
+ if (cytoData) renderCytogeneticMap();
1073
+ }
1074
+
1075
+ function renderCytogeneticMap() {
1076
+ if (!cytoData || !cytoData.chromosomes) return;
1077
+ var canvas = document.getElementById('cytoCanvas');
1078
+ if (!canvas) return;
1079
+ var ctx = canvas.getContext('2d');
1080
+
1081
+ var chromWidth = Math.round((cytoSettings.chromWidth || 28) * cytoZoomVal);
1082
+ var chromSpacing = Math.round((cytoSettings.chromSpacing || 50) * cytoZoomVal);
1083
+ var pxPerCm = (cytoSettings.pxPerCm || 5) * cytoZoomVal;
1084
+ var fontSize = Math.round((cytoSettings.fontSize || 11) * Math.max(0.8, cytoZoomVal));
1085
+ var showScale = cytoSettings.showScale !== false;
1086
+ var showNames = cytoSettings.showNames || false;
1087
+ var scheme = colorSchemes[cytoSettings.colorScheme] || colorSchemes.classic;
1088
+
1089
+ var chrs = cytoData.chromosomes;
1090
+ var n_chr = chrs.length;
1091
+ var maxPos = 0;
1092
+ for (var i = 0; i < n_chr; i++) {
1093
+ if (chrs[i].max_pos > maxPos) maxPos = chrs[i].max_pos;
1094
+ }
1095
+
1096
+ var topPad = Math.round(60 * cytoZoomVal);
1097
+ var botPad = Math.round(60 * cytoZoomVal);
1098
+ var leftPad = Math.round(60 * cytoZoomVal);
1099
+ var rightPad = Math.round(30 * cytoZoomVal);
1100
+ var mapHeight = Math.ceil(maxPos * pxPerCm);
1101
+ var totalW = leftPad + n_chr * chromWidth + (n_chr - 1) * chromSpacing + rightPad;
1102
+ var totalH = topPad + mapHeight + botPad;
1103
+
1104
+ canvas.width = Math.max(totalW, 200);
1105
+ canvas.height = Math.max(totalH, 200);
1106
+ canvas.style.width = canvas.width + 'px';
1107
+ canvas.style.height = canvas.height + 'px';
1108
+
1109
+ // White background
1110
+ ctx.fillStyle = '#ffffff';
1111
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
1112
+
1113
+ // Store hit regions for tooltips
1114
+ canvas._hitRegions = [];
1115
+
1116
+ for (var ci = 0; ci < n_chr; ci++) {
1117
+ var chr = chrs[ci];
1118
+ var chrH = Math.ceil(chr.max_pos * pxPerCm) || 10;
1119
+ var x0 = leftPad + ci * (chromWidth + chromSpacing);
1120
+ var y0 = topPad;
1121
+ var markers = chr.markers;
1122
+ var nMk = markers.length;
1123
+
1124
+ // Draw chromosome outline (rounded rect)
1125
+ var r = Math.min(chromWidth * 0.35, 8);
1126
+ ctx.save();
1127
+ ctx.beginPath();
1128
+ ctx.moveTo(x0 + r, y0);
1129
+ ctx.lineTo(x0 + chromWidth - r, y0);
1130
+ ctx.quadraticCurveTo(x0 + chromWidth, y0, x0 + chromWidth, y0 + r);
1131
+ ctx.lineTo(x0 + chromWidth, y0 + chrH - r);
1132
+ ctx.quadraticCurveTo(x0 + chromWidth, y0 + chrH, x0 + chromWidth - r, y0 + chrH);
1133
+ ctx.lineTo(x0 + r, y0 + chrH);
1134
+ ctx.quadraticCurveTo(x0, y0 + chrH, x0, y0 + chrH - r);
1135
+ ctx.lineTo(x0, y0 + r);
1136
+ ctx.quadraticCurveTo(x0, y0, x0 + r, y0);
1137
+ ctx.closePath();
1138
+ ctx.clip();
1139
+
1140
+ // Fill base
1141
+ ctx.fillStyle = scheme.miss;
1142
+ ctx.fillRect(x0, y0, chromWidth, chrH);
1143
+
1144
+ // Draw bands for each marker
1145
+ for (var mi = 0; mi < nMk; mi++) {
1146
+ var mk = markers[mi];
1147
+ var yTop = y0 + Math.round(mk.position * pxPerCm);
1148
+ var yBot = (mi < nMk - 1)
1149
+ ? y0 + Math.round(markers[mi+1].position * pxPerCm)
1150
+ : y0 + chrH;
1151
+ var bandH = Math.max(yBot - yTop, 1);
1152
+
1153
+ // Pick dominant allele colour
1154
+ var dom = 'miss';
1155
+ var maxFrac = 0;
1156
+ if (mk.allele_a > maxFrac) { maxFrac = mk.allele_a; dom = 'a'; }
1157
+ if (mk.allele_b > maxFrac) { maxFrac = mk.allele_b; dom = 'b'; }
1158
+ if (mk.allele_ab > maxFrac) { maxFrac = mk.allele_ab; dom = 'ab'; }
1159
+
1160
+ ctx.fillStyle = scheme[dom] || scheme.miss;
1161
+ ctx.fillRect(x0, yTop, chromWidth, bandH);
1162
+
1163
+ // Subtle divider line between bands
1164
+ if (mi > 0 && bandH > 2) {
1165
+ ctx.strokeStyle = 'rgba(0,0,0,0.08)';
1166
+ ctx.lineWidth = 0.5;
1167
+ ctx.beginPath(); ctx.moveTo(x0, yTop); ctx.lineTo(x0 + chromWidth, yTop);
1168
+ ctx.stroke();
1169
+ }
1170
+
1171
+ // Store hit region
1172
+ canvas._hitRegions.push({
1173
+ x: x0, y: yTop, w: chromWidth, h: bandH,
1174
+ marker: mk.marker,
1175
+ position: mk.position,
1176
+ chromosome: chr.chromosome,
1177
+ a: mk.allele_a, b: mk.allele_b, ab: mk.allele_ab, miss: mk.allele_miss
1178
+ });
1179
+
1180
+ // Marker name inside band (if enabled and band is tall enough)
1181
+ if (showNames && bandH >= fontSize + 2) {
1182
+ ctx.save();
1183
+ ctx.fillStyle = (dom === 'a') ? '#ffffff' : '#1a1a1a';
1184
+ ctx.font = 'bold ' + (fontSize - 1) + 'px monospace';
1185
+ ctx.textAlign = 'left';
1186
+ ctx.fillText(mk.marker.substring(0, 12), x0 + 3, yTop + bandH / 2 + (fontSize - 1) / 2 - 1);
1187
+ ctx.restore();
1188
+ }
1189
+ }
1190
+ ctx.restore(); // undo clip
1191
+
1192
+ // Chromosome border
1193
+ ctx.save();
1194
+ ctx.strokeStyle = scheme.border;
1195
+ ctx.lineWidth = Math.max(1, Math.round(cytoZoomVal));
1196
+ var r2 = Math.min(chromWidth * 0.35, 8);
1197
+ ctx.beginPath();
1198
+ ctx.moveTo(x0 + r2, y0);
1199
+ ctx.lineTo(x0 + chromWidth - r2, y0);
1200
+ ctx.quadraticCurveTo(x0 + chromWidth, y0, x0 + chromWidth, y0 + r2);
1201
+ ctx.lineTo(x0 + chromWidth, y0 + chrH - r2);
1202
+ ctx.quadraticCurveTo(x0 + chromWidth, y0 + chrH, x0 + chromWidth - r2, y0 + chrH);
1203
+ ctx.lineTo(x0 + r2, y0 + chrH);
1204
+ ctx.quadraticCurveTo(x0, y0 + chrH, x0, y0 + chrH - r2);
1205
+ ctx.lineTo(x0, y0 + r2);
1206
+ ctx.quadraticCurveTo(x0, y0, x0 + r2, y0);
1207
+ ctx.closePath();
1208
+ ctx.stroke();
1209
+ ctx.restore();
1210
+
1211
+ // Chromosome label below
1212
+ ctx.save();
1213
+ ctx.fillStyle = scheme.text;
1214
+ ctx.font = 'bold ' + fontSize + 'px sans-serif';
1215
+ ctx.textAlign = 'center';
1216
+ ctx.fillText('Chr ' + chr.chromosome, x0 + chromWidth / 2, y0 + chrH + fontSize + 6);
1217
+
1218
+ // Marker count
1219
+ ctx.font = (fontSize - 1) + 'px sans-serif';
1220
+ ctx.fillStyle = '#777';
1221
+ ctx.fillText('n=' + chr.n_markers, x0 + chromWidth / 2, y0 + chrH + 2 * fontSize + 8);
1222
+ ctx.restore();
1223
+
1224
+ // Length label above
1225
+ ctx.save();
1226
+ ctx.fillStyle = scheme.text;
1227
+ ctx.font = (fontSize - 1) + 'px sans-serif';
1228
+ ctx.textAlign = 'center';
1229
+ ctx.fillText(chr.max_pos.toFixed(1) + ' cM', x0 + chromWidth / 2, y0 - 6);
1230
+ ctx.restore();
1231
+ }
1232
+
1233
+ // cM scale bar on left
1234
+ if (showScale && maxPos > 0) {
1235
+ var scaleSteps = [5, 10, 20, 25, 50, 100, 150, 200];
1236
+ var step = 10;
1237
+ for (var si = 0; si < scaleSteps.length; si++) {
1238
+ if (mapHeight / (maxPos / scaleSteps[si]) >= 25) { step = scaleSteps[si]; break; }
1239
+ }
1240
+ ctx.save();
1241
+ ctx.strokeStyle = '#888';
1242
+ ctx.lineWidth = 1;
1243
+ ctx.fillStyle = '#555';
1244
+ ctx.font = (fontSize - 1) + 'px sans-serif';
1245
+ ctx.textAlign = 'right';
1246
+ var scaleX = leftPad - 8;
1247
+ ctx.beginPath();
1248
+ ctx.moveTo(scaleX, topPad);
1249
+ ctx.lineTo(scaleX, topPad + mapHeight);
1250
+ ctx.stroke();
1251
+ for (var pos = 0; pos <= maxPos; pos += step) {
1252
+ var ty = topPad + Math.round(pos * pxPerCm);
1253
+ ctx.beginPath();
1254
+ ctx.moveTo(scaleX - 4, ty);
1255
+ ctx.lineTo(scaleX, ty);
1256
+ ctx.stroke();
1257
+ ctx.fillText(pos + '', scaleX - 6, ty + 4);
1258
+ }
1259
+ ctx.restore();
1260
+ }
1261
+ }
1262
+
1263
+ // Tooltip
1264
+ document.addEventListener('mousemove', function(e) {
1265
+ var canvas = document.getElementById('cytoCanvas');
1266
+ if (!canvas || !canvas._hitRegions) return;
1267
+ var rect = canvas.getBoundingClientRect();
1268
+ var scaleX = canvas.width / rect.width;
1269
+ var scaleY = canvas.height / rect.height;
1270
+ var cx = (e.clientX - rect.left) * scaleX;
1271
+ var cy = (e.clientY - rect.top) * scaleY;
1272
+ var tip = document.getElementById('cyto-tooltip');
1273
+ var found = null;
1274
+ var regions = canvas._hitRegions;
1275
+ for (var i = 0; i < regions.length; i++) {
1276
+ var r = regions[i];
1277
+ if (cx >= r.x && cx <= r.x + r.w && cy >= r.y && cy <= r.y + r.h) {
1278
+ found = r; break;
1279
+ }
1280
+ }
1281
+ if (found) {
1282
+ tip.style.display = 'block';
1283
+ tip.style.left = (e.clientX + 14) + 'px';
1284
+ tip.style.top = (e.clientY - 10) + 'px';
1285
+ tip.innerHTML =
1286
+ '<b>' + found.marker + '</b><br>' +
1287
+ 'Chr ' + found.chromosome + ' &nbsp;|&nbsp; ' + found.position.toFixed(2) + ' cM<br>' +
1288
+ 'Parent A: ' + (found.a * 100).toFixed(1) + '%<br>' +
1289
+ 'Parent B: ' + (found.b * 100).toFixed(1) + '%<br>' +
1290
+ 'Het (ab): ' + (found.ab * 100).toFixed(1) + '%<br>' +
1291
+ 'Missing: ' + (found.miss * 100).toFixed(1) + '%';
1292
+ } else {
1293
+ tip.style.display = 'none';
1294
+ }
1295
+ });
1296
+
1297
+ // Shiny message handler: receive plot data
1298
+ Shiny.addCustomMessageHandler('updateCytoPlot', function(msg) {
1299
+ cytoData = msg.data;
1300
+ cytoSettings = msg.settings;
1301
+ updateLegendSwatches(cytoSettings.colorScheme || 'classic');
1302
+ cytoZoomVal = 1.0;
1303
+ var zSlider = document.getElementById('cytoZoom');
1304
+ if (zSlider) zSlider.value = '1';
1305
+ var zLabel = document.getElementById('cytoZoomLabel');
1306
+ if (zLabel) zLabel.textContent = '1.0x';
1307
+ renderCytogeneticMap();
1308
+ });
1309
+
1310
+ // Shiny message handler: update settings only (re-render without new data)
1311
+ Shiny.addCustomMessageHandler('updateCytoSettings', function(msg) {
1312
+ cytoSettings = msg;
1313
+ updateLegendSwatches(cytoSettings.colorScheme || 'classic');
1314
+ if (cytoData) renderCytogeneticMap();
1315
+ });
1316
+
1317
+ // Save PNG
1318
+ document.addEventListener('click', function(e) {
1319
+ if (e.target && e.target.id === 'cyto_save_png') {
1320
+ var canvas = document.getElementById('cytoCanvas');
1321
+ if (!canvas) return;
1322
  var link = document.createElement('a');
1323
+ link.download = 'cytogenetic_map_' + new Date().toISOString().slice(0,10) + '.png';
1324
  link.href = canvas.toDataURL('image/png');
1325
  link.click();
1326
+ }
1327
+ });
1328
+
1329
+ // Legacy ggplot save
1330
+ function captureChromPlot() {
1331
+ var el = document.getElementById('chrom-plot-wrapper');
1332
+ if (!el) { alert('Plot not found.'); return; }
1333
+ html2canvas(el, { backgroundColor:'#ffffff', scale:2, useCORS:true, logging:false })
1334
+ .then(function(canvas) {
1335
+ var link = document.createElement('a');
1336
+ link.download = 'linkage_map_' + new Date().toISOString().slice(0,10) + '.png';
1337
+ link.href = canvas.toDataURL('image/png');
1338
+ link.click();
1339
+ }).catch(function(err) { alert('Capture failed: ' + err); });
1340
  }
1341
  ")),
1342
 
1343
  div(class="footer",
1344
+ "Linkage Map Creator v5.0 | Cytogenetic plot | All-markers positions | Retained markers list | Β© 2024")
1345
  )
1346
 
1347
  # ═══════════════════════════════════════════════════════════════════════════════
 
1355
  upload_log <- reactiveVal("")
1356
 
1357
  output$encoding_table <- renderTable({
1358
+ data.frame(`Numeric Code`=c("2","1","0","-1"),
1359
+ `Text Code`=c("a","b","ab","-"),
1360
+ Meaning=c("Homozygous Parent 1 (AA)","Homozygous Parent 2 (BB)",
1361
+ "Heterozygous (Aa)","Missing data"), check.names=FALSE)
 
 
 
1362
  }, striped=TRUE, hover=TRUE, bordered=TRUE)
1363
 
1364
  observeEvent(input$file, {
 
1367
  df <- load_and_convert_data(input$file$datapath)
1368
  n_chr <- length(unique(df$Chromosome))
1369
  log_msg <- paste0(
1370
+ "\u2713 File loaded: ", input$file$name, "\n",
1371
  " Markers : ", nrow(df), "\n",
1372
  " Individuals : ", ncol(df) - 3, "\n",
1373
  " Chromosomes : ", n_chr,
 
1375
  " Genotype codes converted to a/b/ab/-\n",
1376
  " Marker order will be PRESERVED from input file.\n"
1377
  )
1378
+ uploaded_data(df); upload_log(log_msg)
1379
+ showNotification("File uploaded successfully!", type="message")
 
1380
  }, error=function(e) {
1381
+ upload_log(paste0("\u2717 Error: ", e$message))
1382
  showNotification(paste("Upload error:", e$message), type="error")
1383
  })
1384
  })
1385
 
1386
+ output$upload_status <- renderText({ upload_log() })
1387
+ output$preview_table <- renderDataTable({
 
1388
  req(uploaded_data())
1389
  df_show <- head(uploaded_data(), 10)
1390
  df_show <- df_show[, colnames(df_show) != ".input_order", drop=FALSE]
1391
  datatable(df_show, options=list(scrollX=TRUE, dom="t", pageLength=10), rownames=FALSE)
1392
  })
 
1393
  output$chr_summary_table <- renderDataTable({
1394
  req(uploaded_data())
1395
  df <- uploaded_data()
1396
  chr_tab <- df %>% group_by(Chromosome) %>%
1397
  summarise(N_Markers=n(), .groups="drop") %>%
1398
  arrange(suppressWarnings(as.numeric(Chromosome)))
1399
+ datatable(chr_tab, options=list(dom="t", pageLength=30), rownames=FALSE)
 
1400
  })
1401
 
1402
  observeEvent(input$run_analysis, {
1403
  req(uploaded_data())
1404
+ chi_status <- if (input$enable_chi_square)
1405
+ paste0("Chi-square ENABLED (alpha=", input$chi_square_alpha,
1406
+ if (input$use_bonferroni) " + Bonferroni" else "", ")")
1407
+ else "Chi-square DISABLED"
1408
+ showModal(modalDialog(title="Building Linkage Map\u2026",
1409
+ paste0("Population type: ", input$population_type, "\n", chi_status),
1410
+ footer=NULL))
 
 
 
 
 
 
 
 
 
 
1411
  tryCatch({
1412
  result <- create_linkage_map(
1413
  df = uploaded_data(),
 
1427
  error=function(e) sort(chromosomes))
1428
  updateSelectInput(session, "chromosome_select",
1429
  choices=chr_sorted, selected=chr_sorted)
1430
+ updateSelectInput(session, "cyto_chromosome_select",
1431
+ choices=chr_sorted, selected=chr_sorted)
1432
  removeModal()
 
1433
  n_pos <- sum(!is.na(result$linkage_map$Position))
1434
  n_removed <- nrow(result$removal_log)
1435
+ showNotification(paste0("Analysis complete! ", n_pos,
1436
+ " markers positioned. ", n_removed,
1437
+ " markers removed. See QC Report."), type="message")
 
 
 
 
 
 
 
1438
  }, error=function(e) {
1439
  removeModal()
1440
  showNotification(paste("Analysis error:", e$message), type="error")
 
1444
  output$analysis_run <- reactive({ !is.null(analysis_results()) })
1445
  outputOptions(output, "analysis_run", suspendWhenHidden=FALSE)
1446
 
1447
+ # ── Send cytogenetic plot data to JS ────────────────────────────────────────
1448
+ observe({
1449
+ req(analysis_results(), input$cyto_chromosome_select)
1450
+ res <- analysis_results()
1451
+ lm <- res$linkage_map
1452
+ df_geno <- res$original_data
1453
+
1454
+ cyto_data_list <- build_cyto_plot_data(lm, df_geno, input$cyto_chromosome_select)
1455
+
1456
+ msg <- list(
1457
+ data = list(
1458
+ chromosomes = lapply(cyto_data_list, function(x) x)
1459
+ ),
1460
+ settings = list(
1461
+ chromWidth = input$cyto_chrom_width,
1462
+ chromSpacing = input$cyto_chrom_spacing,
1463
+ pxPerCm = input$cyto_px_per_cm,
1464
+ fontSize = input$cyto_font_size,
1465
+ showScale = input$cyto_show_scale,
1466
+ showNames = input$cyto_show_marker_names,
1467
+ colorScheme = input$cyto_color_scheme
1468
+ )
1469
+ )
1470
+ session$sendCustomMessage("updateCytoPlot", msg)
1471
+ })
1472
+
1473
+ # ── Update settings without re-sending data ─────────────────────────────────
1474
+ observeEvent(list(input$cyto_chrom_width, input$cyto_chrom_spacing,
1475
+ input$cyto_px_per_cm, input$cyto_font_size,
1476
+ input$cyto_show_scale, input$cyto_show_marker_names,
1477
+ input$cyto_color_scheme), {
1478
+ req(analysis_results())
1479
+ session$sendCustomMessage("updateCytoSettings", list(
1480
+ chromWidth = input$cyto_chrom_width,
1481
+ chromSpacing = input$cyto_chrom_spacing,
1482
+ pxPerCm = input$cyto_px_per_cm,
1483
+ fontSize = input$cyto_font_size,
1484
+ showScale = input$cyto_show_scale,
1485
+ showNames = input$cyto_show_marker_names,
1486
+ colorScheme = input$cyto_color_scheme
1487
+ ))
1488
+ }, ignoreInit=TRUE)
1489
+
1490
+ # ── QC outputs ───────────────────────────────────────────────────────────────
1491
  output$qc_report_output <- renderText({
1492
  if (is.null(analysis_results())) return("No analysis run yet.")
1493
  analysis_results()$qc_report
1494
  })
1495
 
 
1496
  output$removal_log_table <- renderDataTable({
1497
  if (is.null(analysis_results())) {
1498
  return(datatable(data.frame(Message="Run analysis first."),
1499
  options=list(dom="t"), rownames=FALSE))
1500
  }
1501
  log_df <- analysis_results()$removal_log
1502
+ if (nrow(log_df) == 0)
1503
+ return(datatable(data.frame(Message="No markers were removed."),
1504
  options=list(dom="t"), rownames=FALSE))
1505
+ datatable(log_df, options=list(scrollX=TRUE, pageLength=25), rownames=FALSE,
1506
+ caption=paste0(nrow(log_df), " marker(s) removed")) %>%
 
 
 
 
1507
  formatStyle("Reason",
1508
  color=styleEqual(
1509
+ c("Excess missing data","Monomorphic marker","Segregation distortion (chi-square)"),
1510
+ c("#c0392b","#8e44ad","#d97706")),
 
 
 
1511
  fontWeight="bold")
1512
  })
1513
 
1514
+ # ── Retained markers table ─────────────────────────────────────────────────
1515
+ output$retained_markers_table <- renderDataTable({
1516
+ req(analysis_results())
1517
+ rml <- analysis_results()$retained_markers_list
1518
+ if (is.null(rml) || nrow(rml) == 0)
1519
+ return(datatable(data.frame(Message="No retained markers."),
1520
+ options=list(dom="t"), rownames=FALSE))
1521
+ datatable(rml, options=list(scrollX=TRUE, pageLength=25), rownames=FALSE,
1522
+ caption=paste0(nrow(rml), " retained markers")) %>%
1523
+ formatRound("Position", 3)
1524
+ })
 
 
1525
 
1526
+ # ── All-markers table ──────────────────────────────────────────────────────
1527
+ output$all_markers_table <- renderDataTable({
1528
  req(analysis_results())
1529
+ amp <- analysis_results()$all_markers_positions
1530
+ if (is.null(amp) || nrow(amp) == 0)
1531
+ return(datatable(data.frame(Message="No marker data."),
1532
+ options=list(dom="t"), rownames=FALSE))
1533
+ datatable(amp, options=list(scrollX=TRUE, pageLength=25), rownames=FALSE,
1534
+ caption=paste0(nrow(amp), " total markers")) %>%
1535
+ formatRound("Position", 3) %>%
1536
+ formatStyle("Status",
1537
+ color=styleEqual(c("Retained","Removed"),
1538
+ c("#059669","#dc2626")),
1539
+ fontWeight="bold")
1540
  })
1541
 
1542
+ output$scaling_summary <- renderText({
1543
+ req(analysis_results())
1544
+ paste0("Method : ", input$scaling_method, "\nMax cM : ", input$max_total_cm)
1545
+ })
1546
  fmt_chr <- function(df) {
1547
  if (is.null(df) || nrow(df) == 0) return("No data.")
1548
  total <- sum(df$Original_Length, na.rm=TRUE)
1549
+ rows <- apply(df, 1, function(x) paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),2), " cM"))
 
1550
  paste0("Total : ", round(total,2), " cM\n", paste(rows, collapse="\n"))
1551
  }
1552
  output$before_scaling_stats <- renderText({ req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_before) })
1553
+ output$after_scaling_stats <- renderText({ req(analysis_results()); fmt_chr(analysis_results()$chrom_lengths_after) })
1554
 
1555
  output$result_table <- renderDataTable({
1556
  req(analysis_results())
1557
  lm <- analysis_results()$linkage_map
1558
+ if (nrow(lm) > 0)
1559
+ datatable(lm, options=list(scrollX=TRUE, pageLength=25), rownames=FALSE) %>%
 
 
1560
  formatRound("Position", 2)
1561
+ else
1562
+ datatable(data.frame(Message="No positioned markers."), options=list(dom="t"), rownames=FALSE)
 
 
1563
  })
1564
 
1565
  output$summary_stats <- renderText({
 
1567
  lm <- analysis_results()$linkage_map
1568
  rec <- analysis_results()$recombination_data
1569
  if (nrow(lm) == 0) return("No positioned markers.")
 
1570
  n_pos <- sum(!is.na(lm$Position))
1571
  n_chr <- length(unique(lm$Chromosome))
1572
  chr_lengths <- lm %>% filter(!is.na(Position)) %>%
1573
  group_by(Chromosome) %>%
1574
  summarise(Length=max(Position,na.rm=TRUE), N_markers=n(), .groups="drop") %>%
1575
  arrange(suppressWarnings(as.numeric(Chromosome)))
1576
+ total_len <- sum(chr_lengths$Length)
1577
+ avg_len <- mean(chr_lengths$Length)
1578
  chr_detail <- paste(apply(chr_lengths, 1, function(x)
1579
+ paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),2), " cM (", x[3], " markers)")),
1580
+ collapse="\n")
1581
+ log_df <- analysis_results()$removal_log
1582
+ n_removed <- nrow(log_df)
1583
+ n_mono <- sum(log_df$Reason == "Monomorphic marker")
1584
+ n_miss <- sum(log_df$Reason == "Excess missing data")
1585
+ n_chi <- sum(log_df$Reason == "Segregation distortion (chi-square)")
1586
+ chi_line <- if (input$enable_chi_square)
 
 
 
1587
  paste0(" Removed (chi-square) : ", n_chi,
1588
+ " [alpha=", input$chi_square_alpha,
1589
+ if (input$use_bonferroni) " Bonferroni" else "", "]")
1590
+ else " Chi-square filter : DISABLED"
 
 
1591
  paste0(
1592
+ "LINKAGE MAP SUMMARY (v5.0)\n===========================\n",
 
1593
  "Population type : ", input$population_type, "\n",
1594
+ "Marker order : Preserved from input file\n\n",
 
1595
  "Total markers input : ", nrow(analysis_results()$original_data), "\n",
1596
  " Removed (missing) : ", n_miss, "\n",
1597
  " Removed (monomorphic): ", n_mono, "\n",
1598
  chi_line, "\n",
1599
+ " Total removed : ", n_removed, "\n",
1600
  "Markers positioned : ", n_pos, "\n",
1601
  "Chromosomes / LGs : ", n_chr, "\n",
1602
  "Total map length : ", round(total_len,2), " cM\n",
 
1632
  )
1633
  }, height=function() input$plot_height)
1634
 
1635
+ # ── Downloads ────────────────────────────────────────────────────────────────
1636
+
1637
+ output$download_removal_log <- downloadHandler(
1638
+ filename=function() paste0("removal_log_", Sys.Date(), ".xlsx"),
1639
+ content=function(file) {
1640
+ req(analysis_results())
1641
+ wb <- createWorkbook(); addWorksheet(wb, "Removed_Markers")
1642
+ log_df <- analysis_results()$removal_log
1643
+ if (nrow(log_df) == 0) log_df <- data.frame(Message="No markers were removed.")
1644
+ writeData(wb, "Removed_Markers", log_df)
1645
+ saveWorkbook(wb, file, overwrite=TRUE)
1646
+ }
1647
+ )
1648
+
1649
+ # NEW: Download all markers with positions
1650
+ output$download_all_markers <- downloadHandler(
1651
+ filename=function() paste0("all_markers_positions_", Sys.Date(), ".xlsx"),
1652
+ content=function(file) {
1653
+ req(analysis_results())
1654
+ amp <- analysis_results()$all_markers_positions
1655
+ wb <- createWorkbook()
1656
+ addWorksheet(wb, "All_Markers_Positions")
1657
+ writeData(wb, "All_Markers_Positions", amp)
1658
+
1659
+ # Style header
1660
+ hs <- createStyle(fontColour="#FFFFFF", fgFill="#1E3A8A",
1661
+ halign="CENTER", textDecoration="Bold", border="Bottom")
1662
+ addStyle(wb, "All_Markers_Positions", hs, rows=1, cols=1:ncol(amp), gridExpand=TRUE)
1663
+
1664
+ # Highlight removed rows in light red
1665
+ removed_rows <- which(amp$Status == "Removed") + 1
1666
+ if (length(removed_rows) > 0) {
1667
+ red_fill <- createStyle(fgFill="#FEE2E2")
1668
+ addStyle(wb, "All_Markers_Positions", red_fill,
1669
+ rows=removed_rows, cols=1:ncol(amp), gridExpand=TRUE)
1670
+ }
1671
+ # Highlight retained rows in light green
1672
+ retained_rows <- which(amp$Status == "Retained") + 1
1673
+ if (length(retained_rows) > 0) {
1674
+ green_fill <- createStyle(fgFill="#D1FAE5")
1675
+ addStyle(wb, "All_Markers_Positions", green_fill,
1676
+ rows=retained_rows, cols=1:ncol(amp), gridExpand=TRUE)
1677
+ }
1678
+ setColWidths(wb, "All_Markers_Positions", cols=1:ncol(amp),
1679
+ widths=c(20, 12, 10, 12, 30, 40))
1680
+ saveWorkbook(wb, file, overwrite=TRUE)
1681
+ }
1682
+ )
1683
+
1684
+ # NEW: Download retained markers list only
1685
+ output$download_retained_markers <- downloadHandler(
1686
+ filename=function() paste0("retained_markers_", Sys.Date(), ".xlsx"),
1687
+ content=function(file) {
1688
+ req(analysis_results())
1689
+ rml <- analysis_results()$retained_markers_list
1690
+ wb <- createWorkbook()
1691
+ addWorksheet(wb, "Retained_Markers")
1692
+ writeData(wb, "Retained_Markers", rml)
1693
+
1694
+ hs <- createStyle(fontColour="#FFFFFF", fgFill="#059669",
1695
+ halign="CENTER", textDecoration="Bold", border="Bottom")
1696
+ addStyle(wb, "Retained_Markers", hs, rows=1, cols=1:ncol(rml), gridExpand=TRUE)
1697
+
1698
+ green_fill <- createStyle(fgFill="#D1FAE5")
1699
+ if (nrow(rml) > 0)
1700
+ addStyle(wb, "Retained_Markers", green_fill,
1701
+ rows=2:(nrow(rml)+1), cols=1:ncol(rml), gridExpand=TRUE)
1702
+ setColWidths(wb, "Retained_Markers", cols=1:ncol(rml), widths=c(20,12,12,10))
1703
+ saveWorkbook(wb, file, overwrite=TRUE)
1704
+ }
1705
+ )
1706
+
1707
+ # Full Excel results
1708
  output$download_results <- downloadHandler(
1709
+ filename=function() paste0("linkage_map_v50_", Sys.Date(), ".xlsx"),
1710
  content=function(file) {
1711
  req(analysis_results())
1712
  wb <- createWorkbook()
1713
  addWorksheet(wb, "Original_Data")
1714
  addWorksheet(wb, "Recombination_Fractions")
1715
  addWorksheet(wb, "Linkage_Map")
1716
+ addWorksheet(wb, "All_Markers_Positions")
1717
+ addWorksheet(wb, "Retained_Markers")
1718
  addWorksheet(wb, "Removal_Log")
1719
  addWorksheet(wb, "QC_Report")
1720
  orig <- analysis_results()$original_data
 
1722
  writeData(wb, "Original_Data", orig)
1723
  writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
1724
  writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
1725
+ writeData(wb, "All_Markers_Positions", analysis_results()$all_markers_positions)
1726
+ writeData(wb, "Retained_Markers", analysis_results()$retained_markers_list)
1727
  writeData(wb, "Removal_Log", analysis_results()$removal_log)
1728
+ writeData(wb, "QC_Report", data.frame(Report=analysis_results()$qc_report))
 
1729
  saveWorkbook(wb, file, overwrite=TRUE)
1730
  }
1731
  )