diff options
| author | Pjotr <wrk@bosa.lan> | 2026-11-14 03:02:37 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-11-14 03:02:37 +0000 |
| commit | a0d7a37d65e98fc874617d5b08983fe66c5f2655 (patch) | |
| tree | 7374546579e518a9c95e62b5a1cf473048349ce6 /src | |
| parent | a5d6437a90686e97b5c410af3a3479114e4ab9c5 (diff) | |
| download | genenetwork4-a0d7a37d65e98fc874617d5b08983fe66c5f2655.tar.gz | |
individuals: select who enters a mapping, by name
Parents and F1s are excluded by default (as in GeneNetwork2/3), with
include_parents_f1 to keep them all. That boolean was not enough for what was
asked -- "include these, drop that substrain" -- and the exclusion list itself
is data (parents_and_f1s.json, seven groups) that no request can reach. F1
names also differ per group (B6D2F1 for BXD, BHF1/HBF1 for BXH,
C57BL/6JxBXD037F1 for the intercross F1s), so pattern matching is the wrong
tool.
Every group-mapping endpoint -- /compute/gemma, /compute/gemma/ravanan,
/compute/rqtl, /compute/qtl2, /compute/fitqtl, /compute/bulklmm -- now takes
"individuals": {"include": [...], "exclude": [...]}
applied after the parent/F1 rule, exclude winning over include. An unknown name
is a 422 invalid_individuals whose message lists the panel: a silently dropped
animal changes a kinship matrix without anyone noticing, so the failure has to
be loud. genotypes::select_panel is the one implementation, and it returns what
it did (dropped parents/F1s, re-included by name, excluded by name) so the
Genotype note can say it: "197 individuals, 38 parents/F1s dropped; 1 excluded
by name".
The note now also spells out the distinction that makes this option
treacherous: the kinship uses *every* individual in the genotype file, the
association uses only those with a trait value -- GEMMA reads no phenotypes for
the kinship. So "include the F1s" changes the relatedness structure without
putting the F1s in the fit, and a request can legitimately have 234 individuals
in the genotype file and 34 in the association. Verified on BXD.8: excluding
BXD1 gives 197 individuals / 33 values; include_parents_f1 with an F1
re-included and a substrain excluded gives 234 / 34.
A basket supplies values by name, so a selection applies to a basket-fed
mapping the same way: the individuals excluded are simply not in the panel any
more, and their basket values are ignored.
GenotypeError gains Invalid for this (422) so a caller's typo is not reported
as a missing genotype file; the read-only endpoints that can never see one map
it the same way for exhaustiveness.
Diffstat (limited to 'src')
| -rw-r--r-- | src/genotypes.rs | 177 | ||||
| -rw-r--r-- | src/routes/bulklmm.rs | 33 | ||||
| -rw-r--r-- | src/routes/fitqtl.rs | 38 | ||||
| -rw-r--r-- | src/routes/frequencies.rs | 8 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 69 | ||||
| -rw-r--r-- | src/routes/genotypes.rs | 13 | ||||
| -rw-r--r-- | src/routes/phewas.rs | 8 | ||||
| -rw-r--r-- | src/routes/qtl2.rs | 38 | ||||
| -rw-r--r-- | src/routes/rqtl.rs | 53 |
9 files changed, 357 insertions, 80 deletions
diff --git a/src/genotypes.rs b/src/genotypes.rs index 9fea4c3..f9864c1 100644 --- a/src/genotypes.rs +++ b/src/genotypes.rs @@ -46,12 +46,15 @@ pub enum GenotypeError { NotFound(String), /// Reading the directory, the JSON, or a `.geno` header failed. Io(String), + /// The request names an individual (or selection) that cannot be honoured: + /// the caller's fault, not a missing file. + Invalid(String), } impl std::fmt::Display for GenotypeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - GenotypeError::NotFound(what) => write!(f, "{what}"), + GenotypeError::NotFound(what) | GenotypeError::Invalid(what) => write!(f, "{what}"), GenotypeError::Io(what) => write!(f, "{what}"), } } @@ -359,6 +362,117 @@ pub fn resolve( }) } +/// The caller's own choice of individuals, on top of the parent/F1 rule. +/// +/// Why this exists: `parents_and_f1s.json` is *data* about seven groups, and a +/// request cannot reach it -- a group it does not list, a renamed parent, or a +/// substrain the caller wants gone (`BXD48a` beside `BXD48`) all needed a code +/// or data change. Naming individuals is also safer than pattern matching: the +/// F1 names differ per group (`B6D2F1` for BXD, `BHF1`/`HBF1` for BXH, +/// `C57BL/6JxBXD037F1` for the intercross F1s). +/// +/// `exclude` wins over `include`, so the two lists cannot contradict silently. +/// An unknown name is an error rather than a shrug: a dropped animal changes a +/// kinship matrix without anyone noticing. +#[derive(Debug, Clone, Default, serde::Deserialize, utoipa::ToSchema)] +pub struct Individuals { + /// Names to keep even where the parent/F1 rule would drop them. + #[serde(default)] + pub include: Vec<String>, + /// Names to drop in addition to (or instead of) the parent/F1 rule. + #[serde(default)] + pub exclude: Vec<String>, +} + +impl Individuals { + pub fn is_empty(&self) -> bool { + self.include.is_empty() && self.exclude.is_empty() + } +} + +/// What a selection did, so a reply can say it rather than leave a reader to +/// infer why a panel shrank. +#[derive(Debug, Clone, Default)] +pub struct Selection { + /// Panel indices that enter the genotype file, in panel order. + pub keep: Vec<usize>, + /// Individuals dropped by the parent/F1 rule (and not re-included). + pub dropped_parents_f1: usize, + /// Individuals the caller named to keep against that rule. + pub included_by_name: usize, + /// Individuals the caller named to drop. + pub excluded_by_name: usize, +} + +/// Choose the individuals of a panel: the parent/F1 rule first, then the +/// caller's `individuals` lists. +/// +/// `include_parents_f1` short-circuits the first step, exactly as before; the +/// caller's lists still apply afterwards, so "everyone except X" and "only +/// these two F1s" are both expressible. +pub fn select_panel( + panel: &[String], + parents_f1s: &BTreeSet<String>, + include_parents_f1: bool, + individuals: &Individuals, +) -> Result<Selection, GenotypeError> { + let position = |name: &str| panel.iter().position(|member| member == name); + let unknown = |name: &str, list: &str| { + let sample: Vec<&str> = panel.iter().take(6).map(String::as_str).collect(); + GenotypeError::Invalid(format!( + "individual '{name}' (in `individuals.{list}`) is not in this panel, which has {} \ + member(s), starting: {}{}", + panel.len(), + sample.join(", "), + if panel.len() > sample.len() { ", …" } else { "" } + )) + }; + // Resolve the names first, so a typo is reported even when the panel would + // otherwise have been filtered to nothing. + let mut include: Vec<usize> = Vec::new(); + for name in &individuals.include { + include.push(position(name).ok_or_else(|| unknown(name, "include"))?); + } + let mut exclude: Vec<usize> = Vec::new(); + for name in &individuals.exclude { + exclude.push(position(name).ok_or_else(|| unknown(name, "exclude"))?); + } + + let mut keep = Vec::with_capacity(panel.len()); + let mut dropped_parents_f1 = 0; + let mut included_by_name = 0; + for (index, name) in panel.iter().enumerate() { + let is_parent_or_f1 = !include_parents_f1 && parents_f1s.contains(name); + if exclude.contains(&index) { + continue; + } + if include.contains(&index) { + if is_parent_or_f1 { + included_by_name += 1; + } + keep.push(index); + continue; + } + if is_parent_or_f1 { + dropped_parents_f1 += 1; + continue; + } + keep.push(index); + } + if keep.is_empty() { + return Err(GenotypeError::Invalid( + "no individuals are left after the parent/F1 rule and `individuals`; \n the request would map nothing".to_string(), + )); + } + let excluded_by_name = exclude.len(); + Ok(Selection { + keep, + dropped_parents_f1, + included_by_name, + excluded_by_name, + }) +} + /// The individuals a mapping should exclude by default: parents and F1s, /// as in GN2 (`incparentsf1` off) and GN3 (`inc_par=False, inc_f1=False`). /// @@ -786,6 +900,67 @@ pub fn align( #[cfg(test)] mod tests { + + fn panel(names: &[&str]) -> Vec<String> { + names.iter().map(|name| (*name).to_string()).collect() + } + + fn parents(names: &[&str]) -> BTreeSet<String> { + names.iter().map(|name| (*name).to_string()).collect() + } + + #[test] + fn the_parent_f1_rule_still_drops_and_counts() { + let p = panel(&["BXD1", "B6D2F1", "C57BL/6J"]); + let selection = select_panel(&p, &parents(&["B6D2F1", "C57BL/6J"]), false, &Individuals::default()) + .unwrap(); + assert_eq!(selection.keep, vec![0]); + assert_eq!(selection.dropped_parents_f1, 2); + assert_eq!(selection.included_by_name, 0); + } + + #[test] + fn a_named_individual_is_kept_against_the_rule() { + let p = panel(&["BXD1", "B6D2F1", "C57BL/6J"]); + let individuals = Individuals { include: vec!["B6D2F1".to_string()], exclude: vec![] }; + let selection = select_panel(&p, &parents(&["B6D2F1", "C57BL/6J"]), false, &individuals).unwrap(); + assert_eq!(selection.keep, vec![0, 1], "the F1 stays, the parent does not"); + assert_eq!(selection.dropped_parents_f1, 1); + assert_eq!(selection.included_by_name, 1); + } + + #[test] + fn exclude_wins_over_include() { + let p = panel(&["BXD1", "BXD48", "BXD48a"]); + let individuals = Individuals { + include: vec!["BXD48a".to_string()], + exclude: vec!["BXD48a".to_string()], + }; + let selection = select_panel(&p, &parents(&[]), false, &individuals).unwrap(); + assert_eq!(selection.keep, vec![0, 1]); + assert_eq!(selection.excluded_by_name, 1); + } + + #[test] + fn an_unknown_name_is_an_error_that_names_the_panel() { + let p = panel(&["BXD1", "BXD2"]); + let individuals = Individuals { include: vec![], exclude: vec!["BXD9x".to_string()] }; + let error = select_panel(&p, &parents(&[]), false, &individuals).unwrap_err(); + let message = error.to_string(); + assert!(message.contains("BXD9x"), "{message}"); + assert!(message.contains("BXD1, BXD2"), "{message}"); + } + + #[test] + fn selecting_everything_away_is_refused() { + let p = panel(&["BXD1", "BXD2"]); + let individuals = Individuals { + include: vec![], + exclude: vec!["BXD1".to_string(), "BXD2".to_string()], + }; + assert!(select_panel(&p, &parents(&[]), false, &individuals).is_err()); + } + use super::*; use std::fs; diff --git a/src/routes/bulklmm.rs b/src/routes/bulklmm.rs index ea4b805..d549f07 100644 --- a/src/routes/bulklmm.rs +++ b/src/routes/bulklmm.rs @@ -55,6 +55,10 @@ pub struct BulklmmRequest { pub genotype_upload: Option<String>, /// Include parents and F1s; off by default, as elsewhere. pub include_parents_f1: Option<bool>, + /// Individuals to keep or drop on top of the parent/F1 rule + /// (`genotypes::Individuals`); `exclude` wins over `include`. + #[serde(default)] + pub individuals: genotypes::Individuals, /// The trait's values by individual name, or `trait_values` positionally. pub samples: Option<Vec<BulklmmSample>>, /// A basket from `/baskets`, in place of `samples`. @@ -250,6 +254,7 @@ pub async fn compute_bulklmm( .with_request_id(rid)); }; let include_parents_f1 = request.include_parents_f1.unwrap_or(false); + let individuals = request.individuals.clone(); let values: Vec<(String, Option<f64>)> = samples .iter() .map(|sample| (sample.name.clone(), sample.value)) @@ -288,22 +293,18 @@ pub async fn compute_bulklmm( } } }; - let excluded = if include_parents_f1 { - std::collections::BTreeSet::new() - } else { - genotypes::non_strains( - std::path::Path::new(&directory_for_scan), - &resolved.version, - &resolved.panel, - ) - }; - let keep: Vec<usize> = resolved - .panel - .iter() - .enumerate() - .filter(|(_, name)| !excluded.contains(*name)) - .map(|(index, _)| index) - .collect(); + let parents_f1s = genotypes::non_strains( + std::path::Path::new(&directory_for_scan), + &resolved.version, + &resolved.panel, + ); + let selection = genotypes::select_panel( + &resolved.panel, + &parents_f1s, + include_parents_f1, + &individuals, + )?; + let keep: Vec<usize> = selection.keep.clone(); let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values); let prepared = genotypes::prepare( std::path::Path::new(&directory_for_scan), diff --git a/src/routes/fitqtl.rs b/src/routes/fitqtl.rs index 73d3bbe..ee2e259 100644 --- a/src/routes/fitqtl.rs +++ b/src/routes/fitqtl.rs @@ -57,6 +57,10 @@ pub struct FitqtlRequest { /// Include parents and F1s; off by default, as elsewhere. pub include_parents_f1: Option<bool>, + /// Individuals to keep or drop on top of the parent/F1 rule + /// (`genotypes::Individuals`); `exclude` wins over `include`. + #[serde(default)] + pub individuals: genotypes::Individuals, /// 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>>, @@ -221,6 +225,7 @@ pub async fn compute_fitqtl( let request_group = request.group.clone(); let include_parents_f1 = request.include_parents_f1.unwrap_or(false); + let individuals = request.individuals.clone(); let mut extra_notes: Vec<String> = Vec::new(); let (genotype_file, samples) = match ( request.genotype_file.clone(), @@ -249,22 +254,18 @@ pub async fn compute_fitqtl( &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 parents_f1s = genotypes::non_strains( + std::path::Path::new(&directory), + &wanted, + &resolved.panel, + ); + let selection = genotypes::select_panel( + &resolved.panel, + &parents_f1s, + include_parents_f1, + &individuals, + )?; + let keep: Vec<usize> = selection.keep.clone(); let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values); let prepared = genotypes::prepare( std::path::Path::new(&directory), @@ -558,6 +559,11 @@ pub async fn compute_fitqtl( fn genotypes_error(error: genotypes::GenotypeError, rid: RequestInfo) -> ApiError { let (status, code, title) = match error { + genotypes::GenotypeError::Invalid(_) => ( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + ), genotypes::GenotypeError::NotFound(_) => ( StatusCode::NOT_FOUND, "genotypes_not_found", diff --git a/src/routes/frequencies.rs b/src/routes/frequencies.rs index e9bc73f..bcd4c42 100644 --- a/src/routes/frequencies.rs +++ b/src/routes/frequencies.rs @@ -364,6 +364,14 @@ fn map_error(error: FreqError, rid: RequestInfo) -> ApiError { /// `genotypes::resolve` failures (group scoping) keep their own codes. fn map_genotype_error(error: genotypes::GenotypeError, rid: RequestInfo) -> ApiError { match error { + genotypes::GenotypeError::Invalid(message) => ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + message, + "genotype_frequencies", + ) + .with_request_id(rid), genotypes::GenotypeError::NotFound(message) => ApiError::new( StatusCode::NOT_FOUND, "genotype_not_found", diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index d774336..fe06edd 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -59,6 +59,12 @@ pub struct GemmaRequest { pub genotype_version: Option<String>, /// Include parents and F1s. Off by default, as in GeneNetwork2/3. pub include_parents_f1: Option<bool>, + /// Individuals to keep or drop on top of the parent/F1 rule + /// (`genotypes::Individuals`). `exclude` wins over `include`, and an + /// unknown name is a 422 rather than a silently dropped animal. + #[serde(default)] + pub individuals: genotypes::Individuals, + /// Covariates to fit alongside the trait: a case attribute of the /// group by name, or explicit per-sample numbers. Same shape as /// `/compute/rqtl`'s; GEMMA needs `group`, since the individuals have @@ -283,6 +289,7 @@ pub(crate) async fn resolve_inputs( let group = request.group.clone(); let version = request.genotype_version.clone(); let include_parents_f1 = request.include_parents_f1.unwrap_or(false); + let individuals = request.individuals.clone(); let named: Vec<(String, Option<f64>)> = request .samples .as_ref() @@ -349,21 +356,26 @@ pub(crate) async fn resolve_inputs( let wanted = group.clone(); let had_samples = !named.is_empty(); let supplied_count = named.len(); - let (prepared, aligned, matched, resolved, kept_names, dropped_empty, parents_f1s) = - tokio::task::spawn_blocking(move || { + let ( + prepared, + aligned, + matched, + resolved, + kept_names, + dropped_empty, + parents_f1s, + included_by_name, + excluded_by_name, + ) = tokio::task::spawn_blocking(move || { let resolved = genotypes::resolve(&directory, &wanted, version.as_deref())?; - let excluded = if include_parents_f1 { - std::collections::BTreeSet::new() - } else { - genotypes::non_strains(&directory, &wanted, &resolved.panel) - }; - let keep: Vec<usize> = resolved - .panel - .iter() - .enumerate() - .filter(|(_, name)| !excluded.contains(*name)) - .map(|(index, _)| index) - .collect(); + let parents_f1s = genotypes::non_strains(&directory, &wanted, &resolved.panel); + let selection = genotypes::select_panel( + &resolved.panel, + &parents_f1s, + include_parents_f1, + &individuals, + )?; + let keep: Vec<usize> = selection.keep.clone(); // An individual with no genotypes at all makes the // kinship singular, so leave those out before anything // else is aligned: they contribute nothing to the fit. @@ -400,6 +412,8 @@ pub(crate) async fn resolve_inputs( kept_names, dropped_empty, parents_f1s, + selection.included_by_name, + selection.excluded_by_name, )) }) .await @@ -468,13 +482,31 @@ pub(crate) async fn resolve_inputs( } else { String::new() }; + // What the selection did, beyond the parent/F1 count: a caller + // who names individuals deserves to be told which way it went. + let selection_clause = { + let mut parts = Vec::new(); + if included_by_name > 0 { + parts.push(format!("{included_by_name} re-included by name against the parent/F1 rule")); + } + if excluded_by_name > 0 { + parts.push(format!("{excluded_by_name} excluded by name")); + } + if parts.is_empty() { + String::new() + } else { + format!("; {}", parts.join(", ")) + } + }; notes.push(format!( - "Genotype: {} (version {}, {} individuals, {} parents/F1s dropped{empty_clause}); \ - {} values used.", + "Genotype: {} (version {}, {} individuals, {} parents/F1s dropped{empty_clause}{selection_clause}); \ + the kinship uses all {} (GEMMA does not read phenotypes for it), the association \ + uses the {} with a trait value.", prepared.note, resolved.version, individuals, parents_f1s, + individuals, trait_values.iter().filter(|value| value.is_some()).count() )); aligned_names = Some(kept_names); @@ -1104,6 +1136,11 @@ fn genotype_error_to_api_error( rid: crate::response::RequestInfo, ) -> ApiError { let (status, code, title) = match error { + genotypes::GenotypeError::Invalid(_) => ( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + ), genotypes::GenotypeError::NotFound(_) => ( StatusCode::NOT_FOUND, "genotypes_not_found", diff --git a/src/routes/genotypes.rs b/src/routes/genotypes.rs index fa1f030..65d6a95 100644 --- a/src/routes/genotypes.rs +++ b/src/routes/genotypes.rs @@ -156,6 +156,14 @@ pub async fn group_genotypes( .with_request_id(rid.clone()) })? .map_err(|e| match e { + GenotypeError::Invalid(_) => ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + e.to_string(), + "group_genotypes", + ) + .with_request_id(rid.clone()), GenotypeError::NotFound(message) => ApiError::new( axum::http::StatusCode::NOT_FOUND, "genotypes_not_found", @@ -701,6 +709,11 @@ fn genotype_error_to_api_error( rid: crate::response::RequestInfo, ) -> ApiError { let (status, code, title) = match error { + GenotypeError::Invalid(_) => ( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + ), GenotypeError::NotFound(_) => ( axum::http::StatusCode::NOT_FOUND, "genotypes_not_found", diff --git a/src/routes/phewas.rs b/src/routes/phewas.rs index 3ccccc3..bcfe50a 100644 --- a/src/routes/phewas.rs +++ b/src/routes/phewas.rs @@ -221,6 +221,14 @@ pub async fn group_phewas( .with_request_id(rid.clone()) })? .map_err(|e| match e { + genotypes::GenotypeError::Invalid(message) => ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + message, + "group_phewas", + ) + .with_request_id(rid.clone()), genotypes::GenotypeError::Io(message) => ApiError::new( axum::http::StatusCode::INTERNAL_SERVER_ERROR, "genotypes_unreadable", diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs index bc68aa5..c8929ac 100644 --- a/src/routes/qtl2.rs +++ b/src/routes/qtl2.rs @@ -66,6 +66,10 @@ pub struct Qtl2Request { pub rqtl2_cross: Option<String>, /// Include parents and F1s; off by default, as elsewhere. pub include_parents_f1: Option<bool>, + /// Individuals to keep or drop on top of the parent/F1 rule + /// (`genotypes::Individuals`); `exclude` wins over `include`. + #[serde(default)] + pub individuals: genotypes::Individuals, /// The trait's values by individual name, or `trait_values` positionally /// in the genotype file's order. pub samples: Option<Vec<Qtl2Sample>>, @@ -235,6 +239,7 @@ pub async fn compute_qtl2( let request_group = request.group.clone(); let include_parents_f1 = request.include_parents_f1.unwrap_or(false); + let individuals = request.individuals.clone(); let mut notes: Vec<String> = Vec::new(); /// Where the scan's genotypes come from. #[derive(Clone)] @@ -328,22 +333,18 @@ pub async fn compute_qtl2( &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 parents_f1s = genotypes::non_strains( + std::path::Path::new(&directory), + &wanted, + &resolved.panel, + ); + let selection = genotypes::select_panel( + &resolved.panel, + &parents_f1s, + include_parents_f1, + &individuals, + )?; + let keep: Vec<usize> = selection.keep.clone(); let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values); let kept_names: Vec<String> = keep .iter() @@ -782,6 +783,11 @@ pub async fn compute_qtl2( fn genotypes_error(error: genotypes::GenotypeError, rid: RequestInfo) -> ApiError { let (status, code, title) = match error { + genotypes::GenotypeError::Invalid(_) => ( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + ), genotypes::GenotypeError::NotFound(_) => ( StatusCode::NOT_FOUND, "genotypes_not_found", diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index 065b034..c02adbe 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -60,6 +60,10 @@ pub struct RqtlRequest { /// GeneNetwork2 (`incparentsf1`) and GeneNetwork3 /// (`get_sample_list(inc_par=False, inc_f1=False)`). pub include_parents_f1: Option<bool>, + /// Individuals to keep or drop on top of the parent/F1 rule + /// (`genotypes::Individuals`); `exclude` wins over `include`. + #[serde(default)] + pub individuals: genotypes::Individuals, pub trait_name: String, /// Covariates to fit alongside the trait, each either inline (named /// numeric values, which you converted yourself) or a case attribute @@ -320,24 +324,22 @@ pub async fn compute_rqtl( let cache_dir = std::path::PathBuf::from(&config.rqtl_cache_dir); let version = request.genotype_version.clone(); let include_parents_f1 = request.include_parents_f1.unwrap_or(false); + let individuals = request.individuals.clone(); let values: Vec<(String, Option<f64>)> = samples .iter() .map(|s| (s.name.clone(), s.value)) .collect(); - let (prepared, aligned, matched) = tokio::task::spawn_blocking(move || { + let (prepared, aligned, matched, included_by_name, excluded_by_name) = + tokio::task::spawn_blocking(move || { let resolved = genotypes::resolve(&directory, &group, version.as_deref())?; - let excluded = if include_parents_f1 { - std::collections::BTreeSet::new() - } else { - genotypes::non_strains(&directory, &group, &resolved.panel) - }; - let keep: Vec<usize> = resolved - .panel - .iter() - .enumerate() - .filter(|(_, name)| !excluded.contains(*name)) - .map(|(index, _)| index) - .collect(); + let parents_f1s = genotypes::non_strains(&directory, &group, &resolved.panel); + let selection = genotypes::select_panel( + &resolved.panel, + &parents_f1s, + include_parents_f1, + &individuals, + )?; + let keep: Vec<usize> = selection.keep.clone(); let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &values); let prepared = genotypes::prepare( &directory, @@ -346,7 +348,13 @@ pub async fn compute_rqtl( &keep, &cache_dir, )?; - Ok::<_, genotypes::GenotypeError>((prepared, aligned, (matched, resolved))) + Ok::<_, genotypes::GenotypeError>(( + prepared, + aligned, + (matched, resolved), + selection.included_by_name, + selection.excluded_by_name, + )) }) .await .map_err(|e| { @@ -377,11 +385,21 @@ pub async fn compute_rqtl( .with_request_id(rid)); } extra_notes.push(format!( - "Genotype: {} (version {}, {} individuals, {} parents/F1s dropped); {} of {} supplied values aligned onto it by name.", + "Genotype: {} (version {}, {} individuals, {} parents/F1s dropped{}); {} of {} supplied values aligned onto it by name.", prepared.note, resolved.version, prepared.individuals, prepared.excluded, + { + let mut parts = Vec::new(); + if included_by_name > 0 { + parts.push(format!("{included_by_name} re-included by name")); + } + if excluded_by_name > 0 { + parts.push(format!("{excluded_by_name} excluded by name")); + } + if parts.is_empty() { String::new() } else { format!("; {}", parts.join(", ")) } + }, matched, samples.len() )); @@ -698,6 +716,11 @@ fn genotype_error_to_api_error( rid: crate::response::RequestInfo, ) -> ApiError { let (status, code, title) = match error { + genotypes::GenotypeError::Invalid(_) => ( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_individuals", + "Unusable individual selection", + ), genotypes::GenotypeError::NotFound(_) => ( StatusCode::NOT_FOUND, "genotypes_not_found", |
