diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-12 17:31:57 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-12 17:31:57 +0000 |
| commit | 2456d66fc2c14345ab0730ef0a4ae07458af8ec6 (patch) | |
| tree | 1c82d1b789b8937cbcb6da6b33ac55ae58759ac9 | |
| parent | 8db38664938c4db10573efc0be04b3d12b249f41 (diff) | |
| download | genenetwork4-2456d66fc2c14345ab0730ef0a4ae07458af8ec6.tar.gz | |
rqtl: add POST /compute/rqtl, running GeneNetwork3's own rqtl_wrapper.R
Same request/response shape as /compute/gemma: synchronous (no job
queue), ?id= + GET /compute/rqtl/status/{run_id} progress-streaming.
Extracted that streaming infrastructure (run_streaming, create_run_log/
RunLogError, status/StatusError, RunStatus/RunStatusParams,
is_valid_run_id, COMPLETION_MARKER) out of src/gemma.rs into a new
src/streaming.rs so both compute endpoints share it instead of
duplicating it; src/routes/gemma.rs updated to the shared names,
confirmed its own 8 tests still pass unchanged.
scripts/rqtl_wrapper.R is GeneNetwork3's script, copied here verbatim
and run via Rscript -- same reasoning as reusing gemma-wrapper rather
than reimplementing GEMMA. Scope: a single scan (scanone) plus, if
nperm > 0, its permutation thresholds (67th/95th percentile, via a
Rust port of numpy.percentile's default linear interpolation) -- the
common case. Not implemented: covariates, interval mapping,
permutation strata, pair-scan (scantwo) -- scantwo in particular needs
cross-referencing the genotype file for nearest-marker lookups and a
second (MAP_) output file, a materially bigger port than this covers.
One fix relative to GeneNetwork3, found by reading the code (no test
covers the real caller's keys): generate_rqtl_cmd's content hash only
ever looks at kwargs keyed "g"/"p", but gn3/api/rqtl.py's real caller
uses keys "geno"/"pheno" -- they never match, so the genotype/
phenotype file contents never actually enter the cache-key hash in
production, only the other options. Two different phenotypes mapped
with the same other options would get the same cached output filename
and silently reuse each other's result. Fixed here: both files'
contents are always hashed (std DefaultHasher -- a cache key, not a
security boundary, so no need for GeneNetwork3's md5).
guix.scm: r, r-qtl, r-optparse, r-stringi and r-stringr added as
propagated-inputs (same category as gemma-wrapper, and same reasoning:
invoked as a subprocess, not linked). All stock Guix -- confirmed the
existing -L (needed only for gemma-wrapper, from guix-bioinformatics)
is not needed for these; the dev shell has Rscript/R-qtl on PATH from
guix.scm's own propagated-inputs alone.
Test fixture: a small, hand-written, valid BXD riset genotype/
phenotype pair (tests/test_data/rqtl_sample1.*), not GeneNetwork3's
own tests/unit/db/.../genotype_sample1.geno -- that fixture has a
genotype code outside its own header's declared set and duplicate
marker names across chromosomes, harmless for the unrelated parsing
unit it's written for there, but both would break a real R/qtl run.
Verified end to end, not just unit tested: tests/rqtl.rs runs the real
Rscript/R-qtl against that fixture (a real scanone scan, real
permutation thresholds with suggestive <= significant, the run-id-
collision 409 pre-seeded with no Rscript needed, and the completion
marker landing in a real log after the run finishes). cargo test
passes in full.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | README.md | 50 | ||||
| -rw-r--r-- | guix.scm | 26 | ||||
| -rw-r--r-- | scripts/rqtl_wrapper.R | 363 | ||||
| -rw-r--r-- | src/config.rs | 28 | ||||
| -rw-r--r-- | src/gemma.rs | 194 | ||||
| -rw-r--r-- | src/lib.rs | 6 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 39 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | src/routes/rqtl.rs | 210 | ||||
| -rw-r--r-- | src/rqtl.rs | 433 | ||||
| -rw-r--r-- | src/streaming.rs | 248 | ||||
| -rw-r--r-- | tests/rqtl.rs | 287 | ||||
| -rw-r--r-- | tests/test_data/rqtl_sample1.geno | 18 | ||||
| -rw-r--r-- | tests/test_data/rqtl_sample1.pheno | 7 |
15 files changed, 1702 insertions, 210 deletions
diff --git a/Cargo.lock b/Cargo.lock index a30f107..c886665 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3533,7 +3533,7 @@ checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "xapian-rs" version = "0.3.0" -source = "git+https://github.com/Alexanderlacuna/xapian-rs?rev=97fd34373e8f32f747f29d981271d6ec47643481#97fd34373e8f32f747f29d981271d6ec47643481" +source = "git+https://github.com/Alexanderlacuna/xapian-rs?rev=70c5eace78dbca29c434cb103cb8b2c5d4246f0d#70c5eace78dbca29c434cb103cb8b2c5d4246f0d" dependencies = [ "autocxx", "autocxx-build", diff --git a/README.md b/README.md index f7c50ce..0dbe4da 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ A Rust/Axum-based API server for GeneNetwork. | POST | `/compute/correlation` | Correlate a trait (STUB: canned data). | | POST | `/compute/gemma` | Map a QTL with GEMMA (real; not feasible yet past ~100K markers -- see below). | | GET | `/compute/gemma/status/{run_id}` | Poll a `/compute/gemma` call's progress while it's running. | +| POST | `/compute/rqtl` | Map a QTL with R/qtl (real; scanone + permutations only -- see below). | +| GET | `/compute/rqtl/status/{run_id}` | Poll a `/compute/rqtl` call's progress while it's running. | | POST | `/get-test-token` | Local callers only: get a bearer token to test with. | | GET | `/search` | Search traits (free-text; xapian query syntax). | | GET | `/openapi.json` | OpenAPI 3.1 document for all of the above. | @@ -986,6 +988,54 @@ Pass `pointer` back as `?peek=` on the next poll; `lines` is empty yet) is a 404, not an empty response -- genuinely different from "nothing new yet". +### `/compute/rqtl` + +Maps a QTL by running GeneNetwork3's own `scripts/rqtl_wrapper.R` (via +`Rscript`), copied into this repo verbatim: a `scanone` genome scan, +plus permutation thresholds if `nperm > 0`. Same request/response shape +as `/compute/gemma` -- synchronous, `?id=`/`GET .../status/{run_id}` +progress-streaming reusing the same infrastructure (`src/streaming.rs`) +-- see `src/rqtl.rs` for the invocation itself, its documented scope +(no covariates, interval mapping or pair-scan `scantwo` -- just the +common single-scan case), and a fix made relative to GeneNetwork3: +its own cache-key hashing of the genotype/phenotype files never +actually looks at their contents (a key-name mismatch between +`generate_rqtl_cmd` and its real caller), so two different phenotypes +mapped with the same other options could silently reuse each other's +cached result there; fixed here by always hashing both files' contents. + +**Important:** R/qtl's cross file format has no per-sample name +matching of its own -- `samples` must list values in exactly the +genotype file's sample-column order, or results are silently +misassigned to the wrong individual. This wrapper can't check that for +you. + +```json +{ + "data": { + "markers": [ + {"name": "rs31443144", "chr": "1", "pos": 3.010274, "lod": 0.0923496}, + {"name": "rs6269442", "chr": "1", "pos": 3.492195, "lod": 0.1131095} + ], + "permutation": null + }, + "meta": {"state": "complete", "took_ms": 420, "request_id": "..."}, + "notes": [ + "markers come from R/qtl's scanone output; permutation is null unless nperm > 0 was requested.", + "Rscript scripts/rqtl_wrapper.R --geno .../rqtl_sample1.geno --pheno .../pheno.txt --model normal --method hk --nperm 0 --scale mb --outdir /tmp/gn4-rqtl --filename <hash>-output.csv" + ], + "next": [] +} +``` + +(Real output, against the tiny 6-marker/6-sample BXD riset fixture in +`tests/test_data/`, trimmed to two markers. `permutation` is `null` +unless `nperm` was set above 0; when it is, it's +`{"values": [...], "suggestive": ..., "significant": ...}`, the 67th- +and 95th-percentile thresholds GeneNetwork3 itself uses -- computed +here with `numpy.percentile`'s default linear interpolation, +reproduced in `src/rqtl.rs`'s `percentile`.) + ## OpenAPI `GET /openapi.json` serves an OpenAPI 3.1 document covering every route. diff --git a/guix.scm b/guix.scm index 5f6e944..54d71fc 100644 --- a/guix.scm +++ b/guix.scm @@ -28,6 +28,8 @@ (gnu packages pkg-config) (gnu packages python) (gnu packages search) ; xapian: the native engine links it + (gnu packages statistics) ; r: POST /compute/rqtl + (gnu packages cran) ; r-qtl, r-optparse, r-stringi, r-stringr: ditto (gnu packages version-control) (gn packages gemma) ; gemma-wrapper: POST /compute/gemma (rust-package)) @@ -168,15 +170,23 @@ replace-with = 'vendored-sources' duckdb lmdb sqlite)) - ;; gemma-wrapper is invoked as a subprocess (src/gemma.rs), not - ;; linked, so it goes in propagated-inputs rather than inputs: the - ;; same category genenetwork3 and GN2's own guix packages use for - ;; it, so that it also lands in the profile of anyone installing - ;; this package, not just in this build's check-phase environment. - ;; It hard-wires its own gemma binary at build time (gemma-gn2, from - ;; (gn packages gemma)), so no separate gemma input is needed here. + ;; gemma-wrapper and r (plus r-qtl/r-optparse/r-stringi/r-stringr, + ;; for scripts/rqtl_wrapper.R) are invoked as subprocesses + ;; (src/gemma.rs, src/rqtl.rs), not linked, so they go in + ;; propagated-inputs rather than inputs: the same category + ;; genenetwork3 and GN2's own guix packages use for gemma-wrapper, + ;; so they also land in the profile of anyone installing this + ;; package, not just in this build's check-phase environment. + ;; gemma-wrapper hard-wires its own gemma binary at build time + ;; (gemma-gn2, from (gn packages gemma)), so no separate gemma input + ;; is needed here. (propagated-inputs - (list gemma-wrapper)) + (list gemma-wrapper + r + r-qtl + r-optparse + r-stringi + r-stringr)) (native-inputs (list git-minimal python diff --git a/scripts/rqtl_wrapper.R b/scripts/rqtl_wrapper.R new file mode 100644 index 0000000..0b39a6a --- /dev/null +++ b/scripts/rqtl_wrapper.R @@ -0,0 +1,363 @@ +library(optparse) +library(qtl) +library(stringi) +library(stringr) + + + +cat("Running the qtl script.\n") + +tmp_dir = Sys.getenv("TMPDIR") +if (!dir.exists(tmp_dir)) { + tmp_dir = "/tmp" +} + +option_list = list( + make_option(c("-g", "--geno"), type="character", help=".geno file containing a dataset's genotypes"), + make_option(c("-p", "--pheno"), type="character", help="File containing two columns - sample names and values"), + make_option(c("-c", "--addcovar"), action="store_true", default=NULL, help="Use covariates (included as extra columns in the phenotype input file)"), + make_option(c("--covarstruct"), type="character", help="File detailing which covariates are categorical or numerical"), + make_option(c("--model"), type="character", default="normal", help="Mapping Model - Normal or Non-Parametric"), + make_option(c("--method"), type="character", default="hk", help="Mapping Method - hk (Haley Knott), ehk (Extended Haley Knott), mr (Marker Regression), em (Expectation-Maximization), imp (Imputation)"), + make_option(c("--pairscan"), action="store_true", default=NULL, help="Run Pair Scan - the R/qtl function scantwo"), + make_option(c("-i", "--interval"), action="store_true", default=NULL, help="Use interval mapping"), + make_option(c("--nperm"), type="integer", default=0, help="Number of permutations"), + make_option(c("--pstrata"), action="store_true", default=NULL, help="Use permutation strata (stored as final column/vector in phenotype input file)"), + make_option(c("-s", "--scale"), type="character", default="mb", help="Mapping scale - Megabases (Mb) or Centimorgans (cM)"), + make_option(c("--control"), type="character", default=NULL, help="Name of marker (contained in genotype file) to be used as a control"), + make_option(c("-o", "--outdir"), type="character", default=file.path(tmp_dir, "gn3"), help="Directory in which to write result file"), + make_option(c("-f", "--filename"), type="character", default=NULL, help="Name to use for result file"), + make_option(c("-v", "--verbose"), action="store_true", default=TRUE, help="Show extra information") +); + +opt_parser = OptionParser(option_list=option_list); +opt = parse_args(opt_parser); + +verbose_print <- function(...){ + if (!is.null(opt$verbose)) { + for(item in list(...)){ + cat(item) + } + cat("\n") + } +} + +adjustXprobs <- function(cross){ + sex <- getsex(cross)$sex + pr <- cross$geno[["X"]]$prob + stopifnot(!is.null(pr), !is.null(sex)) + + for(i in 1:ncol(pr)) { + pr[sex==0,i,3:4] <- 0 + pr[sex==1,i,1:2] <- 0 + pr[,i,] <- pr[,i,]/rowSums(pr[,i,]) + } + cross$geno[["X"]]$prob <- pr + invisible(cross) +} + +if (is.null(opt$geno) || is.null(opt$pheno)){ + print_help(opt_parser) + stop("Both a genotype and phenotype file must be provided.", call.=FALSE) +} + +geno_file = opt$geno +pheno_file = opt$pheno + +# Generate randomized filename for cross object +cross_file = file.path(opt$outdir, "gn3", paste(stri_rand_strings(1, 8), ".cross", sep = "")) + +trim <- function( x ) { gsub("(^[[:space:]]+|[[:space:]]+$)", "", x) } + +get_geno_code <- function(header, name = 'unk'){ + mat = which(unlist(lapply(header,function(x){ length(grep(paste('@',name,sep=''), x)) })) == 1) + return(trim(strsplit(header[mat],':')[[1]][2])) +} + +geno_to_csvr <- function(genotypes, trait_names, trait_vals, out, type, sex = NULL, + mapping_scale = "Mb", verbose = FALSE){ + # Assume a geno header is not longer than 40 lines + header = readLines(genotypes, 40) + + # Major hack to skip the geno headers + toskip = which(unlist(lapply(header, function(x){ length(grep("Chr\t", x)) })) == 1) - 1 + + type <- get_geno_code(header, 'type') + + # Get the genotype codes + if(type == '4-way'){ + genocodes <- NULL + } else { + genocodes <- c(get_geno_code(header, 'mat'), get_geno_code(header, 'het'), + get_geno_code(header, 'pat')) + } + genodata <- read.csv(genotypes, sep='\t', skip=toskip, header=TRUE, + na.strings=get_geno_code(header,'unk'), + colClasses='character', comment.char = '#') + + verbose_print('Genodata:', toskip, " ", dim(genodata), genocodes, '\n') + + # If there isn't a sex phenotype, treat all as males + if(is.null(sex)) sex <- rep('m', (ncol(genodata)-4)) + + cross_items = list() + + # Add trait and covar phenotypes + for (i in 1:length(trait_names)){ + cross_items[[i]] <- c(trait_names[i], '', '', unlist(trait_vals[[i]])) + } + + # Sex phenotype for the mice + cross_items[[length(trait_names) + 1]] <- c('sex', '', '', sex) + # Genotypes + cross_items[[length(trait_names) + 2]] <- cbind(genodata[,c('Locus','Chr', mapping_scale)], + genodata[, 5:ncol(genodata)]) + + out_csvr <- do.call(rbind, cross_items) + + # Save it to a file + write.table(out_csvr, file=out, row.names=FALSE, col.names=FALSE, quote=FALSE, sep=',') + + # Load the created cross file using R/qtl read.cross + if (type == '4-way') { + verbose_print('Loading in as 4-WAY\n') + cross = read.cross(file=out, 'csvr', genotypes=NULL, crosstype="4way") + } else if(type == 'f2') { + verbose_print('Loading in as F2\n') + cross = read.cross(file=out, 'csvr', genotypes=genocodes, crosstype="f2") + } else { + verbose_print('Loading in as normal\n') + cross = read.cross(file=out, 'csvr', genotypes=genocodes) + } + if (type == 'riset') { + # If its a RIL, convert to a RIL in R/qtl + verbose_print('Converting to RISELF\n') + cross <- convert2riself(cross) + } + + return(cross) +} + +create_marker_covars <- function(the_cross, control_marker){ + #' Given a string of one or more marker names (comma separated), fetch + #' the markers' values from the genotypes and return them as vectors/a vector + #' of values + + # In case spaces are added in the string of marker names + covariate_names <- strsplit(str_replace(control_marker, " ", ""), ",") + + genotypes <- pull.geno(the_cross) + covariates_in_geno <- which(covariate_names %in% colnames(genotypes)) + covariate_names <- covariate_names[covariates_in_geno] + marker_covars <- genotypes[, unlist(covariate_names)] + + return(marker_covars) +} + +# Get phenotype vector from input file +df <- read.table(pheno_file, na.strings = "x", header=TRUE, check.names=FALSE) +sample_names <- df$Sample +trait_names <- colnames(df)[2:length(colnames(df))] + +# Since there will always only be one non-covar phenotype, its name will be in the first column +pheno_name = unlist(trait_names)[1] + +trait_vals <- vector(mode = "list", length = length(trait_names)) +for (i in 1:length(trait_names)) { + this_trait <- trait_names[i] + this_vals <- df[this_trait] + trait_vals[[i]] <- this_vals + + trait_names[i] = paste("T_", this_trait, sep = "") +} + +# Get type of genotypes, since it needs to be checked before calc.genoprob +header = readLines(geno_file, 40) +type <- get_geno_code(header, 'type') + +verbose_print('Generating cross object\n') +cross_object = geno_to_csvr(geno_file, trait_names, trait_vals, cross_file, type) + +# Calculate genotype probabilities +if (!is.null(opt$pairscan)) { + verbose_print('Calculating genotype probabilities for pair-scan\n') + cross_object <- calc.genoprob(cross_object, step=10) +} else if (!is.null(opt$interval)) { + verbose_print('Calculating genotype probabilities with interval mapping\n') + cross_object <- calc.genoprob(cross_object, step=5, stepwidth="max") +} else if (!is.null(opt$pairscan)) { + verbose_print('Calculating genotype probabilities for pair-scan\n') + cross_object <- calc.genoprob(cross_object, step=10) +} else { + verbose_print('Calculating genotype probabilities\n') + cross_object <- calc.genoprob(cross_object) +} + +# If 4way, adjust X chromosome genotype probabilities +if (type == "4-way") { + verbose_print('Adjusting genotype probabilities for 4way cross') + cross_object <- adjustXprobs(cross_object) +} + +# Pull covariates out of cross object, if they exist +covars <- c() # Holds the covariates which should be passed to R/qtl +if (!is.null(opt$addcovar)) { + verbose_print('Pulling covariates out of cross object\n') + # If perm strata are being used, it'll be included as the final column in the phenotype file + if (!is.null(opt$pstrata)) { + covar_names = trait_names[2:(length(trait_names)-1)] + } else { + covar_names = trait_names[2:length(trait_names)] + } + covars <- pull.pheno(cross_object, covar_names) + # Read in the covar description file + covarDescr <- read.table(opt$covarstruct, sep="\t", header=FALSE) + for(x in 1:nrow(covarDescr)){ + cat(covarDescr[x, 1]) + name <- paste0("T_", covarDescr[x, 1]) # The covar description file doesn't have T_ in trait names (the cross object does) + type <- covarDescr[x, 2] + if(type == "categorical"){ + verbose_print('Binding covars to covars\n') + if (nrow(covarDescr) < 2){ + this_covar = covars + } else { + this_covar = covars[,name] + } + if(length(table(this_covar)) > 2){ # More then 2 levels create the model matrix for the factor + mdata <- data.frame(toExpand = as.factor(this_covar)) + options(na.action='na.pass') + modelmatrix <- model.matrix(~ toExpand + 0, mdata)[,-1] + covars <- cbind(covars, modelmatrix) + }else{ # 2 levels? just bind the trait as covar + covars <- cbind(covars, this_covar) + } + } + } +} + +# Pull permutation strata out of cross object, if it is being used +perm_strata = vector() +if (!is.null(opt$pstrata)) { + verbose_print('Pulling permutation strata out of cross object\n') + strata_col = trait_names[length(trait_names)] + perm_strata <- pull.pheno(cross_object, strata_col) +} + +# If a marker name is supplied as covariate, get its vector of values and add them as a covariate +if (!is.null(opt$control)) { + verbose_print('Creating marker covariates and binding them to covariates vector\n') + marker_covars = create_marker_covars(cross_object, opt$control) + covars <- cbind(covars, marker_covars) +} + +if (!is.null(opt$pairscan)) { + verbose_print("Running scantwo") + scan_func <- function(...){ + scantwo(...) + } +} else { + verbose_print("Running scanone") + scan_func <- function(...){ + scanone(...) + } +} + +# Calculate permutations +if (opt$nperm > 0) { + if (!is.null(opt$filename)){ + perm_out_file = file.path(opt$outdir, "gn3", paste("PERM_", opt$filename, sep = "" )) + } else { + perm_out_file = file.path(opt$outdir, "gn3", paste(pheno_name, "_PERM_", stri_rand_strings(1, 8), sep = "")) + } + + if (!is.null(opt$addcovar) || !is.null(opt$control)){ + if (!is.null(opt$pstrata)) { + verbose_print('Running permutations with cofactors and strata\n') + perm_results = scan_func(cross_object, pheno.col=1, addcovar=covars, n.perm=opt$nperm, perm.strata=perm_strata, model=opt$model, method=opt$method) + } else { + verbose_print('Running permutations with cofactors\n') + perm_results = scan_func(cross_object, pheno.col=1, addcovar=covars, n.perm=opt$nperm, model=opt$model, method=opt$method) + } + } else { + if (!is.null(opt$pstrata)) { + verbose_print('Running permutations with strata\n') + perm_results = scan_func(cross_object, pheno.col=1, n.perm=opt$nperm, perm.strata=perm_strata, model=opt$model, method=opt$method) + } else { + verbose_print('Running permutations\n') + perm_results = scan_func(cross_object, pheno.col=1, n.perm=opt$nperm, model=opt$model, method=opt$method) + } + } + write.csv(perm_results, perm_out_file) +} + +if (!is.null(opt$filename)){ + out_file = file.path(opt$outdir, "gn3", opt$filename) +} else { + out_file = file.path(opt$outdir, "gn3", paste(pheno_name, "_", stri_rand_strings(1, 8), sep = "")) +} + +if (!is.null(opt$addcovar) || !is.null(opt$control)){ + verbose_print('Running scan with cofactors\n') + qtl_results = scan_func(cross_object, pheno.col=1, addcovar=covars, model=opt$model, method=opt$method) +} else { + verbose_print('Running scan\n') + qtl_results = scan_func(cross_object, pheno.col=1, model=opt$model, method=opt$method) +} + +verbose_print('Writing results to CSV file\n') +if (!is.null(opt$pairscan)) { + map_out_file = file.path(opt$outdir, "gn3", paste("MAP_", opt$filename, sep = "" )) + write.csv(qtl_results[1], out_file) + write.csv(qtl_results[2], map_out_file) +} else { + # QTL main effects on adjusted longevity + getEffects <- function(sdata, gtsprob, marker = "1_24042124", model = "longevity ~ sex + site + cohort + treatment", trait = "longevity"){ + rownames(sdata) <- 1:nrow(sdata) + rownames(gtsprob) <- 1:nrow(gtsprob) + mp <- gtsprob[, grep(marker, colnames(gtsprob))] + gts <- unlist(lapply(lapply(lapply(apply(mp,1,function(x){which(x > 0.85)}),names), strsplit, ":"), function(x){ + if(length(x) > 0){ return(x[[1]][2]); }else{ return(NA) } + })) + + ismissing <- which(apply(sdata, 1, function(x){any(is.na(x))})) + if(length(ismissing) > 0){ + sdata <- sdata[-ismissing, ] + gts <- gts[-ismissing] + } + + mlm <- lm(as.formula(model), data = sdata) + pheAdj <- rep(NA, nrow(sdata)) + adj <- residuals(mlm) + mean(sdata[, trait]) + pheAdj[as.numeric(names(adj))] <- adj + means <- c(mean(pheAdj[which(gts == "AC")],na.rm=TRUE),mean(pheAdj[which(gts == "AD")],na.rm=TRUE),mean(pheAdj[which(gts == "BC")],na.rm=TRUE),mean(pheAdj[which(gts == "BD")],na.rm=TRUE)) + std <- function(x) sd(x,na.rm=TRUE)/sqrt(length(x)) + stderrs <- c(std(pheAdj[which(gts == "AC")]),std(pheAdj[which(gts == "AD")]),std(pheAdj[which(gts == "BC")]),std(pheAdj[which(gts == "BD")])) + paste0(round(means,0), " ± ", round(stderrs,2)) + } + + if (type == "4-way") { + verbose_print("Get phenotype name + genoprob + all phenotypes + models for 4-way crosses") + traitname <- colnames(pull.pheno(cross_object))[1] + gtsp <- pull.genoprob(cross_object) + allpheno <- pull.pheno(cross_object) + if (!is.null(opt$addcovar)) { + model <- paste0(traitname, " ~ ", paste0(covar_names, sep="", collapse=" + ")) + } else { + model <- paste0(traitname, " ~ 1 ") + } + + meffects <- c() + verbose_print("Getting QTL main effects for 4-way crosses") + for(marker in rownames(qtl_results)){ + meff <- getEffects(allpheno, gtsp, marker = marker, model, trait = traitname) + meffects <- rbind(meffects, meff) + } + qtl_results <- cbind(data.frame(qtl_results[,1:3]), meffects) + colnames(qtl_results)[4:7] <- c("AC", "AD", "BC", "BD") + } + + + write.csv(qtl_results, out_file) +} + +cat("End of script. Now working on processing the results.\n") diff --git a/src/config.rs b/src/config.rs index 16286b5..5030576 100644 --- a/src/config.rs +++ b/src/config.rs @@ -68,6 +68,15 @@ pub struct Config { /// results between calls (its own --cache-dir switch). Defaults to /// a "gn4-gemma" directory under the system temp dir. pub gemma_cache_dir: String, + /// Path to scripts/rqtl_wrapper.R (copied here from GeneNetwork3) + /// for POST /compute/rqtl. Defaults to that path relative to the + /// working directory the server is started from. + pub rqtl_wrapper_path: String, + /// Directory POST /compute/rqtl uses for phenotype files, run logs + /// and the "gn3" subdirectory the R script itself writes its + /// output into (see src/rqtl.rs). Defaults to a "gn4-rqtl" + /// directory under the system temp dir. + pub rqtl_cache_dir: String, } impl Config { @@ -118,6 +127,17 @@ impl Config { .to_string_lossy() .into_owned(), ); + values.insert( + "RQTL_WRAPPER_PATH".to_string(), + "scripts/rqtl_wrapper.R".to_string(), + ); + values.insert( + "RQTL_CACHE_DIR".to_string(), + std::env::temp_dir() + .join("gn4-rqtl") + .to_string_lossy() + .into_owned(), + ); // Layers 2 and 3: config files, in increasing priority. for env_key in ["GN4_CONF", "GN4_SECRETS"] { @@ -145,6 +165,8 @@ impl Config { "SEARCH_ENGINE", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "RQTL_WRAPPER_PATH", + "RQTL_CACHE_DIR", ] { if let Ok(value) = std::env::var(key) { values.insert(key.to_string(), value); @@ -173,6 +195,8 @@ impl Config { dev_token_password: values["GN_AUTH_DEV_PASSWORD"].clone(), gemma_wrapper_cmd: values["GEMMA_WRAPPER_CMD"].clone(), gemma_cache_dir: values["GEMMA_CACHE_DIR"].clone(), + rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), + rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(), } } } @@ -245,6 +269,8 @@ mod tests { "SEARCH_ENGINE", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "RQTL_WRAPPER_PATH", + "RQTL_CACHE_DIR", ] { if std::env::var(key).is_ok() { eprintln!("skipping: {key} is set in the environment"); @@ -256,6 +282,8 @@ mod tests { assert_eq!(config.port, 3000); assert_eq!(config.gemma_wrapper_cmd, "gemma-wrapper"); assert!(config.gemma_cache_dir.ends_with("gn4-gemma")); + assert_eq!(config.rqtl_wrapper_path, "scripts/rqtl_wrapper.R"); + assert!(config.rqtl_cache_dir.ends_with("gn4-rqtl")); assert_eq!(config.auth_server_url, "http://127.0.0.1:8081/"); assert_eq!(config.bind, "0.0.0.0"); assert!(config.test_token_enabled, "on by default"); diff --git a/src/gemma.rs b/src/gemma.rs index c855673..9563131 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -9,16 +9,16 @@ //! respects, both found by running the real gemma-wrapper/GEMMA binaries //! against the BXD fixtures rather than trusting GeneNetwork3's own //! (entirely @unittest.skip'd) integration tests -- see `compute_gwa` -//! and `compute` below. +//! and `compute` below. Progress-streaming (`run_id`/`status`) is +//! shared infrastructure; see `crate::streaming`. use std::io; -use std::io::{Read, Seek, SeekFrom, Write}; use std::path::Path; -use std::process::{Output, Stdio}; +use std::process::Output; use serde_json::Value; -use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader}; -use tokio::process::Command; + +use crate::streaming::{self, RunLogError}; /// One phenotype value per strain (genotype-file order), or `None` for /// a missing ("NA") sample. @@ -66,6 +66,15 @@ impl std::fmt::Display for GemmaError { } } +impl From<RunLogError> for GemmaError { + fn from(e: RunLogError) -> Self { + match e { + RunLogError::AlreadyInUse(id) => GemmaError::RunIdInUse(id), + RunLogError::Io(e) => GemmaError::Io(e), + } + } +} + /// Write `values` as a GEMMA/BIMBAM phenotype file: one value per line, /// "NA" for a missing sample. Mirrors /// gn3.computations.gemma.generate_pheno_txt_file, minus its hash-based @@ -82,56 +91,6 @@ pub fn write_pheno_file(path: &Path, values: &TraitValues) -> io::Result<()> { std::fs::write(path, contents) } -/// Run `cmd`, optionally tailing its stderr into `log_path` one line at -/// a time as it runs, and return the same `Output` shape -/// `Command::output()` would have (full stdout, full stderr, exit -/// status) -- callers that don't pass `log_path` see identical -/// behaviour to the plain, non-streaming call it replaces. -/// -/// stderr, not stdout, is what's tailed: gemma-wrapper's own `--json` -/// mode sends all of its human-readable progress (banner, chromosome -/// list, "Executing: ...", per-step info/debug lines) to stderr, and -/// reserves stdout for the one final JSON record, printed once at -/// the very end (`OUTPUT = (options[:json] ? $stderr : $stdout)` in -/// bin/gemma-wrapper) -- so stdout has nothing to stream. -async fn run_streaming(cmd: &str, args: &[&str], log_path: Option<&Path>) -> io::Result<Output> { - let mut child = Command::new(cmd) - .args(args) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn()?; - let stdout_handle = child.stdout.take().expect("stdout was piped"); - let stderr_handle = child.stderr.take().expect("stderr was piped"); - - let stdout_task = tokio::spawn(async move { - let mut buf = Vec::new(); - let mut reader = stdout_handle; - let _ = reader.read_to_end(&mut buf).await; - buf - }); - - let log_path = log_path.map(Path::to_path_buf); - let stderr_task = tokio::spawn(async move { - let mut buf = Vec::new(); - let mut lines = BufReader::new(stderr_handle).lines(); - while let Ok(Some(line)) = lines.next_line().await { - if let Some(path) = &log_path { - if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { - let _ = writeln!(f, "{line}"); - } - } - buf.extend_from_slice(line.as_bytes()); - buf.push(b'\n'); - } - buf - }); - - let status = child.wait().await?; - let stdout = stdout_task.await.unwrap_or_default(); - let stderr = stderr_task.await.unwrap_or_default(); - Ok(Output { status, stdout, stderr }) -} - fn parse_wrapper_output(step: &'static str, output: Output) -> Result<Value, GemmaError> { if !output.status.success() { return Err(GemmaError::CommandFailed { @@ -180,7 +139,7 @@ async fn compute_kinship( log_path: Option<&Path>, ) -> Result<Value, GemmaError> { let args = kinship_args(cache_dir, genotype_file, pheno_file, snps_file); - let output = run_streaming(gemma_wrapper_cmd, &args, log_path) + let output = streaming::run_streaming(gemma_wrapper_cmd, &args, log_path) .await .map_err(GemmaError::Io)?; parse_wrapper_output("kinship", output) @@ -223,7 +182,7 @@ async fn compute_gwa( &lmm_str, k_json_path, ); - let output = run_streaming(gemma_wrapper_cmd, &args, log_path) + let output = streaming::run_streaming(gemma_wrapper_cmd, &args, log_path) .await .map_err(GemmaError::Io)?; parse_wrapper_output("gwa", output) @@ -287,7 +246,7 @@ fn parse_assoc_file(contents: &str) -> Vec<AssocRow> { /// about this between the two steps). async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Result<(), GemmaError> { let archive_path = Path::new(cache_dir).join(archive); - let output = run_streaming( + let output = streaming::run_streaming( "tar", &["xJf", &archive_path.to_string_lossy(), "-C", dest_dir], None, @@ -381,27 +340,6 @@ fn gwa_args<'a>( /// schema) implements `ToSchema` for `serde_json::Value` itself, but /// `Vec<serde_json::Value>` needs `Value: ComposeSchema`, which it does /// not implement in this utoipa version. -/// `run_id` must be a short token of ASCII letters, digits, `-` or `_` -/// (no path separators or `.`): it is joined straight onto `cache_dir` -/// to name the log file `status` reads back, so an unchecked value -/// would let a caller write/read outside `cache_dir` (the same -/// unchecked-`run_id`-as-path-component GeneNetwork3 does for its own -/// `/api/stream/{run_id}` -- not knowingly replicated here). -pub fn is_valid_run_id(run_id: &str) -> bool { - !run_id.is_empty() - && run_id.len() <= 64 - && run_id - .chars() - .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') -} - -/// The line `compute` appends to the log file once it finishes -/// successfully, so a `status` poller can tell "still running" apart -/// from "done" without needing a separate field -- same convention -/// GeneNetwork3 uses ("Done with GN3 Computation" in gn3/api/rqtl2.py), -/// under this project's own name. -pub const COMPLETION_MARKER: &str = "GN4: computation complete"; - pub async fn compute( gemma_wrapper_cmd: &str, cache_dir: &str, @@ -417,20 +355,10 @@ pub async fn compute( write_pheno_file(&pheno_path, trait_values).map_err(GemmaError::Io)?; let pheno_file = pheno_path.to_string_lossy().into_owned(); - // One log file for the whole request (both steps). create_new - // fails if it already exists, atomically: run_id must be unique, - // so a collision errors out here rather than silently truncating - // another run's (possibly still in-progress) log. - let log_path = run_id.map(|id| Path::new(cache_dir).join(format!("{id}.log"))); - if let Some(path) = &log_path { - match std::fs::OpenOptions::new().write(true).create_new(true).open(path) { - Ok(_) => {} - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { - return Err(GemmaError::RunIdInUse(run_id.unwrap().to_string())); - } - Err(e) => return Err(GemmaError::Io(e)), - } - } + // One log file for the whole request (both steps); see + // crate::streaming::create_run_log for why this can't silently + // collide with another run's. + let log_path = streaming::create_run_log(cache_dir, run_id)?; let kinship_note = format!( "Kinship: {gemma_wrapper_cmd} {}", @@ -496,11 +424,7 @@ pub async fn compute( } let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless - if let Some(path) = &log_path { - if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(path) { - let _ = writeln!(f, "{COMPLETION_MARKER}"); - } - } + streaming::mark_complete(&log_path); Ok(GemmaOutput { rows: Value::Array(rows), @@ -508,38 +432,6 @@ pub async fn compute( }) } -/// Why `status` (below) couldn't read a run's log. -#[derive(Debug)] -pub enum StatusError { - /// No log file for this `run_id` (unknown id, or the run hasn't - /// written anything yet -- `compute` creates the file before its - /// first subprocess call, but there is a brief window before that). - NotFound, - Io(io::Error), -} - -/// Lines appended to `run_id`'s log since byte offset `peek`, and the -/// new offset to pass as `peek` next time. Mirrors GeneNetwork3's -/// `GET /api/stream/{run_id}?peak=` (gn3/api/streaming.py, spelled -/// "peak" there), stateless in the same way: the caller tracks `peek`, -/// not the server. -pub fn status(cache_dir: &str, run_id: &str, peek: u64) -> Result<(Vec<String>, u64), StatusError> { - let path = Path::new(cache_dir).join(format!("{run_id}.log")); - let mut file = std::fs::File::open(&path).map_err(|e| { - if e.kind() == io::ErrorKind::NotFound { - StatusError::NotFound - } else { - StatusError::Io(e) - } - })?; - file.seek(SeekFrom::Start(peek)).map_err(StatusError::Io)?; - let mut buf = String::new(); - file.read_to_string(&mut buf).map_err(StatusError::Io)?; - let pointer = peek + buf.len() as u64; - let lines = buf.lines().map(str::to_string).collect(); - Ok((lines, pointer)) -} - #[cfg(test)] mod tests { use super::*; @@ -619,46 +511,4 @@ mod tests { ); assert!(!args.contains(&"-gk"), "the GWA step must never carry -gk alongside -lmm"); } - - #[test] - fn is_valid_run_id_accepts_alnum_dash_underscore() { - for ok in ["abc123", "a-b_c", "A1", "x"] { - assert!(is_valid_run_id(ok), "{ok}"); - } - } - - #[test] - fn is_valid_run_id_rejects_path_separators_and_empty() { - for bad in ["", "../etc/passwd", "a/b", "a.b", "a b", &"x".repeat(65)] { - assert!(!is_valid_run_id(bad), "{bad}"); - } - } - - #[test] - fn status_reads_from_peek_and_returns_a_new_pointer() { - let path = std::env::temp_dir().join(format!("gn4-gemma-status-test-{}", std::process::id())); - let cache_dir = path.to_str().unwrap(); - std::fs::create_dir_all(cache_dir).unwrap(); - std::fs::write(Path::new(cache_dir).join("run1.log"), "line one\nline two\n").unwrap(); - - let (lines, pointer) = status(cache_dir, "run1", 0).unwrap(); - assert_eq!(lines, vec!["line one", "line two"]); - - std::fs::OpenOptions::new() - .append(true) - .open(Path::new(cache_dir).join("run1.log")) - .unwrap() - .write_all(b"line three\n") - .unwrap(); - let (more, _) = status(cache_dir, "run1", pointer).unwrap(); - assert_eq!(more, vec!["line three"]); - - std::fs::remove_dir_all(cache_dir).unwrap(); - } - - #[test] - fn status_unknown_run_id_is_not_found() { - let err = status("/tmp", "no-such-gn4-gemma-run-id", 0).unwrap_err(); - assert!(matches!(err, StatusError::NotFound)); - } } diff --git a/src/lib.rs b/src/lib.rs index 50db2b5..75746d9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -15,6 +15,8 @@ mod gemma; pub mod response; mod routes; pub mod search; +mod streaming; +mod rqtl; use error::ApiError; use response::{Ctx, Envelope}; @@ -80,7 +82,9 @@ pub fn app() -> Router { .routes(routes!(routes::search::search)) .routes(routes!(routes::correlation::correlation)) .routes(routes!(routes::gemma::compute_gemma)) - .routes(routes!(routes::gemma::gemma_status)); + .routes(routes!(routes::gemma::gemma_status)) + .routes(routes!(routes::rqtl::compute_rqtl)) + .routes(routes!(routes::rqtl::rqtl_status)); // Registered -- and so reachable and listed in /openapi.json -- unless // GENENETWORK4_TEST_TOKEN switches it off; when registered it decides // per request whether the caller is local. See src/routes/dev.rs. diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index c79c589..5ed3336 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -12,13 +12,14 @@ use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; use crate::auth::AuthToken; use crate::config::Config; use crate::error::{ApiError, Unauthorized}; -use crate::gemma::{self, GemmaError, StatusError}; +use crate::gemma::{self, GemmaError}; use crate::response::{Ctx, Envelope, RequestInfo}; +use crate::streaming::{self, RunStatus, RunStatusParams, StatusError}; /// `?id=` on `POST /compute/gemma`: an optional, caller-chosen run id /// to log this run's progress under and poll back via `GET @@ -31,24 +32,6 @@ pub struct ComputeGemmaParams { pub id: Option<String>, } -#[derive(Deserialize, utoipa::IntoParams)] -pub struct GemmaStatusParams { - /// Byte offset already read; 0 to read from the start. Echoed back - /// (grown) as `pointer` in the response -- pass that next time. - pub peek: Option<u64>, -} - -#[derive(Serialize, utoipa::ToSchema)] -pub struct GemmaStatus { - pub run_id: String, - /// New lines of gemma-wrapper's stderr (its progress output under - /// --json) since `peek`. The last line, once the run has finished, - /// is the completion marker (`gemma::COMPLETION_MARKER`). - pub lines: Vec<String>, - /// The new byte offset; pass this back as `peek` next poll. - pub pointer: u64, -} - #[derive(Deserialize, utoipa::ToSchema)] pub struct GemmaRequest { /// Path to a BIMBAM genotype file (plain text or gzipped), passed @@ -112,7 +95,7 @@ pub async fn compute_gemma( .with_request_id(rid)); } if let Some(id) = ¶ms.id { - if !gemma::is_valid_run_id(id) { + if !streaming::is_valid_run_id(id) { return Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_run_id", @@ -164,9 +147,9 @@ for this run_id since byte offset `peek`, and a new `pointer` to pass as \ `peek` next time. Call this on a second connection while the POST is \ still in flight, the same tail-the-log-file shape GeneNetwork2/3 use for \ R/qtl.", - params(("run_id" = String, Path, description = "The id passed as ?id= on the POST"), GemmaStatusParams), + params(("run_id" = String, Path, description = "The id passed as ?id= on the POST"), RunStatusParams), responses( - (status = 200, description = "New log lines and the new pointer", body = Envelope<GemmaStatus>), + (status = 200, description = "New log lines and the new pointer", body = Envelope<RunStatus>), Unauthorized, (status = 404, description = "No run with this id (unknown, or not started yet)", body = ApiError), (status = 422, description = "run_id not alnum/-/_ (max 64 chars)", body = ApiError) @@ -175,10 +158,10 @@ pub async fn gemma_status( ctx: Ctx, _token: AuthToken, Path(run_id): Path<String>, - Query(params): Query<GemmaStatusParams>, -) -> Result<Json<Envelope<GemmaStatus>>, ApiError> { + Query(params): Query<RunStatusParams>, +) -> Result<Json<Envelope<RunStatus>>, ApiError> { let rid = ctx.request_info(); - if !gemma::is_valid_run_id(&run_id) { + if !streaming::is_valid_run_id(&run_id) { return Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_run_id", @@ -190,9 +173,9 @@ pub async fn gemma_status( } let config = Config::load(); let peek = params.peek.unwrap_or(0); - gemma::status(&config.gemma_cache_dir, &run_id, peek) + streaming::status(&config.gemma_cache_dir, &run_id, peek) .map(|(lines, pointer)| { - Json(ctx.envelope(GemmaStatus { + Json(ctx.envelope(RunStatus { run_id: run_id.clone(), lines, pointer, diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 3a9f3e3..d050616 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -11,6 +11,7 @@ pub mod gemma; pub mod groups; pub mod mapping_methods; pub mod publications; +pub mod rqtl; pub mod search; pub mod species; pub mod traits; diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs new file mode 100644 index 0000000..0cc7d23 --- /dev/null +++ b/src/routes/rqtl.rs @@ -0,0 +1,210 @@ +//! Compute domain: /compute/rqtl runs GeneNetwork3's own +//! `scripts/rqtl_wrapper.R` (via `Rscript`) to map a QTL from a +//! genotype file and trait values, the same shape as `/compute/gemma` +//! including its progress-streaming `?id=`/`GET .../status/{run_id}` +//! pair -- see `crate::streaming` for that and `crate::rqtl` for the +//! invocation and its documented scope (single scan + permutations; +//! no covariates, interval mapping or pair-scan). + +use axum::Json; +use axum::extract::{Path, Query}; +use axum::http::StatusCode; +use serde::Deserialize; + +use crate::auth::AuthToken; +use crate::config::Config; +use crate::error::{ApiError, Unauthorized}; +use crate::response::{Ctx, Envelope, RequestInfo}; +use crate::rqtl::{self, RqtlError, Sample}; +use crate::streaming::{self, RunStatus, RunStatusParams, StatusError}; + +/// `?id=` on `POST /compute/rqtl`: same as `/compute/gemma`'s -- an +/// optional, caller-chosen, unique run id to log progress under and +/// poll back via `GET /compute/rqtl/status/{id}`. +#[derive(Deserialize, utoipa::IntoParams)] +pub struct ComputeRqtlParams { + pub id: Option<String>, +} + +#[derive(Deserialize, utoipa::ToSchema)] +pub struct RqtlSample { + /// Must match the genotype file's sample-column order exactly; see + /// `crate::rqtl`'s module doc for why (R/qtl's cross format has no + /// per-sample name matching of its own). + pub name: String, + pub value: Option<f64>, +} + +#[derive(Deserialize, utoipa::ToSchema)] +pub struct RqtlRequest { + /// Path to an R/qtl-format `.geno` file (riset/F2/4-way; `@type:` + /// in its header). + pub genotype_file: String, + pub trait_name: String, + pub samples: Vec<RqtlSample>, + /// R/qtl's `--model`: "normal" or "np" (non-parametric). Defaults + /// to "normal". + pub model: Option<String>, + /// R/qtl's `--method`: hk, ehk, mr, em or imp. Defaults to "hk" + /// (Haley-Knott), the R script's own default. + pub method: Option<String>, + /// Number of permutations; 0 (default) skips permutation testing + /// entirely. + pub nperm: Option<u32>, + /// R/qtl's `--scale`: "mb" or "cm". Defaults to "mb", the R + /// script's own default; note the script's `geno_to_csvr` call site + /// does not actually forward this option to its mapping-scale + /// parameter (always "Mb" regardless) -- a latent inconsistency in + /// the script itself, not fixed here since it's GeneNetwork3's own + /// script, copied verbatim. + pub scale: Option<String>, + /// A marker name (from the genotype file) to use as a covariate. + pub control: Option<String>, +} + +#[utoipa::path(post, path = "/compute/rqtl", + summary = "Map a QTL from a genotype file and trait values using R/qtl", + description = "Runs GeneNetwork3's scripts/rqtl_wrapper.R (scanone, \ +plus permutations if nperm > 0) and returns the parsed marker results. \ +Pass ?id= to log progress for GET /compute/rqtl/status/{id} to poll \ +concurrently -- same shape as /compute/gemma.", + params(ComputeRqtlParams), + request_body = RqtlRequest, + responses( + (status = 200, description = "Mapped QTL markers (and, if requested, permutation thresholds)", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 409, description = "id is already in use by another run", body = ApiError), + (status = 422, description = "id not alnum/-/_ (max 64 chars)", body = ApiError), + (status = 502, description = "Rscript or rqtl_wrapper.R failed", body = ApiError) + ))] +pub async fn compute_rqtl( + ctx: Ctx, + _token: AuthToken, + Query(params): Query<ComputeRqtlParams>, + Json(request): Json<RqtlRequest>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + if let Some(id) = ¶ms.id { + if !streaming::is_valid_run_id(id) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_run_id", + "Invalid id", + "id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), + "compute_rqtl", + ) + .with_request_id(rid)); + } + } + + let config = Config::load(); + let samples: Vec<Sample> = request + .samples + .into_iter() + .map(|s| Sample { name: s.name, value: s.value }) + .collect(); + rqtl::compute( + &config.rqtl_wrapper_path, + &config.rqtl_cache_dir, + &request.genotype_file, + &request.trait_name, + &samples, + request.model.as_deref().unwrap_or("normal"), + request.method.as_deref().unwrap_or("hk"), + request.nperm.unwrap_or(0), + request.scale.as_deref().unwrap_or("mb"), + request.control.as_deref(), + params.id.as_deref(), + ) + .await + .map(|output| { + let notes = output.notes.clone(); + let mut envelope = ctx.envelope(rqtl::to_json(output)).with_note( + "markers come from R/qtl's scanone output; permutation is null unless nperm > 0 was requested.", + ); + for note in ¬es { + envelope = envelope.with_note(note); + } + Json(envelope) + }) + .map_err(|e| match e { + RqtlError::RunIdInUse(id) => ApiError::new( + StatusCode::CONFLICT, + "run_id_in_use", + "Run id already in use", + format!("id '{id}' is already in use; pick a different id."), + "compute_rqtl", + ) + .with_request_id(rid.clone()), + other => rqtl_error_to_api_error(other, rid.clone()), + }) +} + +#[utoipa::path(get, path = "/compute/rqtl/status/{run_id}", + summary = "Poll a running (or finished) /compute/rqtl call's progress", + description = "Same as GET /compute/gemma/status/{run_id}, against \ +the run_id passed as ?id= on POST /compute/rqtl.", + params(("run_id" = String, Path, description = "The id passed as ?id= on the POST"), RunStatusParams), + responses( + (status = 200, description = "New log lines and the new pointer", body = Envelope<RunStatus>), + Unauthorized, + (status = 404, description = "No run with this id (unknown, or not started yet)", body = ApiError), + (status = 422, description = "run_id not alnum/-/_ (max 64 chars)", body = ApiError) + ))] +pub async fn rqtl_status( + ctx: Ctx, + _token: AuthToken, + Path(run_id): Path<String>, + Query(params): Query<RunStatusParams>, +) -> Result<Json<Envelope<RunStatus>>, ApiError> { + let rid = ctx.request_info(); + if !streaming::is_valid_run_id(&run_id) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_run_id", + "Invalid run_id", + "run_id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), + "rqtl_status", + ) + .with_request_id(rid)); + } + let config = Config::load(); + let peek = params.peek.unwrap_or(0); + streaming::status(&config.rqtl_cache_dir, &run_id, peek) + .map(|(lines, pointer)| { + Json(ctx.envelope(RunStatus { + run_id: run_id.clone(), + lines, + pointer, + })) + }) + .map_err(|e| match e { + StatusError::NotFound => ApiError::new( + StatusCode::NOT_FOUND, + "run_not_found", + "Run not found", + format!("No run with id '{run_id}' (unknown, or not started yet)."), + "rqtl_status", + ) + .with_request_id(rid), + StatusError::Io(err) => ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + err.to_string(), + "rqtl_status", + ) + .with_request_id(rid), + }) +} + +fn rqtl_error_to_api_error(error: RqtlError, rid: RequestInfo) -> ApiError { + ApiError::new( + StatusCode::BAD_GATEWAY, + "rqtl_failed", + "R/qtl computation failed", + error.to_string(), + "compute_rqtl", + ) + .with_request_id(rid) +} diff --git a/src/rqtl.rs b/src/rqtl.rs new file mode 100644 index 0000000..d68f7e8 --- /dev/null +++ b/src/rqtl.rs @@ -0,0 +1,433 @@ +//! Core logic for POST /compute/rqtl: run GeneNetwork3's own +//! `scripts/rqtl_wrapper.R` (copied here verbatim) via `Rscript` against +//! a genotype file and trait values, and parse the resulting R/qtl +//! `scanone` (and, if requested, permutation) output into QTL mapping +//! rows. +//! +//! Mirrors gn3/computations/rqtl.py and gn3/api/rqtl.py (GeneNetwork3), +//! but synchronously, for the same reason as `crate::gemma`: axum/tokio +//! can await the subprocess directly, no job queue needed. +//! Progress-streaming (`run_id`/`status`) is the shared +//! `crate::streaming` infrastructure. +//! +//! Scope: a single scan (`scanone`) plus, if `nperm > 0`, its +//! permutation thresholds -- the common case, and the one actually +//! exercised against the real script below. Covariates (`addcovar`, +//! `covarstruct`), interval mapping, permutation strata and pair-scan +//! (`scantwo`, GeneNetwork3's `process_rqtl_pairscan`) are not +//! implemented: pair-scan in particular needs cross-referencing the +//! genotype file for nearest-marker lookups and a second (`MAP_`) +//! output file, a materially bigger port than this covers. +//! +//! One fix relative to GeneNetwork3, found by reading the code (not by +//! hitting it live -- this path has no test covering the real caller's +//! keys): `generate_rqtl_cmd`'s content hash only ever looks at kwargs +//! literally keyed `"g"`/`"p"` (`k in ["g", "p"]`), but +//! `gn3/api/rqtl.py`'s real caller builds its kwargs dict with keys +//! `"geno"`/`"pheno"` -- the two never match, so the genotype/phenotype +//! file *contents* never actually enter the uniqueness hash in +//! production, only the other options (model, method, ...). Two +//! different phenotypes mapped with otherwise-identical options would +//! get the same cached output filename and silently reuse each other's +//! result. Fixed here: the genotype and phenotype file contents are +//! always hashed, unconditionally. +//! +//! Important, easily-missed correctness requirement inherited from the +//! R script itself, not something this wrapper can check: R/qtl's +//! `csvr` cross format has no per-sample name matching at all -- +//! phenotype rows are joined to genotype columns purely by position. +//! `samples` here must list values in exactly the genotype file's +//! sample-column order, or results will be silently misassigned to the +//! wrong individual. + +use std::io; +use std::path::Path; + +use serde::Serialize; +use serde_json::Value; + +use crate::streaming::{self, RunLogError}; + +#[derive(Debug)] +pub enum RqtlError { + Io(io::Error), + /// Rscript exited non-zero; carries its stderr. + CommandFailed(String), + /// The main or permutation output CSV could not be read or parsed. + OutputFile(io::Error), + /// `run_id` already has a log file; see `crate::gemma::GemmaError`'s + /// variant of the same name for why this is caught before any + /// subprocess runs. + RunIdInUse(String), +} + +impl std::fmt::Display for RqtlError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RqtlError::Io(e) => write!(f, "failed to run Rscript: {e}"), + RqtlError::CommandFailed(stderr) => write!(f, "rqtl_wrapper.R failed: {stderr}"), + RqtlError::OutputFile(e) => write!(f, "could not read R/qtl output: {e}"), + RqtlError::RunIdInUse(id) => { + write!(f, "run id '{id}' is already in use; pick a different id") + } + } + } +} + +impl From<RunLogError> for RqtlError { + fn from(e: RunLogError) -> Self { + match e { + RunLogError::AlreadyInUse(id) => RqtlError::RunIdInUse(id), + RunLogError::Io(e) => RqtlError::Io(e), + } + } +} + +/// One sample's name and trait value (`None` for missing -- written as +/// the literal string `x`, the R script's own `na.strings`, not `NA` +/// like `crate::gemma`'s pheno file convention). +pub struct Sample { + pub name: String, + pub value: Option<f64>, +} + +/// Write the phenotype file R/qtl's wrapper script expects: +/// `read.table(..., na.strings = "x", header = TRUE)`, a `Sample` +/// column plus one named trait column. +pub fn write_pheno_file(path: &Path, trait_name: &str, samples: &[Sample]) -> io::Result<String> { + let mut contents = format!("Sample\t{trait_name}\n"); + for sample in samples { + contents.push_str(&sample.name); + contents.push('\t'); + match sample.value { + Some(v) => contents.push_str(&v.to_string()), + None => contents.push('x'), + } + contents.push('\n'); + } + std::fs::write(path, &contents)?; + Ok(contents) +} + +/// A cheap, dependency-free (std `DefaultHasher`/`SipHash`) stable hash +/// for a cache-key filename -- not cryptographic, and not meant to be; +/// GeneNetwork3's own `generate_hash_of_string` uses md5 for the same +/// non-adversarial purpose. +fn hash_str(s: &str) -> String { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + let mut h = DefaultHasher::new(); + s.hash(&mut h); + format!("{:016x}", h.finish()) +} + +/// The `Rscript` arguments for one `scripts/rqtl_wrapper.R` invocation, +/// shared between the actual call and the note describing it (see +/// `compute`), so the two can never drift apart. +fn rqtl_args<'a>( + wrapper_path: &'a str, + genotype_file: &'a str, + pheno_file: &'a str, + model: &'a str, + method: &'a str, + nperm_str: &'a str, + scale: &'a str, + control: Option<&'a str>, + outdir: &'a str, + filename: &'a str, +) -> Vec<&'a str> { + let mut args = vec![ + wrapper_path, + "--geno", + genotype_file, + "--pheno", + pheno_file, + "--model", + model, + "--method", + method, + "--nperm", + nperm_str, + "--scale", + scale, + ]; + if let Some(control) = control { + args.push("--control"); + args.push(control); + } + args.push("--outdir"); + args.push(outdir); + args.push("--filename"); + args.push(filename); + args +} + +/// One row of R/qtl's main scanone output CSV (`name`, `chr`, `pos`, +/// `lod`). GeneNetwork3's `process_rqtl_mapping` also handles an +/// extended 4-way-cross shape with four extra mean/SE effect columns; +/// not reproduced here since this port's test fixture (and the common +/// case) is a 2-allele riset/F2 cross -- flagged, not silently dropped, +/// if ever hit (`extra` carries anything past the four known columns). +#[derive(Debug, Serialize, utoipa::ToSchema, PartialEq)] +pub struct MarkerResult { + pub name: String, + pub chr: String, + pub pos: f64, + pub lod: f64, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub extra: Vec<String>, +} + +/// Parse R/qtl's main output CSV: `"","chr","pos","lod"` header, then +/// `"name","chr",pos,lod[,...]` rows (name and chr quoted; pos, lod and +/// any extra columns are not). Confirmed by actually running +/// `scripts/rqtl_wrapper.R` against the BXD riset fixture. +fn parse_mapping_output(contents: &str) -> Vec<MarkerResult> { + contents + .lines() + .skip(1) // header + .filter(|line| !line.is_empty()) + .filter_map(|line| { + let fields: Vec<&str> = line.split(',').collect(); + if fields.len() < 4 { + return None; + } + let unquote = |s: &str| s.trim_matches('"').to_string(); + Some(MarkerResult { + name: unquote(fields[0]), + chr: unquote(fields[1]), + pos: fields[2].parse().ok()?, + lod: fields[3].parse().ok()?, + extra: fields[4..].iter().map(|s| unquote(s)).collect(), + }) + }) + .collect() +} + +/// R/qtl's permutation thresholds: every permutation's LOD, and the +/// suggestive (67th percentile) / significant (95th percentile) +/// thresholds GeneNetwork3 computes from them +/// (`gn3.computations.rqtl.process_perm_output`, via `numpy.percentile` +/// with its default linear interpolation, reproduced in `percentile` +/// below). +#[derive(Debug, Serialize, utoipa::ToSchema, PartialEq)] +pub struct PermutationResult { + pub values: Vec<f64>, + pub suggestive: f64, + pub significant: f64, +} + +/// Parse R/qtl's permutation output CSV: `"","lod"` header, then +/// `"1",value` rows. Confirmed by actually running +/// `scripts/rqtl_wrapper.R --nperm 50` against the BXD riset fixture. +fn parse_permutation_output(contents: &str) -> Vec<f64> { + contents + .lines() + .skip(1) + .filter(|line| !line.is_empty()) + .filter_map(|line| line.split(',').nth(1)?.parse().ok()) + .collect() +} + +/// `numpy.percentile`'s default ("linear") interpolation: for a +/// 0-indexed sorted array of length `n`, the percentile-`p` position is +/// `(n-1) * p/100`; a fractional position interpolates linearly between +/// its floor and ceiling. +fn percentile(sorted: &[f64], p: f64) -> f64 { + match sorted.len() { + 0 => f64::NAN, + 1 => sorted[0], + n => { + let idx = (n - 1) as f64 * p / 100.0; + let lo = idx.floor() as usize; + let hi = idx.ceil() as usize; + if lo == hi { + sorted[lo] + } else { + sorted[lo] + (sorted[hi] - sorted[lo]) * (idx - lo as f64) + } + } + } +} + +pub struct RqtlOutput { + pub markers: Vec<MarkerResult>, + pub permutation: Option<PermutationResult>, + pub notes: Vec<String>, +} + +/// Run `scripts/rqtl_wrapper.R` (`scanone`, plus permutations if +/// `nperm > 0`) and return the parsed results. +#[allow(clippy::too_many_arguments)] +pub async fn compute( + r_wrapper_path: &str, + cache_dir: &str, + genotype_file: &str, + trait_name: &str, + samples: &[Sample], + model: &str, + method: &str, + nperm: u32, + scale: &str, + control: Option<&str>, + run_id: Option<&str>, +) -> Result<RqtlOutput, RqtlError> { + // The R script hardcodes its own output directory as + // "{outdir}/gn3/..." (both the cross file it builds and every + // result file it writes), so that subdirectory has to exist first, + // same as GeneNetwork3's own api/rqtl.py (`os.mkdir(outdir)`) does. + let outdir = Path::new(cache_dir).join("gn3"); + std::fs::create_dir_all(&outdir).map_err(RqtlError::Io)?; + + let unique = format!( + "{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + ); + let pheno_path = Path::new(cache_dir).join(format!("{unique}-pheno.txt")); + let pheno_contents = + write_pheno_file(&pheno_path, trait_name, samples).map_err(RqtlError::Io)?; + let pheno_file = pheno_path.to_string_lossy().into_owned(); + + let geno_contents = std::fs::read(genotype_file).map_err(RqtlError::Io)?; + let options_key = format!("{model},{method},{nperm},{scale},{control:?}"); + let filename = format!( + "{}-output.csv", + hash_str(&format!( + "{}{pheno_contents}{options_key}", + String::from_utf8_lossy(&geno_contents) + )) + ); + + let log_path = streaming::create_run_log(cache_dir, run_id)?; + + let nperm_str = nperm.to_string(); + let args = rqtl_args( + r_wrapper_path, + genotype_file, + &pheno_file, + model, + method, + &nperm_str, + scale, + control, + cache_dir, + &filename, + ); + let note = format!("Rscript {}", args.join(" ")); + let output = streaming::run_streaming("Rscript", &args, log_path.as_deref()) + .await + .map_err(RqtlError::Io)?; + if !output.status.success() { + return Err(RqtlError::CommandFailed( + String::from_utf8_lossy(&output.stderr).into_owned(), + )); + } + + let main_contents = std::fs::read_to_string(outdir.join(&filename)).map_err(RqtlError::OutputFile)?; + let markers = parse_mapping_output(&main_contents); + + let permutation = if nperm > 0 { + let perm_contents = std::fs::read_to_string(outdir.join(format!("PERM_{filename}"))) + .map_err(RqtlError::OutputFile)?; + let values = parse_permutation_output(&perm_contents); + let mut sorted = values.clone(); + sorted.sort_by(|a, b| a.partial_cmp(b).unwrap()); + Some(PermutationResult { + suggestive: percentile(&sorted, 67.0), + significant: percentile(&sorted, 95.0), + values, + }) + } else { + None + }; + + streaming::mark_complete(&log_path); + + Ok(RqtlOutput { + markers, + permutation, + notes: vec![note], + }) +} + +/// `RqtlOutput` as the single JSON value the route returns -- see +/// `crate::gemma`'s own note on why `serde_json::Value`, not a `Vec`, +/// is what utoipa needs here. +pub fn to_json(output: RqtlOutput) -> Value { + serde_json::json!({ + "markers": output.markers, + "permutation": output.permutation, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn write_pheno_file_uses_x_for_missing_and_a_named_trait_column() { + let path = std::env::temp_dir().join(format!("gn4-rqtl-test-{}", std::process::id())); + let samples = vec![ + Sample { name: "BXD1".to_string(), value: Some(9.5) }, + Sample { name: "BXD2".to_string(), value: None }, + ]; + write_pheno_file(&path, "mytrait", &samples).unwrap(); + let contents = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(contents, "Sample\tmytrait\nBXD1\t9.5\nBXD2\tx\n"); + } + + #[test] + fn parse_mapping_output_strips_quotes_from_name_and_chr_only() { + let contents = "\"\",\"chr\",\"pos\",\"lod\"\n\"rs1\",\"1\",3.01,0.092\n\"rs2\",\"2\",5.01,0.013\n"; + let rows = parse_mapping_output(contents); + assert_eq!( + rows, + vec![ + MarkerResult { name: "rs1".into(), chr: "1".into(), pos: 3.01, lod: 0.092, extra: vec![] }, + MarkerResult { name: "rs2".into(), chr: "2".into(), pos: 5.01, lod: 0.013, extra: vec![] }, + ] + ); + } + + #[test] + fn parse_mapping_output_keeps_extra_effect_columns_for_4way_crosses() { + let contents = "\"\",\"chr\",\"pos\",\"lod\",\"AC\",\"AD\"\n\"rs1\",\"1\",3.01,0.092,\"5 ± 1\",\"6 ± 2\"\n"; + let rows = parse_mapping_output(contents); + assert_eq!(rows[0].extra, vec!["5 \u{b1} 1", "6 \u{b1} 2"]); + } + + #[test] + fn parse_permutation_output_skips_header_and_reads_the_second_column() { + let contents = "\"\",\"lod\"\n\"1\",0.54\n\"2\",0.10\n"; + assert_eq!(parse_permutation_output(contents), vec![0.54, 0.10]); + } + + #[test] + fn percentile_matches_numpy_linear_interpolation() { + let sorted = vec![1.0, 2.0, 3.0, 4.0, 5.0]; + assert_eq!(percentile(&sorted, 0.0), 1.0); + assert_eq!(percentile(&sorted, 100.0), 5.0); + assert_eq!(percentile(&sorted, 50.0), 3.0); + // index = (5-1)*25/100 = 1.0 exactly -> sorted[1] = 2.0 + assert_eq!(percentile(&sorted, 25.0), 2.0); + // index = (5-1)*67/100 = 2.68 -> interpolate sorted[2]..sorted[3] + assert!((percentile(&sorted, 67.0) - 3.68).abs() < 1e-9); + } + + #[test] + fn rqtl_args_includes_control_only_when_given() { + let with_control = rqtl_args( + "wrapper.R", "g.geno", "p.txt", "normal", "hk", "0", "cM", Some("rs1"), "/out", "f.csv", + ); + assert!(with_control.contains(&"--control")); + let without = rqtl_args( + "wrapper.R", "g.geno", "p.txt", "normal", "hk", "0", "cM", None, "/out", "f.csv", + ); + assert!(!without.contains(&"--control")); + } +} diff --git a/src/streaming.rs b/src/streaming.rs new file mode 100644 index 0000000..90ce0f4 --- /dev/null +++ b/src/streaming.rs @@ -0,0 +1,248 @@ +//! Shared infrastructure for compute endpoints that run a long external +//! process and want to show progress while it's still running: tail a +//! subprocess's stderr into a per-run log file as it runs, and let a +//! second connection poll that log while the first is still blocked. +//! Used by `crate::gemma` and `crate::rqtl`, which both call a +//! different external tool (gemma-wrapper, Rscript) but need exactly +//! this same shape. Mirrors GeneNetwork2/3's own equivalent +//! (gn3/computations/streaming.py, gn3/api/streaming.py), used there +//! for R/qtl. + +use std::io; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Output, Stdio}; + +use serde::{Deserialize, Serialize}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader}; +use tokio::process::Command; + +/// `?peek=` on a status-polling endpoint: the byte offset already +/// read; 0 to read from the start. +#[derive(Deserialize, utoipa::IntoParams)] +pub struct RunStatusParams { + pub peek: Option<u64>, +} + +/// A status-polling endpoint's response: new log lines since `peek`, +/// and the new offset to pass as `peek` next time. +#[derive(Serialize, utoipa::ToSchema)] +pub struct RunStatus { + pub run_id: String, + /// New lines of the subprocess's stderr since `peek`. The last + /// line, once the run has finished, is `COMPLETION_MARKER`. + pub lines: Vec<String>, + /// The new byte offset; pass this back as `peek` next poll. + pub pointer: u64, +} + +/// A short token of ASCII letters, digits, `-` or `_` (no path +/// separators or `.`). `run_id` is joined straight onto a cache +/// directory to name the log file `status` reads back, so an unchecked +/// value would let a caller write/read outside it -- the same +/// unchecked-`run_id`-as-path-component GeneNetwork3 does for its own +/// `/api/stream/{run_id}`, not knowingly replicated here. +pub fn is_valid_run_id(run_id: &str) -> bool { + !run_id.is_empty() + && run_id.len() <= 64 + && run_id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +/// The line appended to a run's log once it finishes successfully, so +/// a `status` poller can tell "still running" apart from "done" without +/// a separate field -- same convention GeneNetwork3 uses ("Done with +/// GN3 Computation" in gn3/api/rqtl2.py), under this project's own +/// name. +pub const COMPLETION_MARKER: &str = "GN4: computation complete"; + +/// Why `create_run_log` couldn't start a run's log. +#[derive(Debug)] +pub enum RunLogError { + /// `run_id` already has a log file: a run with that id is in + /// progress, or finished and was never polled/cleaned up. + AlreadyInUse(String), + Io(io::Error), +} + +/// Atomically create a fresh, empty log file for `run_id` under +/// `cache_dir` (`None` if `run_id` is `None` -- no streaming wanted), +/// returning its path. `create_new` fails if the file already exists, +/// so a reused id errors out here rather than silently truncating +/// another run's (possibly still in-progress) log -- there is no +/// separate check-then-write step to race. +pub fn create_run_log(cache_dir: &str, run_id: Option<&str>) -> Result<Option<PathBuf>, RunLogError> { + let Some(id) = run_id else { return Ok(None) }; + let path = Path::new(cache_dir).join(format!("{id}.log")); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(_) => Ok(Some(path)), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + Err(RunLogError::AlreadyInUse(id.to_string())) + } + Err(e) => Err(RunLogError::Io(e)), + } +} + +/// Append `COMPLETION_MARKER` to `log_path`, if there is one. Best +/// effort: a failure here (e.g. the log was deleted mid-run) is not +/// worth failing an otherwise-successful computation over. +pub fn mark_complete(log_path: &Option<PathBuf>) { + if let Some(path) = log_path { + if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(path) { + let _ = writeln!(f, "{COMPLETION_MARKER}"); + } + } +} + +/// Run `cmd`, optionally tailing its stderr into `log_path` one line at +/// a time as it runs, and return the same `Output` shape +/// `Command::output()` would have (full stdout, full stderr, exit +/// status) -- callers that don't pass `log_path` see identical +/// behaviour to the plain, non-streaming call it replaces. +/// +/// stderr, not stdout, is what's tailed. For gemma-wrapper, all of its +/// human-readable `--json`-mode progress goes to stderr, with stdout +/// reserved for the one final JSON record (see `crate::gemma`'s own +/// note on this). R/qtl's wrapper script is simpler: its `cat(...)` and +/// `verbose_print(...)` calls just go to stdout by default, but run +/// under `Rscript` with nothing redirecting it, so stderr still carries +/// R's own progress/warning output (package load messages, warnings) -- +/// tailing stderr here is a deliberate, uniform choice across both +/// tools' call sites, not a guarantee every line of every tool's +/// progress ends up in the log. +pub async fn run_streaming(cmd: &str, args: &[&str], log_path: Option<&Path>) -> io::Result<Output> { + let mut child = Command::new(cmd) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + let stdout_handle = child.stdout.take().expect("stdout was piped"); + let stderr_handle = child.stderr.take().expect("stderr was piped"); + + let stdout_task = tokio::spawn(async move { + let mut buf = Vec::new(); + let mut reader = stdout_handle; + let _ = reader.read_to_end(&mut buf).await; + buf + }); + + let log_path = log_path.map(Path::to_path_buf); + let stderr_task = tokio::spawn(async move { + let mut buf = Vec::new(); + let mut lines = BufReader::new(stderr_handle).lines(); + while let Ok(Some(line)) = lines.next_line().await { + if let Some(path) = &log_path { + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = writeln!(f, "{line}"); + } + } + buf.extend_from_slice(line.as_bytes()); + buf.push(b'\n'); + } + buf + }); + + let status = child.wait().await?; + let stdout = stdout_task.await.unwrap_or_default(); + let stderr = stderr_task.await.unwrap_or_default(); + Ok(Output { status, stdout, stderr }) +} + +/// Why `status` couldn't read a run's log. +#[derive(Debug)] +pub enum StatusError { + /// No log file for this `run_id` (unknown id, or the run hasn't + /// written anything yet -- there is a brief window between + /// `create_run_log` and the first subprocess call). + NotFound, + Io(io::Error), +} + +/// Lines appended to `run_id`'s log since byte offset `peek`, and the +/// new offset to pass as `peek` next time. Mirrors GeneNetwork3's +/// `GET /api/stream/{run_id}?peak=` (gn3/api/streaming.py, spelled +/// "peak" there), stateless in the same way: the caller tracks `peek`, +/// not the server. +pub fn status(cache_dir: &str, run_id: &str, peek: u64) -> Result<(Vec<String>, u64), StatusError> { + let path = Path::new(cache_dir).join(format!("{run_id}.log")); + let mut file = std::fs::File::open(&path).map_err(|e| { + if e.kind() == io::ErrorKind::NotFound { + StatusError::NotFound + } else { + StatusError::Io(e) + } + })?; + file.seek(SeekFrom::Start(peek)).map_err(StatusError::Io)?; + let mut buf = String::new(); + file.read_to_string(&mut buf).map_err(StatusError::Io)?; + let pointer = peek + buf.len() as u64; + let lines = buf.lines().map(str::to_string).collect(); + Ok((lines, pointer)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_valid_run_id_accepts_alnum_dash_underscore() { + for ok in ["abc123", "a-b_c", "A1", "x"] { + assert!(is_valid_run_id(ok), "{ok}"); + } + } + + #[test] + fn is_valid_run_id_rejects_path_separators_and_empty() { + for bad in ["", "../etc/passwd", "a/b", "a.b", "a b", &"x".repeat(65)] { + assert!(!is_valid_run_id(bad), "{bad}"); + } + } + + #[test] + fn create_run_log_none_run_id_yields_no_path() { + assert!(matches!(create_run_log("/tmp", None), Ok(None))); + } + + #[test] + fn create_run_log_rejects_a_reused_id() { + let cache_dir = std::env::temp_dir().join(format!("gn4-streaming-test-{}", std::process::id())); + let cache_dir = cache_dir.to_str().unwrap(); + std::fs::create_dir_all(cache_dir).unwrap(); + let id = "dup-run"; + + assert!(matches!(create_run_log(cache_dir, Some(id)), Ok(Some(_)))); + let err = create_run_log(cache_dir, Some(id)).unwrap_err(); + assert!(matches!(err, RunLogError::AlreadyInUse(ref i) if i == id)); + + std::fs::remove_dir_all(cache_dir).unwrap(); + } + + #[test] + fn status_reads_from_peek_and_returns_a_new_pointer() { + let path = std::env::temp_dir().join(format!("gn4-streaming-status-test-{}", std::process::id())); + let cache_dir = path.to_str().unwrap(); + std::fs::create_dir_all(cache_dir).unwrap(); + std::fs::write(Path::new(cache_dir).join("run1.log"), "line one\nline two\n").unwrap(); + + let (lines, pointer) = status(cache_dir, "run1", 0).unwrap(); + assert_eq!(lines, vec!["line one", "line two"]); + + std::fs::OpenOptions::new() + .append(true) + .open(Path::new(cache_dir).join("run1.log")) + .unwrap() + .write_all(b"line three\n") + .unwrap(); + let (more, _) = status(cache_dir, "run1", pointer).unwrap(); + assert_eq!(more, vec!["line three"]); + + std::fs::remove_dir_all(cache_dir).unwrap(); + } + + #[test] + fn status_unknown_run_id_is_not_found() { + let err = status("/tmp", "no-such-gn4-streaming-run-id", 0).unwrap_err(); + assert!(matches!(err, StatusError::NotFound)); + } +} diff --git a/tests/rqtl.rs b/tests/rqtl.rs new file mode 100644 index 0000000..c341254 --- /dev/null +++ b/tests/rqtl.rs @@ -0,0 +1,287 @@ +//! Integration test for POST /compute/rqtl. Runs the real Rscript/R-qtl +//! against a small, hand-written BXD riset fixture (tests/test_data, +//! not copied from genenetwork3 verbatim: its own +//! tests/unit/db/.../genotype_sample1.geno has a genotype code outside +//! its own header's declared set and duplicate marker names across +//! chromosomes, neither of which actually matters for the unrelated +//! parsing unit it's written for, but both would break a real R/qtl +//! run); skips rather than fails when Rscript is not on PATH, same +//! "skip, don't fail" convention as tests/gemma.rs. + +use axum::http::StatusCode; +use http_body_util::BodyExt; +use serde_json::Value; + +mod common; + +fn rscript_available() -> bool { + std::process::Command::new("Rscript") + .arg("--version") + .output() + .is_ok() +} + +fn test_data_path(name: &str) -> String { + format!("{}/tests/test_data/{name}", env!("CARGO_MANIFEST_DIR")) +} + +fn bxd_samples() -> Value { + serde_json::json!([ + {"name": "BXD1", "value": 9.5}, + {"name": "BXD2", "value": 8.2}, + {"name": "BXD5", "value": 7.1}, + {"name": "BXD6", "value": 6.4}, + {"name": "BXD8", "value": 5.9}, + {"name": "BXD9", "value": 4.3}, + ]) +} + +#[tokio::test] +async fn compute_rqtl_maps_a_qtl_from_the_bxd_riset_fixture() { + if !rscript_available() { + eprintln!("skipping compute_rqtl_maps_a_qtl_from_the_bxd_riset_fixture: Rscript not on PATH"); + return; + } + let Some(token) = common::auth_token().await else { + eprintln!("skipping compute_rqtl_maps_a_qtl_from_the_bxd_riset_fixture: no token (see docs/gn-auth.md)"); + return; + }; + + let body = serde_json::json!({ + "genotype_file": test_data_path("rqtl_sample1.geno"), + "trait_name": "mytrait", + "samples": bxd_samples(), + }); + let response = + common::post_json_with_token("POST /compute/rqtl", "/compute/rqtl", &token, &body).await; + let status = response.status(); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes)); + + let data: Value = common::data(&bytes); + let markers = data["markers"].as_array().unwrap(); + // The fixture has 6 markers (3 per chromosome, 2 chromosomes). + assert_eq!(markers.len(), 6); + assert_eq!(markers[0]["name"], "rs31443144"); + assert_eq!(markers[0]["chr"], "1"); + assert!(markers[0]["lod"].as_f64().unwrap() >= 0.0); + assert!(data["permutation"].is_null(), "nperm defaults to 0: {data}"); + + let envelope: Value = serde_json::from_slice(&bytes).unwrap(); + let notes = envelope["notes"].as_array().unwrap(); + let rscript_note = notes.iter().find(|n| n.as_str().unwrap().starts_with("Rscript")); + assert!(rscript_note.is_some(), "{notes:?}"); + let rscript_note = rscript_note.unwrap().as_str().unwrap(); + assert!(rscript_note.contains("--geno") && rscript_note.contains("--pheno"), "{rscript_note}"); +} + +#[tokio::test] +async fn compute_rqtl_with_permutations_returns_thresholds() { + if !rscript_available() { + eprintln!("skipping compute_rqtl_with_permutations_returns_thresholds: Rscript not on PATH"); + return; + } + let Some(token) = common::auth_token().await else { + eprintln!("skipping compute_rqtl_with_permutations_returns_thresholds: no token (see docs/gn-auth.md)"); + return; + }; + + let body = serde_json::json!({ + "genotype_file": test_data_path("rqtl_sample1.geno"), + "trait_name": "mytrait", + "samples": bxd_samples(), + "nperm": 20, + }); + let response = common::post_json_with_token( + "POST /compute/rqtl (with permutations)", + "/compute/rqtl", + &token, + &body, + ) + .await; + let status = response.status(); + let bytes = response.into_body().collect().await.unwrap().to_bytes(); + assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes)); + + let data: Value = common::data(&bytes); + let perm = &data["permutation"]; + assert!(!perm.is_null(), "{data}"); + assert_eq!(perm["values"].as_array().unwrap().len(), 20); + let suggestive = perm["suggestive"].as_f64().unwrap(); + let significant = perm["significant"].as_f64().unwrap(); + assert!(significant >= suggestive, "{perm}"); +} + +#[tokio::test] +async fn compute_rqtl_requires_a_token() { + let body = serde_json::json!({ + "genotype_file": test_data_path("rqtl_sample1.geno"), + "trait_name": "mytrait", + "samples": bxd_samples(), + }); + let request = axum::http::Request::builder() + .method(axum::http::Method::POST) + .uri("/compute/rqtl") + .extension(axum::extract::ConnectInfo(std::net::SocketAddr::from(( + [127, 0, 0, 1], + 40000, + )))) + .header("content-type", "application/json") + .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap())) + .unwrap(); + let response = tower::ServiceExt::oneshot(genenetwork4::app(), request) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn compute_rqtl_rejects_an_invalid_run_id() { + let Some(token) = common::auth_token().await else { + eprintln!("skipping compute_rqtl_rejects_an_invalid_run_id: no token (see docs/gn-auth.md)"); + return; + }; + + let body = serde_json::json!({ + "genotype_file": test_data_path("rqtl_sample1.geno"), + "trait_name": "mytrait", + "samples": bxd_samples(), + }); + let response = common::post_json_with_token( + "POST /compute/rqtl (bad id)", + "/compute/rqtl?id=../etc/passwd", + &token, + &body, + ) + .await; + assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); +} + +#[tokio::test] +async fn rqtl_status_unknown_run_id_returns_404() { + let Some(token) = common::auth_token().await else { + eprintln!("skipping rqtl_status_unknown_run_id_returns_404: no token (see docs/gn-auth.md)"); + return; + }; + let response = common::get_with_token( + "GET /compute/rqtl/status (unknown)", + "/compute/rqtl/status/no-such-gn4-rqtl-run?peek=0", + &token, + ) + .await; + assert_eq!(response.status(), StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn rqtl_status_requires_a_token() { + let request = axum::http::Request::builder() + .method(axum::http::Method::GET) + .uri("/compute/rqtl/status/some-run?peek=0") + .extension(axum::extract::ConnectInfo(std::net::SocketAddr::from(( + [127, 0, 0, 1], + 40000, + )))) + .body(axum::body::Body::empty()) + .unwrap(); + let response = tower::ServiceExt::oneshot(genenetwork4::app(), request) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::UNAUTHORIZED); +} + +#[tokio::test] +async fn compute_rqtl_rejects_a_run_id_already_in_use() { + let Some(token) = common::auth_token().await else { + eprintln!("skipping compute_rqtl_rejects_a_run_id_already_in_use: no token (see docs/gn-auth.md)"); + return; + }; + + // Same reasoning as gemma's equivalent test: the uniqueness check + // runs before any subprocess call, so this doesn't need Rscript. + let cache_dir = genenetwork4::config::Config::load().rqtl_cache_dir; + std::fs::create_dir_all(&cache_dir).unwrap(); + let run_id = format!( + "dup-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + std::fs::write( + std::path::Path::new(&cache_dir).join(format!("{run_id}.log")), + "a previous (or still running) call already owns this id\n", + ) + .unwrap(); + + let body = serde_json::json!({ + "genotype_file": test_data_path("rqtl_sample1.geno"), + "trait_name": "mytrait", + "samples": bxd_samples(), + }); + let response = common::post_json_with_token( + "POST /compute/rqtl (duplicate id)", + &format!("/compute/rqtl?id={run_id}"), + &token, + &body, + ) + .await; + assert_eq!(response.status(), StatusCode::CONFLICT); + + std::fs::remove_file(std::path::Path::new(&cache_dir).join(format!("{run_id}.log"))).unwrap(); +} + +#[tokio::test] +async fn compute_rqtl_streams_progress_while_running() { + if !rscript_available() { + eprintln!("skipping compute_rqtl_streams_progress_while_running: Rscript not on PATH"); + return; + } + let Some(token) = common::auth_token().await else { + eprintln!("skipping compute_rqtl_streams_progress_while_running: no token (see docs/gn-auth.md)"); + return; + }; + + let run_id = format!( + "rqtl-test-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + let body = serde_json::json!({ + "genotype_file": test_data_path("rqtl_sample1.geno"), + "trait_name": "mytrait", + "samples": bxd_samples(), + }); + let post_token = token.clone(); + let post_run_id = run_id.clone(); + let post_handle = tokio::spawn(async move { + common::post_json_with_token( + "POST /compute/rqtl (streamed)", + &format!("/compute/rqtl?id={post_run_id}"), + &post_token, + &body, + ) + .await + }); + + let response = post_handle.await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + + let final_response = common::get_with_token( + "GET /compute/rqtl/status (final)", + &format!("/compute/rqtl/status/{run_id}?peek=0"), + &token, + ) + .await; + assert_eq!(final_response.status(), StatusCode::OK); + let final_bytes = final_response.into_body().collect().await.unwrap().to_bytes(); + let final_status: Value = common::data(&final_bytes); + let lines: Vec<&str> = final_status["lines"] + .as_array() + .unwrap() + .iter() + .map(|l| l.as_str().unwrap()) + .collect(); + assert!(lines.contains(&"GN4: computation complete"), "{lines:?}"); +} diff --git a/tests/test_data/rqtl_sample1.geno b/tests/test_data/rqtl_sample1.geno new file mode 100644 index 0000000..999972c --- /dev/null +++ b/tests/test_data/rqtl_sample1.geno @@ -0,0 +1,18 @@ +# File name: rqtl_sample1 (minimal, valid BXD riset fixture for tests) + +# Metadata: Please retain this header information with file. + +@name: BXD +@type: riset +@mat: B +@pat: D +@het: H +@unk: U + +Chr Locus cM Mb BXD1 BXD2 BXD5 BXD6 BXD8 BXD9 +1 rs31443144 1.50 3.010274 B B D D D B +1 rs6269442 2.10 3.492195 B B D D H D +1 rs32285189 3.60 3.511204 B D D D D B +2 rs48756159 1.20 5.010274 D B B D B D +2 rs49742679 2.80 5.492195 D B H D B D +2 rs33198772 4.10 5.511204 D D B D B D diff --git a/tests/test_data/rqtl_sample1.pheno b/tests/test_data/rqtl_sample1.pheno new file mode 100644 index 0000000..870f662 --- /dev/null +++ b/tests/test_data/rqtl_sample1.pheno @@ -0,0 +1,7 @@ +Sample mytrait +BXD1 9.5 +BXD2 8.2 +BXD5 7.1 +BXD6 6.4 +BXD8 5.9 +BXD9 4.3 |
