diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-09 14:31:27 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-09 14:31:27 +0000 |
| commit | 002cdc41a54f6b398933f9e536217ec433a17eac (patch) | |
| tree | e6cff1ba06cf1ec25348503c80961a1173aa70ed /src | |
| parent | a698c48ee204cd68efc479b01132ae9c037213bb (diff) | |
| download | genenetwork4-002cdc41a54f6b398933f9e536217ec433a17eac.tar.gz | |
compute: add /compute/fitqtl for effect sizes at named markers
`/compute/rqtl` answers "where" -- scanone gives a LOD per marker -- but not "how much": a scan statistic is not a fitted model. R/qtl's `fitqtl` fits one, and reports the QTL's effect, its standard error, the model LOD and the variance explained. That is what a table of effects needs, and it is a separate endpoint because it is a separate question, asked about a handful of markers (a scan's peaks) rather than a genome: `fitqtl` fits one model per marker, so a genome-wide version would be thousands of fits. Cap: 100 markers per request. Rows are positional: marker, chr, pos, lod, pct_var, additive, se, t, p `additive` is fitqtl's estimate for the QTL term -- R/qtl codes the QTL genotype +-1, so it is half the difference between the two homozygote classes, the same convention GeneNetwork's published `additive` uses. **Two independent checks that the numbers are right.** On BXD trait 10001 (`BXD.4`), at the scan's peak: * `lod` = 2.930985, and `/compute/rqtl`'s scanone gives 2.930985 at the same marker -- identical to every digit the CSV carries, because they are the same cross and the same phenotype. That parity is now an integration test; * `additive` = 2.394472, against the value genenetwork.org publishes for that trait (`/api/v_pre1/trait/BXD/10001` -> 2.394444), which is 28 ppm away -- and that published number came from qtlreaper, a different engine. * scripts/qtl_fitqtl.R (new): reads the same `.geno` and two-column phenotype file as `rqtl_wrapper.R` (which is a verbatim copy of GN3's script and so not extended), builds the cross the same way, fits `fitqtl` at each named marker with `get.ests=TRUE`, and writes one CSV row per marker -- plus a one-line summary naming the strongest fit. `calc.genoprob(step=0)`: marker-level probabilities are all a marker-level fit needs. * src/fitqtl.rs (new): runs it, parses the CSV into positional rows (`chr` stays text, it can be `X`), keeps the command line for `notes`. * src/routes/fitqtl.rs (new): the endpoint -- same alignment rules as `/compute/rqtl` (by name onto the panel, parents/F1s excluded unless asked), the same `normalize`/`winsor_*` pipeline (effects come out on that scale), and the same R/qtl gate, so a fitqtl request and a scan queue against one another rather than competing for cores. * src/config.rs: `FITQTL_SCRIPT_PATH` (default `scripts/qtl_fitqtl.R`). * tests/fitqtl.rs: the fixture (columns, sign of the effect, notes), the LOD parity against scanone, and the refusals (no markers, both genotype inputs). * README.md, docs/www/SKILL.md: the endpoint, what each column means, and when to reach for it instead of the scan. 305 tests pass; the same four as before do not.
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 10 | ||||
| -rw-r--r-- | src/fitqtl.rs | 192 | ||||
| -rw-r--r-- | src/lib.rs | 2 | ||||
| -rw-r--r-- | src/routes/fitqtl.rs | 420 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 |
5 files changed, 625 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs index 51c16ca..8a95746 100644 --- a/src/config.rs +++ b/src/config.rs @@ -119,6 +119,10 @@ pub struct Config { /// for POST /compute/rqtl. Defaults to that path relative to the /// working directory the server is started from. pub rqtl_wrapper_path: String, + /// Path to scripts/qtl_fitqtl.R, which POST /compute/fitqtl runs to get + /// effect sizes for named markers. Defaults to that path relative to + /// the working directory the server is started from. + pub fitqtl_script_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" @@ -251,6 +255,10 @@ impl Config { "scripts/rqtl_wrapper.R".to_string(), ); values.insert( + "FITQTL_SCRIPT_PATH".to_string(), + "scripts/qtl_fitqtl.R".to_string(), + ); + values.insert( "RQTL_CACHE_DIR".to_string(), std::env::temp_dir() .join("gn4-rqtl") @@ -303,6 +311,7 @@ impl Config { "RAVANAN_SLURM_NICE", "RAVANAN_SCRATCH", "RQTL_WRAPPER_PATH", + "FITQTL_SCRIPT_PATH", "RQTL_CACHE_DIR", ] { if let Ok(value) = std::env::var(key) { @@ -341,6 +350,7 @@ impl Config { ravanan_batch: parse_ravanan_batch(&values), ravanan_scratch: values["RAVANAN_SCRATCH"].clone(), rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), + fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(), rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(), genotype_files_dir: values["GENOTYPE_FILES"].clone(), sql_check_health: parse_switch(&values["SQL_CHECK_HEALTH"]), diff --git a/src/fitqtl.rs b/src/fitqtl.rs new file mode 100644 index 0000000..26746f2 --- /dev/null +++ b/src/fitqtl.rs @@ -0,0 +1,192 @@ +//! Effect sizes for named markers, via R/qtl's `fitqtl`. +//! +//! `/compute/rqtl` answers "where" -- `scanone` gives a LOD per marker -- +//! but not "how much": a scan statistic is not a fitted model. `fitqtl` +//! fits one at a marker or QTL position and reports the QTL's effect, its +//! standard error, the model LOD and the variance explained. That is what a +//! table of effects needs, and it is a different question, asked +//! deliberately about *named* markers (usually the peaks a scan already +//! found) rather than about every marker on the genome: `fitqtl` fits a +//! model per marker, so a genome-wide sweep would be thousands of fits. +//! +//! `scripts/qtl_fitqtl.R` does the fitting, reading the same GeneNetwork +//! `.geno` file and the same two-column phenotype file as +//! `rqtl_wrapper.R`. This module runs it and turns its CSV into positional +//! rows, the shape the rest of the API uses. + +use std::path::Path; + +use serde_json::Value; + +use crate::rqtl::Sample; +use crate::streaming; + +/// The columns of every row, in order. +pub const COLUMNS: [&str; 9] = [ + "marker", "chr", "pos", "lod", "pct_var", "additive", "se", "t", "p", +]; + +/// Why a fit did not happen. +#[derive(Debug)] +pub enum FitqtlError { + Io(std::io::Error), + /// Rscript failed; the message is its stderr. + CommandFailed(String), + /// The output file was missing or unreadable. + OutputFile(String), +} + +impl std::fmt::Display for FitqtlError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + FitqtlError::Io(error) => write!(f, "{error}"), + FitqtlError::CommandFailed(detail) => write!(f, "{detail}"), + FitqtlError::OutputFile(detail) => write!(f, "{detail}"), + } + } +} + +/// What one `fitqtl` run produced. +pub struct FitqtlOutput { + /// One row per marker that could be fitted, positional in [`COLUMNS`]. + pub rows: Vec<Value>, + /// What the script printed -- one line naming the strongest fit. + pub summary: String, + /// The exact command line, so the run is reproducible. + pub command: String, +} + +/// Fit `markers` in `genotype_file` against `samples`. +/// +/// `samples` must be in the genotype file's own individual order, exactly as +/// for `/compute/rqtl` (the CSV cross format has no name matching). +pub async fn compute( + script: &str, + outdir: &str, + genotype_file: &str, + trait_name: &str, + samples: &[Sample], + markers: &[String], + model: &str, + method: &str, + scale: &str, +) -> Result<FitqtlOutput, FitqtlError> { + std::fs::create_dir_all(outdir).map_err(FitqtlError::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(outdir).join(format!("{unique}-pheno.txt")); + crate::rqtl::write_pheno_file(&pheno_path, trait_name, samples, &[]) + .map_err(FitqtlError::Io)?; + let result_name = format!("{unique}-fitqtl.csv"); + + let pheno_arg = pheno_path.to_string_lossy().into_owned(); + let marker_arg = markers.join(","); + let args = vec![ + script, + "--geno", + genotype_file, + "--pheno", + &pheno_arg, + "--markers", + &marker_arg, + "--model", + model, + "--method", + method, + "--scale", + scale, + "--outdir", + outdir, + "--filename", + &result_name, + ]; + let command = format!("Rscript {}", args.join(" ")); + let output = streaming::run_streaming("Rscript", &args, None) + .await + .map_err(FitqtlError::Io)?; + if !output.status.success() { + return Err(FitqtlError::CommandFailed( + String::from_utf8_lossy(&output.stderr).into_owned(), + )); + } + let contents = std::fs::read_to_string(Path::new(outdir).join(&result_name)) + .map_err(|error| FitqtlError::OutputFile(error.to_string()))?; + Ok(FitqtlOutput { + rows: parse_rows(&contents), + // The script's own last line is its one-line summary; the rest of + // its stdout is read.cross's chatter. + summary: String::from_utf8_lossy(&output.stdout) + .lines() + .filter(|line| !line.trim().is_empty()) + .next_back() + .unwrap_or_default() + .trim() + .to_string(), + command, + }) +} + +/// Parse the script's CSV into positional rows. `chr` stays a string (it can +/// be `X`), everything after it is a number when it parses as one. +fn parse_rows(contents: &str) -> Vec<Value> { + let mut lines = contents.lines(); + let Some(header) = lines.next() else { + return Vec::new(); + }; + let names: Vec<&str> = header.split(',').map(str::trim).collect(); + lines + .filter(|line| !line.trim().is_empty()) + .map(|line| { + let fields: Vec<&str> = line.split(',').map(str::trim).collect(); + let mut row = Vec::with_capacity(COLUMNS.len()); + for column in COLUMNS.iter() { + let field = names + .iter() + .position(|name| name == column) + .and_then(|at| fields.get(at).copied()) + .unwrap_or(""); + row.push(match *column { + "marker" | "chr" => Value::String(field.to_string()), + _ => field + .parse::<f64>() + .map(|n| serde_json::json!(n)) + .unwrap_or(Value::Null), + }); + } + Value::Array(row) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_are_positional_and_chr_stays_text() { + let contents = "marker,chr,pos,lod,pct_var,additive,se,t,p\n\ + rs1,X,3.0,4.2,12.5,-0.51,0.8,-0.6,0.01\n"; + let rows = parse_rows(contents); + assert_eq!(rows.len(), 1); + let row = rows[0].as_array().unwrap(); + assert_eq!(row[0], Value::String("rs1".to_string())); + assert_eq!(row[1], Value::String("X".to_string())); + assert_eq!(row[3], serde_json::json!(4.2)); + assert_eq!(row[5], serde_json::json!(-0.51)); + assert_eq!(row.len(), COLUMNS.len()); + } + + #[test] + fn a_marker_that_could_not_be_fitted_is_simply_absent() { + // The script skips markers it cannot find or fit rather than writing + // a row of NAs, so the count can be lower than the request. + let contents = "marker,chr,pos,lod,pct_var,additive,se,t,p\n"; + assert!(parse_rows(contents).is_empty()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 1e0f9ff..370c612 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ pub mod covariates; pub mod config; pub mod db; pub mod embedded; +pub mod fitqtl; pub mod genotypes; pub mod normalize; mod plot; @@ -126,6 +127,7 @@ pub fn app() -> Router { .routes(routes!(routes::gemma::compute_gemma)) .routes(routes!(routes::gemma::compute_gemma_ravanan)) .routes(routes!(routes::gemma::gemma_status)) + .routes(routes!(routes::fitqtl::compute_fitqtl)) .routes(routes!(routes::rqtl::compute_rqtl)) .routes(routes!(routes::rqtl::rqtl_status)); // Registered -- and so reachable and listed in /openapi.json -- unless diff --git a/src/routes/fitqtl.rs b/src/routes/fitqtl.rs new file mode 100644 index 0000000..f58ca24 --- /dev/null +++ b/src/routes/fitqtl.rs @@ -0,0 +1,420 @@ +//! `POST /compute/fitqtl`: effect sizes for named markers. +//! +//! `/compute/rqtl` says *where* a QTL is (a LOD per marker); this says *how +//! much*, by fitting R/qtl's `fitqtl` at the markers the caller names -- +//! usually the peaks a scan already reported. It is a separate endpoint +//! because it is a separate question, asked about a handful of positions +//! rather than the whole genome: `fitqtl` fits one model per marker, so a +//! genome-wide version of this would be thousands of fits. + +use axum::Json; +use axum::extract::Query; +use axum::http::StatusCode; +use serde::Deserialize; + +use gnauth_macros::{compute_gate, gnauth}; + +use crate::auth::AuthToken; +use crate::compute_gate as gate; +use crate::config::Config; +use crate::error::{ApiError, Unauthorized}; +use crate::fitqtl; +use crate::genotypes; +use crate::normalize; +use crate::response::{Ctx, Envelope, RequestInfo, path_segment}; +use crate::rqtl::Sample; + +/// The most markers one request may fit. Each is a full model fit, so this +/// is a guard against a caller handing over a whole genome by accident. +const MAX_MARKERS: usize = 100; + +#[derive(Deserialize, utoipa::IntoParams)] +pub struct ComputeFitqtlParams { + /// Log progress for `GET /compute/rqtl/status/{id}` (shared with + /// `/compute/rqtl`). + pub id: Option<String>, +} + +/// One trait value, by individual name. +#[derive(Clone, Deserialize, utoipa::ToSchema)] +pub struct FitqtlSample { + pub name: String, + pub value: Option<f64>, +} + +#[derive(Deserialize, utoipa::ToSchema)] +pub struct FitqtlRequest { + /// Group to fit over (an InbredSet name, e.g. "BXD"); the server + /// resolves its genotype file. Give this or `genotype_file`. + pub group: Option<String>, + /// A version from `/groups/{group}/genotypes`, e.g. "BXD.4". + pub genotype_version: Option<String>, + /// Explicit `.geno` path on the server, instead of `group`. + pub genotype_file: Option<String>, + /// Include parents and F1s; off by default, as elsewhere. + pub include_parents_f1: Option<bool>, + /// The trait's values by individual name (aligned onto the panel), or + /// `trait_values` positionally in the genotype file's order. + pub samples: Option<Vec<FitqtlSample>>, + /// Positional values, for a `genotype_file` request. + pub trait_values: Option<Vec<Option<f64>>>, + /// Label for the trait, e.g. "BXD::20010"; used in `notes`. + pub trait_name: Option<String>, + /// The markers to fit (from `/groups/{g}/genotypes/{v}/markers`), at + /// most 100. + pub markers: Vec<String>, + /// R/qtl's `model`: "normal" (default) or "np". + pub model: Option<String>, + /// R/qtl's `method` for the QTL fit: "hk" (default), "ehk", "mr", "em", + /// "imp". + pub method: Option<String>, + /// "mb" (default) or "cm". + pub scale: Option<String>, + /// Normalisation of the trait values, as on `/compute/rqtl`. + pub normalize: Option<String>, + /// Winsorise at a tail fraction, as on `/compute/rqtl`. + pub winsor_quantile: Option<f64>, + /// Winsorise at Tukey fences, as on `/compute/rqtl`. + pub winsor_fences: Option<f64>, +} + +#[utoipa::path(post, path = "/compute/fitqtl", + summary = "Effect sizes for named markers, via R/qtl's fitqtl", + description = "Fits R/qtl's `fitqtl` at each named marker and returns, per \ +marker, the model LOD, the percentage of variance explained, and the QTL's \ +additive effect with its standard error and t. Use /compute/rqtl to find the \ +peaks, then this to size them: a scan statistic is not a fitted model. The \ +`additive` column is fitqtl's estimate for the QTL term -- in R/qtl's +-1 \ +coding, half the difference between the two homozygote classes, the same \ +convention GeneNetwork's own additive uses.", + params(ComputeFitqtlParams), + request_body = FitqtlRequest, + responses( + (status = 200, description = "One row per fitted marker, positional (column names in meta.columns)", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 409, description = "A compute job is already running for this caller", body = ApiError), + (status = 422, description = "No markers, too many, or an unusable genotype/trait input", body = ApiError), + (status = 502, description = "R/qtl failed", body = ApiError) + ) +)] +#[gnauth(token_only)] +#[compute_gate(rqtl, label = "R/qtl fitqtl", run_id = params.id.as_deref())] +pub async fn compute_fitqtl( + ctx: Ctx, + token: AuthToken, + Query(params): Query<ComputeFitqtlParams>, + Json(request): Json<FitqtlRequest>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let config = Config::load(); + let trait_label = request + .trait_name + .clone() + .filter(|name| !name.trim().is_empty()) + .unwrap_or_else(|| format!("{}::fitqtl", request.group.clone().unwrap_or_default())); + + if request.markers.is_empty() { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "missing_markers", + "No markers", + "give `markers`: the marker names to fit (a scan's peaks, usually). \ + /compute/rqtl finds them; this sizes them." + .to_string(), + "compute_fitqtl", + ) + .with_request_id(rid)); + } + if request.markers.len() > MAX_MARKERS { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "too_many_markers", + "Too many markers", + format!( + "{} markers given; at most {MAX_MARKERS} are fitted per request (each is a \ + model fit). Use /compute/rqtl for a genome-wide scan.", + request.markers.len() + ), + "compute_fitqtl", + ) + .with_request_id(rid)); + } + let pipeline = normalize::Pipeline::parse( + request.normalize.as_deref(), + request.winsor_quantile, + request.winsor_fences, + ) + .map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_normalization", + "Invalid normalization", + detail, + "compute_fitqtl", + ) + .with_request_id(rid.clone()) + })?; + + let request_group = request.group.clone(); + let include_parents_f1 = request.include_parents_f1.unwrap_or(false); + let mut extra_notes: Vec<String> = Vec::new(); + let (genotype_file, samples) = match ( + request.genotype_file.clone(), + request.group.clone(), + ) { + (None, Some(group)) => { + let wanted = group.clone(); + let version = request.genotype_version.clone(); + let values = request + .samples + .clone() + .map(|samples| { + samples + .into_iter() + .map(|sample| (sample.name, sample.value)) + .collect::<Vec<_>>() + }) + .unwrap_or_default(); + let directory = config.genotype_files_dir.clone(); + let cache_dir = config.rqtl_cache_dir.clone(); + let supplied = values.len(); + let (prepared, aligned, matched, resolved, kept_names) = + tokio::task::spawn_blocking(move || { + let resolved = genotypes::resolve( + std::path::Path::new(&directory), + &wanted, + version.as_deref(), + )?; + let excluded = if include_parents_f1 { + std::collections::BTreeSet::new() + } else { + genotypes::non_strains( + std::path::Path::new(&directory), + &wanted, + &resolved.panel, + ) + }; + let keep: Vec<usize> = resolved + .panel + .iter() + .enumerate() + .filter(|(_, name)| !excluded.contains(*name)) + .map(|(index, _)| index) + .collect(); + let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values); + let prepared = genotypes::prepare( + std::path::Path::new(&directory), + &resolved, + genotypes::Engine::Rqtl, + &keep, + std::path::Path::new(&cache_dir), + )?; + let kept_names: Vec<String> = keep + .iter() + .filter_map(|index| resolved.panel.get(*index).cloned()) + .collect(); + Ok::<_, genotypes::GenotypeError>(( + prepared, aligned, matched, resolved, kept_names, + )) + }) + .await + .map_err(|e| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + e.to_string(), + "compute_fitqtl", + ) + .with_request_id(rid.clone()) + })? + .map_err(|e| genotypes_error(e, rid.clone()))?; + if matched == 0 { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "no_samples_aligned", + "No samples aligned", + format!( + "none of the {supplied} named samples appear in genotype version '{}'.", + resolved.version + ), + "compute_fitqtl", + ) + .with_request_id(rid)); + } + extra_notes.push(format!( + "Genotype: {} (version {}, {} individuals, {} parents/F1s dropped); {} of {} supplied values aligned onto it by name.", + prepared.note, + resolved.version, + prepared.individuals, + prepared.excluded, + matched, + supplied + )); + let samples: Vec<Sample> = kept_names + .into_iter() + .zip(aligned) + .map(|(name, value)| Sample { name, value }) + .collect(); + (prepared.genotype_file.to_string_lossy().into_owned(), samples) + } + (Some(file), None) => { + let values = request.trait_values.clone().unwrap_or_default(); + if values.is_empty() { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "missing_trait_values", + "No trait values", + "with an explicit genotype_file, give `trait_values` (one per individual, \ + in the file's order)." + .to_string(), + "compute_fitqtl", + ) + .with_request_id(rid)); + } + let samples: Vec<Sample> = values + .into_iter() + .enumerate() + .map(|(index, value)| Sample { + name: format!("individual-{}", index + 1), + value, + }) + .collect(); + (file, samples) + } + (Some(_), Some(_)) => { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "ambiguous_genotype", + "Ambiguous genotype input", + "give either genotype_file or group, not both.".to_string(), + "compute_fitqtl", + ) + .with_request_id(rid)); + } + (None, None) => { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "missing_genotype", + "No genotype input", + "give genotype_file, or group (see /groups/{group}/genotypes).".to_string(), + "compute_fitqtl", + ) + .with_request_id(rid)); + } + }; + + // Normalize after alignment, over the individuals that enter the fits -- + // the effects come out on that scale, as on /compute/rqtl. + let samples = if pipeline.is_identity() { + samples + } else { + let raw: Vec<Option<f64>> = samples.iter().map(|sample| sample.value).collect(); + let (normalized, applied) = pipeline.apply(&raw).map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_normalization", + "Invalid normalization", + detail, + "compute_fitqtl", + ) + .with_request_id(rid.clone()) + })?; + extra_notes.push(pipeline.describe(&applied)); + samples + .into_iter() + .zip(normalized) + .map(|(sample, value)| Sample { + name: sample.name, + value, + }) + .collect() + }; + + let individuals = samples.len(); + __gn4_claim + .claim_slot_or_busy(individuals, rid.clone()) + .await?; + + let script = config.fitqtl_script_path.clone(); + let cache_dir = config.rqtl_cache_dir.clone(); + let markers = request.markers.clone(); + let model = request.model.clone().unwrap_or_else(|| "normal".to_string()); + let method = request.method.clone().unwrap_or_else(|| "hk".to_string()); + let scale = request.scale.clone().unwrap_or_else(|| "mb".to_string()); + let trait_label_for_job = trait_label.clone(); + let rid_for_job = rid.clone(); + let output = gate::rqtl() + .run(__gn4_claim, async move { + fitqtl::compute( + &script, + &cache_dir, + &genotype_file, + &trait_label_for_job, + &samples, + &markers, + &model, + &method, + &scale, + ) + .await + .map_err(|error| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "fitqtl_failed", + "R/qtl fitqtl failed", + error.to_string(), + "compute_fitqtl", + ) + .with_request_id(rid_for_job) + }) + }) + .await?; + + let num_rows = output.rows.len(); + let mut envelope = ctx + .envelope(serde_json::Value::Array(output.rows)) + .with_columns( + fitqtl::COLUMNS.iter().map(|name| name.to_string()).collect(), + num_rows, + ) + .with_note(&format!("Trait: {trait_label}")) + .with_note( + "Rows come from R/qtl's fitqtl, one per marker that could be fitted (positional; see \ + meta.columns). `additive` is the QTL effect in R/qtl's +-1 coding -- half the \ + difference between the two homozygote classes, the same convention GeneNetwork's \ + own additive uses -- with `se` and `t`; `pct_var` is the model's percentage of \ + variance explained and `p` its p-value. These describe this run on these samples; \ + markers that are not in the genotype file, or that fitqtl could not fit, are \ + absent rather than reported as zero.", + ) + .with_note(&output.command) + .with_note(&format!("fitqtl: {}", output.summary)); + for note in &extra_notes { + envelope = envelope.with_note(note); + } + if let Some(group) = request_group { + envelope = envelope.with_next( + &format!("/groups/{}/phewas", path_segment(&group)), + "PheWAS: every published trait peaking near a locus (add ?locus=)", + ); + } + Ok(Json(envelope)) +} + +fn genotypes_error(error: genotypes::GenotypeError, rid: RequestInfo) -> ApiError { + let (status, code, title) = match error { + genotypes::GenotypeError::NotFound(_) => ( + StatusCode::NOT_FOUND, + "genotypes_not_found", + "Genotype file not found", + ), + genotypes::GenotypeError::Io(_) => ( + StatusCode::INTERNAL_SERVER_ERROR, + "genotypes_unreadable", + "Genotype files could not be read", + ), + }; + ApiError::new(status, code, title, error.to_string(), "compute_fitqtl") + .with_request_id(rid) +} diff --git a/src/routes/mod.rs b/src/routes/mod.rs index b40c0a4..b08497f 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod accessions; pub mod correlation; pub mod datasets; pub mod dev; +pub mod fitqtl; pub mod gemma; pub mod genotypes; pub mod groups; |
