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

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +262 -83
app.R CHANGED
@@ -87,8 +87,8 @@ infer_chromosome_from_marker <- function(marker_names) {
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]
@@ -167,13 +167,45 @@ detect_monomorphic_markers <- function(df) {
167
  vals <- row[!is.na(row) & !(row %in% c("-", "NA", ""))]
168
  if (length(vals) == 0) return(FALSE)
169
  unique_vals <- unique(vals[vals %in% c("a", "b", "ab")])
170
- # Monomorphic = only one allele class (e.g. all "a" or all "b"), no variation
171
  length(unique_vals) <= 1
172
  })
173
  names(is_mono) <- df$Marker
174
  is_mono
175
  }
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  # ── Impute / correct ─────────────────────────────────────────────────────────
178
  correct_errors_and_impute_missing <- function(df) {
179
  valid_geno <- c("a", "b", "ab")
@@ -301,7 +333,7 @@ scale_linkage_map <- function(linkage_map, max_total_cm, method = "proportional"
301
  }
302
 
303
  # ═══════════════════════════════════════════════════════════════════════════════
304
- # MASTER ANALYSIS β€” no chi-square, monomorphic removal added
305
  # ═══════════════════════════════════════════════════════════════════════════════
306
 
307
  create_linkage_map <- function(df,
@@ -309,7 +341,10 @@ create_linkage_map <- function(df,
309
  missing_threshold = 0.1,
310
  recombination_threshold = 0.5,
311
  max_total_cm = 1500,
312
- scaling_method = "proportional") {
 
 
 
313
 
314
  empty_result <- function(df_in = df) {
315
  list(original_data = df_in,
@@ -370,7 +405,6 @@ create_linkage_map <- function(df,
370
 
371
  if (length(mono_markers) > 0) {
372
  mono_df <- df[df$Marker %in% mono_markers, ]
373
- # For each monomorphic marker, determine which allele is fixed
374
  geno_cols_idx2 <- setdiff(3:ncol(df), which(colnames(df) == ".input_order"))
375
  details <- sapply(mono_markers, function(mk) {
376
  row <- df[df$Marker == mk, geno_cols_idx2, drop = FALSE]
@@ -379,10 +413,13 @@ create_linkage_map <- function(df,
379
  if (length(vals) == 0) return("No informative genotypes")
380
  tbl <- table(vals)
381
  dominant <- names(which.max(tbl))
382
- allele_name <- switch(dominant, a="Homozygous Parent 1 (AA)",
383
- b="Homozygous Parent 2 (BB)",
384
- ab="Heterozygous only (ab)", dominant)
385
- paste0("Fixed as: ", allele_name, " (", round(max(tbl)/sum(tbl)*100,1), "% of genotyped individuals)")
 
 
 
386
  })
387
  removal_log <- rbind(removal_log, data.frame(
388
  Marker = mono_markers,
@@ -398,18 +435,67 @@ create_linkage_map <- function(df,
398
  res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
399
  }
400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  n_after_qc <- nrow(df)
402
 
 
403
  qc_msg <- paste0(
404
- "QC Report (v4.2 β€” no chi-square filtering)\n",
405
- "==========================================\n",
406
- " Markers input : ", n_input, "\n",
407
- " Removed (missing data) : ", length(failed_miss), "\n",
408
- " Removed (monomorphic) : ", length(mono_markers), "\n",
409
- " Markers retained : ", n_after_qc, "\n\n",
410
- " NOTE: Chi-square / segregation distortion filtering is DISABLED.\n",
411
- " Marker ORDER preserved from input file.\n",
412
- " First marker of each chromosome = 0 cM.\n"
 
413
  )
414
 
415
  # ── Build positions ────────────────────────────────────────────────────────
@@ -570,15 +656,19 @@ ui <- fluidPage(
570
  .btn-primary:hover { background-color:#1E40AF; border-color:#1E3A8A; }
571
  .btn-success { background-color:#059669; color:#ffffff; border-color:#047857; }
572
  .btn-success:hover { background-color:#047857; border-color:#065F46; }
573
- .alert-info { background-color:#DBEAFE; border-color:#93C5FD; color:#1E3A8A; }
 
574
  .dataTables_wrapper { color:#333333; }
575
  table.dataTable { border:1px solid #BFDBFE; }
576
  .footer { position:fixed; bottom:0; width:100%; background-color:#1E3A8A;
577
  color:#cccccc; text-align:center; padding:10px;
578
  border-top:1px solid #1E40AF; font-size:12px; }
579
  .tab-content h3, .tab-content h4 { color:#1E3A8A; }
580
- .removal-reason-missing { color:#c0392b; font-weight:bold; }
581
- .removal-reason-mono { color:#8e44ad; font-weight:bold; }
 
 
 
582
  /* Camera capture button */
583
  #camera-btn {
584
  background: none; border: none; cursor: pointer; padding: 6px 10px;
@@ -591,7 +681,7 @@ ui <- fluidPage(
591
  "))
592
  ),
593
 
594
- navbarPage("Linkage Map Creator v4.2 β€” Input Order Preserved", id="nav",
595
 
596
  # ── Tab 1: Upload ────────────────────────────────────────────────────────
597
  tabPanel("Data Upload", icon=icon("upload"),
@@ -605,9 +695,9 @@ ui <- fluidPage(
605
  choices=c("F2"="F2","RIL"="RIL"), selected="F2"),
606
  hr(),
607
  div(class="alert alert-info",
608
- tags$b("v4.2 Key Behaviour:"), br(),
 
609
  tags$b("β€’ Monomorphic markers removed automatically"), br(),
610
- tags$b("β€’ Chi-square / segregation filter DISABLED"), br(),
611
  tags$b("β€’ Marker order from input file preserved"), br(),
612
  "β€’ First marker of every chromosome = 0 cM", br(),
613
  "β€’ Removal details shown in QC Report tab"
@@ -628,10 +718,50 @@ ui <- fluidPage(
628
  sidebarLayout(
629
  sidebarPanel(width=4, wellPanel(
630
  h3("Analysis Parameters"),
631
- sliderInput("missing_threshold", "Missing Data Threshold (per marker):",
 
 
632
  min=0, max=1, value=0.3, step=0.05),
633
- sliderInput("recombination_threshold", "Max Recombination Fraction (r):",
 
 
634
  min=0, max=0.5, value=0.45, step=0.01),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
  hr(),
636
  h4("Map Scaling"),
637
  numericInput("max_total_cm", "Max Total Map Length (cM):",
@@ -651,18 +781,20 @@ ui <- fluidPage(
651
  tags$li(tags$b("Max Recombination Fraction:"),
652
  " Pairs with r β‰₯ threshold get a 50 cM placeholder gap."),
653
  tags$li(tags$b("Monomorphic Removal:"),
654
- tags$b(" Automatic β€” no parameter needed."),
655
- " Any marker fixed as a single allele class across all individuals is removed."),
656
- tags$li(tags$b("Chi-Square Filter:"),
657
- tags$b(" Disabled in v4.2."),
658
- " All markers passing missing-data and monomorphic checks are retained."),
 
 
659
  tags$li(tags$b("Marker Order:"),
660
  tags$b(" Preserved from input file."), " No MDS reordering.")
661
  ),
662
  br(),
663
- h4("Scaling Summary"), verbatimTextOutput("scaling_summary"),
664
- h4("Before Scaling"), verbatimTextOutput("before_scaling_stats"),
665
- h4("After Scaling"), verbatimTextOutput("after_scaling_stats")
666
  ))
667
  )
668
  ),
@@ -733,14 +865,12 @@ ui <- fluidPage(
733
  column(8, selectInput("chromosome_select", "Select Chromosomes:",
734
  choices=NULL, multiple=TRUE)),
735
  column(4, br(),
736
- # Camera icon button (replaces download button)
737
  tags$button(id="camera-btn", onclick="captureChromPlot()",
738
- tags$span("\U0001F4F7"), # camera emoji
739
  tags$span("Save image", class="label")
740
  )
741
  )
742
  ),
743
- # Wrapper div for html2canvas capture
744
  div(id="chrom-plot-wrapper",
745
  style="background:white;",
746
  plotOutput("chromosome_plot", height="auto")
@@ -756,39 +886,54 @@ ui <- fluidPage(
756
  # ── Tab 7: Help ──────────────────────────────────────────────────────────
757
  tabPanel("Help", icon=icon("question-circle"),
758
  wellPanel(
759
- h3("Application Guide β€” v4.2"),
760
- h4("What's New in v4.2"),
 
761
  div(class="alert alert-info",
762
  tags$ul(
763
- tags$li(tags$b("Monomorphic marker removal added:"),
764
- " Any marker where all genotyped individuals share the same allele class ",
765
- "(e.g. all AA, or all BB) is automatically removed and logged with the ",
766
- "fixed allele and frequency."),
767
- tags$li(tags$b("Chi-square / segregation distortion filter removed:"),
768
- " All markers passing missing-data and monomorphic filters are retained. ",
769
- "Distorted but polymorphic markers are now kept."),
770
- tags$li(tags$b("Full removal log:"),
771
- " Every removed marker is listed in the QC Report tab with Marker, ",
772
- "Chromosome, Reason, and Detail columns. Downloadable as Excel."),
773
- tags$li(tags$b("Camera icon for plot saving:"),
774
- " The download button on the Visualization tab has been replaced by a ",
775
- "camera icon that uses html2canvas to capture the rendered plot exactly ",
776
- "as displayed β€” preventing the distortion caused by ggplot PNG export.")
777
  )
778
  ),
779
- h4("Monomorphic Marker Logic"),
780
- tags$ol(
781
- tags$li("Missing and non-standard genotype values are excluded before the check."),
782
- tags$li("A marker is monomorphic if only one allele class (a, b, or ab) is observed."),
783
- tags$li("The fixed allele and its frequency are reported in the removal log."),
784
- tags$li("Markers with zero informative genotypes are also flagged.")
 
 
 
 
785
  ),
 
 
 
 
 
 
 
 
 
 
786
  h4("Required Input Format"),
787
  tags$ul(
788
  tags$li("Excel (.xlsx): Column 1 = 'Marker', Column 2 = 'Chromosome'"),
789
  tags$li("Genotype columns: a/b/ab/- OR numeric 2/1/0/-1"),
790
  tags$li("Chromosome column: integer numbers OR Excel VLOOKUP formulas")
791
  ),
 
792
  h4("Genotype Encoding Reference"),
793
  tableOutput("encoding_table")
794
  )
@@ -817,7 +962,7 @@ ui <- fluidPage(
817
  ")),
818
 
819
  div(class="footer",
820
- "Linkage Map Creator v4.2 | Monomorphic removal | No chi-square | Input order preserved | Β© 2024")
821
  )
822
 
823
  # ═══════════════════════════════════════════════════════════════════════════════
@@ -884,13 +1029,23 @@ server <- function(input, output, session) {
884
 
885
  observeEvent(input$run_analysis, {
886
  req(uploaded_data())
 
 
 
 
 
 
 
 
887
  showModal(modalDialog(
888
  title="Building Linkage Map…",
889
  paste0("Population type: ", input$population_type, "\n",
890
- "Removing monomorphic markers. Chi-square filter disabled.\n",
 
891
  "Preserving input marker order…"),
892
  footer=NULL
893
  ))
 
894
  tryCatch({
895
  result <- create_linkage_map(
896
  df = uploaded_data(),
@@ -898,7 +1053,10 @@ server <- function(input, output, session) {
898
  missing_threshold = input$missing_threshold,
899
  recombination_threshold = input$recombination_threshold,
900
  max_total_cm = input$max_total_cm,
901
- scaling_method = input$scaling_method
 
 
 
902
  )
903
  analysis_results(result)
904
  chromosomes <- unique(result$linkage_map$Chromosome)
@@ -908,13 +1066,19 @@ server <- function(input, output, session) {
908
  updateSelectInput(session, "chromosome_select",
909
  choices=chr_sorted, selected=chr_sorted)
910
  removeModal()
 
911
  n_pos <- sum(!is.na(result$linkage_map$Position))
912
  n_removed <- nrow(result$removal_log)
913
- showNotification(
914
- paste0("Analysis complete! ", n_pos, " markers positioned. ",
915
- n_removed, " markers removed (see QC Report)."),
916
- type="message"
 
 
 
917
  )
 
 
918
  }, error=function(e) {
919
  removeModal()
920
  showNotification(paste("Analysis error:", e$message), type="error")
@@ -947,8 +1111,10 @@ server <- function(input, output, session) {
947
  caption=paste0(nrow(log_df), " marker(s) removed during QC")) %>%
948
  formatStyle("Reason",
949
  color=styleEqual(
950
- c("Excess missing data","Monomorphic marker"),
951
- c("#c0392b","#8e44ad")
 
 
952
  ),
953
  fontWeight="bold")
954
  })
@@ -1001,6 +1167,7 @@ server <- function(input, output, session) {
1001
  lm <- analysis_results()$linkage_map
1002
  rec <- analysis_results()$recombination_data
1003
  if (nrow(lm) == 0) return("No positioned markers.")
 
1004
  n_pos <- sum(!is.na(lm$Position))
1005
  n_chr <- length(unique(lm$Chromosome))
1006
  chr_lengths <- lm %>% filter(!is.na(Position)) %>%
@@ -1012,22 +1179,34 @@ server <- function(input, output, session) {
1012
  chr_detail <- paste(apply(chr_lengths, 1, function(x)
1013
  paste0(" Chr ", x[1], " : ", round(as.numeric(x[2]),2),
1014
  " cM (", x[3], " markers)")), collapse="\n")
1015
- n_removed_total <- nrow(analysis_results()$removal_log)
1016
- n_mono <- sum(analysis_results()$removal_log$Reason == "Monomorphic marker")
1017
- n_miss <- sum(analysis_results()$removal_log$Reason == "Excess missing data")
 
 
 
 
 
 
 
 
 
 
 
 
1018
  paste0(
1019
- "LINKAGE MAP SUMMARY (v4.2)\n",
1020
  "===========================\n",
1021
  "Population type : ", input$population_type, "\n",
1022
  "Marker order : Preserved from input file\n",
1023
- "Chi-square filter : DISABLED\n",
1024
  "First marker position : 0 cM (per chromosome)\n\n",
1025
  "Total markers input : ", nrow(analysis_results()$original_data), "\n",
1026
- " Removed (missing) : ", n_miss, "\n",
1027
- " Removed (monomorphic): ", n_mono, "\n",
 
1028
  " Total removed : ", n_removed_total, "\n",
1029
- "Markers positioned : ", n_pos, "\n",
1030
- "Chromosomes / LGs : ", n_chr, "\n",
1031
  "Total map length : ", round(total_len,2), " cM\n",
1032
  "Avg chromosome length : ", round(avg_len, 2), " cM\n",
1033
  "Marker pairs analysed : ", nrow(rec), "\n\n",
@@ -1062,7 +1241,7 @@ server <- function(input, output, session) {
1062
  }, height=function() input$plot_height)
1063
 
1064
  output$download_results <- downloadHandler(
1065
- filename=function() paste0("linkage_map_v42_", Sys.Date(), ".xlsx"),
1066
  content=function(file) {
1067
  req(analysis_results())
1068
  wb <- createWorkbook()
@@ -1073,10 +1252,10 @@ server <- function(input, output, session) {
1073
  addWorksheet(wb, "QC_Report")
1074
  orig <- analysis_results()$original_data
1075
  orig <- orig[, colnames(orig) != ".input_order", drop=FALSE]
1076
- writeData(wb, "Original_Data", orig)
1077
- writeData(wb, "Recombination_Fractions", analysis_results()$recombination_data)
1078
- writeData(wb, "Linkage_Map", analysis_results()$linkage_map)
1079
- writeData(wb, "Removal_Log", analysis_results()$removal_log)
1080
  writeData(wb, "QC_Report",
1081
  data.frame(Report=analysis_results()$qc_report))
1082
  saveWorkbook(wb, file, overwrite=TRUE)
 
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]
 
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
171
  })
172
  names(is_mono) <- df$Marker
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")
 
333
  }
334
 
335
  # ═══════════════════════════════════════════════════════════════════════════════
336
+ # MASTER ANALYSIS β€” v4.3: chi-square filter OPTIONAL (toggle in UI)
337
  # ═══════════════════════════════════════════════════════════════════════════════
338
 
339
  create_linkage_map <- function(df,
 
341
  missing_threshold = 0.1,
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,
 
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]
 
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)",
418
+ b = "Homozygous Parent 2 (BB)",
419
+ ab = "Heterozygous only (ab)",
420
+ dominant)
421
+ paste0("Fixed as: ", allele_name,
422
+ " (", round(max(tbl)/sum(tbl)*100, 1), "% of genotyped individuals)")
423
  })
424
  removal_log <- rbind(removal_log, data.frame(
425
  Marker = mono_markers,
 
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),
457
+ " (alpha = ", formatC(alpha_used, format="e", digits=3), ")")
458
+ })
459
+ removal_log <- rbind(removal_log, data.frame(
460
+ Marker = failed_chi_markers,
461
+ Chromosome = chi_df$Chromosome,
462
+ Reason = "Segregation distortion (chi-square)",
463
+ Detail = chi_details,
464
+ stringsAsFactors = FALSE
465
+ ))
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"
473
+ chi_note <- paste0(
474
+ "Chi-square filter : ENABLED\n",
475
+ " Significance : alpha = ", chi_square_alpha, " (", bonf_label, ")\n",
476
+ " Effective alpha : ", formatC(alpha_used, format="e", digits=3), "\n",
477
+ " Markers removed : ", n_failed_chi
478
+ )
479
+ }
480
+
481
+ if (nrow(df) == 0) {
482
+ res <- empty_result(df_orig); res$removal_log <- removal_log; return(res)
483
+ }
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",
494
+ " Removed (chi-square) : ", n_failed_chi, "\n",
495
+ " Markers retained : ", n_after_qc, "\n\n",
496
+ chi_note, "\n\n",
497
+ " Marker ORDER preserved from input file.\n",
498
+ " First marker of each chromosome = 0 cM.\n"
499
  )
500
 
501
  # ── Build positions ────────────────────────────────────────────────────────
 
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;
 
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
  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"
 
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):",
 
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
  ),
 
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")
 
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
  )
 
962
  ")),
963
 
964
  div(class="footer",
965
+ "Linkage Map Creator v4.3 | Chi-square optional | Monomorphic removal | Input order preserved | Β© 2024")
966
  )
967
 
968
  # ═══════════════════════════════════════════════════════════════════════════════
 
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(),
 
1053
  missing_threshold = input$missing_threshold,
1054
  recombination_threshold = input$recombination_threshold,
1055
  max_total_cm = input$max_total_cm,
1056
+ scaling_method = input$scaling_method,
1057
+ enable_chi_square = input$enable_chi_square,
1058
+ chi_square_alpha = input$chi_square_alpha,
1059
+ use_bonferroni = input$use_bonferroni
1060
  )
1061
  analysis_results(result)
1062
  chromosomes <- unique(result$linkage_map$Chromosome)
 
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")
 
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
  })
 
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)) %>%
 
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",
1211
  "Avg chromosome length : ", round(avg_len, 2), " cM\n",
1212
  "Marker pairs analysed : ", nrow(rec), "\n\n",
 
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()
 
1252
  addWorksheet(wb, "QC_Report")
1253
  orig <- analysis_results()$original_data
1254
  orig <- orig[, colnames(orig) != ".input_order", drop=FALSE]
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)