about summary refs log tree commit diff
path: root/scripts
diff options
context:
space:
mode:
Diffstat (limited to 'scripts')
-rwxr-xr-xscripts/qtl2_scan.R74
1 files changed, 74 insertions, 0 deletions
diff --git a/scripts/qtl2_scan.R b/scripts/qtl2_scan.R
index 6044db3..724eb69 100755
--- a/scripts/qtl2_scan.R
+++ b/scripts/qtl2_scan.R
@@ -44,6 +44,14 @@ option_list = list(
   make_option(c("--cores"), type="integer", default=1),
   make_option(c("--cache-dir"), type="character", default=NULL,
               help="where to keep genotype probabilities and kinship"),
+  make_option(c("--nperm"), type="integer", default=0,
+              help="permutations for the LOD thresholds; 0 (default) skips them"),
+  make_option(c("--seed"), type="integer", default=NULL,
+              help="seed for the permutations, so a run is reproducible"),
+  make_option(c("--strata"), type="character", default=NULL,
+              help="permute within strata (e.g. sex): a phenotype-file-shaped column, Sample and stratum"),
+  make_option(c("--perm-out"), type="character", default=NULL,
+              help="where to write one LOD per permutation (default <out>.perm)"),
   make_option(c("--out"), type="character", required=TRUE),
   make_option(c("--quiet"), action="store_true", default=FALSE)
 )
@@ -256,3 +264,69 @@ write.csv(result, opt$out, row.names = FALSE, quote = FALSE)
 best <- result[which.max(result$lod), ]
 say(sprintf("wrote %s: %d markers; strongest %s chr%s %.1f Mb LOD %.2f",
             opt$out, nrow(result), best$marker, best$chr, best$pos, best$lod))
+
+# ---- permutations: the null distribution of the genome-wide maximum ---
+# One permutation is a whole genome scan of a shuffled phenotype, so the
+# cost is nperm x the scan above -- which is why the caller decides how
+# many, and why qtl2's own `cores` argument is used here (the permutations
+# fork cleanly, unlike scan1 on allele probabilities).
+#
+# The output is deliberately the same two-column shape R/qtl's scanone
+# permutations produce ("", "lod"), so one parser reads both. Two things
+# that are NOT the same as R/qtl, and are the caller's business:
+#   * scan1perm permutes phenotypes across individuals, which is the right
+#     null for an outbred cross and only approximate for a selfing RIL
+#     panel (qtl2perm is the statistically correct package for those);
+#   * thresholds at alpha depend on how many permutations there are: with
+#     fewer than ~100 the 0.05 quantile is a coin toss.
+if (opt$nperm > 0) {
+  perm_started <- Sys.time()
+  if (!is.null(opt$seed)) set.seed(opt$seed)
+  strata <- NULL
+  if (!is.null(opt$strata)) {
+    strata_df <- read.table(opt$strata, sep = "\t", header = TRUE,
+                            check.names = FALSE, stringsAsFactors = FALSE)
+    strata_values <- strata_df[[2]][match(ind, strata_df$Sample)]
+    if (all(is.na(strata_values))) {
+      stop("none of the stratum file's samples appear in the cross", call. = FALSE)
+    }
+    # qtl2's perm_strata is a vector *of strata per individual*, named by
+    # individual: a factor reaches get_common_ids and it answers "Not sure
+    # what to do with object of class factor". Characters, names, and the
+    # unassigned left as NA so qtl2 drops those individuals from the
+    # permutation rather than refusing.
+    strata <- stats::setNames(as.character(strata_values), ind)
+    say("permutation strata:", paste(sort(unique(strata[!is.na(strata)])), collapse = ","),
+        "|", sum(!is.na(strata)), "individuals assigned")
+  }
+  # chr_lengths from the map: without it scan1perm derives chromosome
+  # lengths from the marker positions, and the thresholds stop being
+  # comparable with R/qtl's on the same cross.
+  lengths <- qtl2::chr_lengths(map)
+  perm <- scan1perm(scan_probs, pheno, kinship = kinship, addcovar = addcovar,
+                    n_perm = opt$nperm, perm_strata = strata,
+                    chr_lengths = lengths, cores = scan_cores,
+                    model = opt$model)
+  perm_values <- as.numeric(perm)
+  if (all(is.na(perm_values))) {
+    # A placeholder or constant phenotype makes every permutation NaN
+    # without an error, and summary() then reports "0 permutations" with NA
+    # thresholds -- a plausible answer that means nothing. Refuse instead.
+    stop("every permutation returned NA (a constant or placeholder phenotype?)",
+         call. = FALSE)
+  }
+  # optparse keeps the dash in the name (`--perm-out` is opt[["perm-out"]]),
+  # so opt$perm_out is always NULL: the fallback silently took over and the
+  # file landed at <out>.perm while the caller read <out>-perm.csv.
+  perm_path <- if (is.null(opt[["perm-out"]])) paste0(opt$out, ".perm") else opt[["perm-out"]]
+  write.csv(data.frame(lod = perm_values), perm_path, row.names = FALSE,
+            quote = FALSE)
+  thresholds <- stats::quantile(perm_values, probs = c(0.99, 0.95, 0.63),
+                                na.rm = TRUE, names = FALSE)
+  say(sprintf("permutations: %d in %.1f s (%.3f s each); thresholds 0.01=%.3f 0.05=%.3f 0.37=%.3f",
+              opt$nperm,
+              as.numeric(difftime(Sys.time(), perm_started, units = "secs")),
+              as.numeric(difftime(Sys.time(), perm_started, units = "secs")) / opt$nperm,
+              thresholds[1], thresholds[2], thresholds[3]))
+  say("wrote ", perm_path, ": ", length(perm_values), " permutation maxima")
+}